Skip to content

Commit

Permalink
Self-assembling replacement for DEBUG
Browse files Browse the repository at this point in the history
  • Loading branch information
Oliver Smith committed Nov 13, 2014
1 parent 8b21433 commit 9d980f1
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 69 deletions.
30 changes: 15 additions & 15 deletions buildcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ def changeStation(matches):
systemName, stationName = matches.group(1, 2)
facility = systemName.upper() + '/' + stationName.upper()

tdenv.DEBUG(1, "NEW STATION: {}", facility)
tdenv.DEBUG1("NEW STATION: {}", facility)

# Make sure it's valid.
try:
Expand All @@ -382,12 +382,12 @@ def changeStation(matches):
systemName = corrections.correctSystem(systemName)
stationName = corrections.correctStation(stationName)
if systemName == DELETED or stationName == DELETED:
tdenv.DEBUG(1, "DELETED: {}", facility)
tdenv.DEBUG1("DELETED: {}", facility)
stationID = DELETED
facility = systemName.upper() + '/' + stationName.upper()
try:
stationID = systemByName[facility]
tdenv.DEBUG(0, "Renamed: {}", facility)
tdenv.DEBUG0("Renamed: {}", facility)
except KeyError:
raise UnknownStationError(priceFile, lineNo, facility) from None

Expand All @@ -407,7 +407,7 @@ def changeCategory(matches):

categoryName, uiOrder = matches.group(1), 0

tdenv.DEBUG(1, "NEW CATEGORY: {}", categoryName)
tdenv.DEBUG1("NEW CATEGORY: {}", categoryName)

try:
categoryID = categoriesByName[categoryName]
Expand All @@ -421,7 +421,7 @@ def changeCategory(matches):
raise SyntaxError("Category has been deleted.")
try:
categoryID = categoriesByName[categoryName]
tdenv.DEBUG(1, "Renamed: {}", categoryName)
tdenv.DEBUG1("Renamed: {}", categoryName)
except KeyError:
raise UnknownCategoryError(priceFile, lineNo, facility)

Expand Down Expand Up @@ -457,11 +457,11 @@ def processItemLine(matches):
oldName = itemName
itemName = corrections.correctItem(itemName)
if itemName == DELETED:
tdenv.DEBUG(1, "DELETED {}", oldName)
tdenv.DEBUG1("DELETED {}", oldName)
return
try:
itemID = itemByName[itemPrefix + itemName]
tdenv.DEBUG(1, "Renamed {} -> {}", oldName, itemName)
tdenv.DEBUG1("Renamed {} -> {}", oldName, itemName)
except KeyError:
raise UnknownItemError(priceFile, lineNo, itemName)

Expand Down Expand Up @@ -534,10 +534,10 @@ def processItemLine(matches):
######################################################################

def processPricesFile(tdenv, db, pricesPath, stationID=None, defaultZero=False):
tdenv.DEBUG(0, "Processing Prices file '{}'", pricesPath)
tdenv.DEBUG0("Processing Prices file '{}'", pricesPath)

