Source

trac-ticketlinks / scripts / trac-admin

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
__version__ = '0.5-rc1'
__author__ = 'Daniel Lundin <daniel@edgewall.com>, Jonas Borgström <jonas@edgewall.com>'
__copyright__ = 'Copyright (c) 2004 Edgewall Research & Development'
__license__ = """
 Copyright (C) 2003, 2004 Edgewall Research & Development
 Copyright (C) 2003, 2004 Jonas Borgström <jonas@edgewall.com>
 Copyright (C) 2003, 2004 Daniel Lundin <daniel@edgewall.com>

 Trac is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as
 published by the Free Software Foundation; either version 2 of
 the License, or (at your option) any later version.

 Trac is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA."""

import os
import os.path
import sys
import time
import cmd
import shlex
import sqlite
import StringIO
import trac.siteconfig

def my_sum(list):
    """Python2.1 doesn't have sum()"""
    tot = 0
    for item in list:
	tot += item
    return tot


class TracAdmin(cmd.Cmd):
    intro = ''
    license = trac.__license_long__
    credits = trac.__credits__

    doc_header = 'Trac Admin Console %(ver)s\n' \
                 'Available Commands:\n' \
                 % {'ver':__version__ }

    
    ruler = ''
    prompt = "Trac> "

    db_schema = """
CREATE TABLE revision (
	rev 		integer PRIMARY KEY,
	time		integer,
	author		text,
	message		text
);
CREATE TABLE node_change (
	rev 		integer,
	name		text,
	change		char(1),
	UNIQUE(rev, name, change)
);
CREATE TABLE auth_cookie (
	cookie		text,
	name		text,
	ipnr		text,
	time		integer,
	UNIQUE(cookie, name, ipnr)
);
CREATE TABLE enum (
	type		text,
	name		text,
	value		text,
	UNIQUE(name,type)
);
CREATE TABLE config (
	section		text,
	name		text,
	value		text,
	UNIQUE(section, name)
);
CREATE TABLE ticket (
	id		integer PRIMARY KEY,
	time		integer,	-- the time it was created
	changetime	integer,
	component	text,
	severity	text,
	priority	text,
	owner		text,		-- who is this ticket assigned to
	reporter	text,
	cc		text,		-- email addresses to notify
	url		text,		-- url related to this ticket
	version		text,		-- 
	milestone	text,		-- 
	status		text,
	resolution	text,
	summary		text,		-- one-line summary
	description	text		-- problem description (long)
);
CREATE TABLE ticket_change (
	ticket		integer,
	time		integer,
	author		text,
	field		text,
	oldvalue	text,
	newvalue	text
);
CREATE TABLE report (
	id		integer PRIMARY KEY,
	author		text,
	title		text,
	sql		text
);
CREATE TABLE permission (
	user		text,		-- 
	action		text		-- allowable activity
);
CREATE TABLE component (
	 name		 text PRIMARY KEY,
	 owner		 text
);
CREATE TABLE milestone (
	 name		 text PRIMARY KEY,
	 time		 integer
);
CREATE TABLE version (
	 name		 text PRIMARY KEY,
	 time		 integer
);
CREATE TABLE wiki (
	 name		 text,
	 version		 integer,
	 time		 integer,
	 author		 text,
	 ipnr		 text,
	 locked		 integer,
	 text		 text,
	 UNIQUE(name,version)
);
CREATE INDEX node_change_idx ON node_change(rev);
CREATE INDEX ticket_change_idx	ON ticket_change(ticket, time);
CREATE INDEX wiki_idx		ON wiki(name,version);
"""

    # Default data for database
    # (table, (column1, column2), ((row1col1, row1col2), (row2col1, row2col2)))
    db_data = (('component',
                 ('name', 'owner'),
                   (('component1', 'somebody'),
                    ('component2', 'somebody'))),
               ('milestone',
                 ('name', 'time'),
                   (('', 0), 
                    ('milestone1', 0),
                    ('milestone2', 0),
                    ('milestone3', 0),
                    ('milestone4', 0))),
               ('version',
                 ('name', 'time'),
                   (('', 0),
                    ('1.0', 0),
                    ('2.0', 0))),
               ('enum',
                 ('type', 'name', 'value'),
                   (('status', 'new', 1),
                    ('status', 'assigned', 2),
                    ('status', 'reopened', 3),
                    ('status', 'closed', 4),
                    ('resolution', 'fixed', 1),
                    ('resolution', 'invalid', 2),
                    ('resolution', 'wontfix', 3),
                    ('resolution', 'duplicate', 4),
                    ('resolution', 'worksforme', 5),
                    ('severity', 'blocker', 1),
                    ('severity', 'critical', 2),
                    ('severity', 'major', 3),
                    ('severity', 'normal', 4),
                    ('severity', 'minor', 5),
                    ('severity', 'trivial', 6),
                    ('severity', 'enhancement', 7),
                    ('priority', 'highest', 1),
                    ('priority', 'high', 2),
                    ('priority', 'normal', 3),
                    ('priority', 'low', 4),
                    ('priority', 'lowest', 5))),
               ('permission',
                 ('user', 'action'),
                   (('anonymous', 'LOG_VIEW'),
                    ('anonymous', 'FILE_VIEW'),
                    ('anonymous', 'WIKI_VIEW'),
                    ('anonymous', 'WIKI_CREATE'),
                    ('anonymous', 'WIKI_MODIFY'),
                    ('anonymous', 'SEARCH_VIEW'),
                    ('anonymous', 'REPORT_VIEW'),
                    ('anonymous', 'TICKET_VIEW'),
                    ('anonymous', 'TICKET_CREATE'),
                    ('anonymous', 'TICKET_MODIFY'),
                    ('anonymous', 'BROWSER_VIEW'),
                    ('anonymous', 'TIMELINE_VIEW'),
                    ('anonymous', 'CHANGESET_VIEW'))),
               ('config',
                 ('section', 'name', 'value'),
                   (('trac', 'database_version', '1'),
                    ('general', 'htdocs_location', '/trac/'),
                    ('general', 'repository_dir', '/var/svn/myrep'),
                    ('general', 'templates_dir', '/usr/lib/trac/templates'),
                    ('project', 'name', 'My Project'),
                    ('project', 'descr', 'My example project'),
                    ('project', 'url', 'http://example.com/'),
                    ('ticket', 'default_version', ''),
                    ('ticket', 'default_severity', 'normal'),
                    ('ticket', 'default_priority', 'normal'),
                    ('ticket', 'default_milestone', ''),
                    ('ticket', 'default_component', 'component1'),
                    ('header_logo', 'link', 'http://trac.edgewall.com/'),
                    ('header_logo', 'src', 'trac_banner.png'),
                    ('header_logo', 'alt', 'Trac'),
                    ('header_logo', 'width', '199'),
                    ('header_logo', 'height', '38'))),
               ('report',
                 ('id', 'author', 'title', 'sql'),
                   (('1', None, 'Active Tickets',
                     "SELECT id AS ticket, status, severity, priority, owner, "
                     "time as created, summary FROM ticket "
                     "WHERE status IN ('new', 'assigned', 'reopened')"
                     "ORDER BY priority, time"),)))
    
    def __init__(self,dbfile=None):
        cmd.Cmd.__init__(self)
        self.interactive = 0
        if dbfile:
            self.db_set(dbfile)

    def docmd(self, cmd='help'):
        self.onecmd(cmd)

    def run(self):
        self.interactive = 1
        print 'Welcome to trac-admin %(ver)s\n' 			\
              'Interactive Trac adminstration console.\n' 		\
              '%(copy)s\n\n' 					\
              "Type:  '?' or 'help' for help on commands.\n" % 	\
              {'ver':__version__,'copy':__copyright__}
        while 1:
            try:
                self.cmdloop()
                break
            except KeyboardInterrupt:
                print "\n** Interrupt. Use 'quit' to exit **"


    ##
    ## Database methods
    ##

    def db_set(self, dbfile):
        self.dbname = dbfile
        self.prompt = "Trac [%s]> " % self.dbname

    def db_check(self):
        if os.path.isfile(self.dbname):
            f = open (self.dbname)
            data = f.read (50)
            if -1 == data.find("This file contains an SQLite"):
                return 0
            f.close()
            return 1
        return 0
        
    def db_open(self):
        try:
            if not self.db_check():
                raise Exception
            return sqlite.connect (self.dbname)
        except Exception, e:
            print 'Failed to open/create database.', e
            sys.exit(1)

    def db_execsql (self, sql, cursor=None):
        data = []
        if not cursor:
            cnx=self.db_open()
            cursor = cnx.cursor()
        else:
            cnx = None
        cursor.execute(sql)
        while 1:
            row = cursor.fetchone()
            if row == None:
                break
            data.append(row)
        if cnx:
            cnx.commit()
        return data

    ##
    ## Utility methods
    ##

    def arg_tokenize (self, argstr):
        if hasattr(shlex, 'split'):
            toks = shlex.split(argstr)
        else:
	    def my_strip(s, c):
		"""string::strip in python2.1 doesn't support arguments"""
		i = j = 0
		for i in range(len(s)):
		    if not s[i] in c:
			break
		for j in range(len(s), 0, -1):
		    if not s[j-1] in c:
			break
		return s[i:j]
	
	    lexer = shlex.shlex(StringIO.StringIO(argstr))
            lexer.wordchars = lexer.wordchars + ".,_/"
            toks = []
            while 1:
                token = my_strip(lexer.get_token(), '"\'')
                if not token:
                    break
                toks.append(token)
        return toks or ['']

    def word_complete (self, text, words):
        return [a for a in words if a.startswith (text)]

    def print_listing(self, headers, data, sep=' ',decor=1):
        ldata = data
        if decor:
            ldata.insert (0, headers)
        print
        colw=[]
        ncols = len(ldata[0]) # assumes all rows are of equal length
        for cnum in xrange(0, ncols):
            mw = 0
            for cell in [str(d[cnum]) or '' for d in ldata]:
                if len(cell) > mw:
                    mw = len(cell)
            colw.append(mw)
        for rnum in xrange(0, len(ldata)):
            for cnum in xrange(0, ncols):
                if decor and rnum == 0:
                    sp = ('%%%ds' % len(sep)) % ' '  # No separator in header
                else:
                    sp = sep
                if cnum+1 == ncols: sp = '' # No separator after last column
                print ("%%-%ds%s" % (colw[cnum], sp)) % (ldata[rnum][cnum] or ''),
            print
            if rnum == 0 and decor:
                print ''.join(['-' for x in xrange(0,(1+len(sep))*cnum+my_sum(colw))])
        print

    def print_doc(self,doc,decor=0):
        if not doc: return
        self.print_listing (['Command','Description'], doc, '  --', decor) 

    def get_component_list (self):
        data = self.db_execsql ("SELECT name FROM component")
        return [r[0] for r in data]

    def get_config_list (self):
        data = self.db_execsql ("SELECT section||'.'||name FROM config")
        return [r[0] for r in data]

    def get_user_list (self):
        data = self.db_execsql ("SELECT DISTINCT user FROM permission")
        return [r[0] for r in data]

    def get_wiki_list (self):
        data = self.db_execsql('SELECT DISTINCT name FROM wiki') 
        return [r[0] for r in data]

    def get_dir_list (self, pathstr):
        dname = os.path.dirname(pathstr)
        d = os.path.join(os.getcwd(), dname)
        ls = os.listdir(d)
        return ls

    def get_enum_list (self, type):
        data = self.db_execsql("SELECT name FROM enum WHERE type='%s'" % type) 
        return [r[0] for r in data]

    def get_milestone_list (self):
        data = self.db_execsql("SELECT name FROM milestone") 
        return [r[0] for r in data]

    def get_version_list (self):
        data = self.db_execsql("SELECT name FROM version") 
        return [r[0] for r in data]


    ##
    ## Available Commands
    ##

    ## Help
    _help_help = [('help', 'Show documentation')]

    def do_help(self, line=None):
        arg = self.arg_tokenize(line)
        if arg[0]:
            try:
                doc = getattr(self, "_help_" + arg[0])
                self.print_doc (doc)
            except AttributeError:
                print "No documentation found for '%s'" % arg[0]
        else:
            docs = (self._help_about + self._help_help + self._help_initdb +
                    self._help_config + self._help_wiki +
                    self._help_permission + self._help_component +
                    self._help_priority + self._help_severity + 
                    self._help_version + self._help_milestone)
            print 'trac-admin - The Trac Administration Console %s' % __version__
            if not self.interactive:
                print
                print "Usage: trac-admin <dbfile> [command [subcommand] [option ...]]\n"
                print "Invoking trac-admin without command starts "\
                       "interactive mode."
            self.print_doc (docs)
            print self.credits

    
    ## About / Version
    _help_about = [('about', 'Shows information about trac-admin')]

    def do_about(self, line):
        print
        print 'Trac Admin Console %s' % __version__
        print '================================================================='
        print self.license
        print self.credits


    ## Quit / EOF
    _help_quit = [['quit', 'Exit the program']]
    _help_EOF = _help_quit

    def do_quit(self,line):
        print
        sys.exit()

    do_EOF = do_quit # Alias


    ## Config
    _help_config = [('config list', 'Show current configuration'),
                     ('config set <option> <value>', 'Set config')]

    def complete_config (self, text, line, begidx, endidx):
        if begidx > 10 and line.startswith('config set'):
            comp = self.get_config_list()
        else:
            comp = ['list','show','set']
        return self.word_complete(text, comp)

    def do_config(self, line):
        arg = self.arg_tokenize(line)        
        try:
            if arg[0] in ['list', 'show']:
                self._do_config_list()
            elif arg[0] == 'set' and len(arg)==3:
                name = arg[1]
                value = arg[2]
                self._do_config_set(name, value)
            else:    
                self.do_help('config')
        except Exception, e:
            print "Config %s failed:" % arg[0], e

    def _do_config_list(self):
        data = self.db_execsql ('SELECT section, name, value FROM config')
        ldata = [[r[0]+'.'+r[1],r[2]] for r in data]
        self.print_listing(['Name', 'Value'], ldata)

    def _do_config_set(self, name, value):
        try:
            cfsection, cfname = name.split('.')
        except ValueError, e:
            raise Exception, "No such config option '%s'" % name
        data = self.db_execsql ("SELECT value FROM config WHERE "
                                    "section='%s' AND name='%s'" % (cfsection, cfname))
        if not data:
            raise Exception, "No such config option '%s'" % name
        self.db_execsql("UPDATE config SET value='%s' WHERE "
                        "section='%s' AND name='%s'" % (value, cfsection, cfname))
        

    ## Component
    _help_component = [('component list', 'Show available components'),
                       ('component add <name> <owner>', 'Add a new component'),
                       ('component rename <name> <newname>', 'Rename a component'),
                       ('component remove <name>', 'Remove/uninstall component'),
                       ('component chown <name> <owner>', 'Change component ownership')]

    def complete_component (self, text, line, begidx, endidx):
        if begidx in [16,17]:
            comp = self.get_component_list()
        elif begidx > 15 and line.startswith('component chown '):
            comp = self.get_user_list()
        else:
            comp = ['list','add','rename','remove','chown']
        return self.word_complete(text, comp)

    def do_component(self, line):
        arg = self.arg_tokenize(line)
        try:
            if arg[0]  == 'list':
                self._do_component_list()
            elif arg[0] == 'add' and len(arg)==3:
                name = arg[1]
                owner = arg[2]
                self._do_component_add(name, owner)
            elif arg[0] == 'rename' and len(arg)==3:
                name = arg[1]
                newname = arg[2]
                self._do_component_rename(name, newname)
            elif arg[0] == 'remove'  and len(arg)==2:
                name = arg[1]
                self._do_component_remove(name)
            elif arg[0] == 'chown' and len(arg)==3:
                name = arg[1]
                owner = arg[2]
                self._do_component_set_owner(name, owner)
            else:    
                self.do_help ('component')
        except Exception, e:
            print 'Component %s failed:' % arg[0], e

    def _do_component_list(self):
        data = self.db_execsql('SELECT name, owner FROM component') 
        self.print_listing(['Name', 'Owner'], data)

    def _do_component_add(self, name, owner):
            data = self.db_execsql("INSERT INTO component VALUES('%s', '%s')"
                                   % (name, owner))

    def _do_component_rename(self, name, newname):
            data = self.db_execsql("UPDATE component SET name='%s' WHERE name='%s'"
                                   % (newname,name))

    def _do_component_remove(self, name):
            data = self.db_execsql("DELETE FROM component WHERE name='%s'"
                                   % (name))

    def _do_component_set_owner(self, name, owner):
            data = self.db_execsql("UPDATE component SET owner='%s' WHERE name='%s'"
                                   % (owner,name))


    ## Permission
    _help_permission = [('permission list', 'List permission rules'),
                       ('permission add <user> <action>', 'Add a new permission rule'),
                       ('permission remove <user> <action>', 'Remove permission rule')]

    def do_permission(self, line):
        arg = self.arg_tokenize(line)
        try:
            if arg[0]  == 'list':
                self._do_permission_list()
            elif arg[0] == 'add' and len(arg)==3:
                user = arg[1]
                action = arg[2]
                self._do_permission_add(user, action)
            elif arg[0] == 'remove'  and len(arg)==3:
                user = arg[1]
                action = arg[2]
                self._do_permission_remove(user, action)
            else:    
                self.do_help ('permission')
        except Exception, e:
            print 'Permission %s failed:' % arg[0], e

    def _do_permission_list(self):
        data = self.db_execsql('SELECT user, action FROM permission') 
        self.print_listing(['User', 'Action'], data)
        print
        print 'Available actions:'
        print ' LOG_VIEW, FILE_VIEW, CHANGESET_VIEW, BROWSER_VIEW, '
        print ' TICKET_VIEW, TICKET_CREATE, TICKET_MODIFY, TICKET_ADMIN, '
        print ' REPORT_VIEW, REPORT_CREATE, REPORT_MODIFY, REPORT_DELETE, REPORT_ADMIN, '
        print ' WIKI_VIEW, WIKI_CREATE, WIKI_MODIFY, WIKI_DELETE, WIKI_ADMIN, '
        print ' TIMELINE_VIEW and SEARCH_VIEW.'
        print ' CONFIG_VIEW, TRAC_ADMIN.'
        print
        
    def _do_permission_add(self, user, action):
        self.db_execsql("INSERT INTO permission VALUES('%s', '%s')" % (user, action))

    def _do_permission_remove(self, user, action):
        self.db_execsql("DELETE FROM permission WHERE user='%s' AND action='%s'" %
                        (user, action))

    ## Initdb
    _help_initdb = [('initdb', 'Create and initializes a new database')]

    def do_initdb(self, line):
        if self.db_check():
            print "Initdb for '%s' failed.\nDoes a database already exist?" % self.dbname
            return
        try:
            print
            print 'Trac need to known a few installation-specific settings'
            print 'when creating a new database.'
            print
            while 1:
                project_name = raw_input('Project name (will be displayed in the page title)> ')
                repository_dir = raw_input('Subversion repository> ')
                if os.access(os.path.join(repository_dir, 'README.txt'), os.F_OK) and \
                   os.access(os.path.join(repository_dir, 'conf'), os.F_OK):
                    break
                print repository_dir, 'doesn\'t look like a subversion repository'
            while 1:
                dt = trac.siteconfig.__default_templates_dir__
                prompt = 'Trac templates directory [%s]> ' % dt
                templates_dir = raw_input(prompt) or dt
                if os.access(os.path.join(templates_dir, 'browser.cs'), os.F_OK) and \
                   os.access(os.path.join(templates_dir, 'ticket.cs'), os.F_OK):
                    break
                print templates_dir, 'doesn\'t look like a Trac templates directory'
        except KeyboardInterrupt:
            print 'initdb aborted'
            return
        try:
            cnx = sqlite.connect (self.dbname)
            cursor = cnx.cursor ()
            self.initdb_create_tables(cursor)
            self.initdb_insert_default_data (cursor)
            cursor.execute('UPDATE config SET value=%s WHERE section=%s AND name=%s',
                           project_name, 'project', 'name')
            cursor.execute('UPDATE config SET value=%s WHERE name=%s',
                           repository_dir, 'repository_dir')
            cursor.execute('UPDATE config SET value=%s WHERE name=%s',
                           templates_dir, 'templates_dir')
            
            # Add a few default wiki pages
            pages = os.listdir(trac.siteconfig.__default_wiki_dir__)
            for page in pages:
                print 'Importing page', page
                filename = os.path.join(trac.siteconfig.__default_wiki_dir__,
                                        page)
                self._do_wiki_import(filename, page, cursor)
            cnx.commit()
            
        except Exception, e:
            print 'Failed to initialize database.', e
            cnx.rollback()

    def initdb_create_tables (self, cursor):
            cursor.execute (self.db_schema)

    def initdb_insert_default_data (self, cursor):
        def prep_value(v):
            if v == None:
                return 'NULL'
            else:
                return '"%s"' % v

        for t in xrange(0, len(self.db_data)):
            table = self.db_data[t][0]
            cols = ','.join(self.db_data[t][1])
            for row in self.db_data[t][2]:
                values = ','.join(map(prep_value, row))
                sql = "INSERT INTO %s (%s) VALUES(%s);" % (table, cols, values)
                cursor.execute(sql)


    ## Wiki
    _help_wiki = [('wiki list', 'List wiki pages'),
                  ('wiki export <page> [file]',
                   'Export wiki page to file or stdout'),
                  ('wiki import <page> [file]',
                   'Import wiki page from file or stdin')]

    def complete_wiki (self, text, line, begidx, endidx):
        argv = self.arg_tokenize(line)
        argc = len(argv)
        if line[-1] == ' ': # Space starts new argument
            argc += 1
        if begidx > 11:
            if line.startswith('wiki export'):
                if argc==3:
                    comp = self.get_wiki_list()
                elif argc==4:
                    comp = self.get_dir_list(argv[-1])
            else:
                if argc==3:
                    comp = self.get_dir_list(argv[-1])
                elif argc==4:
                    comp = self.get_wiki_list()
        else:
            comp = ['list','import','export']
        return self.word_complete(text, comp)

    def do_wiki(self, line):
        arg = self.arg_tokenize(line)
        try:
            if arg[0]  == 'list':
                self._do_wiki_list()
            elif arg[0] == 'import' and len(arg) == 3:
                title = arg[1]
                file = arg[2]
                self._do_wiki_import(file, title)
            elif arg[0] == 'export'  and len(arg) in [2,3]:
                page = arg[1]
                file = (len(arg) == 3 and arg[2]) or None
                self._do_wiki_export(page, file)
            else:    
                self.do_help ('wiki')
        except Exception, e:
            print 'Wiki %s failed:' % arg[0], e

    def _do_wiki_list(self):
        data = self.db_execsql('SELECT name,max(version),time'
                               ' FROM wiki GROUP BY name ORDER BY name')
        ldata = [(d[0], d[1], time.ctime(d[2])) for d in data]
        self.print_listing(['Title', 'Edits', 'Modified'], ldata)

    def _do_wiki_import(self, filename, title, cursor=None):
        f = file(filename,'r')
        data=f.read()
        data = data.replace("'", "''") # Escape ' for safe SQL
        f.close()
        sql = ("INSERT INTO wiki('version','name','time','author','ipnr','text') "
               " SELECT 1+ifnull(max(version),0),'%(title)s','%(time)s','%(author)s',"
               "   '%(ipnr)s','%(text)s' FROM wiki WHERE name='%(title)s'" 
               % {'title':title,
                  'time':int(time.time()),
                  'author':'trac',
                  'ipnr':'127.0.0.1',
                  'locked':'0',
                  'text':data})
        self.db_execsql(sql, cursor)

