4
# Copyright (C) 2004, 2005 by Martin Pool
5
# Copyright (C) 2005 by Canonical Ltd
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.
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.
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
22
"""Bazaar-NG -- a free distributed version-control tool
24
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
26
Current limitation include:
28
* Metadata format is not stable yet -- you may need to
29
discard history in the future.
31
* No handling of subdirectories, symlinks or any non-text files.
33
* Insufficient error handling.
35
* Many commands unimplemented or partially implemented.
37
* Space-inefficient storage.
39
* No merge operators yet.
41
Interesting commands::
44
Show summary help screen
46
Show software version/licence/non-warranty.
48
Start versioning the current directory
52
Show revision history.
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.
60
Show summary of pending changes.
62
Make a file not versioned.
65
# not currently working:
67
# Show some information about this branch.
71
__copyright__ = "Copyright 2005 Canonical Development Ltd."
72
__author__ = "Martin Pool <mbp@canonical.com>"
73
__docformat__ = "restructuredtext en"
77
import sys, os, random, time, sha, sets, types, re, shutil, tempfile
78
import traceback, socket, fnmatch, difflib
81
from pprint import pprint
86
from bzrlib.store import ImmutableStore
87
from bzrlib.trace import mutter, note, log_error
88
from bzrlib.errors import bailout, BzrError
89
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
90
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
91
from bzrlib.revision import Revision
92
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
95
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
96
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
98
## standard representation
99
NONE_STRING = '(none)'
103
## TODO: Perhaps a different version of inventory commands that
104
## returns iterators...
106
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
108
## TODO: Some kind of locking on branches. Perhaps there should be a
109
## parameter to the branch object saying whether we want a read or
110
## write lock; release it from destructor. Perhaps don't even need a
111
## read lock to look at immutable objects?
113
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
114
## to compare output?
116
## TODO: Some kind of global code to generate the right Branch object
117
## to work on. Almost, but not quite all, commands need one, and it
118
## can be taken either from their parameters or their working
121
## TODO: rename command, needed soon: check destination doesn't exist
122
## either in working copy or tree; move working copy; update
123
## inventory; write out
125
## TODO: move command; check destination is a directory and will not
128
## TODO: command to show renames, one per line, as to->from
133
def cmd_status(all=False):
134
"""Display status summary.
136
For each file there is a single line giving its file state and name.
137
The name is that in the current revision unless it is deleted or
138
missing, in which case the old name is shown.
140
:todo: Don't show unchanged files unless ``--all`` is given?
142
Branch('.').show_status(show_all=all)
146
######################################################################
148
def cmd_get_revision(revision_id):
149
Branch('.').get_revision(revision_id).write_xml(sys.stdout)
152
def cmd_get_file_text(text_id):
153
"""Get contents of a file by hash."""
154
sf = Branch('.').text_store[text_id]
155
pumpfile(sf, sys.stdout)
159
######################################################################
164
"""Show number of revisions on this branch"""
165
print Branch('.').revno()
168
def cmd_add(file_list, verbose=False):
169
"""Add specified files.
171
Fails if the files are already added.
174
b = Branch(file_list[0], find_root=True)
175
b.add(file_list, verbose=verbose)
178
def cmd_inventory(revision=None):
179
"""Show inventory of the current working copy."""
180
## TODO: Also optionally show a previous inventory
181
## TODO: Format options
184
inv = b.read_working_inventory()
186
inv = b.get_revision_inventory(b.lookup_revision(revision))
188
for path, entry in inv.iter_entries():
189
print '%-50s %s' % (entry.file_id, path)
195
print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
197
def plural(n, base='', pl=None):
205
count_version_dirs = 0
207
count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
208
for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
210
count_status[fs] += 1
211
if fs not in ['I', '?'] and st_tup[4] == 'directory':
212
count_version_dirs += 1
215
print 'in the working tree:'
216
for name, fs in (('unchanged', '.'),
217
('modified', 'M'), ('added', 'A'), ('removed', 'D'),
218
('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
220
print ' %5d %s' % (count_status[fs], name)
221
print ' %5d versioned subdirector%s' % (count_version_dirs,
222
plural(count_version_dirs, 'y', 'ies'))
225
print 'branch history:'
226
history = b.revision_history()
228
print ' %5d revision%s' % (revno, plural(revno))
231
committers.add(b.get_revision(rev).committer)
232
print ' %5d committer%s' % (len(committers), plural(len(committers)))
234
firstrev = b.get_revision(history[0])
235
age = int((time.time() - firstrev.timestamp) / 3600 / 24)
236
print ' %5d day%s old' % (age, plural(age))
237
print ' first revision: %s' % format_date(firstrev.timestamp,
240
lastrev = b.get_revision(history[-1])
241
print ' latest revision: %s' % format_date(lastrev.timestamp,
247
def cmd_remove(file_list, verbose=False):
248
Branch('.').remove(file_list, verbose=verbose)
252
def cmd_file_id(filename):
253
i = Branch('.').read_working_inventory().path2id(filename)
255
bailout("%s is not a versioned file" % filename)
260
def cmd_find_filename(fileid):
261
n = find_filename(fileid)
263
bailout("%s is not a live file id" % fileid)
268
def cmd_revision_history():
269
for patchid in Branch('.').revision_history():
275
# TODO: Check we're not already in a working directory? At the
276
# moment you'll get an ugly error.
278
# TODO: What if we're in a subdirectory of a branch? Would like
279
# to allow that, but then the parent may need to understand that
280
# the children have disappeared, or should they be versioned in
283
# TODO: Take an argument/option for branch name.
284
Branch('.', init=True)
287
def cmd_diff(revision=None):
288
"""Show diff from basis to working copy.
290
:todo: Take one or two revision arguments, look up those trees,
293
:todo: Allow diff across branches.
295
:todo: Mangle filenames in diff to be more relevant.
297
:todo: Shouldn't be in the cmd function.
303
old_tree = b.basis_tree()
305
old_tree = b.revision_tree(b.lookup_revision(revision))
307
new_tree = b.working_tree()
308
old_inv = old_tree.inventory
309
new_inv = new_tree.inventory
311
# TODO: Options to control putting on a prefix or suffix, perhaps as a format string
315
DEVNULL = '/dev/null'
316
# Windows users, don't panic about this filename -- it is a
317
# special signal to GNU patch that the file should be created or
318
# deleted respectively.
320
# TODO: Generation of pseudo-diffs for added/deleted files could
321
# be usefully made into a much faster special case.
323
# TODO: Better to return them in sorted order I think.
325
for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
328
# Don't show this by default; maybe do it if an option is passed
329
# idlabel = ' {%s}' % fid
332
# FIXME: Something about the diff format makes patch unhappy
333
# with newly-added files.
335
def diffit(*a, **kw):
336
sys.stdout.writelines(difflib.unified_diff(*a, **kw))
339
if file_state in ['.', '?', 'I']:
341
elif file_state == 'A':
342
print '*** added %s %r' % (kind, new_name)
345
new_tree.get_file(fid).readlines(),
347
tofile=new_label + new_name + idlabel)
348
elif file_state == 'D':
349
assert isinstance(old_name, types.StringTypes)
350
print '*** deleted %s %r' % (kind, old_name)
352
diffit(old_tree.get_file(fid).readlines(), [],
353
fromfile=old_label + old_name + idlabel,
355
elif file_state in ['M', 'R']:
356
if file_state == 'M':
357
assert kind == 'file'
358
assert old_name == new_name
359
print '*** modified %s %r' % (kind, new_name)
360
elif file_state == 'R':
361
print '*** renamed %s %r => %r' % (kind, old_name, new_name)
364
diffit(old_tree.get_file(fid).readlines(),
365
new_tree.get_file(fid).readlines(),
366
fromfile=old_label + old_name + idlabel,
367
tofile=new_label + new_name)
369
bailout("can't represent state %s {%s}" % (file_state, fid))
373
def cmd_root(filename=None):
374
"""Print the branch root."""
375
print bzrlib.branch.find_branch_root(filename)
378
def cmd_log(timezone='original'):
379
"""Show log of this branch.
381
:todo: Options for utc; to show ids; to limit range; etc.
383
Branch('.').write_log(show_timezone=timezone)
386
def cmd_ls(revision=None, verbose=False):
387
"""List files in a tree.
389
:todo: Take a revision or remote path and list that tree instead.
393
tree = b.working_tree()
395
tree = b.revision_tree(b.lookup_revision(revision))
397
for fp, fc, kind, fid in tree.list_files():
399
if kind == 'directory':
406
print '%-8s %s%s' % (fc, fp, kindch)
413
"""List unknown files"""
414
for f in Branch('.').unknowns():
418
def cmd_lookup_revision(revno):
422
bailout("usage: lookup-revision REVNO",
423
["REVNO is a non-negative revision number for this branch"])
425
print Branch('.').lookup_revision(revno) or NONE_STRING
429
def cmd_export(revno, dest):
430
"""Export past revision to destination directory."""
432
rh = b.lookup_revision(int(revno))
433
t = b.revision_tree(rh)
438
######################################################################
439
# internal/test commands
443
"""Print a newly-generated UUID."""
444
print bzrlib.osutils.uuid()
448
def cmd_local_time_offset():
449
print bzrlib.osutils.local_time_offset()
453
def cmd_commit(message=None, verbose=False):
455
bailout("please specify a commit message")
456
Branch('.').commit(message, verbose=verbose)
460
"""Check consistency of the branch."""
464
def cmd_is(pred, *rest):
465
"""Test whether PREDICATE is true."""
467
cmd_handler = globals()['assert_' + pred.replace('-', '_')]
469
bailout("unknown predicate: %s" % quotefn(pred))
473
except BzrCheckError:
474
# by default we don't print the message so that this can
475
# be used from shell scripts without producing noise
480
print bzrlib.osutils.username()
483
def cmd_user_email():
484
print bzrlib.osutils.user_email()
487
def cmd_gen_revision_id():
489
print bzrlib.branch._gen_revision_id(time.time())
492
def cmd_selftest(verbose=False):
493
"""Run internal test suite"""
494
## -v, if present, is seen by doctest; the argument is just here
495
## so our parser doesn't complain
497
## TODO: --verbose option
499
failures, tests = 0, 0
501
import doctest, bzrlib.store, bzrlib.tests
502
bzrlib.trace.verbose = False
504
for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
505
bzrlib.tree, bzrlib.tests, bzrlib.commands:
506
mf, mt = doctest.testmod(m)
509
print '%-40s %3d tests' % (m.__name__, mt),
511
print '%3d FAILED!' % mf
515
print '%-40s %3d tests' % ('total', tests),
517
print '%3d FAILED!' % failures
524
cmd_doctest = cmd_selftest
527
######################################################################
532
# TODO: Specific help for particular commands
537
print "bzr (bazaar-ng) %s" % __version__
539
print "http://bazaar-ng.org/"
542
"""bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and
543
you may use, modify and redistribute it under the terms of the GNU
544
General Public License version 2 or later."""
548
"""Statement of optimism."""
549
print "it sure does!"
553
######################################################################
557
# list of all available options; the rhs can be either None for an
558
# option that takes no argument, or a constructor function that checks
577
# List of options that apply to particular commands; commands not
581
'commit': ['message', 'verbose'],
582
'diff': ['revision'],
583
'inventory': ['revision'],
584
'log': ['show-ids', 'timezone'],
585
'ls': ['revision', 'verbose'],
586
'remove': ['verbose'],
596
'file-id': ['filename'],
597
'root': ['filename?'],
598
'get-file-text': ['text_id'],
599
'get-inventory': ['inventory_id'],
600
'get-revision': ['revision_id'],
601
'get-revision-inventory': ['revision_id'],
603
'lookup-revision': ['revno'],
604
'export': ['revno', 'dest'],
610
def parse_args(argv):
611
"""Parse command line.
613
Arguments and options are parsed at this level before being passed
614
down to specific command handlers. This routine knows, from a
615
lookup table, something about the available options, what optargs
616
they take, and which commands will accept them.
618
>>> parse_args('--help'.split())
620
>>> parse_args('--version'.split())
621
([], {'version': True})
622
>>> parse_args('status --all'.split())
623
(['status'], {'all': True})
624
>>> parse_args('commit --message=biter'.split())
625
(['commit'], {'message': u'biter'})
630
# TODO: Maybe handle '--' to end options?
637
mutter(" got option %r" % a)
639
optname, optarg = a[2:].split('=', 1)
642
if optname not in OPTIONS:
643
bailout('unknown long option %r' % a)
646
if shortopt not in SHORT_OPTIONS:
647
bailout('unknown short option %r' % a)
648
optname = SHORT_OPTIONS[shortopt]
651
# XXX: Do we ever want to support this, e.g. for -r?
652
bailout('repeated option %r' % a)
654
optargfn = OPTIONS[optname]
658
bailout('option %r needs an argument' % a)
661
opts[optname] = optargfn(optarg)
662
mutter(" option argument %r" % opts[optname])
665
bailout('option %r takes no argument' % optname)
674
def _match_args(cmd, args):
675
"""Check non-option arguments match required pattern.
677
>>> _match_args('status', ['asdasdsadasd'])
678
Traceback (most recent call last):
680
BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
681
>>> _match_args('add', ['asdasdsadasd'])
682
{'file_list': ['asdasdsadasd']}
683
>>> _match_args('add', 'abc def gj'.split())
684
{'file_list': ['abc', 'def', 'gj']}
686
# match argument pattern
687
argform = cmd_args.get(cmd, [])
689
# TODO: Need a way to express 'cp SRC... DEST', where it matches
692
# step through args and argform, allowing appropriate 0-many matches
697
argdict[argname] = args.pop(0)
702
bailout("command %r needs one or more %s"
703
% (cmd, argname.upper()))
705
argdict[argname + '_list'] = args[:]
711
bailout("command %r requires argument %s"
712
% (cmd, argname.upper()))
714
argdict[argname] = args.pop(0)
717
bailout("extra arguments to command %s: %r"
725
"""Execute a command.
727
This is similar to main(), but without all the trappings for
728
logging and error handling.
731
args, opts = parse_args(argv[1:])
733
# TODO: pass down other arguments in case they asked for
734
# help on a command name?
737
elif 'version' in opts:
742
log_error('usage: bzr COMMAND\n')
743
log_error(' try "bzr help"\n')
747
cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
749
bailout("unknown command " + `cmd`)
751
# TODO: special --profile option to turn on the Python profiler
753
# check options are reasonable
754
allowed = cmd_options.get(cmd, [])
756
if oname not in allowed:
757
bailout("option %r is not allowed for command %r"
760
cmdargs = _match_args(cmd, args)
763
ret = cmd_handler(**cmdargs) or 0
768
## TODO: Handle command-line options; probably know what options are valid for
771
## TODO: If the arguments are wrong, give a usage message rather
772
## than just a backtrace.
774
bzrlib.trace.create_tracefile(argv)
780
log_error('bzr: error: ' + e.args[0] + '\n')
783
log_error(' ' + h + '\n')
786
log_error('bzr: exception: %s\n' % e)
787
log_error(' see .bzr.log for details\n')
788
traceback.print_exc(None, bzrlib.trace._tracefile)
789
traceback.print_exc(None, sys.stderr)
792
# TODO: Maybe nicer handling of IOError?
796
if __name__ == '__main__':
797
sys.exit(main(sys.argv))
799
##profile.run('main(sys.argv)')