root / pykota / trunk / bin / dumpykota @ 1796

Revision 1796, 11.1 kB (checked in by jalet, 20 years ago)

Renders help translatable

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKota Print Quota Data Dumper
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.13  2004/10/11 12:49:06  jalet
27# Renders help translatable
28#
29# Revision 1.12  2004/10/07 21:14:28  jalet
30# Hopefully final fix for data encoding to and from the database
31#
32# Revision 1.11  2004/10/07 14:35:40  jalet
33# Now edpykota refuses to launch if the user is not a PyKota administrator.
34# dumpykota : now has the same error message than edpykota in this case.
35#
36# Revision 1.10  2004/10/06 10:05:47  jalet
37# Minor changes to allow any PyKota administrator to launch enhanced versions
38# of the commands, and not only the root user.
39#
40# Revision 1.9  2004/10/05 20:08:46  jalet
41# Misleading help message. Thx to Johannes Laemmermann.
42#
43# Revision 1.8  2004/10/05 09:59:19  jalet
44# Restore compatibility with Python 2.1
45#
46# Revision 1.7  2004/10/04 21:25:29  jalet
47# dumpykota can now output datas in the XML format
48#
49# Revision 1.6  2004/09/15 18:28:41  jalet
50# Updated help for dumpykota
51#
52# Revision 1.5  2004/09/15 07:38:05  jalet
53# Fix for uninitialized variable
54#
55# Revision 1.4  2004/09/15 07:26:19  jalet
56# Data dumps are now ordered by entry creation date if applicable.
57# Now dumpykota exits with a message when there's a broken pipe like
58# in dumpykota --data history | head -3
59#
60# Revision 1.3  2004/09/15 06:58:25  jalet
61# User groups membership and printer groups membership can now be dumped too
62#
63# Revision 1.2  2004/09/14 22:29:12  jalet
64# First version of dumpykota. Works fine but only with PostgreSQL backend
65# for now.
66#
67# Revision 1.1  2004/07/01 19:22:37  jalet
68# First draft of dumpykota
69#
70#
71#
72
73import sys
74import os
75import pwd
76
77try :
78    import jaxml
79except ImportError :   
80    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n")
81    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n")
82    hasJAXML = 0
83else :   
84    hasJAXML = 1
85
86from pykota import version
87from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
88from pykota.config import PyKotaConfigError
89from pykota.storage import PyKotaStorageError
90
91__doc__ = N_("""dumpykota v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
92
93Dumps PyKota database's content.
94
95command line usage :
96
97  dumpykota [options]
98
99options :
100
101  -v | --version       Prints dumpykota's version number then exits.
102  -h | --help          Prints this message then exits.
103 
104  -d | --data type     Dumps 'type' datas. Allowed types are :
105                       
106                         - history : dumps the jobs history.
107                         - users : dumps users.
108                         - groups : dumps user groups.
109                         - printers : dump printers.
110                         - upquotas : dump user quotas.
111                         - gpquotas : dump user groups quotas.
112                         - payments : dumps user payments.
113                         - pmembers : dumps printer groups members.
114                         - umembers : dumps user groups members.
115                         
116                       NB : the -d | --data command line option   
117                       is MANDATORY.
118 
119  -f | --format fmt    Dumps datas in the 'fmt' format. When not specified,
120                       the format is to dump datas in the csv format (comma
121                       separated values). All data dumped is between double
122                       quotes. Allowed formats are :
123                       
124                         - csv : separate datas with commas
125                         - ssv : separate datas with semicolons
126                         - tsv : separate datas with tabs
127                         - xml : dump data as XML
128                         
129  -o | --output fname  All datas will be dumped to the file instead of
130                       to the standard output. The special '-' filename
131                       is the default value and means stdout.
132                       WARNING : existing files are truncated !
133 
134Examples :
135
136  $ dumpykota --data history --format csv >myfile.csv
137 
138  This dumps the history in a comma separated values file, for possible
139  use in a spreadsheet.
140 
141  $ dumpykota --data users --format xml -o users.xml
142 
143  Dumps all users datas to the users.xml file.
144 
145This program is free software; you can redistribute it and/or modify
146it under the terms of the GNU General Public License as published by
147the Free Software Foundation; either version 2 of the License, or
148(at your option) any later version.
149
150This program is distributed in the hope that it will be useful,
151but WITHOUT ANY WARRANTY; without even the implied warranty of
152MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
153GNU General Public License for more details.
154
155You should have received a copy of the GNU General Public License
156along with this program; if not, write to the Free Software
157Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
158
159Please e-mail bugs to: %s""") % (version.__version__, version.__author__)
160       
161class DumPyKota(PyKotaTool) :       
162    """A class for dumpykota."""
163    def main(self, arguments, options) :
164        """Print Quota Data Dumper."""
165        if not self.config.isAdmin :
166            raise PyKotaToolError, _("You're not allowed to use this command.")
167           
168        datatype = options["data"]
169        if datatype not in [ "history",
170                             "users",
171                             "groups",
172                             "printers",
173                             "upquotas",
174                             "gpquotas",
175                             "payments",
176                             "pmembers",
177                             "umembers",
178                           ] :
179            raise PyKotaToolError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype
180                   
181        format = options["format"]
182        if format not in [ "csv",
183                           "ssv",
184                           "tsv",
185                           "xml",
186                         ] :
187            raise PyKotaToolError, _("Invalid modifier [%s] for --format command line option, see help.") % datatype
188           
189        if (format == "xml") and not hasJAXML :
190            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
191           
192        entries = getattr(self.storage, "extract%s" % datatype.title())()   
193        if entries :
194            mustclose = 0   
195            if options["output"].strip() == "-" :   
196                self.outfile = sys.stdout
197            else :   
198                self.outfile = open(options["output"], "w")
199                mustclose = 1
200               
201            retcode = getattr(self, "dump%s" % format.title())(entries, datatype)
202           
203            if mustclose :
204                self.outfile.close()
205               
206            return retcode   
207        return 0
208       
209    def dumpWithSeparator(self, separator, entries) :   
210        """Dumps datas with a separator."""
211        for entry in entries :
212            line = separator.join([ '"%s"' % field for field in entry ])
213            try :
214                self.outfile.write("%s\n" % line)
215            except IOError, msg :   
216                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
217                return -1
218        return 0       
219       
220    def dumpCsv(self, entries, dummy) :   
221        """Dumps datas with a comma as the separator."""
222        return self.dumpWithSeparator(",", entries)
223                           
224    def dumpSsv(self, entries, dummy) :   
225        """Dumps datas with a comma as the separator."""
226        return self.dumpWithSeparator(";", entries)
227                           
228    def dumpTsv(self, entries, dummy) :   
229        """Dumps datas with a comma as the separator."""
230        return self.dumpWithSeparator("\t", entries)
231       
232    def dumpXml(self, entries, datatype) :   
233        """Dumps datas as XML."""
234        x = jaxml.XML_document(encoding="UTF-8")
235        x.pykota(version=version.__version__)
236        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
237        headers = entries[0]
238        for entry in entries[1:] :
239            x._push()
240            x.entry()
241            for i in range(len(entry)) :
242                value = str(entry[i])
243                try :
244                    value = unicode(value, self.getCharset()).encode("UTF-8")
245                except UnicodeError :   
246                    pass
247                x.attribute(value, type=type(value).__name__, name=headers[i])
248            x._pop()   
249        x._output(self.outfile)
250                           
251if __name__ == "__main__" : 
252    retcode = 0
253    try :
254        defaults = { \
255                     "format" : "csv", \
256                     "output" : "-", \
257                   }
258        short_options = "vhd:f:o:"
259        long_options = ["help", "version", "data=", "format=", "output="]
260       
261        # Initializes the command line tool
262        dumper = DumPyKota(doc=__doc__)
263       
264        # parse and checks the command line
265        (options, args) = dumper.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
266       
267        # sets long options
268        options["help"] = options["h"] or options["help"]
269        options["version"] = options["v"] or options["version"]
270        options["data"] = options["d"] or options["data"]
271        options["format"] = options["f"] or options["format"] or defaults["format"]
272        options["output"] = options["o"] or options["output"] or defaults["output"]
273       
274        if options["help"] :
275            dumper.display_usage_and_quit()
276        elif options["version"] :
277            dumper.display_version_and_quit()
278        elif options["data"] is None :   
279            raise PyKotaToolError, _("The -d | --data command line option is mandatory, see help.")
280        else :
281            if args :
282                raise PyKotaToolError, _("Too many arguments, see help.")
283            retcode = dumper.main(args, options)
284    except SystemExit :       
285        pass
286    except :
287        try :
288            dumper.crashed("dumpykota failed")
289        except :   
290            crashed("dumpykota failed")
291        retcode = -1
292
293    try :
294        dumper.storage.close()
295    except (TypeError, NameError, AttributeError) :   
296        pass
297       
298    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.