moved common funcs

version number



git-svn-id: https://callirhoe.googlecode.com/svn/branches/phantome@183 81c8bb96-aa45-f2e2-0eef-c4fa4a15c6df
This commit is contained in:
geortz@gmail.com 2014-10-31 17:39:36 +00:00
parent b0deb9523f
commit 9be9c2e185
3 changed files with 130 additions and 127 deletions

View File

@ -44,21 +44,13 @@
# CANNOT UPGRADE TO argparse !!! -- how to handle [[month] year] form?
_version = "0.4.0"
_copyright = """Copyright (C) 2012-2014 George M. Tzoumas
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."""
import calendar
import sys
import time
import optparse
import lib.xcairo as xcairo
import lib.holiday as holiday
class Abort(Exception):
pass
import lib
from lib.plugin import *
# TODO: SEE IF IT CAN BE MOVED INTO lib.plugin ...
@ -140,103 +132,6 @@ def add_list_option(parser, opt):
parser.add_option("--list-%s" % opt, action="store_true", dest="list_%s" % opt, default=False,
help="list available %s" % opt)
def atoi(s, lower_bound=None, upper_bound=None, prefix=''):
"""convert string to integer, exiting on error (for cmdline parsing)
@param lower_bound: perform additional check so that value >= I{lower_bound}
@param upper_bound: perform additional check so that value <= I{upper_bound}
@param prefix: output prefix for error reporting
@rtype: int
"""
try:
k = int(s);
if lower_bound is not None:
if k < lower_bound:
raise Abort(prefix + "value '" + s +"' out of range: should not be less than %d" % lower_bound)
if upper_bound is not None:
if k > upper_bound:
raise Abort(prefix + "value '" + s +"' out of range: should not be greater than %d" % upper_bound)
except ValueError as e:
raise Abort(prefix + "invalid integer value '" + s +"'")
return k
def _parse_month(mstr):
"""get a month value (0-12) from I{mstr}, exiting on error (for cmdline parsing)
@rtype: int
"""
m = atoi(mstr,lower_bound=0,upper_bound=12,prefix='month: ')
if m == 0: m = time.localtime()[1]
return m
def parse_month_range(s):
"""return (Month,Span) by parsing range I{Month}, I{Month1}-I{Month2} or I{Month}:I{Span}
@rtype: (int,int)
"""
if ':' in s:
t = s.split(':')
if len(t) != 2: raise Abort("invalid month range '" + s + "'")
Month = _parse_month(t[0])
MonthSpan = atoi(t[1],lower_bound=0,prefix='month span: ')
elif '-' in s:
t = s.split('-')
if len(t) != 2: raise Abort("invalid month range '" + s + "'")
Month = _parse_month(t[0])
MonthSpan = atoi(t[1],lower_bound=Month+1,prefix='month range: ') - Month + 1
else:
Month = _parse_month(s)
MonthSpan = 1
return (Month,MonthSpan)
def parse_year(ystr):
"""get a year value (>=0) from I{ystr}, exiting on error (for cmdline parsing)
@rtype: int
"""
y = atoi(ystr,lower_bound=0,prefix='year: ')
if y == 0: y = time.localtime()[0]
return y
def extract_parser_args(arglist, parser, pos = -1):
"""extract options belonging to I{parser} along with I{pos} positional arguments
@param arglist: argument list to extract
@param parser: parser object to be used for extracting
@param pos: number of positional options to be extracted
if I{pos}<0 then all positional arguments are extracted, otherwise,
only I{pos} arguments are extracted. arglist[0] (usually sys.argv[0]) is also positional
argument!
@rtype: ([str,...],[str,...])
@return: tuple (argv1,argv2) with extracted argument list and remaining argument list
"""
argv = [[],[]]
posc = 0
push_value = None
for x in arglist:
if push_value:
push_value.append(x)
push_value = None
continue
# get option name (long options stop at '=')
y = x[0:x.find('=')] if '=' in x else x
if x[0] == '-':
if parser.has_option(y):
argv[0].append(x)
if not x.startswith('--') and parser.get_option(y).takes_value():
push_value = argv[0]
else:
argv[1].append(x)
else:
if pos < 0:
argv[0].append(x)
else:
argv[posc >= pos].append(x)
posc += 1
return tuple(argv)
def get_parser():
"""get the argument parser object
@ -247,7 +142,7 @@ def get_parser():
"By default, a calendar of the current year in pdf format is written to FILE. "
"Alternatively, you can select a specific YEAR (0=current), "
"and a month range from MONTH (0-12, 0=current) to MONTH2 or for SPAN months.",
version="callirhoe " + _version + '\n' + _copyright)
version="callirhoe " + lib._version + '\n' + lib._copyright)
parser.add_option("-l", "--lang", dest="lang", default="EN",
help="choose language [%default]")
parser.add_option("-t", "--layout", dest="layout", default="classic",
@ -293,7 +188,7 @@ def get_parser():
def main_program():
parser = get_parser()
sys.argv,argv2 = extract_parser_args(sys.argv,parser)
sys.argv,argv2 = lib.extract_parser_args(sys.argv,parser)
(options,args) = parser.parse_args()
list_and_exit = False
@ -364,16 +259,16 @@ def main_program():
Month, MonthSpan = 1, 12
Outfile = args[0]
elif len(args) == 2:
Year = parse_year(args[0])
Year = lib.parse_year(args[0])
Month, MonthSpan = 1, 12
Outfile = args[1]
elif len(args) == 3:
Month, MonthSpan = parse_month_range(args[0])
Year = parse_year(args[1])
Month, MonthSpan = lib.parse_month_range(args[0])
Year = lib.parse_year(args[1])
Outfile = args[2]
if MonthSpan == 0:
raise Abort("callirhoe: empty calendar requested, aborting")
raise lib.Abort("callirhoe: empty calendar requested, aborting")
Geometry.landscape = options.landscape
xcairo.XDPI = options.dpi
@ -399,11 +294,11 @@ def main_program():
Language.month_name = Language.long_month_name
renderer = Layout.CalendarRenderer(Outfile, Year, Month, MonthSpan,
(Style,Geometry,Language), hprovider, _version, loptions)
(Style,Geometry,Language), hprovider, lib._version, loptions)
renderer.render()
if __name__ == "__main__":
try:
main_program()
except Abort as e:
except lib.Abort as e:
sys.exit(e.args[0])

View File

@ -34,7 +34,7 @@ import optparse
import Queue
import threading
from callirhoe import extract_parser_args, parse_month_range, parse_year, atoi, Abort, _version, _copyright
import lib
from lib.geom import rect_rel_scale
# MAYBE-TODO
@ -198,7 +198,7 @@ def get_parser():
If IMAGE is a single file, then a calendar of the current month is overlayed. If IMAGE contains wildcards,
then every month is generated according to the --range option, advancing one month for every photo file.
Photos will be reused in a round-robin fashion if more calendar
months are requested.""", version="callirhoe.CalMagick " + _version + '\n' + _copyright)
months are requested.""", version="callirhoe.CalMagick " + lib._version + '\n' + lib._copyright)
parser.add_option("--outdir", default=".",
help="set directory for the output image(s); directory will be created if it does not already exist [%default]")
parser.add_option("--outfile", default=None,
@ -300,11 +300,11 @@ def check_parsed_options(options):
if options.min_size is None:
options.min_size = 0.333 if options.placement in ['min','max','random'] else 0.05
if options.sample is not None and not options.range:
raise Abort("calmagick: --sample requested without --range")
raise lib.Abort("calmagick: --sample requested without --range")
if options.outfile is not None and options.range:
raise Abort("calmagick: you cannot specify both --outfile and --range options")
raise lib.Abort("calmagick: you cannot specify both --outfile and --range options")
if options.sample is not None and options.shuffle:
raise Abort("calmagick: you cannot specify both --shuffle and --sample options")
raise lib.Abort("calmagick: you cannot specify both --shuffle and --sample options")
if options.shuffle:
options.sample = 0
if options.sample is None:
@ -370,7 +370,7 @@ def get_outfile(infile, outdir, base_prefix, format, hint=None):
if format: ext = '.' + format
outfile = os.path.join(outdir,base_prefix+base+ext)
if os.path.exists(outfile) and os.path.samefile(infile, outfile):
if hint: raise Abort("calmagick: --outfile same as input, aborting")
if hint: raise lib.Abort("calmagick: --outfile same as input, aborting")
outfile = os.path.join(outdir,base_prefix+base+'_calmagick'+ext)
return outfile
@ -523,7 +523,7 @@ def compose_calendar(img, outimg, options, callirhoe_args, magick_args, stats=No
if '/' in options.ratio:
tmp = options.ratio.split('/')
calratio = float(atoi(tmp[0],1))/atoi(tmp[1],1)
calratio = float(lib.atoi(tmp[0],1))/lib.atoi(tmp[1],1)
else:
calratio = float(options.ratio)
if options.placement == 'min' or options.placement == 'max':
@ -596,9 +596,9 @@ def parse_range(s,hint=None):
"""
if '/' in s:
t = s.split('/')
month,span = parse_month_range(t[0])
month,span = lib.parse_month_range(t[0])
if hint and span == 0: span = hint
year = parse_year(t[1])
year = lib.parse_year(t[1])
margs = []
for m in xrange(span):
margs += [(month,year)]
@ -606,7 +606,7 @@ def parse_range(s,hint=None):
if month > 12: month = 1; year += 1
return margs
else:
raise Abort("calmagick: invalid range format '%s'" % options.range)
raise lib.Abort("calmagick: invalid range format '%s'" % options.range)
def range_worker(q,ev,i):
"""worker thread for a (I{Month,Year}) tuple
@ -638,7 +638,7 @@ def main_program():
parser = get_parser()
magick_args = parse_magick_args()
sys.argv,argv2 = extract_parser_args(sys.argv,parser,2)
sys.argv,argv2 = lib.extract_parser_args(sys.argv,parser,2)
(options,args) = parser.parse_args()
check_parsed_options(options)
@ -682,12 +682,12 @@ def main_program():
else:
img = args[0]
if not os.path.isfile(img):
raise Abort("calmagick: input image '%s' does not exist" % img)
raise lib.Abort("calmagick: input image '%s' does not exist" % img)
outimg = get_outfile(img,options.outdir,'',options.format,options.outfile)
compose_calendar(img, outimg, options, argv2, magick_args)
if __name__ == '__main__':
try:
main_program()
except Abort as e:
except lib.Abort as e:
sys.exit(e.args[0])

View File

@ -0,0 +1,108 @@
import time
_version = "0.4.1"
_copyright = """Copyright (C) 2012-2014 George M. Tzoumas
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."""
class Abort(Exception):
pass
def extract_parser_args(arglist, parser, pos = -1):
"""extract options belonging to I{parser} along with I{pos} positional arguments
@param arglist: argument list to extract
@param parser: parser object to be used for extracting
@param pos: number of positional options to be extracted
if I{pos}<0 then all positional arguments are extracted, otherwise,
only I{pos} arguments are extracted. arglist[0] (usually sys.argv[0]) is also positional
argument!
@rtype: ([str,...],[str,...])
@return: tuple (argv1,argv2) with extracted argument list and remaining argument list
"""
argv = [[],[]]
posc = 0
push_value = None
for x in arglist:
if push_value:
push_value.append(x)
push_value = None
continue
# get option name (long options stop at '=')
y = x[0:x.find('=')] if '=' in x else x
if x[0] == '-':
if parser.has_option(y):
argv[0].append(x)
if not x.startswith('--') and parser.get_option(y).takes_value():
push_value = argv[0]
else:
argv[1].append(x)
else:
if pos < 0:
argv[0].append(x)
else:
argv[posc >= pos].append(x)
posc += 1
return tuple(argv)
def atoi(s, lower_bound=None, upper_bound=None, prefix=''):
"""convert string to integer, exiting on error (for cmdline parsing)
@param lower_bound: perform additional check so that value >= I{lower_bound}
@param upper_bound: perform additional check so that value <= I{upper_bound}
@param prefix: output prefix for error reporting
@rtype: int
"""
try:
k = int(s);
if lower_bound is not None:
if k < lower_bound:
raise Abort(prefix + "value '" + s +"' out of range: should not be less than %d" % lower_bound)
if upper_bound is not None:
if k > upper_bound:
raise Abort(prefix + "value '" + s +"' out of range: should not be greater than %d" % upper_bound)
except ValueError as e:
raise Abort(prefix + "invalid integer value '" + s +"'")
return k
def _parse_month(mstr):
"""get a month value (0-12) from I{mstr}, exiting on error (for cmdline parsing)
@rtype: int
"""
m = atoi(mstr,lower_bound=0,upper_bound=12,prefix='month: ')
if m == 0: m = time.localtime()[1]
return m
def parse_month_range(s):
"""return (Month,Span) by parsing range I{Month}, I{Month1}-I{Month2} or I{Month}:I{Span}
@rtype: (int,int)
"""
if ':' in s:
t = s.split(':')
if len(t) != 2: raise Abort("invalid month range '" + s + "'")
Month = _parse_month(t[0])
MonthSpan = atoi(t[1],lower_bound=0,prefix='month span: ')
elif '-' in s:
t = s.split('-')
if len(t) != 2: raise Abort("invalid month range '" + s + "'")
Month = _parse_month(t[0])
MonthSpan = atoi(t[1],lower_bound=Month+1,prefix='month range: ') - Month + 1
else:
Month = _parse_month(s)
MonthSpan = 1
return (Month,MonthSpan)
def parse_year(ystr):
"""get a year value (>=0) from I{ystr}, exiting on error (for cmdline parsing)
@rtype: int
"""
y = atoi(ystr,lower_bound=0,prefix='year: ')
if y == 0: y = time.localtime()[0]
return y