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
 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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
#!/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
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':trac.__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', '236'),
                    ('header_logo', 'height', '73'))),
               ('report',
                 ('id', 'author', 'title', 'sql'),

# Active Ticket
                   (('1', None, 'Active Tickets',
"""
-- List all active tickets by priority
-- Color each row based on priority
-- If a ticket has been accepted, a '*' is appended after the owner's name

SELECT p.value AS __color__,
       id AS ticket, summary, component, version, milestone, severity, 
       (CASE status WHEN 'assigned' THEN owner||' *' ELSE owner END) AS owner,
       time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t, enum p
  WHERE status IN ('new', 'assigned', 'reopened') 
    AND p.name = t.priority AND p.type = 'priority'
  ORDER BY p.value, milestone, severity, time
"""),

# Active Tickets By Version 
                    ('2', None, 'Active Tickets by Version',
"""
-- This report shows how to color results based on priority,
-- group results based on milestone. Last modification time, 
-- description and reporter are included as hidden fields for 
-- a useful RSS export.

SELECT p.value AS __color__,
       version AS __group__,
       id AS ticket, summary, component, version, severity, 
       (CASE status WHEN 'assigned' THEN owner||' *' ELSE owner END) AS owner,
       time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t, enum p
  WHERE status IN ('new', 'assigned', 'reopened') 
    AND p.name = t.priority AND p.type = 'priority'
  ORDER BY (version IS NULL),version, p.value, severity, time
"""),

# Active Tickets By Milestone
                    ('3', None, 'All Tickets by Milestone',
"""
-- This report shows how to color results based on priority,
-- group results based on milestone. Last modification time, 
-- description and reporter are included as hidden fields for 
-- a useful RSS export.

SELECT p.value AS __color__,
       milestone||' Release' AS __group__,
       id AS ticket, summary, component, version, severity, 
       (CASE status WHEN 'assigned' THEN owner||' *' ELSE owner END) AS owner,
       time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t, enum p
  WHERE status IN ('new', 'assigned', 'reopened') 
    AND p.name = t.priority AND p.type = 'priority'
  ORDER BY (milestone IS NULL),milestone, p.value, severity, time
"""),

# Assigned, Active Tickets by Owner
                    ('4', None, 'Assigned, Active Tickets by Owner',
"""
-- List assigned tickets, group by ticket owner, sorted by priority

SELECT p.value AS __color__,
       owner AS __group__,
       id AS ticket, summary, component, milestone, severity, time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t,enum p
  WHERE status = 'assigned'
    AND p.name=t.priority AND p.type='priority'
  ORDER BY owner, p.value, severity, time
"""),

# Assigned, Active Tickets by Owner (Full Description)
                    ('5', None, 'Assigned, Active Tickets by Owner (Full Description)',
"""
-- List tickets assigned, group by ticket owner
-- This report demonstrates the use of full-row display.

SELECT p.value AS __color__,
       owner AS __group__,
       id AS ticket, summary, component, milestone, severity, time AS created,
       description AS _description_,
       changetime AS _changetime, reporter AS _reporter
  FROM ticket t, enum p
  WHERE status = 'assigned'
    AND p.name = t.priority AND p.type = 'priority'
  ORDER BY owner, p.value, severity, time
"""),

# All Tickets By Milestone  (Including closed)
                    ('6', None, 'All Tickets By Milestone  (Including closed)',
"""
-- A more complex example to show how to make advanced reports

SELECT p.value AS __color__,
       t.milestone AS __group__,
       (CASE status 
          WHEN 'closed' THEN 'color: #777; background: #ddd; border-color: #ccc;'
          ELSE 
            (CASE owner WHEN '$USER' THEN 'font-weight: bold' END)
        END) AS __style__,
       id AS ticket, summary, component, status, 
       resolution,version, severity, priority, owner,
       changetime AS modified,
       time AS _time,reporter AS _reporter
  FROM ticket t,enum p
  WHERE p.name=t.priority AND p.type='priority'
  ORDER BY (milestone IS NULL), milestone DESC, (status = 'closed'), 
            (CASE status WHEN 'closed' THEN modified ELSE -p.value END) DESC
"""),

# My Tickets
                    ('7', None, 'My Tickets',
"""
-- This report demonstrates the use of the automatically set 
-- $USER dynamic variable, replaced with the username of the
-- logged in user when executed.

SELECT p.value AS __color__,
       (CASE status WHEN 'assigned' THEN 'Assigned' ELSE 'Owned' END) AS __group__,
       id AS ticket, summary, component, version, milestone,
       severity, priority, time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t, enum p
  WHERE t.status IN ('new', 'assigned', 'reopened') 
    AND p.name = t.priority AND p.type = 'priority' AND owner = '$USER'
  ORDER BY (status = 'assigned') DESC, p.value, milestone, severity, time
"""),

# Active Tickets, Mine first
                    ('8', None, 'Active Tickets, Mine first',
"""
-- List all active tickets by priority
-- Show all tickets owned by the logged in user in a group first.

SELECT p.value AS __color__,
       (CASE owner 
         WHEN '$USER' THEN 'My Tickets' 
         ELSE 'Active Tickets' 
        END) AS __group__,
       id AS ticket, summary, component, version, milestone, severity, 
       (CASE status WHEN 'assigned' THEN owner||' *' ELSE owner END) AS owner,
       time AS created,
       changetime AS _changetime, description AS _description, reporter AS _reporter
  FROM ticket t, enum p
  WHERE status IN ('new', 'assigned', 'reopened') 
    AND p.name = t.priority AND p.type = 'priority'
  ORDER BY (owner = '$USER') DESC, p.value, milestone, severity, time
""")
                    
                    )))  # End of default values
    
    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':trac.__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,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_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' % trac.__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' % trac.__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):
        cnx = sqlite.connect (self.dbname)
        cursor = cnx.cursor ()
        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):
        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 'Creating a new Trac project database at %s' % self.dbname
            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'
            project_name = raw_input('Project Name [%s]> ' % dp) or dp

            from svn import util, repos, core
            core.apr_initialize()
            pool = core.svn_pool_create(None)
            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
            while 1:
                try:
                    drp = '/var/svn/test'
                    prompt = 'Path to repository [%s]> ' % drp
                    repository_dir = raw_input(prompt) or drp
                    
                    # 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)
                    break
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except Exception, e:
                    print repository_dir, 'Repository access error: %s' % e

            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
            while 1:
                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 '\n* initdb aborted'
            return
        try:
            print 'Creating and Initializing Project'
            cnx = sqlite.connect (self.dbname)
            cursor = cnx.cursor ()
            print ' Creating tables'
            self.initdb_create_tables(cursor)
            print ' Inserting default data'
            self.initdb_insert_default_data (cursor)
            cnx.commit()

            print ' Configuring Project'
            print '  general.repository_dir'
            self._do_config_set('general.repository_dir', repository_dir)
            print '  general.templates_dir'
            self._do_config_set('general.templates_dir', templates_dir)
            print '  project.name'
            self._do_config_set('project.name', project_name)
            # Add a few default wiki pages
            print ' Installing wiki pages'
            self._do_wiki_load(trac.siteconfig.__default_wiki_dir__,cursor)
            cnx.commit()

            from trac import sync, db
            print ' Indexing repository'
            sync.sync(cnx, rep, fs_ptr, pool)
            print 'Done.'
        except Exception, e:
            print 'Failed to initialize database.', e
            cnx.rollback()


        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.dbname
        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_DB "%s"' % self.dbname
	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

    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'),
                  ('wiki dump <directory>',
                   'Export all wiki pages to files named by title'),
                  ('wiki load <directory>',
                   'Import all wiki pages from directory')]

    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'])
            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=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 '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()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.