Generate the list of generators automatically

Generate new traylayout class to make this work with the web interface
Minor fix to not error out in web interface for non existing doc string
This commit is contained in:
Florian Festi 2016-07-31 17:18:17 +02:00
parent b6d84b5c58
commit 6dd482be9c
4 changed files with 53 additions and 58 deletions

View File

@ -1,27 +1,29 @@
import pkgutil
__all__ = [ import inspect
"box", import importlib
"box2", import boxes
"box3",
"castle",
"drillbox",
"flexbox",
"flexbox2",
"flexbox3",
"flexbox4",
"flextest",
"flextest2",
"folder",
"lamp",
"magazinefile",
"pulley",
"silverwarebox",
"trayinsert",
"traylayout",
"typetray",
]
def getAllBoxGenerators(): def getAllBoxGenerators():
import importlib generators = {}
return {name: importlib.import_module("boxes.generators." + name) for importer, modname, ispkg in pkgutil.walk_packages(
for name in __all__} path=__path__,
prefix=__name__+'.',
onerror=lambda x: None):
module = importlib.import_module(modname)
for k, v in module.__dict__.items():
if v is boxes.Boxes:
continue
if inspect.isclass(v) and issubclass(v, boxes.Boxes):
generators[modname + '.' + v.__name__] = v
return generators
def getAllGeneratorModules():
generators = {}
for importer, modname, ispkg in pkgutil.walk_packages(
path=__path__,
prefix=__name__+'.',
onerror=lambda x: None):
module = importlib.import_module(modname)
generators[modname.split('.')[-1]] = module
return generators

View File

@ -19,7 +19,11 @@ from boxes import *
import boxes import boxes
class Layout(Boxes): class Layout(Boxes):
"""Generate a typetray from a layout file""" """Generate a typetray from a layout file"""
webinterface = False
def __init__(self, input=None, webargs=False): def __init__(self, input=None, webargs=False):
Boxes.__init__(self) Boxes.__init__(self)
self.buildArgParser("h", "hi", "outside") self.buildArgParser("h", "hi", "outside")
@ -353,10 +357,12 @@ class Layout(Boxes):
self.vwalls = vwalls self.vwalls = vwalls
self.floors = floors self.floors = floors
class LayoutGenerator(Layout): class TrayLayout(Layout):
"""Type tray with each wall and floor tile being optional""" """Type tray with each wall and floor tile being optional"""
webinterface = True
def __init__(self): def __init__(self):
Boxes.__init__(self) Boxes.__init__(self)
self.argparser = boxes.ArgumentParser() self.argparser = boxes.ArgumentParser()
@ -370,6 +376,18 @@ class LayoutGenerator(Layout):
def render(self): def render(self):
return return
class TrayLayout2(Layout):
"""Generate a typetray from a layout file"""
webinterface = True
def __init__(self, input=None):
Boxes.__init__(self)
self.buildArgParser("h", "hi", "outside")
self.argparser.add_argument(
"--layout", action="store", type=str)
def main(): def main():
l = Layout() l = Layout()
l.parseArgs() l.parseArgs()

View File

@ -21,8 +21,8 @@ boxes [NAME] [options]
""") """)
def main(): def main():
modules = boxes.generators.getAllBoxGenerators() modules = boxes.generators.getAllGeneratorModules()
del modules['_template']
if len(sys.argv) == 1: if len(sys.argv) == 1:
printusage() printusage()
elif sys.argv[1] in modules: elif sys.argv[1] in modules:
@ -33,6 +33,8 @@ def main():
elif sys.argv[1] == '--list': elif sys.argv[1] == '--list':
print("Available generators:") print("Available generators:")
for name in sorted(modules): for name in sorted(modules):
if not hasattr(modules[name], "main"):
continue
print(" * ", name) print(" * ", name)
else: else:
print("Unknown generator name. Use boxes --list to get a list of available commands.") print("Unknown generator name. Use boxes --list to get a list of available commands.")

View File

@ -25,13 +25,6 @@ except ImportError:
sys.path.append(os.path.dirname(__file__) + "/..") sys.path.append(os.path.dirname(__file__) + "/..")
import boxes.generators import boxes.generators
from boxes.generators import box, box2, box3, drillbox
from boxes.generators import flexbox, flexbox2, flexbox3, flexbox4, gearbox
from boxes.generators import flextest, flextest2, folder, planetary, pulley
from boxes.generators import magazinefile, trayinsert, traylayout, typetray, silverwarebox
class FileChecker(threading.Thread): class FileChecker(threading.Thread):
def __init__(self, files=[], checkmodules=True): def __init__(self, files=[], checkmodules=True):
super(FileChecker, self).__init__() super(FileChecker, self).__init__()
@ -76,28 +69,8 @@ boxes.ArgumentParser = ThrowingArgumentParser # Evil hack
class BServer: class BServer:
def __init__(self): def __init__(self):
self.boxes = { self.boxes = {b.__name__ : b() for b in boxes.generators.getAllBoxGenerators().values() if b.webinterface}
"Box" : box.Box(),
"Box2" : box2.Box(),
"Box3" : box3.Box(),
"DrillBox" : drillbox.Box(),
"FlexBox" : flexbox.FlexBox(),
"FlexBox2" : flexbox2.FlexBox(),
"FlexBox3" : flexbox3.FlexBox(),
"FlexBox4" : flexbox4.FlexBox(),
"FlexTest": flextest.FlexTest(),
"FlexTest2": flextest2.FlexTest(),
"Folder": folder.Folder(),
"GearBox" : gearbox.GearBox(),
"MagazinFile" : magazinefile.Box(),
"TrayInsert" : trayinsert.TrayInsert(),
"PlanetaryGear" : planetary.Planetary(),
"Pulley" : pulley.Pulley(),
"TypeTray" : typetray.TypeTray(),
"SilverwareBox" : silverwarebox.Silverware(),
"TrayLayout" : traylayout.LayoutGenerator(),
"TrayLayout2" : traylayout.Layout(webargs=True),
}
def arg2html(self, a): def arg2html(self, a):
name = a.option_strings[0].replace("-", "") name = a.option_strings[0].replace("-", "")
if isinstance(a, argparse._HelpAction): if isinstance(a, argparse._HelpAction):
@ -130,7 +103,7 @@ class BServer:
result = ["""<html><head><title>Boxes - """, name, """</title></head> result = ["""<html><head><title>Boxes - """, name, """</title></head>
<body> <body>
<h1>""", name, """</h1> <h1>""", name, """</h1>
<p>""", box.__doc__, """</p> <p>""", box.__doc__ or "", """</p>
<form action="%s" method="GET" target="_blank"> <form action="%s" method="GET" target="_blank">
<table> <table>
""" % (action)] """ % (action)]