root / pykota / trunk / bin / dumpykota @ 1803

Revision 1803, 11.2 kB (checked in by jalet, 20 years ago)

Postponed string interpolation to help message's output method

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