~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-09-01 02:34:38 UTC
  • Revision ID: mbp@sourcefrog.net-20050901023437-bf791a0ef5edae8d
- old docs: clarify that this is not mainly descended from arch anymore

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Martin Pool
2
 
# Copyright (C) 2005 by Canonical Ltd
3
 
 
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
4
2
 
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
16
14
# along with this program; if not, write to the Free Software
17
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
16
 
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
 
 
38
 
  bzr help [COMMAND]
39
 
       Show help screen
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.
58
 
  bzr info
59
 
       Show statistics about this branch.
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
 
17
 
 
18
# TODO: probably should say which arguments are candidates for glob
 
19
# expansion on windows and do that at the command level.
 
20
 
 
21
# TODO: Help messages for options.
 
22
 
 
23
# TODO: Define arguments by objects, rather than just using names.
 
24
# Those objects can specify the expected type of the argument, which
 
25
# would help with validation and shell completion.
 
26
 
 
27
 
 
28
import sys
 
29
import os
72
30
 
73
31
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
 
 
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
 
 
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
 
 
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
 
 
156
 
    
157
 
def cmd_add(file_list, verbose=False):
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
 
    """
175
 
    bzrlib.add.smart_add(file_list, verbose)
176
 
    
177
 
 
178
 
def cmd_relpath(filename):
179
 
    """Show path of file relative to root"""
180
 
    print Branch(filename).relpath(filename)
181
 
 
182
 
 
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():
199
 
    """info: Show statistical information for this branch
200
 
 
201
 
usage: bzr info"""
202
 
    import info
203
 
    info.show_info(Branch('.'))        
204
 
    
205
 
 
206
 
 
207
 
def cmd_remove(file_list, verbose=False):
208
 
    b = Branch(file_list[0])
209
 
    b.remove([b.relpath(f) for f in file_list], verbose=verbose)
210
 
 
211
 
 
212
 
 
213
 
def cmd_file_id(filename):
214
 
    b = Branch(filename)
215
 
    i = b.inventory.path2id(b.relpath(filename))
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):
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.
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
 
 
342
 
def cmd_deleted(show_ids=False):
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
 
 
351
 
    for path, ie in old.inventory.iter_entries():
352
 
        if not new.has_id(ie.file_id):
353
 
            if show_ids:
354
 
                print '%-50s %s' % (path, ie.file_id)
355
 
            else:
356
 
                print path
357
 
                
358
 
    
359
 
 
360
 
 
361
 
def cmd_root(filename=None):
362
 
    """Print the branch root."""
363
 
    print bzrlib.branch.find_branch_root(filename)
364
 
    
365
 
 
366
 
def cmd_log(timezone='original'):
367
 
    """Show log of this branch.
368
 
 
369
 
    :todo: Options for utc; to show ids; to limit range; etc.
370
 
    """
371
 
    Branch('.').write_log(show_timezone=timezone)
372
 
 
373
 
 
374
 
def cmd_ls(revision=None, verbose=False):
375
 
    """List files in a tree.
376
 
 
377
 
    :todo: Take a revision or remote path and list that tree instead.
378
 
    """
379
 
    b = Branch('.')
380
 
    if revision == None:
381
 
        tree = b.working_tree()
382
 
    else:
383
 
        tree = b.revision_tree(b.lookup_revision(revision))
384
 
        
385
 
    for fp, fc, kind, fid in tree.list_files():
386
 
        if verbose:
387
 
            if kind == 'directory':
388
 
                kindch = '/'
389
 
            elif kind == 'file':
390
 
                kindch = ''
391
 
            else:
392
 
                kindch = '???'
393
 
                
394
 
            print '%-8s %s%s' % (fc, fp, kindch)
395
 
        else:
396
 
            print fp
397
 
    
398
 
    
399
 
 
400
 
def cmd_unknowns():
401
 
    """List unknown files"""
402
 
    for f in Branch('.').unknowns():
403
 
        print quotefn(f)
404
 
 
405
 
 
406
 
 
407
 
def cmd_ignored(verbose=True):
408
 
    """List ignored files and the patterns that matched them.
409
 
      """
410
 
    tree = Branch('.').working_tree()
411
 
    for path, file_class, kind, id in tree.list_files():
412
 
        if file_class != 'I':
413
 
            continue
414
 
        ## XXX: Slightly inefficient since this was already calculated
415
 
        pat = tree.is_ignored(path)
416
 
        print '%-50s %s' % (path, pat)
417
 
    
418
 
 
419
 
 
420
 
def cmd_lookup_revision(revno):
421
 
    try:
422
 
        revno = int(revno)
423
 
    except ValueError:
424
 
        bailout("usage: lookup-revision REVNO",
425
 
                ["REVNO is a non-negative revision number for this branch"])
426
 
 
427
 
    print Branch('.').lookup_revision(revno) or NONE_STRING
428
 
 
429
 
 
430
 
 
431
 
def cmd_export(revno, dest):
432
 
    """Export past revision to destination directory."""
433
 
    b = Branch('.')
434
 
    rh = b.lookup_revision(int(revno))
435
 
    t = b.revision_tree(rh)
436
 
    t.export(dest)
437
 
 
438
 
 
439
 
 
440
 
######################################################################
441
 
# internal/test commands
442
 
 
443
 
 
444
 
def cmd_uuid():
445
 
    """Print a newly-generated UUID."""
446
 
    print bzrlib.osutils.uuid()
447
 
 
448
 
 
449
 
 
450
 
def cmd_local_time_offset():
451
 
    print bzrlib.osutils.local_time_offset()
452
 
 
453
 
 
454
 
 
455
 
def cmd_commit(message=None, verbose=False):
456
 
    """Commit changes to a new revision.
