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

Revision 3337, 6.0 kB (checked in by jerome, 16 years ago)

Added some utility methods.
Made generic --logo help not depend anymore on the pkbanner's
command context.

  • 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
68class PyKotaOptionParser(optparse.OptionParser) :
69    """
70    This class to define additional methods, and different help
71    formatting, from the traditional OptionParser.
72    """   
73    def __init__(self, *args, **kwargs) :
74        """
75        Initializes our option parser with additional attributes.
76        """
77        self.examples = []
78        kwargs["version"] = "%s (PyKota) %s" % (os.path.basename(sys.argv[0]),
79                                                version.__version__)
80        optparse.OptionParser.__init__(self, *args, **kwargs)
81        self.disable_interspersed_args()
82        self.remove_version_and_help()
83        self.add_generic_options()
84       
85    def format_help(self, formatter=None) :
86        """
87        Reformats help our way : adding examples and copyright
88        message at the end.
89        """
90        if formatter is None :
91            formatter = self.formatter
92        result = []
93        result.append(optparse.OptionParser.format_help(self, formatter) + "\n")
94        result.append(self.format_examples())
95        result.append(self.format_copyright())
96        return "".join(result)
97           
98    #   
99    # Below are PyKota specific additions   
100    #
101    def format_examples(self, formatter=None) :
102        """Formats examples our way."""
103        if formatter is None :
104            formatter = self.formatter
105        result = []
106        if self.examples :
107            result.append(formatter.format_heading(_("examples")))
108            formatter.indent()
109            for (cmd, explanation) in self.examples :
110                result.append(formatter.format_description(self.expand_prog_name(cmd)))
111                result.append(formatter.format_description(self.expand_prog_name(explanation)) + "\n")
112            formatter.dedent()
113        return "".join(result)   
114       
115    def format_copyright(self, formatter=None) :
116        """Formats copyright message our way."""
117        if formatter is None :
118            formatter = self.formatter
119        result = []   
120        result.append(formatter.format_heading(_("licensing terms")))
121        formatter.indent()
122        result.append(formatter.format_description("(c) %s %s\n" \
123                                                      % (version.__years__, \
124                                                         version.__author__)))
125        for part in version.__gplblurb__.split("\n\n") :
126            result.append(formatter.format_description(part) + "\n")
127        formatter.dedent()   
128        return "".join(result)
129       
130    def add_example(self, command, doc) :   
131        """Adds an usage example."""
132        self.examples.append(("%prog " + command, doc))
133       
134    def remove_version_and_help(self) :   
135        """Removes the default definitions for options version and help."""
136        for o in ("-h", "-help", "--help", "-v", "-version", "--version") :
137            try :
138                self.remove_option(o)
139            except ValueError :     
140                pass
141               
142    def add_generic_options(self) :   
143        """Adds options which are common to all PyKota command line tools."""
144        self.add_option("-h", "--help",
145                              action="help",
146                              help=_("show this help message and exit"))
147        self.add_option("-v", "--version",
148                              action="version",
149                              help=_("show the version number and exit"))
Note: See TracBrowser for help on using the browser.