#        sql = "INSERT INTO wiki('version','name','time','author',
#        select max(version) from wiki where name="HejsanHoppsan";

    def _do_wiki_export(self, page, filename):
        data=self.db_execsql("SELECT text FROM wiki "
                             " WHERE name='%s'"
                             " ORDER BY version DESC LIMIT 1" % page)
        text = data[0][0]
        if not filename:
            print text
        else:
            if os.path.isfile(filename):
                raise Exception("File '%s' exists" % filename)
            f = file (filename,'w')
            f.write(text)
            f.close()


    ## (Ticket) Priority
    _help_priority = [('priority list', 'Show possible ticket priorities'),
                       ('priority add <value>', 'Add a priority value option'),
                       ('priority change <value> <newvalue>',
                        'Change a priority value'),
                       ('priority remove <value>', 'Remove priority value')]

    def complete_priority (self, text, line, begidx, endidx):
        if begidx == 16:
            comp = self.get_enum_list ('priority')
        elif begidx < 15:
            comp = ['list','add','change','remove']
        return self.word_complete(text, comp)

    def do_priority(self, line):
        self._do_enum('priority', line)

    ## (Ticket) Severity
    _help_severity = [('severity list', 'Show possible ticket priorities'),
                       ('severity add <value>', 'Add a severity value option'),
                       ('severity change <value> <newvalue>',
                        'Change a severity value'),
                       ('severity remove <value>', 'Remove severity value')]

    def complete_severity (self, text, line, begidx, endidx):
        if begidx == 16:
            comp = self.get_enum_list ('severity')
        elif begidx < 15:
            comp = ['list','add','change','remove']
        return self.word_complete(text, comp)

    def do_severity(self, line):
        self._do_enum('severity', line)

    # Priority and Severity share the same datastructure and methods:
    
    def _do_enum(self, type, line):
        arg = self.arg_tokenize(line)
        try:
            if arg[0]  == 'list':
                self._do_enum_list(type)
            elif arg[0] == 'add' and len(arg)==2:
                name = arg[1]
                self._do_enum_add(type, name)
            elif arg[0] == 'change'  and len(arg)==3:
                name = arg[1]
                newname = arg[2]
                self._do_enum_change(type, name, newname)
            elif arg[0] == 'remove'  and len(arg)==2:
                name = arg[1]
                self._do_enum_remove(type, name)
            else:    
                self.do_help (type)
        except Exception, e:
            print 'Priority %s failed:' % arg[0], e

    def _do_enum_list(self, type):
        data = self.db_execsql("SELECT name FROM enum WHERE type='%s'"
                               % type)
        self.print_listing(['Possible Values'], data)

    def _do_enum_add(self, type, name):
        sql = ("INSERT INTO enum('value','type','name') "
               " SELECT 1+ifnull(max(value),0),'%(type)s','%(name)s'"
               "   FROM enum WHERE type='%(type)s'" 
               % {'type':type,
                  'name':name})
        data = self.db_execsql(sql)

    def _do_enum_change(self, type, name, newname):
        d = {'name':name, 'newname':newname, 'type':type}
        data = self.db_execsql("SELECT name FROM enum" 
                               " WHERE type='%(type)s' AND name='%(name)s'" % d)
        if not data:
            raise Exception, "No such value '%s'" % name
        data = self.db_execsql("UPDATE enum SET name='%(newname)s'" 
                               " WHERE type='%(type)s' AND name='%(name)s'" % d)

    def _do_enum_remove(self, type, name):
        data = self.db_execsql("SELECT name FROM enum" 
                               " WHERE type='%s' AND name='%s'" % (type, name))
        if not data:
            raise Exception, "No such value '%s'" % name
        data = self.db_execsql("DELETE FROM enum WHERE type='%s' AND name='%s'"
                               % (type, name))


    ## Milestone
    _help_milestone = [('milestone list', 'Show milestones'),
                       ('milestone add <name> [time]', 'Add milestone'),
                       ('milestone rename <name> <newname>',
                        'Rename milestone'),
                       ('milestone time <name> <time>', 'Set milestone date/time'),
                       ('milestone remove <name>', 'Remove milestone')]

    def complete_milestone (self, text, line, begidx, endidx):

        if begidx in [15,17]:
            comp = self.get_milestone_list ()
        elif begidx < 15:
            comp = ['list','add','rename','time','remove']
        return self.word_complete(text, comp)

    def do_milestone(self, line):
        self._do_mile_ver('milestone', line)


    ## Version
    _help_version = [('version list', 'Show versions'),
                       ('version add <name> [time]', 'Add version'),
                       ('version rename <name> <newname>',
                        'Rename version'),
                       ('version time <name> <time>', 'Set version date/time'),
                       ('version remove <name>', 'Remove version')]

    def complete_version (self, text, line, begidx, endidx):

        if begidx in [15,17]:
            comp = self.get_version_list ()
        elif begidx < 15:
            comp = ['list','add','rename','time','remove']
        return self.word_complete(text, comp)

    def do_version(self, line):
        self._do_mile_ver('version', line)

        
    # Milestone and Version are identical,  methods

    def _do_mile_ver(self, type, line):
        arg = self.arg_tokenize(line)
        try:
            if arg[0]  == 'list':
                self._do_mile_ver_list(type)
            elif arg[0] == 'add' and len(arg) in [2,3]:
                name = arg[1]
                time = len(arg) == 3 and arg[2]
                self._do_mile_ver_add(type, name, time)
            elif arg[0] == 'rename'  and len(arg)==3:
                name = arg[1]
                newname = arg[2]
                self._do_mile_ver_rename(type, name, newname)
            elif arg[0] == 'time'  and len(arg)==3:
                name = arg[1]
                time = arg[2]
                self._do_mile_ver_time(type, name, time)
            elif arg[0] == 'remove'  and len(arg)==2:
                name = arg[1]
                self._do_mile_ver_remove(type, name)
            else:    
                self.do_help (type)
        except Exception, e:
            print 'Command %s failed:' % arg[0], e

    def _do_mile_ver_list(self, type):
        data = self.db_execsql("SELECT name,time FROM %s ORDER BY time,name"
                               % type)
        self.print_listing(['Name', 'Time'], data)

    def _do_mile_ver_rename(self, type, name, newname):
        d = {'name':name, 'newname':newname, 'type':type}
        data = self.db_execsql("SELECT name FROM %(type)s" 
                               " WHERE name='%(name)s'" % d)
        if not data:
            raise Exception, "No such %s '%s'" % (type, name)
        data = self.db_execsql("UPDATE %(type)s SET name='%(newname)s'" 
                               " WHERE name='%(name)s'" % d)

    def _do_mile_ver_add(self, type, name, time):
        sql = ("INSERT INTO %(type)s('name','time') "
               " VALUES('%(name)s', '%(time)s')" 
               % {'type':type, 'name':name, 'time':time})
        data = self.db_execsql(sql)
        
    def _do_mile_ver_remove(self, type, name):
        d = {'name':name, 'type':type}
        data = self.db_execsql("SELECT name FROM %(type)s" 
                               " WHERE name='%(name)s'" % d)
        if not data:
            raise Exception, "No such %s '%s'" % (type, name)
        data = self.db_execsql("DELETE FROM %(type)s" 
                               " WHERE name='%(name)s'" % d)



## ---------------------------------------------------------------------------

##
## Main
##

def main():
    tracadm = TracAdmin()
    if len (sys.argv) > 1:
        if sys.argv[1] in ['-h','--help','help']:
            tracadm.docmd ("help")
        elif sys.argv[1] in ['-v','--version','about']:
            tracadm.docmd ("about")
        else:
            tracadm.db_set(sys.argv[1])
            if len (sys.argv) > 2:
                s_args = ' '.join(["'%s'" % c for c in sys.argv[3:]])
                command = sys.argv[2] + ' ' +s_args
                tracadm.docmd (command)
            else:
                while 1:
                    tracadm.run()
    else:
        tracadm.docmd ("help")




if __name__ == '__main__':
    main()