457
 
 
458
 
--message MESSAGE
459
 
    Description of changes in this revision; free form text.
460
 
    It is recommended that the first line be a single-sentence
461
 
    summary.
462
 
--verbose
463
 
    Show status of changed files,
464
 
 
465
 
TODO: Commit only selected files.
466
 
 
467
 
TODO: Run hooks on tree to-be-committed, and after commit.
468
 
 
469
 
TODO: Strict commit that fails if there are unknown or deleted files.
470
 
"""
471
 
 
472
 
    if not message:
473
 
        bailout("please specify a commit message")
474
 
    Branch('.').commit(message, verbose=verbose)
475
 
 
476
 
 
477
 
def cmd_check(dir='.'):
478
 
    """check: Consistency check of branch history.
479
 
 
480
 
usage: bzr check [-v] [BRANCH]
481
 
 
482
 
options:
483
 
  --verbose, -v         Show progress of checking.
484
 
 
485
 
This command checks various invariants about the branch storage to
486
 
detect data corruption or bzr bugs.
487
 
"""
488
 
    import bzrlib.check
489
 
    bzrlib.check.check(Branch(dir, find_root=False))
490
 
 
491
 
 
492
 
def cmd_is(pred, *rest):
493
 
    """Test whether PREDICATE is true."""
494
 
    try:
495
 
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
496
 
    except KeyError:
497
 
        bailout("unknown predicate: %s" % quotefn(pred))
498
 
        
499
 
    try:
500
 
        cmd_handler(*rest)
501
 
    except BzrCheckError:
502
 
        # by default we don't print the message so that this can
503
 
        # be used from shell scripts without producing noise
504
 
        sys.exit(1)
505
 
 
506
 
 
507
 
def cmd_username():
508
 
    print bzrlib.osutils.username()
509
 
 
510
 
 
511
 
def cmd_user_email():
512
 
    print bzrlib.osutils.user_email()
513
 
 
514
 
 
515
 
def cmd_gen_revision_id():
516
 
    import time
517
 
    print bzrlib.branch._gen_revision_id(time.time())
518
 
 
519
 
 
520
 
def cmd_selftest(verbose=False):
521
 
    """Run internal test suite"""
522
 
    ## -v, if present, is seen by doctest; the argument is just here
523
 
    ## so our parser doesn't complain
524
 
 
525
 
    ## TODO: --verbose option
526
 
 
527
 
    failures, tests = 0, 0
528
 
    
529
 
    import doctest, bzrlib.store, bzrlib.tests
530
 
    bzrlib.trace.verbose = False
531
 
 
532
 
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
533
 
        bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
534
 
        mf, mt = doctest.testmod(m)
535
 
        failures += mf
536
 
        tests += mt
537
 
        print '%-40s %3d tests' % (m.__name__, mt),
538
 
        if mf:
539
 
            print '%3d FAILED!' % mf
540
 
        else:
541
 
            print
542
 
 
543
 
    print '%-40s %3d tests' % ('total', tests),
544
 
    if failures:
545
 
        print '%3d FAILED!' % failures
546
 
    else:
547
 
        print
548
 
 
549
 
 
550
 
 
551
 
# deprecated
552
 
cmd_doctest = cmd_selftest
553
 
 
554
 
 
555
 
######################################################################
556
 
# help
557
 
 
558
 
 
559
 
def cmd_help(topic=None):
560
 
    if topic == None:
561
 
        print __doc__
562
 
        return
563
 
 
564
 
    # otherwise, maybe the name of a command?
565
 
    try:
566
 
        cmdfn = globals()['cmd_' + topic.replace('-', '_')]
567
 
    except KeyError:
568
 
        bailout("no help for %r" % topic)
569
 
 
570
 
    doc = cmdfn.__doc__
571
 
    if doc == None:
572
 
        bailout("sorry, no detailed help yet for %r" % topic)
573
 
 
574
 
    print doc
575
 
        
576
 
 
577
 
 
578
 
 
579
 
def cmd_version():
580
 
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
581
 
    print bzrlib.__copyright__
582
 
    print "http://bazaar-ng.org/"
583
 
    print
584
 
    print \
585
 
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
586
 
you may use, modify and redistribute it under the terms of the GNU 
587
 
General Public License version 2 or later."""
588
 
 
589
 
 
590
 
