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