Source

trac-ticketlinks / scripts / trac-admin

Full commit
   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
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
__author__ = 'Daniel Lundin <daniel@edgewall.com>, Jonas Borgström <jonas@edgewall.com>'
__copyright__ = 'Copyright (c) 2004 Edgewall Software'
__license__ = """
 Copyright (C) 2003, 2004 Edgewall Software
 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

from trac import util
from trac import sync
import trac.siteconfig
import trac.Environment

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':trac.__version__ }
    ruler = ''
    prompt = "Trac> "
    __env = None
    
    def __init__(self,envdir=None):
        cmd.Cmd.__init__(self)
        self.interactive = 0
        if envdir:
            self.env_set(os.path.abspath(envdir))

    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':trac.__version__,'copy':__copyright__}
        while 1:
            try:
                self.cmdloop()
                break
            except KeyboardInterrupt:
                print "\n** Interrupt. Use 'quit' to exit **"

    ##
    ## Environment methods
    ##

    def env_set(self, envname):
        self.envname = envname
        self.prompt = "Trac [%s]> " % self.envname

    def env_check(self):
        try:
            self.__env = trac.Environment.Environment(self.envname)
        except:
            return 0
        return 1
        
    def env_create(self):
        try:
            self.__env = trac.Environment.Environment (self.envname, create=1)
            return self.__env
        except Exception, e:
            print 'Failed to create environment.', e
            sys.exit(1)

    def db_open(self):
        try:
            if not self.__env:
                self.__env = trac.Environment.Environment (self.envname)
            return self.__env.get_db_cnx()
        except Exception, e:
            print 'Failed to open environment.', 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 username 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,justdirs=0):
        dname = os.path.dirname(pathstr)
        d = os.path.join(os.getcwd(), dname)
        dlist = os.listdir(d)
        if justdirs:
            result = []
            for entry in dlist:
                try:
                    if os.path.isdir(entry):
                        result.append(entry)
                except:
                    pass
        else:
            result = dlist
        return result

    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_initenv + self._help_hotcopy +
                    self._help_resync + self._help_upgrade +
                    self._help_wiki +
#                    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' % trac.__version__
            if not self.interactive:
                print
                print "Usage: trac-admin </path/to/projenv> [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' % trac.__version__
        print '================================================================='
        print self.license
        print self.credits


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

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

    do_exit = do_quit # Alias
    do_EOF = do_quit # Alias

#    ## 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):
        cnx = self.db_open()
        cursor = cnx.cursor ()
        cursor.execute('SELECT name FROM component WHERE name=%s', name)
        data = cursor.fetchone()
        if not data:
            raise Exception("No such component '%s'" % name)
        self.db_execsql("UPDATE component SET name='%s' WHERE name='%s'"
                        % (newname,name), cursor)
        self.db_execsql("UPDATE ticket SET component='%s' WHERE component='%s'"
                        % (newname,name), cursor)
        cnx.commit()

    def _do_component_remove(self, name):
        cnx = self.db_open()
        cursor = cnx.cursor ()
        cursor.execute('SELECT name FROM component WHERE name=%s', name)
        data = cursor.fetchone()
        if not data:
            raise Exception("No such component '%s'" % name)
        data = self.db_execsql("DELETE FROM component WHERE name='%s'"
                               % (name))

    def _do_component_set_owner(self, name, owner):
        cnx = self.db_open()
        cursor = cnx.cursor ()
        cursor.execute('SELECT name FROM component WHERE name=%s', name)
        data = cursor.fetchone()
        if not data:
            raise Exception("No such component '%s'" % name)
        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> [action] [...]', 'Add a new permission rule'),
                       ('permission remove <user> <action> [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]
                for action in arg[2:]:
                    self._do_permission_add(user, action)
            elif arg[0] == 'remove'  and len(arg) >= 3:
                user = arg[1]
                for action in 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 username, action FROM permission ORDER BY username, action') 
        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 ' MILESTONE_VIEW, MILESTONE_CREATE, MILESTONE_MODIFY, MILESTONE_DELETE, '
        print ' ROADMAP_VIEW, ROADMAP_ADMIN, TIMELINE_VIEW, SEARCH_VIEW, '
        print ' REPORT_SQL_VIEW, CONFIG_VIEW and TRAC_ADMIN.'
        print

    def _do_permission_add(self, user, action):
        if not action.islower() and not action.isupper():
            print 'group-names must be in lower case and permissions in upper case'
            return
        self.db_execsql("INSERT INTO permission VALUES('%s', '%s')" % (user, action))

    def _do_permission_remove(self, user, action):
        sql = "DELETE FROM permission"
        clauses = []
        if action != '*':
            clauses.append("action='%s'" % action)
        if user != '*':
            clauses.append("username='%s'" % user)
        if clauses:
            sql += " WHERE " + " AND ".join(clauses)
        self.db_execsql(sql)

    ## Initenv
    _help_initenv = [('initenv', 'Create and initialize a new environment interactively'),
                     ('initenv <projectname> <repospath> <templatepath>',
                      'Create and initialize a new environment from arguments')]

    def do_initdb(self, line):
        self.do_initenv(line)
        
    def get_initenv_args(self):
        returnvals = []
        print 'Creating a new Trac environment at %s' % self.envname
        print
        print 'Trac will first ask a few questions about your environment '
        print 'in order to initalize and prepare the project database.'
        print
        print " Please enter the name of your project."
        print " This name will be used in page titles and descriptions."
        print
        dp = 'My Project'
        returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp)
        print
        print ' Please specify the absolute path to the project Subversion repository.'
        print ' Repository must be local, and trac-admin requires read+write'
        print ' permission to initialize the Trac database.'
        print
        drp = '/var/svn/test'
        prompt = 'Path to repository [%s]> ' % drp
        returnvals.append(raw_input(prompt) or drp)
        print
        print ' Please enter location of Trac page templates.'
        print ' Default is the location of the site-wide templates installed with Trac.'
        print
        dt = trac.siteconfig.__default_templates_dir__
        prompt = 'Templates directory [%s]> ' % dt
        returnvals.append(raw_input(prompt) or dt)
        return returnvals
         
    def do_initenv(self, line):
        if self.env_check():
            print "Initenv for '%s' failed.\nDoes an environment already exist?" % self.envname
            return
        arg = self.arg_tokenize(line)
        project_name = None
        repository_dir = None
        templates_dir = None
        if len(arg) == 1:
            returnvals = self.get_initenv_args()
            project_name = returnvals[0]
            repository_dir = returnvals[1]
            templates_dir = returnvals[2]
        elif len(arg)!= 3:
            print 'Wrong number of arguments to initenv %d' % len(arg)
            return
        else:
            project_name = arg[0]
            repository_dir = arg[1]
            templates_dir = arg[2]
        from svn import core, repos
        core.apr_initialize()
        pool = core.svn_pool_create(None)
        try:
            # Remove any trailing slash or else subversion might abort
            if not os.path.split(repository_dir)[1]:
                repository_dir = os.path.split(repository_dir)[0]
            rep = repos.svn_repos_open(repository_dir, pool)
            fs_ptr = repos.svn_repos_fs(rep)
        except Exception, e:
            print repository_dir, 'Repository access error: %s' % e
            return
        if not os.access(os.path.join(templates_dir, 'browser.cs'), os.F_OK) \
           or not os.access(os.path.join(templates_dir, 'ticket.cs'), os.F_OK):
            print templates_dir, "doesn't look like a Trac templates directory"
            return
        try:
            print 'Creating and Initializing Project'
            self.env_create()
            cnx = self.__env.get_db_cnx()
            print ' Inserting default data'
            self.__env.insert_default_data()
            
            print ' Configuring Project'
            print '  trac.repository_dir'
            self.__env.set_config('trac', 'repository_dir', repository_dir)
            print '  trac.templates_dir'
            self.__env.set_config('trac', 'templates_dir', templates_dir)
            print '  project.name'
            self.__env.set_config('project', 'name', project_name)
            self.__env.save_config()
            # Add a few default wiki pages
            print ' Installing wiki pages'
            cursor = cnx.cursor()
            self._do_wiki_load(trac.siteconfig.__default_wiki_dir__,cursor)

            print ' Indexing repository'
            sync.sync(cnx, rep, fs_ptr, pool)
        except Exception, e:
            print 'Failed to initialize database.', e
            sys.exit(2)


        print "---------------------------------------------------------------------"
        print
        print 'Project database for \'%s\' created.' % project_name
        print
        print ' Customize settings for your project using the command:'
        print
        print '   trac-admin %s' % self.envname
        print
        print ' Don\'t forget, you also need to copy (or symlink) "trac/cgi-bin/trac.cgi"'
        print ' to you web server\'s /cgi-bin/ directory, and then configure the server.'
        print
        print ' If you\'re using Apache, this config example snippet might be helpful:'
        print
        print '    Alias /trac "/wherever/you/installed/trac/htdocs/"'
        print '    <Location "/cgi-bin/trac.cgi">'
        print '        SetEnv TRAC_ENV "%s"' % self.envname
        print '    </Location>'
        print
        print '    # You need something like this to authenticate users'
        print '    <Location "/cgi-bin/trac.cgi/login">'
        print '        AuthType Basic'
        print '        AuthName "%s"' % project_name
        print '        AuthUserFile /somewhere/trac.htpasswd'
        print '        Require valid-user'
        print '    </Location>'
        print

        print ' The latest documentation can also always be found on the project website:'
        print ' http://projects.edgewall.com/trac/'
        print
        print 'Congratulations!'
        print
        
    _help_resync = [('resync', 'Re-synchronize trac with the repository')]
    
    ## Resync
    def do_resync(self, line):
        from svn import repos, core
        core.apr_initialize()
        pool = core.svn_pool_create(None)

        self.db_open() # We need to call this function to open the env, really stupid

        # Remove any trailing slash or else subversion might abort
        repository_dir = self.__env.get_config('trac', 'repository_dir')
        if not os.path.split(repository_dir)[1]:
            repository_dir = os.path.split(repository_dir)[0]
            
        rep = repos.svn_repos_open(repository_dir, pool)
        fs_ptr = repos.svn_repos_fs(rep)
        
        cnx = self.__env.get_db_cnx()
        print 'resyncing...'
        self.db_execsql("DELETE FROM revision")
        self.db_execsql("DELETE FROM node_change")
        sync.sync(cnx, rep, fs_ptr, pool)
        print 'done.'
        
    ## 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'),
                  ('wiki dump <directory>',
                   'Export all wiki pages to files named by title'),
                  ('wiki load <directory>',
                   'Import all wiki pages from directory'),
                  ('wiki upgrade',
                   'Upgrade default wiki pages to current version')]

    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 argc==2:
            comp = ['list','import','export','dump','load']
        else:
            if argv[1] in ['dump','load']:
                comp = self.get_dir_list(argv[-1], 1)
            elif argv[1] in ['export', 'import']:
                if argc==3:
                    comp = self.get_wiki_list()
                elif argc==4:
                    comp = self.get_dir_list(argv[-1])
        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)
            elif arg[0] == 'dump' and len(arg) in [1,2]:
                dir = (len(arg) == 2 and arg[1]) or ''
                self._do_wiki_dump(dir)
            elif arg[0] == 'load' and len(arg) in [1,2]:
                dir = (len(arg) == 2 and arg[1]) or ''
                self._do_wiki_load(dir)
            elif arg[0] == 'upgrade' and len(arg) == 1:
                self._do_wiki_load(trac.siteconfig.__default_wiki_dir__,
                                   ignore=['WikiStart', 'checkwiki.py'])
            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):
        if not os.path.isfile(filename):
            print "%s is not a file" % filename
            return
        f = open(filename,'r')
        data = util.to_utf8(f.read())

        # Make sure we don't insert the exact same page twice
        old = self.db_execsql("SELECT text FROM wiki "
                              "WHERE name='%s' "
                              "ORDER BY version DESC LIMIT 1" % title, cursor)
        if old and data == old[0][0]:
            print '  %s already up to date.' % title
            return
        
        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)

    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 = open(filename,'w')
            f.write(text)
            f.close()

    def _do_wiki_dump(self, dir):
        pages = self.get_wiki_list()
        for p in pages:
            dst = os.path.join(dir,p)
            print " %s => %s" % (p, dst)
            self._do_wiki_export(p, dst)

    def _do_wiki_load(self, dir,cursor=None, ignore=[]):
        for page in os.listdir(dir):
            if page in ignore:
                continue
            filename = os.path.join(dir, page)
            if os.path.isfile(filename):
                print " %s => %s" % (filename, page)
                self._do_wiki_import(filename, page, cursor)


    ## (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 'Command %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 (Format: "Jun 3, 2003")'),
                       ('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 (Format: "Jun 3, 2003")'),
                       ('version remove <name>', 'Remove version')]

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

        if begidx in [13, 15]:
            comp = self.get_version_list ()
        elif begidx < 13:
            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]
                self._do_mile_ver_add(type, name)
                if len(arg) == 3:
                    time = arg[2]
                    self._do_mile_ver_time(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)
        data = map(lambda x: (x[0], x[1] and time.strftime('%c', time.localtime(x[1]))), data)
        #print data
        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):
        sql = ("INSERT INTO %(type)s('name', 'time') "
               " VALUES('%(name)s', 0)" 
               % {'type':type, 'name':name})
        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)

    def _do_mile_ver_time(self, type, name, t):
        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)
        seconds = None
        t = t.strip()
        if t == 'now':
            seconds = int(time.time())
        else:
            for format in ['%x %X', '%x, %X', '%X %x', '%X, %x', '%x', '%c',
                           '%b %d, %Y']:
                try:
                    pt = time.strptime(t, format)
                    #print pt
                    seconds = str(time.mktime(pt))
                except ValueError:
                    continue
                break
        if seconds == None:
            try:
                seconds = int(t)
            except ValueError:
                pass
        if seconds != None:
            data = self.db_execsql("UPDATE %s SET time='%s'" 
                                   " WHERE name='%s'" % (type, seconds, name))
        else:
            print >> sys.stderr, 'Unknown time format'

    _help_upgrade = [('upgrade', 'Upgrade database to current version.')]
    def do_upgrade(self, line):
        arg = self.arg_tokenize(line)
        do_backup = 1
        if arg[0] in ['-b', '--no-backup']:
            do_backup = 0
        db = self.db_open()
        try:
            curr = self.__env.get_version()
            latest = trac.db_default.db_version
            if  curr < latest:
                print "Upgrade: Upgrading %s to db version %i" % (self.envname, latest)
                if do_backup:
                    print "Upgrade: Backup of old database saved in " \
                          "%s/db/trac.db.%i.bak" % (self.envname, curr)
                else:
                    print "Upgrade: Backup disabled. Non-existant warranty voided."
                self.__env.upgrade(do_backup)
            else:
                print "Upgrade: Database is up to date, no upgrade necessary."
        except Exception, e:
            print "Upgrade failed: ",e

    _help_hotcopy = [('hotcopy <backupdir>', 'Make a hot backup copy of an environment.')]
    def do_hotcopy(self, line):
        arg = self.arg_tokenize(line)
        if arg[0]:
            dest = arg[0]
        else:
            self.do_help('hotcopy')
            return
        cnx=self.db_open()
        # Lock the database while copying files
        cnx.db.execute("BEGIN")
        import shutil
        print 'Hotcopying %s to %s ...' % (self.__env.path, dest),
        try:
            shutil.copytree(self.__env.path, dest, symlinks=1)
            print 'OK'
        except Exception, err:
            print err
        # Unlock database
        cnx.db.execute("ROLLBACK")

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

##
## 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.env_set(os.path.abspath(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()