def cmd_rocks():
591
 
    """Statement of optimism."""
592
 
    print "it sure does!"
593
 
 
594
 
 
595
 
 
596
 
######################################################################
597
 
# main routine
 
32
import bzrlib.trace
 
33
from bzrlib.trace import mutter, note, log_error, warning
 
34
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
35
from bzrlib.branch import find_branch
 
36
from bzrlib import BZRDIR
 
37
 
 
38
 
 
39
plugin_cmds = {}
 
40
 
 
41
 
 
42
def register_command(cmd):
 
43
    "Utility function to help register a command"
 
44
    global plugin_cmds
 
45
    k = cmd.__name__
 
46
    if k.startswith("cmd_"):
 
47
        k_unsquished = _unsquish_command_name(k)
 
48
    else:
 
49
        k_unsquished = k
 
50
    if not plugin_cmds.has_key(k_unsquished):
 
51
        plugin_cmds[k_unsquished] = cmd
 
52
        mutter('registered plugin command %s', k_unsquished)      
 
53
    else:
 
54
        log_error('Two plugins defined the same command: %r' % k)
 
55
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
56
 
 
57
 
 
58
def _squish_command_name(cmd):
 
59
    return 'cmd_' + cmd.replace('-', '_')
 
60
 
 
61
 
 
62
def _unsquish_command_name(cmd):
 
63
    assert cmd.startswith("cmd_")
 
64
    return cmd[4:].replace('_','-')
 
65
 
 
66
 
 
67
def _parse_revision_str(revstr):
 
68
    """This handles a revision string -> revno.
 
69
 
 
70
    This always returns a list.  The list will have one element for 
 
71
 
 
72
    It supports integers directly, but everything else it
 
73
    defers for passing to Branch.get_revision_info()
 
74
 
 
75
    >>> _parse_revision_str('234')
 
76
    [234]
 
77
    >>> _parse_revision_str('234..567')
 
78
    [234, 567]
 
79
    >>> _parse_revision_str('..')
 
80
    [None, None]
 
81
    >>> _parse_revision_str('..234')
 
82
    [None, 234]
 
83
    >>> _parse_revision_str('234..')
 
84
    [234, None]
 
85
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
86
    [234, 456, 789]
 
87
    >>> _parse_revision_str('234....789') # Error?
 
88
    [234, None, 789]
 
89
    >>> _parse_revision_str('revid:test@other.com-234234')
 
90
    ['revid:test@other.com-234234']
 
91
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
92
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
93
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
94
    ['revid:test@other.com-234234', 23]
 
95
    >>> _parse_revision_str('date:2005-04-12')
 
96
    ['date:2005-04-12']
 
97
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
98
    ['date:2005-04-12 12:24:33']
 
99
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
100
    ['date:2005-04-12T12:24:33']
 
101
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
102
    ['date:2005-04-12,12:24:33']
 
103
    >>> _parse_revision_str('-5..23')
 
104
    [-5, 23]
 
105
    >>> _parse_revision_str('-5')
 
106
    [-5]
 
107
    >>> _parse_revision_str('123a')
 
108
    ['123a']
 
109
    >>> _parse_revision_str('abc')
 
110
    ['abc']
 
111
    """
 
112
    import re
 
113
    old_format_re = re.compile('\d*:\d*')
 
114
    m = old_format_re.match(revstr)
 
115
    if m:
 
116
        warning('Colon separator for revision numbers is deprecated.'
 
117
                ' Use .. instead')
 
118
        revs = []
 
119
        for rev in revstr.split(':'):
 
120
            if rev:
 
121
                revs.append(int(rev))
 
122
            else:
 
123
                revs.append(None)
 
124
        return revs
 
125
    revs = []
 
126
    for x in revstr.split('..'):
 
127
        if not x:
 
128
            revs.append(None)
 
129
        else:
 
130
            try:
 
131
                revs.append(int(x))
 
132
            except ValueError:
 
133
                revs.append(x)
 
134
    return revs
 
135
 
 
136
 
 
137
def get_merge_type(typestring):
 
138
    """Attempt to find the merge class/factory associated with a string."""
 
139
    from merge import merge_types
 
140
    try:
 
141
        return merge_types[typestring][0]
 
142
    except KeyError:
 
143
        templ = '%s%%7s: %%s' % (' '*12)
 
144
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
145
        type_list = '\n'.join(lines)
 
146
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
147
            (typestring, type_list)
 
148
        raise BzrCommandError(msg)
 
149
    
 
150
 
 
151
def get_merge_type(typestring):
 
152
    """Attempt to find the merge class/factory associated with a string."""
 
153
    from merge import merge_types
 
154
    try:
 
155
        return merge_types[typestring][0]
 
156
    except KeyError:
 
157
        templ = '%s%%7s: %%s' % (' '*12)
 
158
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
159
        type_list = '\n'.join(lines)
 
160
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
161
            (typestring, type_list)
 
162
        raise BzrCommandError(msg)
 
163
    
 
164
 
 
165
 
 
166
def _get_cmd_dict(plugins_override=True):
 
