/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1 by mbp at sourcefrog
import from baz patch-364
1
#! /usr/bin/python
2
3
4
# Copyright (C) 2004, 2005 by Martin Pool
5
# Copyright (C) 2005 by Canonical Ltd
6
7
8
# This program is free software; you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation; either version 2 of the License, or
11
# (at your option) any later version.
12
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
# GNU General Public License for more details.
17
18
# You should have received a copy of the GNU General Public License
19
# along with this program; if not, write to the Free Software
20
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22
"""Bazaar-NG -- a free distributed version-control tool
23
24
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
25
26
Current limitation include:
27
28
* Metadata format is not stable yet -- you may need to
29
  discard history in the future.
30
31
* No handling of subdirectories, symlinks or any non-text files.
32
33
* Insufficient error handling.
34
35
* Many commands unimplemented or partially implemented.
36
37
* Space-inefficient storage.
38
39
* No merge operators yet.
40
41
Interesting commands::
42
43
  bzr help
44
       Show summary help screen
45
  bzr version
46
       Show software version/licence/non-warranty.
47
  bzr init
48
       Start versioning the current directory
49
  bzr add FILE...
50
       Make files versioned.
51
  bzr log
52
       Show revision history.
53
  bzr diff
54
       Show changes from last revision to working copy.
55
  bzr commit -m 'MESSAGE'
56
       Store current state as new revision.
57
  bzr export REVNO DESTINATION
58
       Export the branch state at a previous version.
59
  bzr status
60
       Show summary of pending changes.
61
  bzr remove FILE...
62
       Make a file not versioned.
76 by mbp at sourcefrog
mention "info" in top-level help
63
  bzr info
64
       Show statistics about this branch.
1 by mbp at sourcefrog
import from baz patch-364
65
"""
66
67
68
69
__copyright__ = "Copyright 2005 Canonical Development Ltd."
70
__author__ = "Martin Pool <mbp@canonical.com>"
71
__docformat__ = "restructuredtext en"
72
__version__ = '0.0.0'
73
74
75
import sys, os, random, time, sha, sets, types, re, shutil, tempfile
76
import traceback, socket, fnmatch, difflib
77
from os import path
78
from sets import Set
79
from pprint import pprint
80
from stat import *
81
from glob import glob
82
83
import bzrlib
84
from bzrlib.store import ImmutableStore
85
from bzrlib.trace import mutter, note, log_error
86
from bzrlib.errors import bailout, BzrError
87
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
88
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
89
from bzrlib.revision import Revision
90
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
91
     format_date
92
93
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
94
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
95
96
## standard representation
97
NONE_STRING = '(none)'
98
EMPTY = 'empty'
99
100
101
## TODO: Perhaps a different version of inventory commands that
102
## returns iterators...
103
104
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
105
106
## TODO: Some kind of locking on branches.  Perhaps there should be a
107
## parameter to the branch object saying whether we want a read or
108
## write lock; release it from destructor.  Perhaps don't even need a
109
## read lock to look at immutable objects?
110
111
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
112
## to compare output?
113
34 by mbp at sourcefrog
doc
114
## TODO: Some kind of global code to generate the right Branch object
115
## to work on.  Almost, but not quite all, commands need one, and it
116
## can be taken either from their parameters or their working
117
## directory.
118
46 by Martin Pool
todo
119
## TODO: rename command, needed soon: check destination doesn't exist
120
## either in working copy or tree; move working copy; update
121
## inventory; write out
122
123
## TODO: move command; check destination is a directory and will not
124
## clash; move it.
125
126
## TODO: command to show renames, one per line, as to->from
127
128
1 by mbp at sourcefrog
import from baz patch-364
129
130
131
def cmd_status(all=False):
132
    """Display status summary.
133
134
    For each file there is a single line giving its file state and name.
135
    The name is that in the current revision unless it is deleted or
136
    missing, in which case the old name is shown.
137
138
    :todo: Don't show unchanged files unless ``--all`` is given?
139
    """
140
    Branch('.').show_status(show_all=all)
