root / pykota / trunk / pykota / commandline.py @ 3341

Revision 3341, 9.3 kB (checked in by jerome, 16 years ago)

pkinvoice now works new style.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# -*- coding: UTF-8 -*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21
22"""This modules defines a command line options parser for PyKota's command line tools."""
23
24import sys
25import os
26import optparse
27from gettext import gettext as _
28
29from pykota import version
30from pykota.utils import loginvalidparam
31
32def checkandset_pagesize(option, opt, value, optionparser) :
33    """Checks and sets the page size."""
34    from pykota.pdfutils import getPageSize
35    if getPageSize(value) is None :
36        loginvalidparam(opt, value, option.default)
37        setattr(optionparser.values, option.dest, option.default)
38    else :   
39        setattr(optionparser.values, option.dest, value)
40   
41def checkandset_savetoner(option, opt, value, optionparser) :   
42    """Checks and sets the save toner value."""
43    if (value < 0.0) or (value > 99.0) :
44        loginvalidparam(opt, value, option.default, \
45                        _("Allowed range is (0..99)"))
46        setattr(optionparser.values, option.dest, option.default)
47    else :   
48        setattr(optionparser.values, option.dest, value)
49       
50def checkandset_positiveint(option, opt, value, optionparser) :   
51    """Checks if an option argument is a positive integer and validates the option if it is the case."""
52    if not (value >= 0) :
53        loginvalidparam(opt, value, option.default, \
54                        _("Value must be positive"))
55        setattr(optionparser.values, option.dest, option.default)
56    else :   
57        setattr(optionparser.values, option.dest, value)
58       
59def checkandset_positivefloat(option, opt, value, optionparser) :   
60    """Checks if an option argument is a positive integer and validates the option if it is the case."""
61    if not (value >= 0.0) :
62        loginvalidparam(opt, value, option.default, \
63                        _("Value must be positive"))
64        setattr(optionparser.values, option.dest, option.default)
65    else :   
66        setattr(optionparser.values, option.dest, value)
67
68def checkandset_percent(option, opt, value, optionparser) :   
69    """Checks if an option argument is comprised between 0.0 included and 100.0 not included, and validates the option if it is the case."""
70    if not (0.0 <= value < 100.0) :
71        loginvalidparam(opt, value, option.default, \
72                        _("Value must be comprised between 0.0 included and 100.0 not included"))
73        setattr(optionparser.values, option.dest, option.default)
74    else :   
75        setattr(optionparser.values, option.dest, value)
76
77class PyKotaOptionParser(optparse.OptionParser) :
78    """
79    This class to define additional methods, and different help
80    formatting, from the traditional OptionParser.
81    """   
82    def __init__(self, *args, **kwargs) :
83        """
84        Initializes our option parser with additional attributes.
85        """
86        self.filterexpressions = []
87        self.examples = []
88        kwargs["version"] = "%s (PyKota) %s" % (os.path.basename(sys.argv[0]),
89                                                version.__version__)
90        optparse.OptionParser.__init__(self, *args, **kwargs)
91        self.disable_interspersed_args()
92        self.remove_version_and_help()
93        self.add_generic_options()
94       
95    def format_help(self, formatter=None) :
96        """
97        Reformats help our way : adding examples and copyright
98        message at the end.
99        """
100        if formatter is None :
101            formatter = self.formatter
102        result = []
103        result.append(optparse.OptionParser.format_help(self, formatter) + "\n")
104        result.append(self.format_filterexpressions())
105        result.append(self.format_examples())
106        result.append(self.format_copyright())
107        return "".join(result)
108           
109    #   
110    # Below are PyKota specific additions   
111    #
112    def format_filterexpressions(self, formatter=None) :
113        """Formats filter expressions our way."""
114        if formatter is None :
115            formatter = self.formatter
116        result = []   
117        if self.filterexpressions :
118            result.append(formatter.format_heading(_("filtering expressions")))
119            formatter.indent()
120            result.append(formatter.format_description(_("Use the filtering expressions to extract only parts of the datas. Allowed filters are of the form 'key=value'. Wildcards are not expanded as part of these filtering expressions, so you can't use them here.")))
121            result.append("\n")
122            result.append(formatter.format_heading(_("allowed keys for now")))
123            formatter.indent() 
124            for (expression, explanation) in self.filterexpressions :
125                result.append(formatter.format_description("%s : %s" % (expression, explanation)))
126            formatter.dedent()   
127            result.append("\n")
128            result.append(formatter.format_heading(_("formatting of dates with the 'start' and 'end' filtering keys")))
129            formatter.indent()
130            result.append(formatter.format_description(_("YYYY : year boundaries")))
131            result.append(formatter.format_description(_("YYYYMM : month boundaries")))
132            result.append(formatter.format_description(_("YYYYMMDD : day boundaries")))
133            result.append(formatter.format_description(_("YYYYMMDDhh : hour boundaries")))
134            result.append(formatter.format_description(_("YYYYMMDDhhmm : minute boundaries")))
135            result.append(formatter.format_description(_("YYYYMMDDhhmmss : second boundaries")))
136            result.append(formatter.format_description(_("yesterday[+-N] : yesterday more or less N days (e.g. : yesterday-15)")))
137            result.append(formatter.format_description(_("today[+-N] : today more or less N days (e.g. : today-15)")))
138            result.append(formatter.format_description(_("tomorrow[+-N] : tomorrow more or less N days (e.g. : tomorrow-15)")))
139            result.append(formatter.format_description(_("now[+-N] : now more or less N days (e.g. now-15)")))
140            formatter.dedent()   
141            result.append("\n")
142            result.append(formatter.format_description(_("'now' and 'today' are not exactly the same since 'today' represents the first or last second of the day depending on if it's used in a 'start=' or 'end=' date expression.")))
143            result.append("\n")
144        return "".join(result)
145       
146    def format_examples(self, formatter=None) :
147        """Formats examples our way."""
148        if formatter is None :
149            formatter = self.formatter
150        result = []
151        if self.examples :
152            result.append(formatter.format_heading(_("examples")))
153            formatter.indent()
154            for (cmd, explanation) in self.examples :
155                result.append(formatter.format_description(self.expand_prog_name(cmd)))
156                result.append(formatter.format_description(self.expand_prog_name(explanation)) + "\n")
157            formatter.dedent()
158        return "".join(result)   
159       
160    def format_copyright(self, formatter=None) :
161        """Formats copyright message our way."""
162        if formatter is None :
163            formatter = self.formatter
164        result = []   
165        result.append(formatter.format_heading(_("licensing terms")))
166        formatter.indent()
167        result.append(formatter.format_description("(c) %s %s\n" \
168                                                      % (version.__years__, \
169                                                         version.__author__)))
170        for part in version.__gplblurb__.split("\n\n") :
171            result.append(formatter.format_description(part) + "\n")
172        formatter.dedent()   
173        return "".join(result)
174       
175    def add_filterexpression(self, expression, doc) :   
176        """Adds a filtering expression."""
177        self.filterexpressions.append((expression, doc))
178       
179    def add_example(self, command, doc) :   
180        """Adds an usage example."""
181        self.examples.append(("%prog " + command, doc))
182       
183    def remove_version_and_help(self) :   
184        """Removes the default definitions for options version and help."""
185        for o in ("-h", "-help", "--help", "-v", "-version", "--version") :
186            try :
187                self.remove_option(o)
188            except ValueError :     
189                pass
190               
191    def add_generic_options(self) :   
192        """Adds options which are common to all PyKota command line tools."""
193        self.add_option("-h", "--help",
194                              action="help",
195                              help=_("show this help message and exit"))
196        self.add_option("-v", "--version",
197                              action="version",
198                              help=_("show the version number and exit"))
Note: See TracBrowser for help on using the browser.