if stationID:
tdenv.DEBUG(0, "Deleting stale entries for {}", stationID)
tdenv.DEBUG0("Deleting stale entries for {}", stationID)
db.execute(
"DELETE FROM Price WHERE station_id = ?",
[stationID]
Expand All @@ -546,7 +546,7 @@ def processPricesFile(tdenv, db, pricesPath, stationID=None, defaultZero=False):
with pricesPath.open() as pricesFile:
bindValues = []
for price in genSQLFromPriceLines(tdenv, pricesFile, db, defaultZero):
tdenv.DEBUG(2, price)
tdenv.DEBUG2(price)
bindValues += [ price ]
stmt = """
INSERT OR REPLACE INTO Price (
Expand Down Expand Up @@ -590,7 +590,7 @@ def deprecationCheckStation(line, debug):


def processImportFile(tdenv, db, importPath, tableName):
tdenv.DEBUG(0, "Processing import file '{}' for table '{}'", str(importPath), tableName)
tdenv.DEBUG0("Processing import file '{}' for table '{}'", str(importPath), tableName)

fkeySelectStr = ("("
"SELECT {newValue}"
Expand Down Expand Up @@ -646,7 +646,7 @@ def processImportFile(tdenv, db, importPath, tableName):
columns=','.join(bindColumns),
values=','.join(bindValues)
)
tdenv.DEBUG(0, "SQL-Statement: {}", sql_stmt)
tdenv.DEBUG0("SQL-Statement: {}", sql_stmt)

# Check if there is a deprecation check for this table.
deprecationFn = getattr(sys.modules[__name__],
Expand All @@ -659,7 +659,7 @@ def processImportFile(tdenv, db, importPath, tableName):
for linein in csvin:
lineNo = csvin.line_num
if len(linein) == columnCount:
tdenv.DEBUG(1, " Values: {}", ', '.join(linein))
tdenv.DEBUG1(" Values: {}", ', '.join(linein))
if deprecationFn: deprecationFn(linein, tdenv.debug)
for (colNo, index) in uniqueIndexes:
colValue = linein[colNo]
Expand Down Expand Up @@ -693,13 +693,13 @@ def processImportFile(tdenv, db, importPath, tableName):
) from None
importCount += 1
db.commit()
tdenv.DEBUG(0, "{count} {table}s imported",
tdenv.DEBUG0("{count} {table}s imported",
count=importCount,
table=tableName)


def generateSystemLinks(tdenv, db, maxLinkDist):
tdenv.DEBUG(0, "Generating SystemLinks table")
tdenv.DEBUG0("Generating SystemLinks table")
db.create_function("sqrt", 1, math.sqrt)
db.execute("""
CREATE TABLE SystemLinks
Expand Down
10 changes: 5 additions & 5 deletions commands/buy_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def run(results, cmdenv, tdb):
from commands.commandenv import ResultRow

item = tdb.lookupItem(cmdenv.item)
cmdenv.DEBUG(0, "Looking up item {} (#{})", item.name(), item.ID)
cmdenv.DEBUG0("Looking up item {} (#{})", item.name(), item.ID)

# Constraints
constraints = [ "(item_id = {})".format(item.ID), "buy_from > 0", "stock != 0" ]
Expand All @@ -73,13 +73,13 @@ def run(results, cmdenv, tdb):
results.summary.near = nearSystem
results.summary.ly = maxLy

cmdenv.DEBUG(0, "Searching within {}ly of {}", maxLy, nearSystem.name())
cmdenv.DEBUG0("Searching within {}ly of {}", maxLy, nearSystem.name())

def genStationIDs():
nonlocal distances
for (sys, dist) in tdb.genSystemsInRange(
nearSystem, maxLy, includeSelf=True):
cmdenv.DEBUG(2, "Checking stations in {}", sys.name())
cmdenv.DEBUG2("Checking stations in {}", sys.name())
hadStation = False
for station in sys.stations:
if station.itemCount > 0:
Expand All @@ -103,14 +103,14 @@ def genStationIDs():
FROM Price
WHERE {}
""".format(whereClause)
cmdenv.DEBUG(0, 'SQL: {}', stmt)
cmdenv.DEBUG0('SQL: {}', stmt)
cur = tdb.query(stmt, bindValues)

stationByID = tdb.stationByID
for (stationID, priceCr, stock) in cur:
row = ResultRow()
row.station = stationByID[stationID]
cmdenv.DEBUG(2, "{} {}cr {} units", row.station.name(), priceCr, stock)
cmdenv.DEBUG2("{} {}cr {} units", row.station.name(), priceCr, stock)
if nearSystem:
row.dist = distances[row.station.system.ID]
row.price = priceCr
Expand Down
6 changes: 3 additions & 3 deletions commands/commandenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, properties, argv, cmdModule):
exePath = pathlib.Path(argv[0]).parent.resolve()
if cwdPath != exePath:
self.cwd = str(exePath)
self.DEBUG(1, "cwd at launch was: {}, changing to {} to match trade.py",
self.DEBUG1("cwd at launch was: {}, changing to {} to match trade.py",
cwdPath, self.cwd)
if self.cwd:
os.chdir(self.cwd)
Expand Down Expand Up @@ -176,11 +176,11 @@ def checkAvoids(self):
if system and station and station.system != system:
raise AmbiguityError('Avoidance', avoid, [ system.str(), station.str() ])

self.DEBUG(0, "Avoiding items %s, systems %s, stations %s" % (
self.DEBUG0("Avoiding items {}, systems {}, stations {}",
[ item.name() for item in avoidItems ],
[ system.name() for system in avoidSystems ],
[ station.name() for station in avoidStations ]
))
)

self.avoidPlaces = self.avoidSystems + self.avoidStations

Expand Down
2 changes: 1 addition & 1 deletion commands/local_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def render(results, cmdenv, tdb):
key=lambda row: '{}ls'.format(row.dist) if row.dist else '')
)

cmdenv.DEBUG(0,
cmdenv.DEBUG0(
"Systems within {ly:<5.2f}ly of {sys}.\n",
sys=results.summary.near.name(),
ly=results.summary.ly,
Expand Down
2 changes: 1 addition & 1 deletion commands/nav_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def run(results, cmdenv, tdb):
dstSystem = cmdenv.stopSystem
maxLyPer = cmdenv.maxLyPer or tdb.maxSystemLinkLy

cmdenv.DEBUG(0, "Route from {} to {} with max {} ly per jump.",
cmdenv.DEBUG0("Route from {} to {} with max {} ly per jump.",
srcSystem.name(), dstSystem.name(), maxLyPer)

openList = { srcSystem: 0.0 }
Expand Down
8 changes: 4 additions & 4 deletions commands/run_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def validateRunArguments(tdb, cmdenv):
def run(results, cmdenv, tdb):
from commands.commandenv import ResultRow

cmdenv.DEBUG(1, "loading trades")
cmdenv.DEBUG1("loading trades")

if tdb.tradingCount == 0:
raise NoDataError("Database does not contain any profitable trades.")
Expand All @@ -323,7 +323,7 @@ def run(results, cmdenv, tdb):
viaStartPos = 1 if startStn else 0
cmdenv.maxJumps = None

cmdenv.DEBUG(0,
cmdenv.DEBUG0(
"From {fromStn}, To {toStn}, Via {via}, "
"Cap {cap}, Credits {cr}, "
"Hops {hops}, Jumps/Hop {jumpsPer}, Ly/Jump {lyPer:.2f}"
Expand All @@ -341,11 +341,11 @@ def run(results, cmdenv, tdb):
# Instantiate the calculator object
calc = TradeCalc(tdb, cmdenv)

cmdenv.DEBUG(1, "unspecified hops {}, numHops {}, viaSet {}",
cmdenv.DEBUG1("unspecified hops {}, numHops {}, viaSet {}",
cmdenv.unspecifiedHops, numHops, len(viaSet))

for hopNo in range(numHops):
cmdenv.DEBUG(1, "Hop {}", hopNo)
cmdenv.DEBUG1("Hop {}", hopNo)

restrictTo = None
if hopNo == lastHop and stopStn:
Expand Down
18 changes: 9 additions & 9 deletions commands/update_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class TemporaryFileExistsError(TradeException):


def getEditorPaths(cmdenv, editorName, envVar, windowsFolders, winExe, nixExe):
cmdenv.DEBUG(0, "Locating {} editor", editorName)
cmdenv.DEBUG0("Locating {} editor", editorName)
try:
return os.environ[envVar]
except KeyError: pass
Expand Down Expand Up @@ -112,7 +112,7 @@ def getEditorPaths(cmdenv, editorName, envVar, windowsFolders, winExe, nixExe):


def importDataFromFile(cmdenv, tdb, path, stationID, dbFilename):
cmdenv.DEBUG(0, "Importing data from {}".format(str(path)))
cmdenv.DEBUG0("Importing data from {}".format(str(path)))
buildcache.processPricesFile(cmdenv,
db=tdb.getDB(),
pricesPath=path,
Expand All @@ -121,7 +121,7 @@ def importDataFromFile(cmdenv, tdb, path, stationID, dbFilename):
)

# If everything worked, we need to re-build the prices file.
cmdenv.DEBUG(0, "Update complete, regenerating .prices file")
cmdenv.DEBUG0("Update complete, regenerating .prices file")

with tdb.pricesPath.open("w") as pricesFile:
prices.dumpPrices(dbFilename, prices.Element.full, file=pricesFile, debug=cmdenv.debug)
Expand All @@ -140,32 +140,32 @@ def editUpdate(tdb, cmdenv, stationID):
database and regenerate the master .prices file.
"""

cmdenv.DEBUG(0, "'update' mode with editor. editor:{} station:{}",
cmdenv.DEBUG0("'update' mode with editor. editor:{} station:{}",
cmdenv.editor, cmdenv.origin)

editor, editorArgs = cmdenv.editor, []
if cmdenv.editing == 'sublime':
cmdenv.DEBUG(0, "Sublime mode")
cmdenv.DEBUG0("Sublime mode")
editor = editor or getEditorPaths(cmdenv,
"sublime", "SUBLIME_EDITOR",
["Sublime Text 3", "Sublime Text 2"], "sublime_text.exe", "subl")
editorArgs += [ "--wait" ]
elif cmdenv.editing == 'npp':
cmdenv.DEBUG(0, "Notepad++ mode")
cmdenv.DEBUG0("Notepad++ mode")
editor = editor or getEditorPaths(cmdenv,
"notepad++", "NOTEPADPP_EDITOR",
["Notepad++"], "notepad++.exe", "notepad++")
if not cmdenv.quiet:
print("NOTE: You'll need to exit Notepad++ to return control back to trade.py")
elif cmdenv.editing == "vim":
cmdenv.DEBUG(0, "VI iMproved mode")
cmdenv.DEBUG0("VI iMproved mode")
if not editor:
# Hack... Hackity hack, hack, hack.
# This has a disadvantage in that: we don't check for just "vim" (no .exe) under Windows
vimDirs = [ "Git\\share\\vim\\vim{}".format(vimVer) for vimVer in range(70,75) ]
editor = getEditorPaths(cmdenv, "vim", "EDITOR", vimDirs, "vim.exe", "vim")
elif cmdenv.editing == "notepad":
cmdenv.DEBUG(0, "Notepad mode")
cmdenv.DEBUG0("Notepad mode")
editor = editor or "notepad.exe" # herp

try:
Expand Down Expand Up @@ -207,7 +207,7 @@ def editUpdate(tdb, cmdenv, stationID):

# Launch the editor
editorCommandLine = [ editor ] + editorArgs + [ absoluteFilename ]
cmdenv.DEBUG(0, "Invoking [{}]", ' '.join(editorCommandLine))
cmdenv.DEBUG0("Invoking [{}]", ' '.join(editorCommandLine))
try:
result = subprocess.call(editorCommandLine)
except FileNotFoundError:
Expand Down
17 changes: 10 additions & 7 deletions tradecalc.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,10 @@ def getBestTrade(self, src, dst, credits=None, fitFunction=None):
if credits is None: credits = tdenv.credits - getattr(tdenv, 'insurance', 0)
capacity = tdenv.capacity
avoidItems = tdenv.avoidItems
self.tdenv.DEBUG(0, "{} -> {} with {:n}cr", src.name(), dst.name(), credits)
self.tdenv.DEBUG0("{}/{} -> {}/{} with {:n}cr",
src.system.dbname, src.dbname,
dst.system.dbname, src.dbname,
credits)

if not dst in src.tradingWith:
raise ValueError("%s does not have a link to %s" % (src.name(), dst.name()))
Expand Down Expand Up @@ -410,7 +413,7 @@ def getBestHops(self, routes, restrictTo=None):
safetyMargin = 1.0 - tdenv.margin
unique = tdenv.unique
for route in routes:
tdenv.DEBUG(1, "Route = {}", route.str())
tdenv.DEBUG1("Route = {}", route.str())

src = route.route[-1]
startCr = credits + int(route.gainCr * safetyMargin)
Expand All @@ -421,26 +424,26 @@ def getBestHops(self, routes, restrictTo=None):
maxLyPer=maxLyPer,
avoidPlaces=avoidPlaces,
):
tdenv.DEBUG(2, "destSys {}, destStn {}, jumps {}, distLy {}",
tdenv.DEBUG2("destSys {}, destStn {}, jumps {}, distLy {}",
dest.system.name(),
dest.station.name(),
"->".join([jump.str() for jump in dest.via]),
dest.distLy)
if not dest.station in src.tradingWith:
tdenv.DEBUG(3, "{} is not in my station list", dest.station.name())
tdenv.DEBUG3("{} is not in my station list", dest.station.name())
continue
if restrictTo:
if not dest.station in restrictTo and not dest.system in restrictTo:
tdenv.DEBUG(3, "{} doesn't match restrict {}",
tdenv.DEBUG3("{} doesn't match restrict {}",
dest.station.name(), restrictTo)
continue
if unique and dest.station in route.route:
tdenv.DEBUG(3, "{} is already in the list, not unique", dest.station.name())
tdenv.DEBUG3("{} is already in the list, not unique", dest.station.name())
continue

trade = self.getBestTrade(src, dest.station, startCr)
if not trade:
tdenv.DEBUG(3, "No trade")
tdenv.DEBUG3("No trade")
continue

dstID = dest.station.ID
Expand Down
Loading

0 comments on commit 9d980f1

Please sign in to comment.