root / pykota / trunk / bin / dumpykota @ 1779

Revision 1779, 10.3 kB (checked in by jalet, 20 years ago)

Misleading help message. Thx to Johannes Laemmermann.

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