167
    import bzrlib.builtins
 
168
    
 
169
    d = {}
 
170
    builtins = bzrlib.builtins.__dict__
 
171
    for name in builtins:
 
172
        if name.startswith("cmd_"):
 
173
            d[_unsquish_command_name(name)] = builtins[name]
 
174
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
175
    if plugins_override:
 
176
        d.update(plugin_cmds)
 
177
    else:
 
178
        d2 = plugin_cmds.copy()
 
179
        d2.update(d)
 
180
        d = d2
 
181
    return d
 
182
 
 
183
    
 
184
def get_all_cmds(plugins_override=True):
 
185
    """Return canonical name and class for all registered commands."""
 
186
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
187
        yield k,v
 
188
 
 
189
 
 
190
def get_cmd_class(cmd, plugins_override=True):
 
191
    """Return the canonical name and command class for a command.
 
192
    """
 
193
    cmd = str(cmd)                      # not unicode
 
194
 
 
195
    # first look up this command under the specified name
 
196
    cmds = _get_cmd_dict(plugins_override=plugins_override)
 
197
    mutter("all commands: %r", cmds.keys())
 
198
    try:
 
199
        return cmd, cmds[cmd]
 
200
    except KeyError:
 
201
        pass
 
202
 
 
203
    # look for any command which claims this as an alias
 
204
    for cmdname, cmdclass in cmds.iteritems():
 
205
        if cmd in cmdclass.aliases:
 
206
            return cmdname, cmdclass
 
207
 
 
208
    cmdclass = ExternalCommand.find_command(cmd)
 
209
    if cmdclass:
 
210
        return cmd, cmdclass
 
211
 
 
212
    raise BzrCommandError("unknown command %r" % cmd)
 
213
 
 
214
 
 
215
class Command(object):
 
216
    """Base class for commands.
 
217
 
 
218
    The docstring for an actual command should give a single-line
 
219
    summary, then a complete description of the command.  A grammar
 
220
    description will be inserted.
 
221
 
 
222
    takes_args
 
223
        List of argument forms, marked with whether they are optional,
 
224
        repeated, etc.
 
225
 
 
226
    takes_options
 
227
        List of options that may be given for this command.
 
228
 
 
229
    hidden
 
230
        If true, this command isn't advertised.
 
231
    """
 
232
    aliases = []
 
233
    
 
234
    takes_args = []
 
235
    takes_options = []
 
236
 
 
237
    hidden = False
 
238
    
 
239
    def __init__(self, options, arguments):
 
240
        """Construct and run the command.
 
241
 
 
242
        Sets self.status to the return value of run()."""
 
243
        assert isinstance(options, dict)
 
244
        assert isinstance(arguments, dict)
 
245
        cmdargs = options.copy()
 
246
        cmdargs.update(arguments)
 
247
        if self.__doc__ == Command.__doc__:
 
248
            from warnings import warn
 
249
            warn("No help message set for %r" % self)
 
250
        self.status = self.run(**cmdargs)
 
251
        if self.status is None:
 
252
            self.status = 0
 
253
 
 
254
    
 
255
    def run(self, *args, **kwargs):
 
256
        """Override this in sub-classes.
 
257
 
 
258
        This is invoked with the options and arguments bound to
 
259
        keyword parameters.
 
260
 
 
261
        Return 0 or None if the command was successful, or a shell
 
262
        error code if not.
 
263
        """
 
264
        raise NotImplementedError()
 
265
 
 
266
 
 
267
class ExternalCommand(Command):
 
268
    """Class to wrap external commands.
 
269
 
 
270
    We cheat a little here, when get_cmd_class() calls us we actually
 
271
    give it back an object we construct that has the appropriate path,
 
272
    help, options etc for the specified command.
 
273
 
 
274
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
275
    the __call__ method, which we override to call the Command.__init__
 
276
    method. That then calls our run method which is pretty straight
 
277
    forward.
 
278
 
 
279
    The only wrinkle is that we have to map bzr's dictionary of options
 
280
    and arguments back into command line options and arguments for the
 
281
    script.
 
282
    """
 
283
 
 
284
    def find_command(cls, cmd):
 
285
        import os.path
 
286
        bzrpath = os.environ.get('BZRPATH', '')
 
287
 
 
288
        for dir in bzrpath.split(os.pathsep):
 
289
            path = os.path.join(dir, cmd)
 
290
            if os.path.isfile(path):
 
291
                return ExternalCommand(path)
 
292
 
 
293
        return None
 
294
 
 
295
    find_command = classmethod(find_command)
 
296
 
 
297
    def __init__(self, path):
 
298
        self.path = path
 
299
 
 
300
        pipe = os.popen('%s --bzr-usage' % path, 'r')
 
301
        self.takes_options = pipe.readline().split()
 
302
 
 
303
        for opt in self.takes_options:
 
304
            if not opt in OPTIONS:
 
305
                raise BzrError("Unknown option '%s' returned by external command %s"
 
306
                               % (opt, path))
 
