Commit 1e4d9a00 authored by Hartmut Goebel's avatar Hartmut Goebel
Browse files

Use std-module `optparse` instead of `twisted.python.usage` and save a lot of code.

parent 9e7e8d81
......@@ -5,16 +5,14 @@
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Frank Scholz <fs@beebits.net>
# Copyright 2011, Hartmut Goebel <h.goebel@crazy-compilers.com>
""" Cadre is a PictureFrame application based on
the Coherence DLNA/UPnP framework
"""
import os, sys
from twisted.python import usage, text
import os
from cadre import __version__
......@@ -40,153 +38,6 @@ def daemonize():
raise
os.close(null)
"""
taken with minor adjustments from twisted.python.text.py
"""
def greedyWrap(inString, width=80):
"""Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation.
"""
outLines = []
#eww, evil hacks to allow paragraphs delimited by two \ns :(
if inString.find('\n\n') >= 0:
paragraphs = inString.split('\n\n')
for para in paragraphs:
outLines.extend(greedyWrap(para, width) + [''])
return outLines
inWords = inString.split()
column = 0
ptr_line = 0
while inWords:
column = column + len(inWords[ptr_line])
ptr_line = ptr_line + 1
if (column > width):
if ptr_line == 1:
# This single word is too long, it will be the whole line.
pass
else:
# We've gone too far, stop the line one word back.
ptr_line = ptr_line - 1
(l, inWords) = (inWords[0:ptr_line], inWords[ptr_line:])
outLines.append(''.join(l))
ptr_line = 0
column = 0
elif not (len(inWords) > ptr_line):
# Clean up the last bit.
outLines.append(' '.join(inWords))
del inWords[:]
else:
# Space
column = column + 1
# next word
return outLines
"""
taken with minor adjustments from twisted.python.usage.py
"""
def docMakeChunks(optList, width=80):
"""
Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline.
"""
# XXX: sanity check to make sure we have a sane combination of keys.
maxOptLen = 0
for opt in optList:
optLen = len(opt.get('long', ''))
if optLen:
if opt.get('optType', None) == "parameter":
# these take up an extra character
optLen = optLen + 1
maxOptLen = max(optLen, maxOptLen)
colWidth1 = maxOptLen + len(" -s, -- ")
colWidth2 = width - colWidth1
# XXX - impose some sane minimum limit.
# Then if we don't have enough room for the option and the doc
# to share one line, they can take turns on alternating lines.
colFiller1 = " " * colWidth1
optChunks = []
seen = {}
for opt in optList:
if opt.get('short', None) in seen or opt.get('long', None) in seen:
continue
for x in opt.get('short', None), opt.get('long', None):
if x is not None:
seen[x] = 1
optLines = []
comma = " "
if opt.get('short', None):
short = "-%c" % (opt['short'],)
else:
short = ''
if opt.get('long', None):
long = opt['long']
if opt.get("optType", None) == "parameter":
long = long + '='
long = "%-*s" % (maxOptLen, long)
if short:
comma = ","
else:
long = " " * (maxOptLen + len('--'))
if opt.get('optType', None) == 'command':
column1 = ' %s ' % long
else:
column1 = " %2s%c --%s " % (short, comma, long)
if opt.get('doc', ''):
doc = opt['doc'].strip()
else:
doc = ''
if (opt.get("optType", None) == "parameter") \
and not (opt.get('default', None) is None):
doc = "%s [default: %s]" % (doc, opt['default'])
if (opt.get("optType", None) == "parameter") \
and opt.get('dispatch', None) is not None:
d = opt['dispatch']
if isinstance(d, usage.CoerceParameter) and d.doc:
doc = "%s. %s" % (doc, d.doc)
if doc:
column2_l = greedyWrap(doc, colWidth2)
else:
column2_l = ['']
optLines.append("%s%s\n" % (column1, column2_l.pop(0)))
for line in column2_l:
optLines.append("%s%s\n" % (colFiller1, line))
optChunks.append(''.join(optLines))
return optChunks
usage.docMakeChunks = docMakeChunks
def setConfigFile():
def findConfigDir():
......@@ -199,37 +50,13 @@ def setConfigFile():
return os.path.join( findConfigDir(), '.cadre')
class Options(usage.Options):
optFlags = [['daemon','d', 'daemonize'],
['noconfig', None, 'ignore any configfile found'],
['version','v', 'print out version']
]
optParameters = [['configfile', 'c', setConfigFile(), 'configfile'],
['logfile', 'l', None, 'logfile'],
['option', 'o', None, 'activate option (name and value separated by a colon (`:`)'],
]
def __init__(self):
usage.Options.__init__(self)
self['options'] = {}
def opt_version(self):
print "Cadre version:", __version__
sys.exit(0)
def opt_help(self):
sys.argv.remove('--help')
print self.__str__()
sys.exit(0)
def opt_option(self,option):
try:
key, value = option.split(':', 1)
self['options'][key] = value
except:
pass
def __opt_option(option, opt, value, parser):
try:
key, val = value.split(':', 1)
except:
key = value
val = ''
parser.values.options[key] = val
def main(config):
......@@ -237,39 +64,46 @@ def main(config):
c = Cadre(config)
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, errortext:
print '%s: %s' % (sys.argv[0], errortext)
print '%s: Try --help for usage details.' % (sys.argv[0])
sys.exit(0)
if options['daemon'] == 1:
import optparse
parser = optparse.OptionParser('%prog [options]',
version="Cadre version: %s" % __version__)
parser.add_option('-d', '--daemon', action='store_true',
help='daemonize')
parser.add_option('--noconfig', action='store_false', dest='configfile',
help='ignore any configfile found')
parser.add_option('-c', '--configfile', default=setConfigFile(),
help='configfile to use, default: %default')
parser.add_option('-l', '--logfile', help='logfile to use')
parser.add_option('-o', '--option', action='callback',
dest='options',
default={}, callback=__opt_option, type='string',
help='activate option (name and value separated by a colon (`:`)')
options, args = parser.parse_args()
if args:
parser.error('takes no arguments')
if options.daemon:
daemonize()
config = {}
config['logging'] = {}
if options['noconfig'] != 1:
if options.configfile:
try:
config = Config(options['configfile'],root='config').config
config = Config(options.configfile, root='config').config
except IOError:
print "no config file %r found" % options['configfile']
print "Config file %r not found, ignoring" % options.configfile
pass
for k,v in options['options'].items():
config[k] = v
# copy options pass by -o/--option into config
config.update(dict(options.options))
if options['logfile'] != None:
if options.logfile:
config['logging'] = {}
config['logging']['logfile'] = options['logfile']
if options['daemon'] == 1:
if options['logfile'] == None:
config.get('logging').get('level','none')
config['logging']['logfile'] = options.logfile
elif options.daemon:
config.get('logging').get('level','none')
grafics = config.get('grafics')
if grafics is None:
......@@ -298,4 +132,4 @@ if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main, config)
reactor.run()
reactor.run(
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment