Skip to content

Commit

Permalink
Provide a TradeEnv base for CommandEnv
Browse files Browse the repository at this point in the history
This facilities the old "t = TradeDB()" behavior, e.g.

```

Meanwhile it also slightly simplified CommandEnv
   from tradedb import *
   tdb = TradeDB()

   # or specify arguments
   from tradeenv import *
   tenv = TradeEnv(debug=1, dbFilename='test.db')
   tdb = TradeDB(tenv)
```
  • Loading branch information
kfsone committed Nov 3, 2014
1 parent e74fa9d commit 0fcd6c4
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 43 deletions.
2 changes: 1 addition & 1 deletion commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,5 +184,5 @@ def error(self, message):

from commands.commandenv import CommandEnv

return CommandEnv(argv, cmdModule, properties)
return CommandEnv(properties, argv, cmdModule)

31 changes: 9 additions & 22 deletions commands/commandenv.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from commands.exceptions import CommandLineError
from tradeenv import TradeEnv
import pathlib
import sys
import os


class CommandResults(object):
"""
Expand All @@ -20,22 +24,22 @@ class ResultRow(object):
pass


class CommandEnv(object):
class CommandEnv(TradeEnv):
"""
Base class for a TradeDangerous sub-command which has auxilliary
"environment" data in the form of command line options.
"""

def __init__(self, argv, cmdModule, properties):
def __init__(self, properties, argv, cmdModule):
super().__init__(properties=properties)
self.tdb = None
self.mfd = None
self.argv = argv or sys.argv

if properties.detail and properties.quiet:
raise CommandLineError("'--detail' (-v) and '--quiet' (-q) are mutually exclusive.")

self._argv = argv
self._cmd = cmdModule
self._props = properties
self._cmd = cmdModule or __main__
self.wantsTradeDB = getattr(cmdModule, 'wantsTradeDB', True)

# We need to relocate to the working directory so that
Expand All @@ -52,23 +56,6 @@ def __init__(self, argv, cmdModule, properties):
os.chdir(self.cwd)


def __getattr__(self, key, default=None):
""" Fall back to _props when accessing attributes. """
try:
return getattr(self._props, key, default)
except AttributeError:
return default


def DEBUG(self, debugLevel, outText, *args, **kwargs):
"""
Output text to stderr on the condition that
the current debug setting is higher than debugLevel
"""
if self.debug > debugLevel:
print('#', outText.format(*args, **kwargs))


def run(self, tdb):
"""
Set the current database context for this env and check that
Expand Down
42 changes: 22 additions & 20 deletions tradedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from pathlib import Path

from tradeexcept import TradeException
from tradeenv import TradeEnv

import locale
locale.setlocale(locale.LC_ALL, '')
Expand Down Expand Up @@ -341,14 +342,15 @@ class TradeDB(object):