141
142
143
144
######################################################################
145
# examining history
146
def cmd_get_revision(revision_id):
147
    Branch('.').get_revision(revision_id).write_xml(sys.stdout)
148
149
150
def cmd_get_file_text(text_id):
151
    """Get contents of a file by hash."""
152
    sf = Branch('.').text_store[text_id]
153
    pumpfile(sf, sys.stdout)
154
155
156
157
######################################################################
158
# commands
159
    
160
161
def cmd_revno():
162
    """Show number of revisions on this branch"""
163
    print Branch('.').revno()
164
    
165
70 by mbp at sourcefrog
Prepare for smart recursive add.
166
    
1 by mbp at sourcefrog
import from baz patch-364
167
def cmd_add(file_list, verbose=False):
70 by mbp at sourcefrog
Prepare for smart recursive add.
168
    """Add specified files or directories.
169
170
    In non-recursive mode, all the named items are added, regardless
171
    of whether they were previously ignored.  A warning is given if
172
    any of the named files are already versioned.
173
174
    In recursive mode (the default), files are treated the same way
175
    but the behaviour for directories is different.  Directories that
176
    are already versioned do not give a warning.  All directories,
177
    whether already versioned or not, are searched for files or
178
    subdirectories that are neither versioned or ignored, and these
179
    are added.  This search proceeds recursively into versioned
180
    directories.
181
182
    Therefore simply saying 'bzr add .' will version all files that
183
    are currently unknown.
184
    """
185
    if True:
186
        bzrlib.add.smart_add(file_list, verbose)
187
    else:
188
        # old way
189
        assert file_list
190
        b = Branch(file_list[0], find_root=True)
191
        b.add([b.relpath(f) for f in file_list], verbose=verbose)
192
1 by mbp at sourcefrog
import from baz patch-364
193
    
194
68 by mbp at sourcefrog
- new relpath command and function
195
def cmd_relpath(filename):
196
    print Branch(filename).relpath(filename)
197
198
1 by mbp at sourcefrog
import from baz patch-364
199
def cmd_inventory(revision=None):
200
    """Show inventory of the current working copy."""
201
    ## TODO: Also optionally show a previous inventory
202
    ## TODO: Format options
203
    b = Branch('.')
204
    if revision == None:
205
        inv = b.read_working_inventory()
206
    else:
207
        inv = b.get_revision_inventory(b.lookup_revision(revision))
208
        
209
    for path, entry in inv.iter_entries():
210
        print '%-50s %s' % (entry.file_id, path)
211
212
213
214
def cmd_info():
215
    b = Branch('.')
216
    print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
21 by mbp at sourcefrog
- bzr info: show summary information on branch history
217
218
    def plural(n, base='', pl=None):
219
        if n == 1:
220
            return base
221
        elif pl is not None:
222
            return pl
223
        else:
224
            return 's'
18 by mbp at sourcefrog
show count of versioned/unknown/ignored files
225
226
    count_version_dirs = 0
19 by mbp at sourcefrog
more information in info command
227
228
    count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
229
    for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
230
        fs = st_tup[0]
231
        count_status[fs] += 1
232
        if fs not in ['I', '?'] and st_tup[4] == 'directory':
233
            count_version_dirs += 1
234
235
    print
236
    print 'in the working tree:'