307
 
 
308
        # TODO: Is there any way to check takes_args is valid here?
 
309
        self.takes_args = pipe.readline().split()
 
310
 
 
311
        if pipe.close() is not None:
 
312
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
 
313
 
 
314
        pipe = os.popen('%s --bzr-help' % path, 'r')
 
315
        self.__doc__ = pipe.read()
 
316
        if pipe.close() is not None:
 
317
            raise BzrError("Failed funning '%s --bzr-help'" % path)
 
318
 
 
319
    def __call__(self, options, arguments):
 
320
        Command.__init__(self, options, arguments)
 
321
        return self
 
322
 
 
323
    def run(self, **kargs):
 
324
        opts = []
 
325
        args = []
 
326
 
 
327
        keys = kargs.keys()
 
328
        keys.sort()
 
329
        for name in keys:
 
330
            optname = name.replace('_','-')
 
331
            value = kargs[name]
 
332
            if OPTIONS.has_key(optname):
 
333
                # it's an option
 
334
                opts.append('--%s' % optname)
 
335
                if value is not None and value is not True:
 
336
                    opts.append(str(value))
 
337
            else:
 
338
                # it's an arg, or arg list
 
339
                if type(value) is not list:
 
340
                    value = [value]
 
341
                for v in value:
 
342
                    if v is not None:
 
343
                        args.append(str(v))
 
344
 
 
345
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
 
346
        return self.status
 
347
 
 
348
 
 
349
 
 
350
def parse_spec(spec):
 
351
    """
 
352
    >>> parse_spec(None)
 
353
    [None, None]
 
354
    >>> parse_spec("./")
 
355
    ['./', None]
 
356
    >>> parse_spec("../@")
 
357
    ['..', -1]
 
358
    >>> parse_spec("../f/@35")
 
359
    ['../f', 35]
 
360
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
361
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
362
    """
 
363
    if spec is None:
 
364
        return [None, None]
 
365
    if '/@' in spec:
 
366
        parsed = spec.split('/@')
 
367
        assert len(parsed) == 2
 
368
        if parsed[1] == "":
 
369
            parsed[1] = -1
 
370
        else:
 
371
            try:
 
372
                parsed[1] = int(parsed[1])
 
373
            except ValueError:
 
374
                pass # We can allow stuff like ./@revid:blahblahblah
 
375
            else:
 
376
                assert parsed[1] >=0
 
377
    else:
 
378
        parsed = [spec, None]
 
379
    return parsed
 
380
 
 
381
 
598
382
 
599
383
 
600
384
# list of all available options; the rhs can be either None for an
602
386
# the type.
603
387
OPTIONS = {
604
388
    'all':                    None,
 
389
    'diff-options':           str,
605
390
    'help':                   None,
 
391
    'file':                   unicode,
 
392
    'force':                  None,
 
393
    'format':                 unicode,
 
394
    'forward':                None,
606
395
    'message':                unicode,
 
396
    'no-recurse':             None,
607
397
    'profile':                None,
608
 
    'revision':               int,
 
398
    'revision':               _parse_revision_str,
 
399
    'short':                  None,
609
400
    'show-ids':               None,
610
401
    'timezone':               str,
611
402
    'verbose':                None,
612
403
    'version':                None,
 
404
    'email':                  None,
 
405
    'unchanged':              None,
 
406
    'update':                 None,
 
407
    'long':                   None,
 
408
    'root':                   str,
 
409
    'no-backup':              None,
 
410
    'merge-type':             get_merge_type,
 
411
    'pattern':                str,
613
412
    }
614
413
 
615
414
SHORT_OPTIONS = {
 
415
    'F':                      'file', 
 
416
    'h':                      'help',
616
417
    'm':                      'message',
617
418
    'r':                      'revision',
618
419
    'v':                      'verbose',
 
420
    'l':                      'long',
619
421
}
620
422
 
621
 
# List of options that apply to particular commands; commands not
622
 
# listed take none.
623
 
cmd_options = {
624
 
    'add':                    ['verbose'],
625
 
    'commit':                 ['message', 'verbose'],
626
 
    'deleted':                ['show-ids'],
627
 
    'diff':                   ['revision'],
628
 
    'inventory':              ['revision'],
629
 
    'log':                    ['timezone'],
630
 
    'ls':                     ['revision', 'verbose'],
631
 
    'remove':                 ['verbose'],
632
 
    'status':                 ['all'],
633
 
    }
634
 
 
635
 
 
636
 
cmd_args = {
637
 
    'add':                    ['file+'],
638
 
    'commit':                 [],
639
 
    'diff':                   [],
640
 
    'export':                 ['revno', 'dest'],
641
 
    'file-id':                ['filename'],
642
 
    'get-file-text':          ['text_id'],
643
 
    'get-inventory':          ['inventory_id'],
644
 
    'get-revision':           ['revision_id'],
645
 
    'get-revision-inventory': ['revision_id'],
646
 
    'help':                   ['topic?'],
647
 
    'init':                   [],
648
 
    'log':                    [],
649
 
    'lookup-revision':        ['revno'],
650
 
    'relpath':                ['filename'],
651
 
    'remove':                 ['file+'],
652
 
    'root':                   ['filename?'],
653
 
    'status':                 [],
654
 
    }
