0

Added a new 'listify' parameter to the config file parser

Specifying listify on an option will cause it to be parsed as a list.
Use listdelim to specify the delimiter (defaults to ',')

Examples, assuming you had the following option:
add_option("--test","test", type="int", listify=True)

Command line:
  --test 1          results in [1]
  --test 1,2,3      results in [1,2,3]

Config file:
  test=1            results in [1]
  test="1,2,3"      results in [1,2,3]
  test=[1,4,9]      results in [1,4,9]
This commit is contained in:
Andrew Chin
2011-03-25 20:38:25 -04:00
parent 6c9bbc25da
commit 82e0bf53b9
2 changed files with 43 additions and 24 deletions

View File

@@ -13,9 +13,11 @@ class ConfigOptionParser(object):
# these are arguments not understood by OptionParser, so they must be removed
# in add_option before being passed to the OptionParser
# note that default is a valid OptionParser argument, but we remove it
# because we want to do our default value handling
self.customArgs = ["required", "commandLineOnly", "default"]
self.customArgs = ["required", "commandLineOnly", "default", "listify", "listdelim", "choices"]
self.requiredArgs = []
@@ -35,6 +37,8 @@ class ConfigOptionParser(object):
for arg in self.customArgs:
if arg in kwargs.keys(): del kwargs[arg]
if kwargs.get("type", None):
kwargs['type'] = 'string' # we'll do our own converting later
self.cmdParser.add_option(*args, **kwargs)
def print_help(self):
@@ -114,29 +118,15 @@ class ConfigOptionParser(object):
# sixth, check types
for a in self.configVars:
n = a['dest']
if 'listify' in a.keys():
# this thing may be a list!
if configResults.__dict__[n] != None and type(configResults.__dict__[n]) == str:
configResults.__dict__[n] = configResults.__dict__[n].split(a.get("listdelim",","))
elif type(configResults.__dict__[n]) != list:
configResults.__dict__[n] = [configResults.__dict__[n]]
if 'type' in a.keys() and configResults.__dict__[n] != None:
try:
# switch on type. there are only 6 types that can be used with optparse
if a['type'] == "int":
configResults.__dict__[n] = int(configResults.__dict__[n])
elif a['type'] == "string":
configResults.__dict__[n] = str(configResults.__dict__[n])
elif a['type'] == "long":
configResults.__dict__[n] = long(configResults.__dict__[n])
elif a['type'] == "choice":
if configResults.__dict__[n] not in a['choices']:
print "The value '%s' is not valid for config parameter '%s'" % (configResults.__dict__[n], n)
sys.exit(1)
elif a['type'] == "float":
configResults.__dict__[n] = long(configResults.__dict__[n])
elif a['type'] == "complex":
configResults.__dict__[n] = complex(configResults.__dict__[n])
elif a['type'] == "function":
if not callable(configResults.__dict__[n]):
raise ValueError("Not callable")
else:
print "Unknown type!"
sys.exit(1)
configResults.__dict__[n] = self.checkType(configResults.__dict__[n], a)
except ValueError, ex:
print "There was a problem converting the value '%s' to type %s for config parameter '%s'" % (configResults.__dict__[n], a['type'], n)
import traceback
@@ -149,3 +139,30 @@ class ConfigOptionParser(object):
return configResults, args
def checkType(self, value, a):
if type(value) == list:
return map(lambda x: self.checkType(x, a), value)
# switch on type. there are only 7 types that can be used with optparse
if a['type'] == "int":
return int(value)
elif a['type'] == "string":
return str(value)
elif a['type'] == "long":
return long(value)
elif a['type'] == "choice":
if value not in a['choices']:
print "The value '%s' is not valid for config parameter '%s'" % (value, a['dest'])
sys.exit(1)
return value
elif a['type'] == "float":
return long(value)
elif a['type'] == "complex":
return complex(value)
elif a['type'] == "function":
if not callable(value):
raise ValueError("Not callable")
else:
print "Unknown type!"
sys.exit(1)

View File

@@ -64,7 +64,7 @@ def main():
parser.add_option("-z", "--zoom", dest="zoom", help="Sets the zoom level manually instead of calculating it. This can be useful if you have outlier chunks that make your world too big. This value will make the highest zoom level contain (2**ZOOM)^2 tiles", action="store", type="int", configFileOnly=True)
parser.add_option("-d", "--delete", dest="delete", help="Clear all caches. Next time you render your world, it will have to start completely over again. This is probably not a good idea for large worlds. Use this if you change texture packs and want to re-render everything.", action="store_true", commandLineOnly=True)
parser.add_option("--chunklist", dest="chunklist", help="A file containing, on each line, a path to a chunkfile to update. Instead of scanning the world directory for chunks, it will just use this list. Normal caching rules still apply.")
parser.add_option("--rendermode", dest="rendermode", help="Specifies the render type: normal (default), lighting, night, or spawn.", type="choice", choices=["normal", "lighting", "night", "spawn"], required=True, default="normal")
parser.add_option("--rendermodes", dest="rendermode", help="Specifies the render type: normal (default), lighting, night, or spawn.", type="choice", choices=["normal", "lighting", "night", "spawn"], required=True, default="normal", listify=True)
parser.add_option("--imgformat", dest="imgformat", help="The image output format to use. Currently supported: png(default), jpg. NOTE: png will always be used as the intermediate image format.", configFileOnly=True )
parser.add_option("--optimize-img", dest="optimizeimg", help="If using png, perform image file size optimizations on the output. Specify 1 for pngcrush, 2 for pngcrush+optipng+advdef. This may double (or more) render times, but will produce up to 30% smaller images. NOTE: requires corresponding programs in $PATH or %PATH%", configFileOnly=True)
parser.add_option("--web-assets-hook", dest="web_assets_hook", help="If provided, run this function after the web assets have been copied, but before actual tile rendering begins. It should accept a QuadtreeGen object as its only argument.", action="store", metavar="SCRIPT", type="function", configFileOnly=True)
@@ -76,6 +76,7 @@ def main():
options, args = parser.parse_args()
if options.version:
print "Minecraft-Overviewer"
print "Git version: %s" % util.findGitVersion()
@@ -178,7 +179,8 @@ def main():
# create the quadtrees
# TODO chunklist
q = quadtree.QuadtreeGen(w, destdir, depth=options.zoom, imgformat=imgformat, optimizeimg=optimizeimg, rendermode=options.rendermode)
# NOTE: options.rendermode is now a list of rendermodes. for now, always use the first one
q = quadtree.QuadtreeGen(w, destdir, depth=options.zoom, imgformat=imgformat, optimizeimg=optimizeimg, rendermode=options.rendermode[0])
# write out the map and web assets
m = googlemap.MapGen([q,], skipjs=options.skipjs, web_assets_hook=options.web_assets_hook)