237
    for name, fs in (('unchanged', '.'),
238
                     ('modified', 'M'), ('added', 'A'), ('removed', 'D'),
239
                     ('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
240
                     ):
241
        print '  %5d %s' % (count_status[fs], name)
21 by mbp at sourcefrog
- bzr info: show summary information on branch history
242
    print '  %5d versioned subdirector%s' % (count_version_dirs,
243
                                             plural(count_version_dirs, 'y', 'ies'))
244
245
    print
246
    print 'branch history:'
247
    history = b.revision_history()
248
    revno = len(history)
249
    print '  %5d revision%s' % (revno, plural(revno))
250
    committers = Set()
251
    for rev in history:
252
        committers.add(b.get_revision(rev).committer)
253
    print '  %5d committer%s' % (len(committers), plural(len(committers)))
254
    if revno > 0:
255
        firstrev = b.get_revision(history[0])
256
        age = int((time.time() - firstrev.timestamp) / 3600 / 24)
257
        print '  %5d day%s old' % (age, plural(age))
22 by mbp at sourcefrog
bzr info: show date of first and latest commit
258
        print '  first revision: %s' % format_date(firstrev.timestamp,
259
                                                 firstrev.timezone)
260
261
        lastrev = b.get_revision(history[-1])
262
        print '  latest revision: %s' % format_date(lastrev.timestamp,
263
                                                    lastrev.timezone)
264
        
21 by mbp at sourcefrog
- bzr info: show summary information on branch history
265
    
1 by mbp at sourcefrog
import from baz patch-364
266
267
268
def cmd_remove(file_list, verbose=False):
69 by Martin Pool
handle add, remove, file-id being given filenames that are
269
    b = Branch(file_list[0])
270
    b.remove([b.relpath(f) for f in file_list], verbose=verbose)
1 by mbp at sourcefrog
import from baz patch-364
271
272
273
274
def cmd_file_id(filename):
69 by Martin Pool
handle add, remove, file-id being given filenames that are
275
    b = Branch(filename)
276
    i = b.inventory.path2id(b.relpath(filename))
1 by mbp at sourcefrog
import from baz patch-364
277
    if i is None:
278
        bailout("%s is not a versioned file" % filename)
279
    else:
280
        print i
281
282
283
def cmd_find_filename(fileid):
284
    n = find_filename(fileid)
285
    if n is None:
286
        bailout("%s is not a live file id" % fileid)
287
    else:
288
        print n
289
290
291
def cmd_revision_history():
292
    for patchid in Branch('.').revision_history():
293
        print patchid
294
295
296
297
def cmd_init():
298
    # TODO: Check we're not already in a working directory?  At the
299
    # moment you'll get an ugly error.
300
    
301
    # TODO: What if we're in a subdirectory of a branch?  Would like
302
    # to allow that, but then the parent may need to understand that
303
    # the children have disappeared, or should they be versioned in
304
    # both?
305
306
    # TODO: Take an argument/option for branch name.
307
    Branch('.', init=True)
308
309
310
def cmd_diff(revision=None):
311
    """Show diff from basis to working copy.
312
313
    :todo: Take one or two revision arguments, look up those trees,
314
           and diff them.
315
316
    :todo: Allow diff across branches.
317
318
    :todo: Mangle filenames in diff to be more relevant.
319
320
    :todo: Shouldn't be in the cmd function.
321
    """
322
323
    b = Branch('.')
324
325
    if revision == None:
326
        old_tree = b.basis_tree()
327
    else:
328
        old_tree = b.revision_tree(b.lookup_revision(revision))
329
        
330
    new_tree = b.working_tree()
331
    old_inv = old_tree.inventory
332
    new_inv = new_tree.inventory
333
334
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
335
    old_label = ''
336
    new_label = ''
337
338
    DEVNULL = '/dev/null'
339
    # Windows users, don't panic about this filename -- it is a
340
    # special signal to GNU patch that the file should be created or
341
    # deleted respectively.
342
343
    # TODO: Generation of pseudo-diffs for added/deleted files could
344
    # be usefully made into a much faster special case.
345
346
    # TODO: Better to return them in sorted order I think.
347
    
348
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
349
        d = None
350
351
        # Don't show this by default; maybe do it if an option is passed
352
        # idlabel = '      {%s}' % fid
353
        idlabel = ''
354
355
        # FIXME: Something about the diff format makes patch unhappy
356
        # with newly-added files.
357
358
        def diffit(*a, **kw):
359
            sys.stdout.writelines(difflib.unified_diff(*a, **kw))
360
            print
361
        
362
        if file_state in ['.', '?', 'I']:
363
            continue
364
        elif file_state == 'A':
365
            print '*** added %s %r' % (kind, new_name)
366
            if kind == 'file':
367
                diffit([],
368
                       new_tree.get_file(fid).readlines(),
369
                       fromfile=DEVNULL,
370
                       tofile=new_label + new_name + idlabel)
371
        elif file_state == 'D':
372
            assert isinstance(old_name, types.StringTypes)
373
            print '*** deleted %s %r' % (kind, old_name)
374
            if kind == 'file':
375
                diffit(old_tree.get_file(fid).readlines(), [],
376
                       fromfile=old_label + old_name + idlabel,
377
                       tofile=DEVNULL)
378
        elif file_state in ['M', 'R']:
379
            if file_state == 'M':
380
                assert kind == 'file'
381
                assert old_name == new_name
382
                print '*** modified %s %r' % (kind, new_name)
383
            elif file_state == 'R':
384
                print '*** renamed %s %r => %r' % (kind, old_name, new_name)
385
386
            if kind == 'file':
387
                diffit(old_tree.get_file(fid).readlines(),
388
                       new_tree.get_file(fid).readlines(),
389
                       fromfile=old_label + old_name + idlabel,
390
                       tofile=new_label + new_name)
391
        else:
392
            bailout("can't represent state %s {%s}" % (file_state, fid))
393
394
395
65 by mbp at sourcefrog
rename 'find-branch-root' command to just 'root'
396
def cmd_root(filename=None):
397
    """Print the branch root."""
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
398
    print bzrlib.branch.find_branch_root(filename)
399
    
400
13 by mbp at sourcefrog
fix up cmd_log args
401
def cmd_log(timezone='original'):
1 by mbp at sourcefrog
import from baz patch-364
402
    """Show log of this branch.
403
404
    :todo: Options for utc; to show ids; to limit range; etc.
405
    """
12 by mbp at sourcefrog
new --timezone option for bzr log
406
    Branch('.').write_log(show_timezone=timezone)
1 by mbp at sourcefrog
import from baz patch-364
407
408
409
def cmd_ls(revision=None, verbose=False):
410
    """List files in a tree.
411
412
    :todo: Take a revision or remote path and list that tree instead.
413
    """
414
    b = Branch('.')
415
    if revision == None:
416
        tree = b.working_tree()
417
    else:
418
        tree = b.revision_tree(b.lookup_revision(revision))
419
        
420
    for fp, fc, kind, fid in tree.list_files():
421
        if verbose:
422
            if kind == 'directory':
423
                kindch = '/'
424
            elif kind == 'file':
425
                kindch = ''
426
            else:
427
                kindch = '???'
428
                
429
            print '%-8s %s%s' % (fc, fp, kindch)
430
        else:
431
            print fp
432
    
433
    
434
435
def cmd_unknowns():
436
    """List unknown files"""
437
    for f in Branch('.').unknowns():
438
        print quotefn(f)
439
440
441
def cmd_lookup_revision(revno):
442
    try:
443
        revno = int(revno)
444
    except ValueError:
445
        bailout("usage: lookup-revision REVNO",
446
                ["REVNO is a non-negative revision number for this branch"])
447
448
    print Branch('.').lookup_revision(revno) or NONE_STRING
449
450
451
452
def cmd_export(revno, dest):
453
    """Export past revision to destination directory."""
454
    b = Branch('.')
455
    rh = b.lookup_revision(int(revno))
456
    t = b.revision_tree(rh)
457
    t.export(dest)
458
459
460
461
######################################################################
462
# internal/test commands
463
464
465
def cmd_uuid():
466
    """Print a newly-generated UUID."""
63 by mbp at sourcefrog
fix up uuid command
467
    print bzrlib.osutils.uuid()
1 by mbp at sourcefrog
import from baz patch-364
468
469
470
8 by mbp at sourcefrog
store committer's timezone in revision and show
471
def cmd_local_time_offset():
472
    print bzrlib.osutils.local_time_offset()
473
474
475
57 by mbp at sourcefrog
error if --message is not given for commit
476
def cmd_commit(message=None, verbose=False):
477
    if not message:
478
        bailout("please specify a commit message")
1 by mbp at sourcefrog
import from baz patch-364
479
    Branch('.').commit(message, verbose=verbose)
480
481
482
def cmd_check():
483
    """Check consistency of the branch."""
484
    check()
485
486
487
def cmd_is(pred, *rest):
488
    """Test whether PREDICATE is true."""
489
    try:
490
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
491
    except KeyError:
492
        bailout("unknown predicate: %s" % quotefn(pred))
493
        
494
    try:
495
        cmd_handler(*rest)
496
    except BzrCheckError:
497
        # by default we don't print the message so that this can
498
        # be used from shell scripts without producing noise
499
        sys.exit(1)
500
501
502
def cmd_username():
503
    print bzrlib.osutils.username()
504
505
506
def cmd_user_email():
507
    print bzrlib.osutils.user_email()
508
509
510
def cmd_gen_revision_id():
511
    import time
512
    print bzrlib.branch._gen_revision_id(time.time())
513
514
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
515
def cmd_selftest(verbose=False):
516
    """Run internal test suite"""
1 by mbp at sourcefrog
import from baz patch-364
517
    ## -v, if present, is seen by doctest; the argument is just here
518
    ## so our parser doesn't complain
519
520
    ## TODO: --verbose option
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
521
522
    failures, tests = 0, 0
1 by mbp at sourcefrog
import from baz patch-364
523
    
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
524
    import doctest, bzrlib.store, bzrlib.tests
1 by mbp at sourcefrog
import from baz patch-364
525
    bzrlib.trace.verbose = False
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
526
527
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
70 by mbp at sourcefrog
Prepare for smart recursive add.
528
        bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
529
        mf, mt = doctest.testmod(m)
530
        failures += mf
531
        tests += mt
532
        print '%-40s %3d tests' % (m.__name__, mt),
533
        if mf:
534
            print '%3d FAILED!' % mf
535
        else:
536
            print
537
538
    print '%-40s %3d tests' % ('total', tests),
539
    if failures:
540
        print '%3d FAILED!' % failures
541
    else:
542
        print
543
544
545
546
# deprecated
547
cmd_doctest = cmd_selftest
53 by mbp at sourcefrog
'selftest' command instead of 'doctest'
548
549
1 by mbp at sourcefrog
import from baz patch-364
550
######################################################################
551
# help
552
553
554
def cmd_help():
555
    # TODO: Specific help for particular commands
556
    print __doc__
557
558
559
def cmd_version():
560
    print "bzr (bazaar-ng) %s" % __version__
561
    print __copyright__
562
    print "http://bazaar-ng.org/"
563
    print
564
    print \
565
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
566
you may use, modify and redistribute it under the terms of the GNU 
567
General Public License version 2 or later."""
568
569
570
def cmd_rocks():
571
    """Statement of optimism."""
572
    print "it sure does!"
573
574
575
576
######################################################################
577
# main routine
578
579
580
# list of all available options; the rhs can be either None for an
581
# option that takes no argument, or a constructor function that checks
582
# the type.
583
OPTIONS = {
584
    'all':                    None,
585
    'help':                   None,
586
    'message':                unicode,
587
    'revision':               int,
588
    'show-ids':               None,
12 by mbp at sourcefrog
new --timezone option for bzr log
589
    'timezone':               str,
1 by mbp at sourcefrog
import from baz patch-364
590
    'verbose':                None,
591
    'version':                None,
592
    }
593
594
SHORT_OPTIONS = {
595
    'm':                      'message',
596
    'r':                      'revision',
597
    'v':                      'verbose',
598
}
599
600
# List of options that apply to particular commands; commands not
601
# listed take none.
602
cmd_options = {
603
    'add':                    ['verbose'],
604
    'commit':                 ['message', 'verbose'],
605
    'diff':                   ['revision'],
606
    'inventory':              ['revision'],
12 by mbp at sourcefrog
new --timezone option for bzr log
607
    'log':                    ['show-ids', 'timezone'],
1 by mbp at sourcefrog
import from baz patch-364
608
    'ls':                     ['revision', 'verbose'],
12 by mbp at sourcefrog
new --timezone option for bzr log
609
    'remove':                 ['verbose'],
1 by mbp at sourcefrog
import from baz patch-364
610
    'status':                 ['all'],
611
    }
612
613
614
cmd_args = {
615
    'init':                   [],
616
    'add':                    ['file+'],
617
    'commit':                 [],
618
    'diff':                   [],
619
    'file-id':                ['filename'],
65 by mbp at sourcefrog
rename 'find-branch-root' command to just 'root'
620
    'root':                   ['filename?'],
68 by mbp at sourcefrog
- new relpath command and function
621
    'relpath':                ['filename'],
1 by mbp at sourcefrog
import from baz patch-364
622
    'get-file-text':          ['text_id'],
623
    'get-inventory':          ['inventory_id'],
624
    'get-revision':           ['revision_id'],
625
    'get-revision-inventory': ['revision_id'],
626
    'log':                    [],
627
    'lookup-revision':        ['revno'],
628
    'export':                 ['revno', 'dest'],
629
    'remove':                 ['file+'],
630
    'status':                 [],
631
    }
632
633
634
def parse_args(argv):
635
    """Parse command line.
636
    
637
    Arguments and options are parsed at this level before being passed
638
    down to specific command handlers.  This routine knows, from a
639
    lookup table, something about the available options, what optargs
640
    they take, and which commands will accept them.
641
31 by Martin Pool
fix up parse_args doctest
642
    >>> parse_args('--help'.split())
1 by mbp at sourcefrog
import from baz patch-364
643
    ([], {'help': True})
31 by Martin Pool
fix up parse_args doctest
644
    >>> parse_args('--version'.split())
1 by mbp at sourcefrog
import from baz patch-364
645
    ([], {'version': True})
31 by Martin Pool
fix up parse_args doctest
646
    >>> parse_args('status --all'.split())
1 by mbp at sourcefrog
import from baz patch-364
647
    (['status'], {'all': True})
31 by Martin Pool
fix up parse_args doctest
648
    >>> parse_args('commit --message=biter'.split())
17 by mbp at sourcefrog
allow --option=ARG syntax
649
    (['commit'], {'message': u'biter'})
1 by mbp at sourcefrog
import from baz patch-364
650
    """
651
    args = []
652
    opts = {}
653
654
    # TODO: Maybe handle '--' to end options?
655
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
656
    while argv:
657
        a = argv.pop(0)
1 by mbp at sourcefrog
import from baz patch-364
658
        if a[0] == '-':
17 by mbp at sourcefrog
allow --option=ARG syntax
659
            optarg = None
1 by mbp at sourcefrog
import from baz patch-364
660
            if a[1] == '-':
661
                mutter("  got option %r" % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
662
                if '=' in a:
663
                    optname, optarg = a[2:].split('=', 1)
664
                else:
665
                    optname = a[2:]
1 by mbp at sourcefrog
import from baz patch-364
666
                if optname not in OPTIONS:
667
                    bailout('unknown long option %r' % a)
668
            else:
669
                shortopt = a[1:]
670
                if shortopt not in SHORT_OPTIONS:
671
                    bailout('unknown short option %r' % a)
672
                optname = SHORT_OPTIONS[shortopt]
673
            
674
            if optname in opts:
675
                # XXX: Do we ever want to support this, e.g. for -r?
676
                bailout('repeated option %r' % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
677
                
1 by mbp at sourcefrog
import from baz patch-364
678
            optargfn = OPTIONS[optname]
679
            if optargfn:
17 by mbp at sourcefrog
allow --option=ARG syntax
680
                if optarg == None:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
681
                    if not argv:
17 by mbp at sourcefrog
allow --option=ARG syntax
682
                        bailout('option %r needs an argument' % a)
683
                    else:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
684
                        optarg = argv.pop(0)
17 by mbp at sourcefrog
allow --option=ARG syntax
685
                opts[optname] = optargfn(optarg)
1 by mbp at sourcefrog
import from baz patch-364
686
                mutter("    option argument %r" % opts[optname])
687
            else:
17 by mbp at sourcefrog
allow --option=ARG syntax
688
                if optarg != None:
689
                    bailout('option %r takes no argument' % optname)
1 by mbp at sourcefrog
import from baz patch-364
690
                opts[optname] = True
691
        else:
692
            args.append(a)
693
694
    return args, opts
695
696
697
698
def _match_args(cmd, args):
699
    """Check non-option arguments match required pattern.
700
701
    >>> _match_args('status', ['asdasdsadasd'])
702
    Traceback (most recent call last):
703
    ...
704
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
705
    >>> _match_args('add', ['asdasdsadasd'])
706
    {'file_list': ['asdasdsadasd']}
707
    >>> _match_args('add', 'abc def gj'.split())
708
    {'file_list': ['abc', 'def', 'gj']}
709
    """
710
    # match argument pattern
711
    argform = cmd_args.get(cmd, [])
712
    argdict = {}
713
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
714
    # all but one.
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
715
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
716
    # step through args and argform, allowing appropriate 0-many matches
1 by mbp at sourcefrog
import from baz patch-364
717
    for ap in argform:
718
        argname = ap[:-1]
719
        if ap[-1] == '?':
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
720
            if args:
721
                argdict[argname] = args.pop(0)
1 by mbp at sourcefrog
import from baz patch-364
722
        elif ap[-1] == '*':
723
            assert 0
724
        elif ap[-1] == '+':
725
            if not args:
726
                bailout("command %r needs one or more %s"
727
                        % (cmd, argname.upper()))
728
            else:
729
                argdict[argname + '_list'] = args[:]
730
                args = []
731
        else:
732
            # just a plain arg
733
            argname = ap
734
            if not args:
735
                bailout("command %r requires argument %s"
736
                        % (cmd, argname.upper()))
737
            else:
738
                argdict[argname] = args.pop(0)
739
            
740
    if args:
741
        bailout("extra arguments to command %s: %r"
742
                % (cmd, args))
743
744
    return argdict
745
746
747
748
def run_bzr(argv):
749
    """Execute a command.
750
751
    This is similar to main(), but without all the trappings for
752
    logging and error handling.
753
    """
754
    try:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
755
        args, opts = parse_args(argv[1:])
1 by mbp at sourcefrog
import from baz patch-364
756
        if 'help' in opts:
757
            # TODO: pass down other arguments in case they asked for
758
            # help on a command name?
759
            cmd_help()
760
            return 0
761
        elif 'version' in opts:
762
            cmd_version()
763
            return 0
764
        cmd = args.pop(0)
765
    except IndexError:
766
        log_error('usage: bzr COMMAND\n')
767
        log_error('  try "bzr help"\n')
768
        return 1
769
            
770
    try:
771
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
772
    except KeyError:
773
        bailout("unknown command " + `cmd`)
774
775
    # TODO: special --profile option to turn on the Python profiler
776
777
    # check options are reasonable
778
    allowed = cmd_options.get(cmd, [])
779
    for oname in opts:
780
        if oname not in allowed:
781
            bailout("option %r is not allowed for command %r"
782
                    % (oname, cmd))
783
784
    cmdargs = _match_args(cmd, args)
785
    cmdargs.update(opts)
786
787
    ret = cmd_handler(**cmdargs) or 0
788
789
790
791
def main(argv):
792
    ## TODO: Handle command-line options; probably know what options are valid for
793
    ## each command
794
795
    ## TODO: If the arguments are wrong, give a usage message rather
796
    ## than just a backtrace.
797
59 by mbp at sourcefrog
lift out tracefile creation code
798
    bzrlib.trace.create_tracefile(argv)
799
    
1 by mbp at sourcefrog
import from baz patch-364
800
    try:
801
        ret = run_bzr(argv)
802
        return ret
803
    except BzrError, e:
804
        log_error('bzr: error: ' + e.args[0] + '\n')
805
        if len(e.args) > 1:
806
            for h in e.args[1]:
807
                log_error('  ' + h + '\n')
808
        return 1
809
    except Exception, e:
810
        log_error('bzr: exception: %s\n' % e)
811
        log_error('    see .bzr.log for details\n')
812
        traceback.print_exc(None, bzrlib.trace._tracefile)
813
        traceback.print_exc(None, sys.stderr)
814
        return 1
815
816
    # TODO: Maybe nicer handling of IOError?
817
818
819
820
if __name__ == '__main__':
821
    sys.exit(main(sys.argv))
822
    ##import profile
823
    ##profile.run('main(sys.argv)')
824