655
 
 
656
423
 
657
424
def parse_args(argv):
658
425
    """Parse command line.
664
431
 
665
432
    >>> parse_args('--help'.split())
666
433
    ([], {'help': True})
 
434
    >>> parse_args('help -- --invalidcmd'.split())
 
435
    (['help', '--invalidcmd'], {})
667
436
    >>> parse_args('--version'.split())
668
437
    ([], {'version': True})
669
438
    >>> parse_args('status --all'.split())
670
439
    (['status'], {'all': True})
671
440
    >>> parse_args('commit --message=biter'.split())
672
441
    (['commit'], {'message': u'biter'})
 
442
    >>> parse_args('log -r 500'.split())
 
443
    (['log'], {'revision': [500]})
 
444
    >>> parse_args('log -r500..600'.split())
 
445
    (['log'], {'revision': [500, 600]})
 
446
    >>> parse_args('log -vr500..600'.split())
 
447
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
448
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
449
    (['log'], {'revision': ['v500', 600]})
673
450
    """
674
451
    args = []
675
452
    opts = {}
676
453
 
677
 
    # TODO: Maybe handle '--' to end options?
678
 
 
 
454
    argsover = False
679
455
    while argv:
680
456
        a = argv.pop(0)
681
 
        if a[0] == '-':
 
457
        if not argsover and a[0] == '-':
 
458
            # option names must not be unicode
 
459
            a = str(a)
682
460
            optarg = None
683
461
            if a[1] == '-':
 
462
                if a == '--':
 
463
                    # We've received a standalone -- No more flags
 
464
                    argsover = True
 
465
                    continue
684
466
                mutter("  got option %r" % a)
685
467
                if '=' in a:
686
468
                    optname, optarg = a[2:].split('=', 1)
687
469
                else:
688
470
                    optname = a[2:]
689
471
                if optname not in OPTIONS:
690
 
                    bailout('unknown long option %r' % a)
 
472
                    raise BzrError('unknown long option %r' % a)
691
473
            else:
692
474
                shortopt = a[1:]
693
 
                if shortopt not in SHORT_OPTIONS:
694
 
                    bailout('unknown short option %r' % a)
695
 
                optname = SHORT_OPTIONS[shortopt]
 
475
                if shortopt in SHORT_OPTIONS:
 
476
                    # Multi-character options must have a space to delimit
 
477
                    # their value
 
478
                    optname = SHORT_OPTIONS[shortopt]
 
479
                else:
 
480
                    # Single character short options, can be chained,
 
481
                    # and have their value appended to their name
 
482
                    shortopt = a[1:2]
 
483
                    if shortopt not in SHORT_OPTIONS:
 
484
                        # We didn't find the multi-character name, and we
 
485
                        # didn't find the single char name
 
486
                        raise BzrError('unknown short option %r' % a)
 
487
                    optname = SHORT_OPTIONS[shortopt]
 
488
 
 
489
                    if a[2:]:
 
490
                        # There are extra things on this option
 
491
                        # see if it is the value, or if it is another
 
492
                        # short option
 
493
                        optargfn = OPTIONS[optname]
 
494
                        if optargfn is None:
 
495
                            # This option does not take an argument, so the
 
496
                            # next entry is another short option, pack it back
 
497
                            # into the list
 
498
                            argv.insert(0, '-' + a[2:])
 
499
                        else:
 
500
                            # This option takes an argument, so pack it
 
501
                            # into the array
 
502
                            optarg = a[2:]
696
503
            
697
504
            if optname in opts:
698
505
                # XXX: Do we ever want to support this, e.g. for -r?
699
 
                bailout('repeated option %r' % a)
 
506
                raise BzrError('repeated option %r' % a)
700
507
                
701
508
            optargfn = OPTIONS[optname]
702
509
            if optargfn:
703
510
                if optarg == None:
704
511
                    if not argv:
705
 
                        bailout('option %r needs an argument' % a)
 
512
                        raise BzrError('option %r needs an argument' % a)
706
513
                    else:
707
514
                        optarg = argv.pop(0)
708
515
                opts[optname] = optargfn(optarg)
709
516
            else:
710
517
                if optarg != None:
711
 
                    bailout('option %r takes no argument' % optname)
 
518
                    raise BzrError('option %r takes no argument' % optname)
712
519
                opts[optname] = True
713
520
        else:
714
521
            args.append(a)
717
524
 
718
525
 
719
526
 
720
 
def _match_args(cmd, args):
721
 
    """Check non-option arguments match required pattern.
722
527
 
723
 
    >>> _match_args('status', ['asdasdsadasd'])
724
 
    Traceback (most recent call last):
725
 
    ...
726
 
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
727
 
    >>> _match_args('add', ['asdasdsadasd'])
728
 
    {'file_list': ['asdasdsadasd']}
729
 
    >>> _match_args('add', 'abc def gj'.split())
730
 
    {'file_list': ['abc', 'def', 'gj']}
731
 
    """