def __init__(self,
cmdenv,
tdenv=None,
sqlFilename=None,
pricesFilename=None,
buildLinks=True,
includeTrades=True
):
self.cmdenv = cmdenv
self.dbPath = Path(cmdenv.dbFilename or TradeDB.defaultDB)
tdenv = tdenv or TradeEnv()
self.tdenv = tdenv
self.dbPath = Path(tdenv.dbFilename or TradeDB.defaultDB)
self.dbURI = str(self.dbPath)
self.sqlPath = Path(sqlFilename or TradeDB.defaultSQL)
self.pricesPath = Path(pricesFilename or TradeDB.defaultPrices)
Expand All @@ -359,7 +361,7 @@ def __init__(self,

self.reloadCache()

self.load(maxSystemLinkLy=cmdenv.maxSystemLinkLy,
self.load(maxSystemLinkLy=tdenv.maxSystemLinkLy,
buildLinks=buildLinks,
includeTrades=includeTrades,
)
Expand All @@ -371,7 +373,7 @@ def __init__(self,
def getDB(self):
if self.conn: return self.conn
try:
self.cmdenv.DEBUG(1, "Connecting to DB")
self.tdenv.DEBUG(1, "Connecting to DB")
import sqlite3
return sqlite3.connect(self.dbURI)
except ImportError as e:
Expand Down Expand Up @@ -420,18 +422,18 @@ def getMostRecentTimestamp(altPath):
# check if any of the table files have changed.
changedFiles = [ fileName for (fileName, _) in self.importTables if getMostRecentTimestamp(Path(fileName)) > dbFileCreatedTimestamp ]
if not changedFiles:
self.cmdenv.DEBUG(1, "DB Cache is up to date.")
self.tdenv.DEBUG(1, "DB Cache is up to date.")
return
self.cmdenv.DEBUG(0, "Rebuilding DB Cache because of modified {}",
self.tdenv.DEBUG(0, "Rebuilding DB Cache because of modified {}",
', '.join(changedFiles))
else:
self.cmdenv.DEBUG(0, "Rebuilding DB Cache [db:{}, sql:{}, prices:{}]",
self.tdenv.DEBUG(0, "Rebuilding DB Cache [db:{}, sql:{}, prices:{}]",
dbFileCreatedTimestamp, sqlTimestamp, pricesTimestamp)
else:
self.cmdenv.DEBUG(0, "Building DB Cache")
self.tdenv.DEBUG(0, "Building DB Cache")

import buildcache
buildcache.buildCache(self.cmdenv, dbPath=self.dbPath, sqlPath=self.sqlPath, pricesPath=self.pricesPath, importTables=self.importTables)
buildcache.buildCache(self.tdenv, dbPath=self.dbPath, sqlPath=self.sqlPath, pricesPath=self.pricesPath, importTables=self.importTables)


############################################################
Expand All @@ -457,7 +459,7 @@ def _loadSystems(self):
systemByID[ID] = systemByName[name] = System(ID, name, posX, posY, posZ)

self.systemByID, self.systemByName = systemByID, systemByName
self.cmdenv.DEBUG(1, "Loaded {:n} Systems", len(systemByID))
self.tdenv.DEBUG(1, "Loaded {:n} Systems", len(systemByID))


def buildLinks(self):
Expand All @@ -482,9 +484,9 @@ def buildLinks(self):
lhs.links[rhs] = rhs.links[lhs] = math.sqrt(distSq)
self.numLinks += 1

self.cmdenv.DEBUG(2, "Number of links between systems: {:n}", self.numLinks)
self.tdenv.DEBUG(2, "Number of links between systems: {:n}", self.numLinks)

if self.cmdenv.debug:
if self.tdenv.debug:
self._validate()


Expand Down Expand Up @@ -545,7 +547,7 @@ def _loadStations(self):
stationByID[ID] = stationByName[name] = Station(ID, systemByID[systemID], name, lsFromStar, itemCount)

self.stationByID, self.stationByName = stationByID, stationByName
self.cmdenv.DEBUG(1, "Loaded {:n} Stations", len(stationByID))
self.tdenv.DEBUG(1, "Loaded {:n} Stations", len(stationByID))


def lookupStation(self, name, system=None):
Expand Down Expand Up @@ -626,7 +628,7 @@ def _loadShips(self):
self.cur.execute(stmt)
self.shipByID = { row[0]: Ship(*row, stations=[]) for row in self.cur }

self.cmdenv.DEBUG(1, "Loaded {} Ships", len(self.shipByID))
self.tdenv.DEBUG(1, "Loaded {} Ships", len(self.shipByID))


def lookupShip(self, name):
Expand Down Expand Up @@ -657,7 +659,7 @@ def _loadCategories(self):
"""
self.categoryByID = { ID: Category(ID, name, []) for (ID, name) in self.cur.execute(stmt) }

self.cmdenv.DEBUG(1, "Loaded {} Categories", len(self.categoryByID))
self.tdenv.DEBUG(1, "Loaded {} Categories", len(self.categoryByID))


def lookupCategory(self, name):
Expand Down Expand Up @@ -703,12 +705,12 @@ def _loadItems(self):
item = itemByID[itemID]
item.altname = altName
itemByName[altName] = item
self.cmdenv.DEBUG(1, "'{}' alias for #{} '{}'", altName, itemID, item.fullname)
self.tdenv.DEBUG(1, "'{}' alias for #{} '{}'", altName, itemID, item.fullname)

self.itemByID = itemByID
self.itemByName = itemByName

self.cmdenv.DEBUG(1, "Loaded {:n} Items, {:n} AltItemNames",
self.tdenv.DEBUG(1, "Loaded {:n} Items, {:n} AltItemNames",
len(self.itemByID), aliases)


Expand Down Expand Up @@ -800,7 +802,7 @@ def load(self, dbFilename=None, maxSystemLinkLy=None, buildLinks=True, includeTr
tdb.load() # x now points to an orphan Aulin
"""

self.cmdenv.DEBUG(1, "Loading data")
self.tdenv.DEBUG(1, "Loading data")

conn = self.getDB()
self.cur = conn.cursor()
Expand All @@ -822,7 +824,7 @@ def load(self, dbFilename=None, maxSystemLinkLy=None, buildLinks=True, includeTr
self.maxSystemLinkLy = longestJumper.maxLyEmpty
else:
self.maxSystemLinkLy = maxSystemLinkLy
self.cmdenv.DEBUG(2, "Max ship jump distance: {} @ {:.02f}",
self.tdenv.DEBUG(2, "Max ship jump distance: {} @ {:.02f}",
longestJumper.name(), self.maxSystemLinkLy)

if buildLinks:
Expand Down
30 changes: 30 additions & 0 deletions tradeenv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class TradeEnv(object):
"""
Container for a TradeDangerous "environment", which is a
collection of operational parameters.
"""

def __init__(self, properties=None, **kwargs):
properties = properties or type('Properties', (), dict())

self._props = properties
for arg, value in kwargs.items():
setattr(self, arg, value)


def __getattr__(self, key, default=None):
""" Fall back to _props when accessing attributes. """
try:
return getattr(self._props, key, default)
except AttributeError:
return default


def DEBUG(self, debugLevel, outText, *args, **kwargs):
"""
Output text to stderr on the condition that
the current debug setting is higher than debugLevel
"""
if self.debug > debugLevel:
print('#', outText.format(*args, **kwargs))

0 comments on commit 0fcd6c4

Please sign in to comment.