Code

fixed rego email bugs (sf bug 699809)
[roundup.git] / roundup / admin.py
1 #! /usr/bin/env python
2 #
3 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
4 # This module is free software, and you may redistribute it and/or modify
5 # under the same terms as Python, so long as this copyright message and
6 # disclaimer are retained in their original form.
7 #
8 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
9 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
10 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
11 # POSSIBILITY OF SUCH DAMAGE.
12 #
13 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
14 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
15 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
16 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
17 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
18
19 # $Id: admin.py,v 1.43 2003-03-16 22:24:54 kedder Exp $
21 '''Administration commands for maintaining Roundup trackers.
22 '''
24 import sys, os, getpass, getopt, re, UserDict, shlex, shutil
25 try:
26     import csv
27 except ImportError:
28     csv = None
29 from roundup import date, hyperdb, roundupdb, init, password, token
30 from roundup import __version__ as roundup_version
31 import roundup.instance
32 from roundup.i18n import _
34 class CommandDict(UserDict.UserDict):
35     '''Simple dictionary that lets us do lookups using partial keys.
37     Original code submitted by Engelbert Gruber.
38     '''
39     _marker = []
40     def get(self, key, default=_marker):
41         if self.data.has_key(key):
42             return [(key, self.data[key])]
43         keylist = self.data.keys()
44         keylist.sort()
45         l = []
46         for ki in keylist:
47             if ki.startswith(key):
48                 l.append((ki, self.data[ki]))
49         if not l and default is self._marker:
50             raise KeyError, key
51         return l
53 class UsageError(ValueError):
54     pass
56 class AdminTool:
57     ''' A collection of methods used in maintaining Roundup trackers.
59         Typically these methods are accessed through the roundup-admin
60         script. The main() method provided on this class gives the main
61         loop for the roundup-admin script.
63         Actions are defined by do_*() methods, with help for the action
64         given in the method docstring.
66         Additional help may be supplied by help_*() methods.
67     '''
68     def __init__(self):
69         self.commands = CommandDict()
70         for k in AdminTool.__dict__.keys():
71             if k[:3] == 'do_':
72                 self.commands[k[3:]] = getattr(self, k)
73         self.help = {}
74         for k in AdminTool.__dict__.keys():
75             if k[:5] == 'help_':
76                 self.help[k[5:]] = getattr(self, k)
77         self.tracker_home = ''
78         self.db = None
80     def get_class(self, classname):
81         '''Get the class - raise an exception if it doesn't exist.
82         '''
83         try:
84             return self.db.getclass(classname)
85         except KeyError:
86             raise UsageError, _('no such class "%(classname)s"')%locals()
88     def props_from_args(self, args):
89         ''' Produce a dictionary of prop: value from the args list.
91             The args list is specified as ``prop=value prop=value ...``.
92         '''
93         props = {}
94         for arg in args:
95             if arg.find('=') == -1:
96                 raise UsageError, _('argument "%(arg)s" not propname=value'
97                     )%locals()
98             try:
99                 key, value = arg.split('=')
100             except ValueError:
101                 raise UsageError, _('argument "%(arg)s" not propname=value'
102                     )%locals()
103             if value:
104                 props[key] = value
105             else:
106                 props[key] = None
107         return props
109     def usage(self, message=''):
110         ''' Display a simple usage message.
111         '''
112         if message:
113             message = _('Problem: %(message)s)\n\n')%locals()
114         print _('''%(message)sUsage: roundup-admin [options] <command> <arguments>
116 Options:
117  -i instance home  -- specify the issue tracker "home directory" to administer
118  -u                -- the user[:password] to use for commands
119  -c                -- when outputting lists of data, just comma-separate them
121 Help:
122  roundup-admin -h
123  roundup-admin help                       -- this help
124  roundup-admin help <command>             -- command-specific help
125  roundup-admin help all                   -- all available help
126 ''')%locals()
127         self.help_commands()
129     def help_commands(self):
130         ''' List the commands available with their precis help.
131         '''
132         print _('Commands:'),
133         commands = ['']
134         for command in self.commands.values():
135             h = command.__doc__.split('\n')[0]
136             commands.append(' '+h[7:])
137         commands.sort()
138         commands.append(_('Commands may be abbreviated as long as the abbreviation matches only one'))
139         commands.append(_('command, e.g. l == li == lis == list.'))
140         print '\n'.join(commands)
141         print
143     def help_commands_html(self, indent_re=re.compile(r'^(\s+)\S+')):
144         ''' Produce an HTML command list.
145         '''
146         commands = self.commands.values()
147         def sortfun(a, b):
148             return cmp(a.__name__, b.__name__)
149         commands.sort(sortfun)
150         for command in commands:
151             h = command.__doc__.split('\n')
152             name = command.__name__[3:]
153             usage = h[0]
154             print _('''
155 <tr><td valign=top><strong>%(name)s</strong></td>
156     <td><tt>%(usage)s</tt><p>
157 <pre>''')%locals()
158             indent = indent_re.match(h[3])
159             if indent: indent = len(indent.group(1))
160             for line in h[3:]:
161                 if indent:
162                     print line[indent:]
163                 else:
164                     print line
165             print _('</pre></td></tr>\n')
167     def help_all(self):
168         print _('''
169 All commands (except help) require a tracker specifier. This is just the path
170 to the roundup tracker you're working with. A roundup tracker is where 
171 roundup keeps the database and configuration file that defines an issue
172 tracker. It may be thought of as the issue tracker's "home directory". It may
173 be specified in the environment variable TRACKER_HOME or on the command
174 line as "-i tracker".
176 A designator is a classname and a nodeid concatenated, eg. bug1, user10, ...
178 Property values are represented as strings in command arguments and in the
179 printed results:
180  . Strings are, well, strings.
181  . Date values are printed in the full date format in the local time zone, and
182    accepted in the full format or any of the partial formats explained below.
183  . Link values are printed as node designators. When given as an argument,
184    node designators and key strings are both accepted.
185  . Multilink values are printed as lists of node designators joined by commas.
186    When given as an argument, node designators and key strings are both
187    accepted; an empty string, a single node, or a list of nodes joined by
188    commas is accepted.
190 When property values must contain spaces, just surround the value with
191 quotes, either ' or ". A single space may also be backslash-quoted. If a
192 valuu must contain a quote character, it must be backslash-quoted or inside
193 quotes. Examples:
194            hello world      (2 tokens: hello, world)
195            "hello world"    (1 token: hello world)
196            "Roch'e" Compaan (2 tokens: Roch'e Compaan)
197            Roch\'e Compaan  (2 tokens: Roch'e Compaan)
198            address="1 2 3"  (1 token: address=1 2 3)
199            \\               (1 token: \)
200            \n\r\t           (1 token: a newline, carriage-return and tab)
202 When multiple nodes are specified to the roundup get or roundup set
203 commands, the specified properties are retrieved or set on all the listed
204 nodes. 
206 When multiple results are returned by the roundup get or roundup find
207 commands, they are printed one per line (default) or joined by commas (with
208 the -c) option. 
210 Where the command changes data, a login name/password is required. The
211 login may be specified as either "name" or "name:password".
212  . ROUNDUP_LOGIN environment variable
213  . the -u command-line option
214 If either the name or password is not supplied, they are obtained from the
215 command-line. 
217 Date format examples:
218   "2000-04-17.03:45" means <Date 2000-04-17.08:45:00>
219   "2000-04-17" means <Date 2000-04-17.00:00:00>
220   "01-25" means <Date yyyy-01-25.00:00:00>
221   "08-13.22:13" means <Date yyyy-08-14.03:13:00>
222   "11-07.09:32:43" means <Date yyyy-11-07.14:32:43>
223   "14:25" means <Date yyyy-mm-dd.19:25:00>
224   "8:47:11" means <Date yyyy-mm-dd.13:47:11>
225   "." means "right now"
227 Command help:
228 ''')
229         for name, command in self.commands.items():
230             print _('%s:')%name
231             print _('   '), command.__doc__
233     def do_help(self, args, nl_re=re.compile('[\r\n]'),
234             indent_re=re.compile(r'^(\s+)\S+')):
235         '''Usage: help topic
236         Give help about topic.
238         commands  -- list commands
239         <command> -- help specific to a command
240         initopts  -- init command options
241         all       -- all available help
242         '''
243         if len(args)>0:
244             topic = args[0]
245         else:
246             topic = 'help'
247  
249         # try help_ methods
250         if self.help.has_key(topic):
251             self.help[topic]()
252             return 0
254         # try command docstrings
255         try:
256             l = self.commands.get(topic)
257         except KeyError:
258             print _('Sorry, no help for "%(topic)s"')%locals()
259             return 1
261         # display the help for each match, removing the docsring indent
262         for name, help in l:
263             lines = nl_re.split(help.__doc__)
264             print lines[0]
265             indent = indent_re.match(lines[1])
266             if indent: indent = len(indent.group(1))
267             for line in lines[1:]:
268                 if indent:
269                     print line[indent:]
270                 else:
271                     print line
272         return 0
274     def help_initopts(self):
275         import roundup.templates
276         templates = roundup.templates.listTemplates()
277         print _('Templates:'), ', '.join(templates)
278         import roundup.backends
279         backends = roundup.backends.__all__
280         print _('Back ends:'), ', '.join(backends)
282     def do_install(self, tracker_home, args):
283         '''Usage: install [template [backend [admin password]]]
284         Install a new Roundup tracker.
286         The command will prompt for the tracker home directory (if not supplied
287         through TRACKER_HOME or the -i option). The template, backend and admin
288         password may be specified on the command-line as arguments, in that
289         order.
291         The initialise command must be called after this command in order
292         to initialise the tracker's database. You may edit the tracker's
293         initial database contents before running that command by editing
294         the tracker's dbinit.py module init() function.
296         See also initopts help.
297         '''
298         if len(args) < 1:
299             raise UsageError, _('Not enough arguments supplied')
301         # make sure the tracker home can be created
302         parent = os.path.split(tracker_home)[0]
303         if not os.path.exists(parent):
304             raise UsageError, _('Instance home parent directory "%(parent)s"'
305                 ' does not exist')%locals()
307         # select template
308         import roundup.templates
309         templates = roundup.templates.listTemplates()
310         template = len(args) > 1 and args[1] or ''
311         if template not in templates:
312             print _('Templates:'), ', '.join(templates)
313         while template not in templates:
314             template = raw_input(_('Select template [classic]: ')).strip()
315             if not template:
316                 template = 'classic'
318         # select hyperdb backend
319         import roundup.backends
320         backends = roundup.backends.__all__
321         backend = len(args) > 2 and args[2] or ''
322         if backend not in backends:
323             print _('Back ends:'), ', '.join(backends)
324         while backend not in backends:
325             backend = raw_input(_('Select backend [anydbm]: ')).strip()
326             if not backend:
327                 backend = 'anydbm'
328         # XXX perform a unit test based on the user's selections
330         # install!
331         init.install(tracker_home, template)
332         init.write_select_db(tracker_home, backend)
334         print _('''
335  You should now edit the tracker configuration file:
336    %(config_file)s
337  ... at a minimum, you must set MAILHOST, TRACKER_WEB, MAIL_DOMAIN and
338  ADMIN_EMAIL.
340  If you wish to modify the default schema, you should also edit the database
341  initialisation file:
342    %(database_config_file)s
343  ... see the documentation on customizing for more information.
344 ''')%{
345     'config_file': os.path.join(tracker_home, 'config.py'),
346     'database_config_file': os.path.join(tracker_home, 'dbinit.py')
348         return 0
351     def do_initialise(self, tracker_home, args):
352         '''Usage: initialise [adminpw]
353         Initialise a new Roundup tracker.
355         The administrator details will be set at this step.
357         Execute the tracker's initialisation function dbinit.init()
358         '''
359         # password
360         if len(args) > 1:
361             adminpw = args[1]
362         else:
363             adminpw = ''
364             confirm = 'x'
365             while adminpw != confirm:
366                 adminpw = getpass.getpass(_('Admin Password: '))
367                 confirm = getpass.getpass(_('       Confirm: '))
369         # make sure the tracker home is installed
370         if not os.path.exists(tracker_home):
371             raise UsageError, _('Instance home does not exist')%locals()
372         try:
373             tracker = roundup.instance.open(tracker_home)
374         except roundup.instance.TrackerError:
375             raise UsageError, _('Instance has not been installed')%locals()
377         # is there already a database?
378         try:
379             db_exists = tracker.select_db.Database.exists(tracker.config)
380         except AttributeError:
381             # TODO: move this code to exists() static method in every backend
382             db_exists = os.path.exists(os.path.join(tracker_home, 'db'))
383         if db_exists:
384             print _('WARNING: The database is already initialised!')
385             print _('If you re-initialise it, you will lose all the data!')
386             ok = raw_input(_('Erase it? Y/[N]: ')).strip()
387             if ok.lower() != 'y':
388                 return 0
390             # Get a database backend in use by tracker
391             try:
392                 # nuke it
393                 tracker.select_db.Database.nuke(tracker.config)
394             except AttributeError:
395                 # TODO: move this code to nuke() static method in every backend
396                 shutil.rmtree(os.path.join(tracker_home, 'db'))
398         # GO
399         init.initialise(tracker_home, adminpw)
401         return 0
404     def do_get(self, args):
405         '''Usage: get property designator[,designator]*
406         Get the given property of one or more designator(s).
408         Retrieves the property value of the nodes specified by the designators.
409         '''
410         if len(args) < 2:
411             raise UsageError, _('Not enough arguments supplied')
412         propname = args[0]
413         designators = args[1].split(',')
414         l = []
415         for designator in designators:
416             # decode the node designator
417             try:
418                 classname, nodeid = hyperdb.splitDesignator(designator)
419             except hyperdb.DesignatorError, message:
420                 raise UsageError, message
422             # get the class
423             cl = self.get_class(classname)
424             try:
425                 if self.comma_sep:
426                     l.append(cl.get(nodeid, propname))
427                 else:
428                     print cl.get(nodeid, propname)
429             except IndexError:
430                 raise UsageError, _('no such %(classname)s node "%(nodeid)s"')%locals()
431             except KeyError:
432                 raise UsageError, _('no such %(classname)s property '
433                     '"%(propname)s"')%locals()
434         if self.comma_sep:
435             print ','.join(l)
436         return 0
439     def do_set(self, args, pwre = re.compile(r'{(\w+)}(.+)')):
440         '''Usage: set [items] property=value property=value ...
441         Set the given properties of one or more items(s).
443         The items may be specified as a class or as a comma-separeted
444         list of item designators (ie "designator[,designator,...]").
446         This command sets the properties to the values for all designators
447         given. If the value is missing (ie. "property=") then the property is
448         un-set. If the property is a multilink, you specify the linked ids
449         for the multilink as comma-separated numbers (ie "1,2,3").
450         '''
451         if len(args) < 2:
452             raise UsageError, _('Not enough arguments supplied')
453         from roundup import hyperdb
455         designators = args[0].split(',')
456         if len(designators) == 1:
457             designator = designators[0]
458             try:
459                 designator = hyperdb.splitDesignator(designator)
460                 designators = [designator]
461             except hyperdb.DesignatorError:
462                 cl = self.get_class(designator)
463                 designators = [(designator, x) for x in cl.list()]
464         else:
465             try:
466                 designators = [hyperdb.splitDesignator(x) for x in designators]
467             except hyperdb.DesignatorError, message:
468                 raise UsageError, message
470         # get the props from the args
471         props = self.props_from_args(args[1:])
473         # now do the set for all the nodes
474         for classname, itemid in designators:
475             cl = self.get_class(classname)
477             properties = cl.getprops()
478             for key, value in props.items():
479                 proptype =  properties[key]
480                 if isinstance(proptype, hyperdb.Multilink):
481                     if value is None:
482                         props[key] = []
483                     else:
484                         props[key] = value.split(',')
485                 elif value is None:
486                     continue
487                 elif isinstance(proptype, hyperdb.String):
488                     continue
489                 elif isinstance(proptype, hyperdb.Password):
490                     m = pwre.match(value)
491                     if m:
492                         # password is being given to us encrypted
493                         p = password.Password()
494                         p.scheme = m.group(1)
495                         p.password = m.group(2)
496                         props[key] = p
497                     else:
498                         props[key] = password.Password(value)
499                 elif isinstance(proptype, hyperdb.Date):
500                     try:
501                         props[key] = date.Date(value)
502                     except ValueError, message:
503                         raise UsageError, '"%s": %s'%(value, message)
504                 elif isinstance(proptype, hyperdb.Interval):
505                     try:
506                         props[key] = date.Interval(value)
507                     except ValueError, message:
508                         raise UsageError, '"%s": %s'%(value, message)
509                 elif isinstance(proptype, hyperdb.Link):
510                     props[key] = value
511                 elif isinstance(proptype, hyperdb.Boolean):
512                     props[key] = value.lower() in ('yes', 'true', 'on', '1')
513                 elif isinstance(proptype, hyperdb.Number):
514                     props[key] = float(value)
516             # try the set
517             try:
518                 apply(cl.set, (itemid, ), props)
519             except (TypeError, IndexError, ValueError), message:
520                 import traceback; traceback.print_exc()
521                 raise UsageError, message
522         return 0
524     def do_find(self, args):
525         '''Usage: find classname propname=value ...
526         Find the nodes of the given class with a given link property value.
528         Find the nodes of the given class with a given link property value. The
529         value may be either the nodeid of the linked node, or its key value.
530         '''
531         if len(args) < 1:
532             raise UsageError, _('Not enough arguments supplied')
533         classname = args[0]
534         # get the class
535         cl = self.get_class(classname)
537         # handle the propname=value argument
538         props = self.props_from_args(args[1:])
540         # if the value isn't a number, look up the linked class to get the
541         # number
542         for propname, value in props.items():
543             num_re = re.compile('^\d+$')
544             if not num_re.match(value):
545                 # get the property
546                 try:
547                     property = cl.properties[propname]
548                 except KeyError:
549                     raise UsageError, _('%(classname)s has no property '
550                         '"%(propname)s"')%locals()
552                 # make sure it's a link
553                 if (not isinstance(property, hyperdb.Link) and not
554                         isinstance(property, hyperdb.Multilink)):
555                     raise UsageError, _('You may only "find" link properties')
557                 # get the linked-to class and look up the key property
558                 link_class = self.db.getclass(property.classname)
559                 try:
560                     props[propname] = link_class.lookup(value)
561                 except TypeError:
562                     raise UsageError, _('%(classname)s has no key property"')%{
563                         'classname': link_class.classname}
565         # now do the find 
566         try:
567             if self.comma_sep:
568                 print ','.join(apply(cl.find, (), props))
569             else:
570                 print apply(cl.find, (), props)
571         except KeyError:
572             raise UsageError, _('%(classname)s has no property '
573                 '"%(propname)s"')%locals()
574         except (ValueError, TypeError), message:
575             raise UsageError, message
576         return 0
578     def do_specification(self, args):
579         '''Usage: specification classname
580         Show the properties for a classname.
582         This lists the properties for a given class.
583         '''
584         if len(args) < 1:
585             raise UsageError, _('Not enough arguments supplied')
586         classname = args[0]
587         # get the class
588         cl = self.get_class(classname)
590         # get the key property
591         keyprop = cl.getkey()
592         for key, value in cl.properties.items():
593             if keyprop == key:
594                 print _('%(key)s: %(value)s (key property)')%locals()
595             else:
596                 print _('%(key)s: %(value)s')%locals()
598     def do_display(self, args):
599         '''Usage: display designator
600         Show the property values for the given node.
602         This lists the properties and their associated values for the given
603         node.
604         '''
605         if len(args) < 1:
606             raise UsageError, _('Not enough arguments supplied')
608         # decode the node designator
609         try:
610             classname, nodeid = hyperdb.splitDesignator(args[0])
611         except hyperdb.DesignatorError, message:
612             raise UsageError, message
614         # get the class
615         cl = self.get_class(classname)
617         # display the values
618         for key in cl.properties.keys():
619             value = cl.get(nodeid, key)
620             print _('%(key)s: %(value)s')%locals()
622     def do_create(self, args, pwre = re.compile(r'{(\w+)}(.+)')):
623         '''Usage: create classname property=value ...
624         Create a new entry of a given class.
626         This creates a new entry of the given class using the property
627         name=value arguments provided on the command line after the "create"
628         command.
629         '''
630         if len(args) < 1:
631             raise UsageError, _('Not enough arguments supplied')
632         from roundup import hyperdb
634         classname = args[0]
636         # get the class
637         cl = self.get_class(classname)
639         # now do a create
640         props = {}
641         properties = cl.getprops(protected = 0)
642         if len(args) == 1:
643             # ask for the properties
644             for key, value in properties.items():
645                 if key == 'id': continue
646                 name = value.__class__.__name__
647                 if isinstance(value , hyperdb.Password):
648                     again = None
649                     while value != again:
650                         value = getpass.getpass(_('%(propname)s (Password): ')%{
651                             'propname': key.capitalize()})
652                         again = getpass.getpass(_('   %(propname)s (Again): ')%{
653                             'propname': key.capitalize()})
654                         if value != again: print _('Sorry, try again...')
655                     if value:
656                         props[key] = value
657                 else:
658                     value = raw_input(_('%(propname)s (%(proptype)s): ')%{
659                         'propname': key.capitalize(), 'proptype': name})
660                     if value:
661                         props[key] = value
662         else:
663             props = self.props_from_args(args[1:])
665         # convert types
666         for propname, value in props.items():
667             # get the property
668             try:
669                 proptype = properties[propname]
670             except KeyError:
671                 raise UsageError, _('%(classname)s has no property '
672                     '"%(propname)s"')%locals()
674             if isinstance(proptype, hyperdb.Date):
675                 try:
676                     props[propname] = date.Date(value)
677                 except ValueError, message:
678                     raise UsageError, _('"%(value)s": %(message)s')%locals()
679             elif isinstance(proptype, hyperdb.Interval):
680                 try:
681                     props[propname] = date.Interval(value)
682                 except ValueError, message:
683                     raise UsageError, _('"%(value)s": %(message)s')%locals()
684             elif isinstance(proptype, hyperdb.Password):
685                 m = pwre.match(value)
686                 if m:
687                     # password is being given to us encrypted
688                     p = password.Password()
689                     p.scheme = m.group(1)
690                     p.password = m.group(2)
691                     props[propname] = p
692                 else:
693                     props[propname] = password.Password(value)
694             elif isinstance(proptype, hyperdb.Multilink):
695                 props[propname] = value.split(',')
696             elif isinstance(proptype, hyperdb.Boolean):
697                 props[propname] = value.lower() in ('yes', 'true', 'on', '1')
698             elif isinstance(proptype, hyperdb.Number):
699                 props[propname] = float(value)
701         # check for the key property
702         propname = cl.getkey()
703         if propname and not props.has_key(propname):
704             raise UsageError, _('you must provide the "%(propname)s" '
705                 'property.')%locals()
707         # do the actual create
708         try:
709             print apply(cl.create, (), props)
710         except (TypeError, IndexError, ValueError), message:
711             raise UsageError, message
712         return 0
714     def do_list(self, args):
715         '''Usage: list classname [property]
716         List the instances of a class.
718         Lists all instances of the given class. If the property is not
719         specified, the  "label" property is used. The label property is tried
720         in order: the key, "name", "title" and then the first property,
721         alphabetically.
722         '''
723         if len(args) < 1:
724             raise UsageError, _('Not enough arguments supplied')
725         classname = args[0]
727         # get the class
728         cl = self.get_class(classname)
730         # figure the property
731         if len(args) > 1:
732             propname = args[1]
733         else:
734             propname = cl.labelprop()
736         if self.comma_sep:
737             print ','.join(cl.list())
738         else:
739             for nodeid in cl.list():
740                 try:
741                     value = cl.get(nodeid, propname)
742                 except KeyError:
743                     raise UsageError, _('%(classname)s has no property '
744                         '"%(propname)s"')%locals()
745                 print _('%(nodeid)4s: %(value)s')%locals()
746         return 0
748     def do_table(self, args):
749         '''Usage: table classname [property[,property]*]
750         List the instances of a class in tabular form.
752         Lists all instances of the given class. If the properties are not
753         specified, all properties are displayed. By default, the column widths
754         are the width of the property names. The width may be explicitly defined
755         by defining the property as "name:width". For example::
756           roundup> table priority id,name:10
757           Id Name
758           1  fatal-bug 
759           2  bug       
760           3  usability 
761           4  feature   
762         '''
763         if len(args) < 1:
764             raise UsageError, _('Not enough arguments supplied')
765         classname = args[0]
767         # get the class
768         cl = self.get_class(classname)
770         # figure the property names to display
771         if len(args) > 1:
772             prop_names = args[1].split(',')
773             all_props = cl.getprops()
774             for spec in prop_names:
775                 if ':' in spec:
776                     try:
777                         propname, width = spec.split(':')
778                     except (ValueError, TypeError):
779                         raise UsageError, _('"%(spec)s" not name:width')%locals()
780                 else:
781                     propname = spec
782                 if not all_props.has_key(propname):
783                     raise UsageError, _('%(classname)s has no property '
784                         '"%(propname)s"')%locals()
785         else:
786             prop_names = cl.getprops().keys()
788         # now figure column widths
789         props = []
790         for spec in prop_names:
791             if ':' in spec:
792                 name, width = spec.split(':')
793                 props.append((name, int(width)))
794             else:
795                 props.append((spec, len(spec)))
797         # now display the heading
798         print ' '.join([name.capitalize().ljust(width) for name,width in props])
800         # and the table data
801         for nodeid in cl.list():
802             l = []
803             for name, width in props:
804                 if name != 'id':
805                     try:
806                         value = str(cl.get(nodeid, name))
807                     except KeyError:
808                         # we already checked if the property is valid - a
809                         # KeyError here means the node just doesn't have a
810                         # value for it
811                         value = ''
812                 else:
813                     value = str(nodeid)
814                 f = '%%-%ds'%width
815                 l.append(f%value[:width])
816             print ' '.join(l)
817         return 0
819     def do_history(self, args):
820         '''Usage: history designator
821         Show the history entries of a designator.
823         Lists the journal entries for the node identified by the designator.
824         '''
825         if len(args) < 1:
826             raise UsageError, _('Not enough arguments supplied')
827         try:
828             classname, nodeid = hyperdb.splitDesignator(args[0])
829         except hyperdb.DesignatorError, message:
830             raise UsageError, message
832         try:
833             print self.db.getclass(classname).history(nodeid)
834         except KeyError:
835             raise UsageError, _('no such class "%(classname)s"')%locals()
836         except IndexError:
837             raise UsageError, _('no such %(classname)s node "%(nodeid)s"')%locals()
838         return 0
840     def do_commit(self, args):
841         '''Usage: commit
842         Commit all changes made to the database.
844         The changes made during an interactive session are not
845         automatically written to the database - they must be committed
846         using this command.
848         One-off commands on the command-line are automatically committed if
849         they are successful.
850         '''
851         self.db.commit()
852         return 0
854     def do_rollback(self, args):
855         '''Usage: rollback
856         Undo all changes that are pending commit to the database.
858         The changes made during an interactive session are not
859         automatically written to the database - they must be committed
860         manually. This command undoes all those changes, so a commit
861         immediately after would make no changes to the database.
862         '''
863         self.db.rollback()
864         return 0
866     def do_retire(self, args):
867         '''Usage: retire designator[,designator]*
868         Retire the node specified by designator.
870         This action indicates that a particular node is not to be retrieved by
871         the list or find commands, and its key value may be re-used.
872         '''
873         if len(args) < 1:
874             raise UsageError, _('Not enough arguments supplied')
875         designators = args[0].split(',')
876         for designator in designators:
877             try:
878                 classname, nodeid = hyperdb.splitDesignator(designator)
879             except hyperdb.DesignatorError, message:
880                 raise UsageError, message
881             try:
882                 self.db.getclass(classname).retire(nodeid)
883             except KeyError:
884                 raise UsageError, _('no such class "%(classname)s"')%locals()
885             except IndexError:
886                 raise UsageError, _('no such %(classname)s node "%(nodeid)s"')%locals()
887         return 0
889     def do_restore(self, args):
890         '''Usage: restore designator[,designator]*
891         Restore the retired node specified by designator.
893         The given nodes will become available for users again.
894         '''
895         if len(args) < 1:
896             raise UsageError, _('Not enough arguments supplied')
897         designators = args[0].split(',')
898         for designator in designators:
899             try:
900                 classname, nodeid = hyperdb.splitDesignator(designator)
901             except hyperdb.DesignatorError, message:
902                 raise UsageError, message
903             try:
904                 self.db.getclass(classname).restore(nodeid)
905             except KeyError:
906                 raise UsageError, _('no such class "%(classname)s"')%locals()
907             except IndexError:
908                 raise UsageError, _('no such %(classname)s node "%(nodeid)s"')%locals()
909         return 0
911     def do_export(self, args):
912         '''Usage: export [class[,class]] export_dir
913         Export the database to colon-separated-value files.
915         This action exports the current data from the database into
916         colon-separated-value files that are placed in the nominated
917         destination directory. The journals are not exported.
918         '''
919         # we need the CSV module
920         if csv is None:
921             raise UsageError, \
922                 _('Sorry, you need the csv module to use this function.\n'
923                 'Get it from: http://www.object-craft.com.au/projects/csv/')
925         # grab the directory to export to
926         if len(args) < 1:
927             raise UsageError, _('Not enough arguments supplied')
928         dir = args[-1]
930         # get the list of classes to export
931         if len(args) == 2:
932             classes = args[0].split(',')
933         else:
934             classes = self.db.classes.keys()
936         # use the csv parser if we can - it's faster
937         p = csv.parser(field_sep=':')
939         # do all the classes specified
940         for classname in classes:
941             cl = self.get_class(classname)
942             f = open(os.path.join(dir, classname+'.csv'), 'w')
943             properties = cl.getprops()
944             propnames = properties.keys()
945             propnames.sort()
946             l = propnames[:]
947             l.append('is retired')
948             print >> f, p.join(l)
950             # all nodes for this class (not using list() 'cos it doesn't
951             # include retired nodes)
953             for nodeid in self.db.getclass(classname).getnodeids():
954                 # get the regular props
955                 print >>f, p.join(cl.export_list(propnames, nodeid))
956         return 0
958     def do_import(self, args):
959         '''Usage: import import_dir
960         Import a database from the directory containing CSV files, one per
961         class to import.
963         The files must define the same properties as the class (including having
964         a "header" line with those property names.)
966         The imported nodes will have the same nodeid as defined in the
967         import file, thus replacing any existing content.
969         The new nodes are added to the existing database - if you want to
970         create a new database using the imported data, then create a new
971         database (or, tediously, retire all the old data.)
972         '''
973         if len(args) < 1:
974             raise UsageError, _('Not enough arguments supplied')
975         if csv is None:
976             raise UsageError, \
977                 _('Sorry, you need the csv module to use this function.\n'
978                 'Get it from: http://www.object-craft.com.au/projects/csv/')
980         from roundup import hyperdb
982         for file in os.listdir(args[0]):
983             f = open(os.path.join(args[0], file))
985             # get the classname
986             classname = os.path.splitext(file)[0]
988             # ensure that the properties and the CSV file headings match
989             cl = self.get_class(classname)
990             p = csv.parser(field_sep=':')
991             file_props = p.parse(f.readline())
993 # XXX we don't _really_ need to do this...
994 #            properties = cl.getprops()
995 #            propnames = properties.keys()
996 #            propnames.sort()
997 #            m = file_props[:]
998 #            m.sort()
999 #            if m != propnames:
1000 #                raise UsageError, _('Import file doesn\'t define the same '
1001 #                    'properties as "%(arg0)s".')%{'arg0': args[0]}
1003             # loop through the file and create a node for each entry
1004             maxid = 1
1005             while 1:
1006                 line = f.readline()
1007                 if not line: break
1009                 # parse lines until we get a complete entry
1010                 while 1:
1011                     l = p.parse(line)
1012                     if l: break
1013                     line = f.readline()
1014                     if not line:
1015                         raise ValueError, "Unexpected EOF during CSV parse"
1017                 # do the import and figure the current highest nodeid
1018                 maxid = max(maxid, int(cl.import_list(file_props, l)))
1020             print 'setting', classname, maxid+1
1021             self.db.setid(classname, str(maxid+1))
1022         return 0
1024     def do_pack(self, args):
1025         '''Usage: pack period | date
1027 Remove journal entries older than a period of time specified or
1028 before a certain date.
1030 A period is specified using the suffixes "y", "m", and "d". The
1031 suffix "w" (for "week") means 7 days.
1033       "3y" means three years
1034       "2y 1m" means two years and one month
1035       "1m 25d" means one month and 25 days
1036       "2w 3d" means two weeks and three days
1038 Date format is "YYYY-MM-DD" eg:
1039     2001-01-01
1040     
1041         '''
1042         if len(args) <> 1:
1043             raise UsageError, _('Not enough arguments supplied')
1044         
1045         # are we dealing with a period or a date
1046         value = args[0]
1047         date_re = re.compile(r'''
1048               (?P<date>\d\d\d\d-\d\d?-\d\d?)? # yyyy-mm-dd
1049               (?P<period>(\d+y\s*)?(\d+m\s*)?(\d+d\s*)?)?
1050               ''', re.VERBOSE)
1051         m = date_re.match(value)
1052         if not m:
1053             raise ValueError, _('Invalid format')
1054         m = m.groupdict()
1055         if m['period']:
1056             pack_before = date.Date(". - %s"%value)
1057         elif m['date']:
1058             pack_before = date.Date(value)
1059         self.db.pack(pack_before)
1060         return 0
1062     def do_reindex(self, args):
1063         '''Usage: reindex
1064         Re-generate a tracker's search indexes.
1066         This will re-generate the search indexes for a tracker. This will
1067         typically happen automatically.
1068         '''
1069         self.db.indexer.force_reindex()
1070         self.db.reindex()
1071         return 0
1073     def do_security(self, args):
1074         '''Usage: security [Role name]
1075         Display the Permissions available to one or all Roles.
1076         '''
1077         if len(args) == 1:
1078             role = args[0]
1079             try:
1080                 roles = [(args[0], self.db.security.role[args[0]])]
1081             except KeyError:
1082                 print _('No such Role "%(role)s"')%locals()
1083                 return 1
1084         else:
1085             roles = self.db.security.role.items()
1086             role = self.db.config.NEW_WEB_USER_ROLES
1087             if ',' in role:
1088                 print _('New Web users get the Roles "%(role)s"')%locals()
1089             else:
1090                 print _('New Web users get the Role "%(role)s"')%locals()
1091             role = self.db.config.NEW_EMAIL_USER_ROLES
1092             if ',' in role:
1093                 print _('New Email users get the Roles "%(role)s"')%locals()
1094             else:
1095                 print _('New Email users get the Role "%(role)s"')%locals()
1096         roles.sort()
1097         for rolename, role in roles:
1098             print _('Role "%(name)s":')%role.__dict__
1099             for permission in role.permissions:
1100                 if permission.klass:
1101                     print _(' %(description)s (%(name)s for "%(klass)s" '
1102                         'only)')%permission.__dict__
1103                 else:
1104                     print _(' %(description)s (%(name)s)')%permission.__dict__
1105         return 0
1107     def run_command(self, args):
1108         '''Run a single command
1109         '''
1110         command = args[0]
1112         # handle help now
1113         if command == 'help':
1114             if len(args)>1:
1115                 self.do_help(args[1:])
1116                 return 0
1117             self.do_help(['help'])
1118             return 0
1119         if command == 'morehelp':
1120             self.do_help(['help'])
1121             self.help_commands()
1122             self.help_all()
1123             return 0
1125         # figure what the command is
1126         try:
1127             functions = self.commands.get(command)
1128         except KeyError:
1129             # not a valid command
1130             print _('Unknown command "%(command)s" ("help commands" for a '
1131                 'list)')%locals()
1132             return 1
1134         # check for multiple matches
1135         if len(functions) > 1:
1136             print _('Multiple commands match "%(command)s": %(list)s')%{'command':
1137                 command, 'list': ', '.join([i[0] for i in functions])}
1138             return 1
1139         command, function = functions[0]
1141         # make sure we have a tracker_home
1142         while not self.tracker_home:
1143             self.tracker_home = raw_input(_('Enter tracker home: ')).strip()
1145         # before we open the db, we may be doing an install or init
1146         if command == 'initialise':
1147             try:
1148                 return self.do_initialise(self.tracker_home, args)
1149             except UsageError, message:
1150                 print _('Error: %(message)s')%locals()
1151                 return 1
1152         elif command == 'install':
1153             try:
1154                 return self.do_install(self.tracker_home, args)
1155             except UsageError, message:
1156                 print _('Error: %(message)s')%locals()
1157                 return 1
1159         # get the tracker
1160         try:
1161             tracker = roundup.instance.open(self.tracker_home)
1162         except ValueError, message:
1163             self.tracker_home = ''
1164             print _("Error: Couldn't open tracker: %(message)s")%locals()
1165             return 1
1167         # only open the database once!
1168         if not self.db:
1169             self.db = tracker.open('admin')
1171         # do the command
1172         ret = 0
1173         try:
1174             ret = function(args[1:])
1175         except UsageError, message:
1176             print _('Error: %(message)s')%locals()
1177             print
1178             print function.__doc__
1179             ret = 1
1180         except:
1181             import traceback
1182             traceback.print_exc()
1183             ret = 1
1184         return ret
1186     def interactive(self):
1187         '''Run in an interactive mode
1188         '''
1189         print _('Roundup %s ready for input.'%roundup_version)
1190         print _('Type "help" for help.')
1191         try:
1192             import readline
1193         except ImportError:
1194             print _('Note: command history and editing not available')
1196         while 1:
1197             try:
1198                 command = raw_input(_('roundup> '))
1199             except EOFError:
1200                 print _('exit...')
1201                 break
1202             if not command: continue
1203             args = token.token_split(command)
1204             if not args: continue
1205             if args[0] in ('quit', 'exit'): break
1206             self.run_command(args)
1208         # exit.. check for transactions
1209         if self.db and self.db.transactions:
1210             commit = raw_input(_('There are unsaved changes. Commit them (y/N)? '))
1211             if commit and commit[0].lower() == 'y':
1212                 self.db.commit()
1213         return 0
1215     def main(self):
1216         try:
1217             opts, args = getopt.getopt(sys.argv[1:], 'i:u:hc')
1218         except getopt.GetoptError, e:
1219             self.usage(str(e))
1220             return 1
1222         # handle command-line args
1223         self.tracker_home = os.environ.get('TRACKER_HOME', '')
1224         # TODO: reinstate the user/password stuff (-u arg too)
1225         name = password = ''
1226         if os.environ.has_key('ROUNDUP_LOGIN'):
1227             l = os.environ['ROUNDUP_LOGIN'].split(':')
1228             name = l[0]
1229             if len(l) > 1:
1230                 password = l[1]
1231         self.comma_sep = 0
1232         for opt, arg in opts:
1233             if opt == '-h':
1234                 self.usage()
1235                 return 0
1236             if opt == '-i':
1237                 self.tracker_home = arg
1238             if opt == '-c':
1239                 self.comma_sep = 1
1241         # if no command - go interactive
1242         # wrap in a try/finally so we always close off the db
1243         ret = 0
1244         try:
1245             if not args:
1246                 self.interactive()
1247             else:
1248                 ret = self.run_command(args)
1249                 if self.db: self.db.commit()
1250             return ret
1251         finally:
1252             if self.db:
1253                 self.db.close()
1255 if __name__ == '__main__':
1256     tool = AdminTool()
1257     sys.exit(tool.main())
1259 # vim: set filetype=python ts=4 sw=4 et si