732
 
    # match argument pattern
733
 
    argform = cmd_args.get(cmd, [])
 
528
def _match_argform(cmd, takes_args, args):
734
529
    argdict = {}
735
 
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
736
 
    # all but one.
737
530
 
738
 
    # step through args and argform, allowing appropriate 0-many matches
739
 
    for ap in argform:
 
531
    # step through args and takes_args, allowing appropriate 0-many matches
 
532
    for ap in takes_args:
740
533
        argname = ap[:-1]
741
534
        if ap[-1] == '?':
742
535
            if args:
743
536
                argdict[argname] = args.pop(0)
744
 
        elif ap[-1] == '*':
745
 
            assert 0
 
537
        elif ap[-1] == '*': # all remaining arguments
 
538
            if args:
 
539
                argdict[argname + '_list'] = args[:]
 
540
                args = []
 
541
            else:
 
542
                argdict[argname + '_list'] = None
746
543
        elif ap[-1] == '+':
747
544
            if not args:
748
 
                bailout("command %r needs one or more %s"
 
545
                raise BzrCommandError("command %r needs one or more %s"
749
546
                        % (cmd, argname.upper()))
750
547
            else:
751
548
                argdict[argname + '_list'] = args[:]
752
549
                args = []
 
550
        elif ap[-1] == '$': # all but one
 
551
            if len(args) < 2:
 
552
                raise BzrCommandError("command %r needs one or more %s"
 
553
                        % (cmd, argname.upper()))
 
554
            argdict[argname + '_list'] = args[:-1]
 
555
            args[:-1] = []                
753
556
        else:
754
557
            # just a plain arg
755
558
            argname = ap
756
559
            if not args:
757
 
                bailout("command %r requires argument %s"
 
560
                raise BzrCommandError("command %r requires argument %s"
758
561
                        % (cmd, argname.upper()))
759
562
            else:
760
563
                argdict[argname] = args.pop(0)
761
564
            
762
565
    if args:
763
 
        bailout("extra arguments to command %s: %r"
764
 
                % (cmd, args))
 
566
        raise BzrCommandError("extra argument to command %s: %s"
 
567
                              % (cmd, args[0]))
765
568
 
766
569
    return argdict
767
570
 
771
574
    """Execute a command.
772
575
 
773
576
    This is similar to main(), but without all the trappings for
774
 
    logging and error handling.
 
577
    logging and error handling.  
 
578
    
 
579
    argv
 
580
       The command-line arguments, without the program name from argv[0]
 
581
    
 
582
    Returns a command status or raises an exception.
 
583
 
 
584
    Special master options: these must come before the command because
 
585
    they control how the command is interpreted.
 
586
 
 
587
    --no-plugins
 
588
        Do not load plugin modules at all
 
589
 
 
590
    --builtin
 
591
        Only use builtin commands.  (Plugins are still allowed to change
 
592
        other behaviour.)
 
593
 
 
594
    --profile
 
595
        Run under the Python profiler.
775
596
    """
776
 
    try:
777
 
        args, opts = parse_args(argv[1:])
778
 
        if 'help' in opts:
779
 
            # TODO: pass down other arguments in case they asked for
780
 
            # help on a command name?
781
 
            cmd_help()
782
 
            return 0
783
 
        elif 'version' in opts:
784
 
            cmd_version()
785
 
            return 0
786
 
        cmd = args.pop(0)
787
 
    except IndexError:
788
 
        log_error('usage: bzr COMMAND\n')
789
 
        log_error('  try "bzr help"\n')
790
 
        return 1
791
 
 
792
 
    try:
793
 
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
794
 
    except KeyError:
795
 
        bailout("unknown command " + `cmd`)
796
 
 
797
 
    # global option
798
 
    if 'profile' in opts:
799
 
        profile = True
800
 
        del opts['profile']
801
 
    else:
802
 
        profile = False
 
597
    
 
598
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
 
599
 
 
600
    opt_profile = opt_no_plugins = opt_builtin = False
 
601
 
 
602
    # --no-plugins is handled specially at a very early stage. We need
 
603
    # to load plugins before doing other command parsing so that they
 
604
    # can override commands, but this needs to happen first.
 
605
 
 
606
    for a in argv[:]:
 
607
        if a == '--profile':
 
608
            opt_profile = True
 
609
        elif a == '--no-plugins':
 
610
            opt_no_plugins = True
 
611
        elif a == '--builtin':
 
612
            opt_builtin = True
 
613
        else:
 
614
            break
 
615
        argv.remove(a)
 
616
 
 
617
    if not opt_no_plugins:
 
618
        from bzrlib.plugin import load_plugins
 
619
        load_plugins()
 
620
 
 
621
    args, opts = parse_args(argv)
 
622
 
 
623
    if 'help' in opts:
 
624
        from bzrlib.help import help
 
625
        if args:
 
626
            help(args[0])
 
627
        else:
 
628
            help()
 
629
        return 0            
 
630
        
 
631
    if 'version' in opts:
 
632
        from bzrlib.builtins import show_version
 
633
        show_version()
 
634
        return 0
 
635
    
 
636
    if not args:
 
637
        from bzrlib.help import help
 
638
        help(None)
 
639
        return 0
 
640
    
 
641
    cmd = str(args.pop(0))
 
642
 
 
643
    canonical_cmd, cmd_class = \
 
644
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
803
645
 
804
646
    # check options are reasonable
805
 
    allowed = cmd_options.get(cmd, [])
 
647
    allowed = cmd_class.takes_options
806
648
    for oname in opts:
807
649
        if oname not in allowed:
808
 
            bailout("option %r is not allowed for command %r"
809
 
                    % (oname, cmd))
 
650
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
651
                                  % (oname, cmd))
810
652
 
811
653
    # mix arguments and options into one dictionary
812
 
    cmdargs = _match_args(cmd, args)
 
654
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
 
655
    cmdopts = {}
813
656
    for k, v in opts.items():
814
 
        cmdargs[k.replace('-', '_')] = v
815
 
 
816
 
    if profile:
817
 
        import hotshot
818
 
        prof = hotshot.Profile('.bzr.profile')
819
 
        ret = prof.runcall(cmd_handler, **cmdargs) or 0
820
 
        prof.close()
821
 
 
822
 
        import hotshot.stats
823
 
        stats = hotshot.stats.load('.bzr.profile')
824
 
        #stats.strip_dirs()
825
 
        stats.sort_stats('cumulative', 'calls')
826
 
        stats.print_stats(20)
 
657
        cmdopts[k.replace('-', '_')] = v
 
658
 
 
659
    if opt_profile:
 
660
        import hotshot, tempfile
 
661
        pffileno, pfname = tempfile.mkstemp()
 
662
        try:
 
663
            prof = hotshot.Profile(pfname)
 
664
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
 
665
            prof.close()
 
666
 
 
667
            import hotshot.stats
 
668
            stats = hotshot.stats.load(pfname)
 
669
            #stats.strip_dirs()
 
670
            stats.sort_stats('time')
 
671
            ## XXX: Might like to write to stderr or the trace file instead but
 
672
            ## print_stats seems hardcoded to stdout
 
673
            stats.print_stats(20)
 
674
            
 
675
            return ret.status
 
676
 
 
677
        finally:
 
678
            os.close(pffileno)
 
679
            os.remove(pfname)
827
680
    else:
828
 
        return cmd_handler(**cmdargs) or 0
829
 
 
 
681
        return cmd_class(cmdopts, cmdargs).status 
830
682
 
831
683
 
832
684
def main(argv):
833
 
    ## TODO: Handle command-line options; probably know what options are valid for
834
 
    ## each command
835
 
 
836
 
    ## TODO: If the arguments are wrong, give a usage message rather
837
 
    ## than just a backtrace.
838
 
 
839
 
    bzrlib.trace.create_tracefile(argv)
840
 
    
 
685
    import bzrlib.ui
 
686
    bzrlib.trace.log_startup(argv)
 
687
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
 
688
 
841
689
    try:
842
 
        ret = run_bzr(argv)
843
 
        return ret
 
690
        try:
 
691
            return run_bzr(argv[1:])
 
692
        finally:
 
693
            # do this here inside the exception wrappers to catch EPIPE
 
694
            sys.stdout.flush()
 
695
    except BzrCommandError, e:
 
696
        # command line syntax error, etc
 
697
        log_error(str(e))
 
698
        return 1
844
699
    except BzrError, e:
845
 
        log_error('bzr: error: ' + e.args[0] + '\n')
846
 
        if len(e.args) > 1:
847
 
            for h in e.args[1]:
848
 
                log_error('  ' + h + '\n')
 
700
        bzrlib.trace.log_exception()
849
701
        return 1
 
702
    except AssertionError, e:
 
703
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
704
        return 3
 
705
    except KeyboardInterrupt, e:
 
706
        bzrlib.trace.note('interrupted')
 
707
        return 2
850
708
    except Exception, e:
851
 
        log_error('bzr: exception: %s\n' % e)
852
 
        log_error('    see .bzr.log for details\n')
853
 
        traceback.print_exc(None, bzrlib.trace._tracefile)
854
 
        traceback.print_exc(None, sys.stderr)
855
 
        return 1
856
 
 
857
 
    # TODO: Maybe nicer handling of IOError?
858
 
 
 
709
        import errno
 
710
        if (isinstance(e, IOError) 
 
711
            and hasattr(e, 'errno')
 
712
            and e.errno == errno.EPIPE):
 
713
            bzrlib.trace.note('broken pipe')
 
714
            return 2
 
715
        else:
 
716
            bzrlib.trace.log_exception()
 
717
            return 2
859
718
 
860
719
 
861
720
if __name__ == '__main__':
862
721
    sys.exit(main(sys.argv))
863
 
    ##import profile
864
 
    ##profile.run('main(sys.argv)')
865