1
# Copyright (C) 2004, 2005 by Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# DO NOT change this to cStringIO - it results in control files
19
# FIXIT! (Only deal with byte streams OR unicode at any one layer.)
21
from StringIO import StringIO
26
from bzrlib import BZRDIR
27
from bzrlib.commands import Command, display_command
28
from bzrlib.branch import Branch
29
from bzrlib.revision import common_ancestor
30
import bzrlib.errors as errors
31
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError,
32
NotBranchError, DivergedBranches, NotConflicted,
33
NoSuchFile, NoWorkingTree, FileInWrongBranch)
34
from bzrlib.option import Option
35
from bzrlib.revisionspec import RevisionSpec
37
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
38
from bzrlib.workingtree import WorkingTree
41
def tree_files(file_list, default_branch=u'.'):
43
return internal_tree_files(file_list, default_branch)
44
except FileInWrongBranch, e:
45
raise BzrCommandError("%s is not in the same branch as %s" %
46
(e.path, file_list[0]))
48
def internal_tree_files(file_list, default_branch=u'.'):
50
Return a branch and list of branch-relative paths.
51
If supplied file_list is empty or None, the branch default will be used,
52
and returned file_list will match the original.
54
if file_list is None or len(file_list) == 0:
55
return WorkingTree.open_containing(default_branch)[0], file_list
56
tree = WorkingTree.open_containing(file_list[0])[0]
58
for filename in file_list:
60
new_list.append(tree.relpath(filename))
61
except errors.PathNotChild:
62
raise FileInWrongBranch(tree.branch, filename)
66
# TODO: Make sure no commands unconditionally use the working directory as a
67
# branch. If a filename argument is used, the first of them should be used to
68
# specify the branch. (Perhaps this can be factored out into some kind of
69
# Argument class, representing a file in a branch, where the first occurrence
72
class cmd_status(Command):
73
"""Display status summary.
75
This reports on versioned and unknown files, reporting them
76
grouped by state. Possible states are:
79
Versioned in the working copy but not in the previous revision.
82
Versioned in the previous revision but removed or deleted
86
Path of this file changed from the previous revision;
87
the text may also have changed. This includes files whose
88
parent directory was renamed.
91
Text has changed since the previous revision.
94
Nothing about this file has changed since the previous revision.
95
Only shown with --all.
98
Not versioned and not matching an ignore pattern.
100
To see ignored files use 'bzr ignored'. For details in the
101
changes to file texts, use 'bzr diff'.
103
If no arguments are specified, the status of the entire working
104
directory is shown. Otherwise, only the status of the specified
105
files or directories is reported. If a directory is given, status
106
is reported for everything inside that directory.
108
If a revision argument is given, the status is calculated against
109
that revision, or between two revisions if two are provided.
112
# TODO: --no-recurse, --recurse options
114
takes_args = ['file*']
115
takes_options = ['all', 'show-ids', 'revision']
116
aliases = ['st', 'stat']
119
def run(self, all=False, show_ids=False, file_list=None, revision=None):
120
tree, file_list = tree_files(file_list)
122
from bzrlib.status import show_status
123
show_status(tree.branch, show_unchanged=all, show_ids=show_ids,
124
specific_files=file_list, revision=revision)
127
class cmd_cat_revision(Command):
128
"""Write out metadata for a revision.
130
The revision to print can either be specified by a specific
131
revision identifier, or you can use --revision.
135
takes_args = ['revision_id?']
136
takes_options = ['revision']
139
def run(self, revision_id=None, revision=None):
141
if revision_id is not None and revision is not None:
142
raise BzrCommandError('You can only supply one of revision_id or --revision')
143
if revision_id is None and revision is None:
144
raise BzrCommandError('You must supply either --revision or a revision_id')
145
b = WorkingTree.open_containing(u'.')[0].branch
146
if revision_id is not None:
147
sys.stdout.write(b.get_revision_xml(revision_id))
148
elif revision is not None:
151
raise BzrCommandError('You cannot specify a NULL revision.')
152
revno, rev_id = rev.in_history(b)
153
sys.stdout.write(b.get_revision_xml(rev_id))
156
class cmd_revno(Command):
157
"""Show current revision number.
159
This is equal to the number of revisions on this branch."""
160
takes_args = ['location?']
162
def run(self, location=u'.'):
163
print Branch.open_containing(location)[0].revno()
166
class cmd_revision_info(Command):
167
"""Show revision number and revision id for a given revision identifier.
170
takes_args = ['revision_info*']
171
takes_options = ['revision']
173
def run(self, revision=None, revision_info_list=[]):
176
if revision is not None:
177
revs.extend(revision)
178
if revision_info_list is not None:
179
for rev in revision_info_list:
180
revs.append(RevisionSpec(rev))
182
raise BzrCommandError('You must supply a revision identifier')
184
b = WorkingTree.open_containing(u'.')[0].branch
187
revinfo = rev.in_history(b)
188
if revinfo.revno is None:
189
print ' %s' % revinfo.rev_id
191
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
194
class cmd_add(Command):
195
"""Add specified files or directories.
197
In non-recursive mode, all the named items are added, regardless
198
of whether they were previously ignored. A warning is given if
199
any of the named files are already versioned.
201
In recursive mode (the default), files are treated the same way
202
but the behaviour for directories is different. Directories that
203
are already versioned do not give a warning. All directories,
204
whether already versioned or not, are searched for files or
205
subdirectories that are neither versioned or ignored, and these
206
are added. This search proceeds recursively into versioned
207
directories. If no names are given '.' is assumed.
209
Therefore simply saying 'bzr add' will version all files that
210
are currently unknown.
212
Adding a file whose parent directory is not versioned will
213
implicitly add the parent, and so on up to the root. This means
214
you should never need to explictly add a directory, they'll just
215
get added when you add a file in the directory.
217
takes_args = ['file*']
218
takes_options = ['no-recurse']
220
def run(self, file_list, no_recurse=False):
221
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
223
reporter = add_reporter_null
225
reporter = add_reporter_print
226
smart_add(file_list, not no_recurse, reporter)
229
class cmd_mkdir(Command):
230
"""Create a new versioned directory.
232
This is equivalent to creating the directory and then adding it.
234
takes_args = ['dir+']
236
def run(self, dir_list):
239
wt, dd = WorkingTree.open_containing(d)
244
class cmd_relpath(Command):
245
"""Show path of a file relative to root"""
246
takes_args = ['filename']
250
def run(self, filename):
251
tree, relpath = WorkingTree.open_containing(filename)
255
class cmd_inventory(Command):
256
"""Show inventory of the current working copy or a revision.
258
It is possible to limit the output to a particular entry
259
type using the --kind option. For example; --kind file.
261
takes_options = ['revision', 'show-ids', 'kind']
264
def run(self, revision=None, show_ids=False, kind=None):
265
if kind and kind not in ['file', 'directory', 'symlink']:
266
raise BzrCommandError('invalid kind specified')
267
tree = WorkingTree.open_containing(u'.')[0]
269
inv = tree.read_working_inventory()
271
if len(revision) > 1:
272
raise BzrCommandError('bzr inventory --revision takes'
273
' exactly one revision identifier')
274
inv = tree.branch.get_revision_inventory(
275
revision[0].in_history(tree.branch).rev_id)
277
for path, entry in inv.entries():
278
if kind and kind != entry.kind:
281
print '%-50s %s' % (path, entry.file_id)
286
class cmd_move(Command):
287
"""Move files to a different directory.
292
The destination must be a versioned directory in the same branch.
294
takes_args = ['source$', 'dest']
295
def run(self, source_list, dest):
296
tree, source_list = tree_files(source_list)
297
# TODO: glob expansion on windows?
298
tree.move(source_list, tree.relpath(dest))
301
class cmd_rename(Command):
302
"""Change the name of an entry.
305
bzr rename frob.c frobber.c
306
bzr rename src/frob.c lib/frob.c
308
It is an error if the destination name exists.
310
See also the 'move' command, which moves files into a different
311
directory without changing their name.
313
# TODO: Some way to rename multiple files without invoking
314
# bzr for each one?"""
315
takes_args = ['from_name', 'to_name']
317
def run(self, from_name, to_name):
318
tree, (from_name, to_name) = tree_files((from_name, to_name))
319
tree.rename_one(from_name, to_name)
322
class cmd_mv(Command):
323
"""Move or rename a file.
326
bzr mv OLDNAME NEWNAME
327
bzr mv SOURCE... DESTINATION
329
If the last argument is a versioned directory, all the other names
330
are moved into it. Otherwise, there must be exactly two arguments
331
and the file is changed to a new name, which must not already exist.
333
Files cannot be moved between branches.
335
takes_args = ['names*']
336
def run(self, names_list):
337
if len(names_list) < 2:
338
raise BzrCommandError("missing file argument")
339
tree, rel_names = tree_files(names_list)
341
if os.path.isdir(names_list[-1]):
342
# move into existing directory
343
for pair in tree.move(rel_names[:-1], rel_names[-1]):
344
print "%s => %s" % pair
346
if len(names_list) != 2:
347
raise BzrCommandError('to mv multiple files the destination '
348
'must be a versioned directory')
349
tree.rename_one(rel_names[0], rel_names[1])
350
print "%s => %s" % (rel_names[0], rel_names[1])
353
class cmd_pull(Command):
354
"""Pull any changes from another branch into the current one.
356
If there is no default location set, the first pull will set it. After
357
that, you can omit the location to use the default. To change the
358
default, use --remember.
360
This command only works on branches that have not diverged. Branches are
361
considered diverged if both branches have had commits without first
362
pulling from the other.
364
If branches have diverged, you can use 'bzr merge' to pull the text changes
365
from one into the other. Once one branch has merged, the other should
366
be able to pull it again.
368
If you want to forget your local changes and just update your branch to
369
match the remote one, use --overwrite.
371
takes_options = ['remember', 'overwrite', 'verbose']
372
takes_args = ['location?']
374
def run(self, location=None, remember=False, overwrite=False, verbose=False):
375
from bzrlib.merge import merge
376
from shutil import rmtree
378
# FIXME: too much stuff is in the command class
379
tree_to = WorkingTree.open_containing(u'.')[0]
380
stored_loc = tree_to.branch.get_parent()
382
if stored_loc is None:
383
raise BzrCommandError("No pull location known or specified.")
385
print "Using saved location: %s" % stored_loc
386
location = stored_loc
388
br_from = Branch.open(location)
389
br_to = tree_to.branch
391
old_rh = br_to.revision_history()
392
count = tree_to.pull(br_from, overwrite)
394
if br_to.get_parent() is None or remember:
395
br_to.set_parent(location)
396
note('%d revision(s) pulled.' % (count,))
399
new_rh = tree_to.branch.revision_history()
402
from bzrlib.log import show_changed_revisions
403
show_changed_revisions(tree_to.branch, old_rh, new_rh)
406
class cmd_push(Command):
407
"""Push this branch into another branch.
409
The remote branch will not have its working tree populated because this
410
is both expensive, and may not be supported on the remote file system.
412
Some smart servers or protocols *may* put the working tree in place.
414
If there is no default push location set, the first push will set it.
415
After that, you can omit the location to use the default. To change the
416
default, use --remember.
418
This command only works on branches that have not diverged. Branches are
419
considered diverged if the branch being pushed to is not an older version
422
If branches have diverged, you can use 'bzr push --overwrite' to replace
423
the other branch completely.
425
If you want to ensure you have the different changes in the other branch,
426
do a merge (see bzr help merge) from the other branch, and commit that
427
before doing a 'push --overwrite'.
429
takes_options = ['remember', 'overwrite',
430
Option('create-prefix',
431
help='Create the path leading up to the branch '
432
'if it does not already exist')]
433
takes_args = ['location?']
435
def run(self, location=None, remember=False, overwrite=False,
436
create_prefix=False, verbose=False):
437
# FIXME: Way too big! Put this into a function called from the
440
from shutil import rmtree
441
from bzrlib.transport import get_transport
443
tree_from = WorkingTree.open_containing(u'.')[0]
444
br_from = tree_from.branch
445
stored_loc = tree_from.branch.get_push_location()
447
if stored_loc is None:
448
raise BzrCommandError("No push location known or specified.")
450
print "Using saved location: %s" % stored_loc
451
location = stored_loc
453
br_to = Branch.open(location)
454
except NotBranchError:
456
transport = get_transport(location).clone('..')
457
if not create_prefix:
459
transport.mkdir(transport.relpath(location))
461
raise BzrCommandError("Parent directory of %s "
462
"does not exist." % location)
464
current = transport.base
465
needed = [(transport, transport.relpath(location))]
468
transport, relpath = needed[-1]
469
transport.mkdir(relpath)
472
new_transport = transport.clone('..')
473
needed.append((new_transport,
474
new_transport.relpath(transport.base)))
475
if new_transport.base == transport.base:
476
raise BzrCommandError("Could not creeate "
478
br_to = Branch.initialize(location)
479
old_rh = br_to.revision_history()
482
tree_to = br_to.working_tree()
483
except NoWorkingTree:
484
# TODO: This should be updated for branches which don't have a
485
# working tree, as opposed to ones where we just couldn't
487
warning('Unable to update the working tree of: %s' % (br_to.base,))
488
count = br_to.pull(br_from, overwrite)
490
count = tree_to.pull(br_from, overwrite)
491
except DivergedBranches:
492
raise BzrCommandError("These branches have diverged."
493
" Try a merge then push with overwrite.")
494
if br_from.get_push_location() is None or remember:
495
br_from.set_push_location(location)
496
note('%d revision(s) pushed.' % (count,))
499
new_rh = br_to.revision_history()
502
from bzrlib.log import show_changed_revisions
503
show_changed_revisions(br_to, old_rh, new_rh)
506
class cmd_branch(Command):
507
"""Create a new copy of a branch.
509
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
510
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
512
To retrieve the branch as of a particular revision, supply the --revision
513
parameter, as in "branch foo/bar -r 5".
515
--basis is to speed up branching from remote branches. When specified, it
516
copies all the file-contents, inventory and revision data from the basis
517
branch before copying anything from the remote branch.
519
takes_args = ['from_location', 'to_location?']
520
takes_options = ['revision', 'basis']
521
aliases = ['get', 'clone']
523
def run(self, from_location, to_location=None, revision=None, basis=None):
524
from bzrlib.clone import copy_branch
526
from shutil import rmtree
529
elif len(revision) > 1:
530
raise BzrCommandError(
531
'bzr branch --revision takes exactly 1 revision value')
533
br_from = Branch.open(from_location)
535
if e.errno == errno.ENOENT:
536
raise BzrCommandError('Source location "%s" does not'
537
' exist.' % to_location)
542
if basis is not None:
543
basis_branch = WorkingTree.open_containing(basis)[0].branch
546
if len(revision) == 1 and revision[0] is not None:
547
revision_id = revision[0].in_history(br_from)[1]
550
if to_location is None:
551
to_location = os.path.basename(from_location.rstrip("/\\"))
554
name = os.path.basename(to_location) + '\n'
556
os.mkdir(to_location)
558
if e.errno == errno.EEXIST:
559
raise BzrCommandError('Target directory "%s" already'
560
' exists.' % to_location)
561
if e.errno == errno.ENOENT:
562
raise BzrCommandError('Parent of "%s" does not exist.' %
567
copy_branch(br_from, to_location, revision_id, basis_branch)
568
except bzrlib.errors.NoSuchRevision:
570
msg = "The branch %s has no revision %s." % (from_location, revision[0])
571
raise BzrCommandError(msg)
572
except bzrlib.errors.UnlistableBranch:
574
msg = "The branch %s cannot be used as a --basis"
575
raise BzrCommandError(msg)
576
branch = Branch.open(to_location)
578
name = StringIO(name)
579
branch.put_controlfile('branch-name', name)
580
note('Branched %d revision(s).' % branch.revno())
585
class cmd_renames(Command):
586
"""Show list of renamed files.
588
# TODO: Option to show renames between two historical versions.
590
# TODO: Only show renames under dir, rather than in the whole branch.
591
takes_args = ['dir?']
594
def run(self, dir=u'.'):
595
tree = WorkingTree.open_containing(dir)[0]
596
old_inv = tree.branch.basis_tree().inventory
597
new_inv = tree.read_working_inventory()
599
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
601
for old_name, new_name in renames:
602
print "%s => %s" % (old_name, new_name)
605
class cmd_info(Command):
606
"""Show statistical information about a branch."""
607
takes_args = ['branch?']
610
def run(self, branch=None):
612
b = WorkingTree.open_containing(branch)[0].branch
616
class cmd_remove(Command):
617
"""Make a file unversioned.
619
This makes bzr stop tracking changes to a versioned file. It does
620
not delete the working copy.
622
takes_args = ['file+']
623
takes_options = ['verbose']
626
def run(self, file_list, verbose=False):
627
tree, file_list = tree_files(file_list)
628
tree.remove(file_list, verbose=verbose)
631
class cmd_file_id(Command):
632
"""Print file_id of a particular file or directory.
634
The file_id is assigned when the file is first added and remains the
635
same through all revisions where the file exists, even when it is
639
takes_args = ['filename']
641
def run(self, filename):
642
tree, relpath = WorkingTree.open_containing(filename)
643
i = tree.inventory.path2id(relpath)
645
raise BzrError("%r is not a versioned file" % filename)
650
class cmd_file_path(Command):
651
"""Print path of file_ids to a file or directory.
653
This prints one line for each directory down to the target,
654
starting at the branch root."""
656
takes_args = ['filename']
658
def run(self, filename):
659
tree, relpath = WorkingTree.open_containing(filename)
661
fid = inv.path2id(relpath)
663
raise BzrError("%r is not a versioned file" % filename)
664
for fip in inv.get_idpath(fid):
668
class cmd_revision_history(Command):
669
"""Display list of revision ids on this branch."""
673
branch = WorkingTree.open_containing(u'.')[0].branch
674
for patchid in branch.revision_history():
678
class cmd_ancestry(Command):
679
"""List all revisions merged into this branch."""
683
tree = WorkingTree.open_containing(u'.')[0]
685
# FIXME. should be tree.last_revision
686
for revision_id in b.get_ancestry(b.last_revision()):
690
class cmd_init(Command):
691
"""Make a directory into a versioned branch.
693
Use this to create an empty branch, or before importing an
696
Recipe for importing a tree of files:
701
bzr commit -m 'imported project'
703
takes_args = ['location?']
704
def run(self, location=None):
705
from bzrlib.branch import Branch
709
# The path has to exist to initialize a
710
# branch inside of it.
711
# Just using os.mkdir, since I don't
712
# believe that we want to create a bunch of
713
# locations if the user supplies an extended path
714
if not os.path.exists(location):
716
Branch.initialize(location)
719
class cmd_diff(Command):
720
"""Show differences in working tree.
722
If files are listed, only the changes in those files are listed.
723
Otherwise, all changes for the tree are listed.
730
# TODO: Allow diff across branches.
731
# TODO: Option to use external diff command; could be GNU diff, wdiff,
732
# or a graphical diff.
734
# TODO: Python difflib is not exactly the same as unidiff; should
735
# either fix it up or prefer to use an external diff.
737
# TODO: If a directory is given, diff everything under that.
739
# TODO: Selected-file diff is inefficient and doesn't show you
742
# TODO: This probably handles non-Unix newlines poorly.
744
takes_args = ['file*']
745
takes_options = ['revision', 'diff-options']
746
aliases = ['di', 'dif']
749
def run(self, revision=None, file_list=None, diff_options=None):
750
from bzrlib.diff import show_diff
752
tree, file_list = internal_tree_files(file_list)
755
except FileInWrongBranch:
756
if len(file_list) != 2:
757
raise BzrCommandError("Files are in different branches")
759
b, file1 = Branch.open_containing(file_list[0])
760
b2, file2 = Branch.open_containing(file_list[1])
761
if file1 != "" or file2 != "":
762
# FIXME diff those two files. rbc 20051123
763
raise BzrCommandError("Files are in different branches")
765
if revision is not None:
767
raise BzrCommandError("Can't specify -r with two branches")
768
if len(revision) == 1:
769
return show_diff(tree.branch, revision[0], specific_files=file_list,
770
external_diff_options=diff_options)
771
elif len(revision) == 2:
772
return show_diff(tree.branch, revision[0], specific_files=file_list,
773
external_diff_options=diff_options,
774
revision2=revision[1])
776
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
779
return show_diff(b, None, specific_files=file_list,
780
external_diff_options=diff_options, b2=b2)
782
return show_diff(tree.branch, None, specific_files=file_list,
783
external_diff_options=diff_options)
786
class cmd_deleted(Command):
787
"""List files deleted in the working tree.
789
# TODO: Show files deleted since a previous revision, or
790
# between two revisions.
791
# TODO: Much more efficient way to do this: read in new
792
# directories with readdir, rather than stating each one. Same
793
# level of effort but possibly much less IO. (Or possibly not,
794
# if the directories are very large...)
796
def run(self, show_ids=False):
797
tree = WorkingTree.open_containing(u'.')[0]
798
old = tree.branch.basis_tree()
799
for path, ie in old.inventory.iter_entries():
800
if not tree.has_id(ie.file_id):
802
print '%-50s %s' % (path, ie.file_id)
807
class cmd_modified(Command):
808
"""List files modified in working tree."""
812
from bzrlib.delta import compare_trees
814
tree = WorkingTree.open_containing(u'.')[0]
815
td = compare_trees(tree.branch.basis_tree(), tree)
817
for path, id, kind, text_modified, meta_modified in td.modified:
822
class cmd_added(Command):
823
"""List files added in working tree."""
827
wt = WorkingTree.open_containing(u'.')[0]
828
basis_inv = wt.branch.basis_tree().inventory
831
if file_id in basis_inv:
833
path = inv.id2path(file_id)
834
if not os.access(b.abspath(path), os.F_OK):
840
class cmd_root(Command):
841
"""Show the tree root directory.
843
The root is the nearest enclosing directory with a .bzr control
845
takes_args = ['filename?']
847
def run(self, filename=None):
848
"""Print the branch root."""
849
tree = WorkingTree.open_containing(filename)[0]
853
class cmd_log(Command):
854
"""Show log of this branch.
856
To request a range of logs, you can use the command -r begin..end
857
-r revision requests a specific revision, -r ..end or -r begin.. are
861
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
863
takes_args = ['filename?']
864
takes_options = [Option('forward',
865
help='show from oldest to newest'),
866
'timezone', 'verbose',
867
'show-ids', 'revision',
868
Option('line', help='format with one line per revision'),
871
help='show revisions whose message matches this regexp',
873
Option('short', help='use moderately short format'),
876
def run(self, filename=None, timezone='original',
885
from bzrlib.log import log_formatter, show_log
887
assert message is None or isinstance(message, basestring), \
888
"invalid message argument %r" % message
889
direction = (forward and 'forward') or 'reverse'
895
tree, fp = WorkingTree.open_containing(filename)
898
inv = tree.read_working_inventory()
899
except NotBranchError:
902
b, fp = Branch.open_containing(filename)
904
inv = b.get_inventory(b.last_revision())
906
file_id = inv.path2id(fp)
908
file_id = None # points to branch root
910
tree, relpath = WorkingTree.open_containing(u'.')
917
elif len(revision) == 1:
918
rev1 = rev2 = revision[0].in_history(b).revno
919
elif len(revision) == 2:
920
rev1 = revision[0].in_history(b).revno
921
rev2 = revision[1].in_history(b).revno
923
raise BzrCommandError('bzr log --revision takes one or two values.')
925
# By this point, the revision numbers are converted to the +ve
926
# form if they were supplied in the -ve form, so we can do
927
# this comparison in relative safety
929
(rev2, rev1) = (rev1, rev2)
931
mutter('encoding log as %r', bzrlib.user_encoding)
933
# use 'replace' so that we don't abort if trying to write out
934
# in e.g. the default C locale.
935
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
942
lf = log_formatter(log_format,
945
show_timezone=timezone)
958
class cmd_touching_revisions(Command):
959
"""Return revision-ids which affected a particular file.
961
A more user-friendly interface is "bzr log FILE"."""
963
takes_args = ["filename"]
965
def run(self, filename):
966
tree, relpath = WorkingTree.open_containing(filename)
968
inv = tree.read_working_inventory()
969
file_id = inv.path2id(relpath)
970
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
971
print "%6d %s" % (revno, what)
974
class cmd_ls(Command):
975
"""List files in a tree.
977
# TODO: Take a revision or remote path and list that tree instead.
979
takes_options = ['verbose', 'revision',
980
Option('non-recursive',
981
help='don\'t recurse into sub-directories'),
983
help='Print all paths from the root of the branch.'),
984
Option('unknown', help='Print unknown files'),
985
Option('versioned', help='Print versioned files'),
986
Option('ignored', help='Print ignored files'),
988
Option('null', help='Null separate the files'),
991
def run(self, revision=None, verbose=False,
992
non_recursive=False, from_root=False,
993
unknown=False, versioned=False, ignored=False,
997
raise BzrCommandError('Cannot set both --verbose and --null')
998
all = not (unknown or versioned or ignored)
1000
selection = {'I':ignored, '?':unknown, 'V':versioned}
1002
tree, relpath = WorkingTree.open_containing(u'.')
1007
if revision is not None:
1008
tree = tree.branch.revision_tree(
1009
revision[0].in_history(tree.branch).rev_id)
1010
for fp, fc, kind, fid, entry in tree.list_files():
1011
if fp.startswith(relpath):
1012
fp = fp[len(relpath):]
1013
if non_recursive and '/' in fp:
1015
if not all and not selection[fc]:
1018
kindch = entry.kind_character()
1019
print '%-8s %s%s' % (fc, fp, kindch)
1021
sys.stdout.write(fp)
1022
sys.stdout.write('\0')
1028
class cmd_unknowns(Command):
1029
"""List unknown files."""
1032
from bzrlib.osutils import quotefn
1033
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1037
class cmd_ignore(Command):
1038
"""Ignore a command or pattern.
1040
To remove patterns from the ignore list, edit the .bzrignore file.
1042
If the pattern contains a slash, it is compared to the whole path
1043
from the branch root. Otherwise, it is compared to only the last
1044
component of the path. To match a file only in the root directory,
1047
Ignore patterns are case-insensitive on case-insensitive systems.
1049
Note: wildcards must be quoted from the shell on Unix.
1052
bzr ignore ./Makefile
1053
bzr ignore '*.class'
1055
# TODO: Complain if the filename is absolute
1056
takes_args = ['name_pattern']
1058
def run(self, name_pattern):
1059
from bzrlib.atomicfile import AtomicFile
1062
tree, relpath = WorkingTree.open_containing(u'.')
1063
ifn = tree.abspath('.bzrignore')
1065
if os.path.exists(ifn):
1068
igns = f.read().decode('utf-8')
1074
# TODO: If the file already uses crlf-style termination, maybe
1075
# we should use that for the newly added lines?
1077
if igns and igns[-1] != '\n':
1079
igns += name_pattern + '\n'
1082
f = AtomicFile(ifn, 'wt')
1083
f.write(igns.encode('utf-8'))
1088
inv = tree.inventory
1089
if inv.path2id('.bzrignore'):
1090
mutter('.bzrignore is already versioned')
1092
mutter('need to make new .bzrignore file versioned')
1093
tree.add(['.bzrignore'])
1096
class cmd_ignored(Command):
1097
"""List ignored files and the patterns that matched them.
1099
See also: bzr ignore"""
1102
tree = WorkingTree.open_containing(u'.')[0]
1103
for path, file_class, kind, file_id, entry in tree.list_files():
1104
if file_class != 'I':
1106
## XXX: Slightly inefficient since this was already calculated
1107
pat = tree.is_ignored(path)
1108
print '%-50s %s' % (path, pat)
1111
class cmd_lookup_revision(Command):
1112
"""Lookup the revision-id from a revision-number
1115
bzr lookup-revision 33
1118
takes_args = ['revno']
1121
def run(self, revno):
1125
raise BzrCommandError("not a valid revision-number: %r" % revno)
1127
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1130
class cmd_export(Command):
1131
"""Export past revision to destination directory.
1133
If no revision is specified this exports the last committed revision.
1135
Format may be an "exporter" name, such as tar, tgz, tbz2. If none is
1136
given, try to find the format with the extension. If no extension
1137
is found exports to a directory (equivalent to --format=dir).
1139
Root may be the top directory for tar, tgz and tbz2 formats. If none
1140
is given, the top directory will be the root name of the file.
1142
Note: export of tree with non-ascii filenames to zip is not supported.
1144
Supported formats Autodetected by extension
1145
----------------- -------------------------
1148
tbz2 .tar.bz2, .tbz2
1152
takes_args = ['dest']
1153
takes_options = ['revision', 'format', 'root']
1154
def run(self, dest, revision=None, format=None, root=None):
1156
from bzrlib.export import export
1157
tree = WorkingTree.open_containing(u'.')[0]
1159
if revision is None:
1160
# should be tree.last_revision FIXME
1161
rev_id = b.last_revision()
1163
if len(revision) != 1:
1164
raise BzrError('bzr export --revision takes exactly 1 argument')
1165
rev_id = revision[0].in_history(b).rev_id
1166
t = b.revision_tree(rev_id)
1168
export(t, dest, format, root)
1169
except errors.NoSuchExportFormat, e:
1170
raise BzrCommandError('Unsupported export format: %s' % e.format)
1173
class cmd_cat(Command):
1174
"""Write a file's text from a previous revision."""
1176
takes_options = ['revision']
1177
takes_args = ['filename']
1180
def run(self, filename, revision=None):
1181
if revision is not None and len(revision) != 1:
1182
raise BzrCommandError("bzr cat --revision takes exactly one number")
1185
tree, relpath = WorkingTree.open_containing(filename)
1187
except NotBranchError:
1191
b, relpath = Branch.open_containing(filename)
1192
if revision is None:
1193
revision_id = b.last_revision()
1195
revision_id = revision[0].in_history(b).rev_id
1196
b.print_file(relpath, revision_id)
1199
class cmd_local_time_offset(Command):
1200
"""Show the offset in seconds from GMT to local time."""
1204
print bzrlib.osutils.local_time_offset()
1208
class cmd_commit(Command):
1209
"""Commit changes into a new revision.
1211
If no arguments are given, the entire tree is committed.
1213
If selected files are specified, only changes to those files are
1214
committed. If a directory is specified then the directory and everything
1215
within it is committed.
1217
A selected-file commit may fail in some cases where the committed
1218
tree would be invalid, such as trying to commit a file in a
1219
newly-added directory that is not itself committed.
1221
# TODO: Run hooks on tree to-be-committed, and after commit.
1223
# TODO: Strict commit that fails if there are deleted files.
1224
# (what does "deleted files" mean ??)
1226
# TODO: Give better message for -s, --summary, used by tla people
1228
# XXX: verbose currently does nothing
1230
takes_args = ['selected*']
1231
takes_options = ['message', 'verbose',
1233
help='commit even if nothing has changed'),
1234
Option('file', type=str,
1236
help='file containing commit message'),
1238
help="refuse to commit if there are unknown "
1239
"files in the working tree."),
1241
aliases = ['ci', 'checkin']
1243
def run(self, message=None, file=None, verbose=True, selected_list=None,
1244
unchanged=False, strict=False):
1245
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1247
from bzrlib.msgeditor import edit_commit_message, \
1248
make_commit_message_template
1249
from bzrlib.status import show_status
1250
from tempfile import TemporaryFile
1253
# TODO: Need a blackbox test for invoking the external editor; may be
1254
# slightly problematic to run this cross-platform.
1256
# TODO: do more checks that the commit will succeed before
1257
# spending the user's valuable time typing a commit message.
1259
# TODO: if the commit *does* happen to fail, then save the commit
1260
# message to a temporary file where it can be recovered
1261
tree, selected_list = tree_files(selected_list)
1262
if message is None and not file:
1263
template = make_commit_message_template(tree, selected_list)
1264
message = edit_commit_message(template)
1266
raise BzrCommandError("please specify a commit message"
1267
" with either --message or --file")
1268
elif message and file:
1269
raise BzrCommandError("please specify either --message or --file")
1273
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1276
raise BzrCommandError("empty commit message specified")
1279
tree.commit(message, specific_files=selected_list,
1280
allow_pointless=unchanged, strict=strict)
1281
except PointlessCommit:
1282
# FIXME: This should really happen before the file is read in;
1283
# perhaps prepare the commit; get the message; then actually commit
1284
raise BzrCommandError("no changes to commit",
1285
["use --unchanged to commit anyhow"])
1286
except ConflictsInTree:
1287
raise BzrCommandError("Conflicts detected in working tree. "
1288
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1289
except StrictCommitFailed:
1290
raise BzrCommandError("Commit refused because there are unknown "
1291
"files in the working tree.")
1292
note('Committed revision %d.' % (tree.branch.revno(),))
1295
class cmd_check(Command):
1296
"""Validate consistency of branch history.
1298
This command checks various invariants about the branch storage to
1299
detect data corruption or bzr bugs.
1301
takes_args = ['branch?']
1302
takes_options = ['verbose']
1304
def run(self, branch=None, verbose=False):
1305
from bzrlib.check import check
1307
tree = WorkingTree.open_containing()[0]
1308
branch = tree.branch
1310
branch = Branch.open(branch)
1311
check(branch, verbose)
1314
class cmd_scan_cache(Command):
1317
from bzrlib.hashcache import HashCache
1323
print '%6d stats' % c.stat_count
1324
print '%6d in hashcache' % len(c._cache)
1325
print '%6d files removed from cache' % c.removed_count
1326
print '%6d hashes updated' % c.update_count
1327
print '%6d files changed too recently to cache' % c.danger_count
1334
class cmd_upgrade(Command):
1335
"""Upgrade branch storage to current format.
1337
The check command or bzr developers may sometimes advise you to run
1340
This version of this command upgrades from the full-text storage
1341
used by bzr 0.0.8 and earlier to the weave format (v5).
1343
takes_args = ['dir?']
1345
def run(self, dir=u'.'):
1346
from bzrlib.upgrade import upgrade
1350
class cmd_whoami(Command):
1351
"""Show bzr user id."""
1352
takes_options = ['email']
1355
def run(self, email=False):
1357
b = WorkingTree.open_containing(u'.')[0].branch
1358
config = bzrlib.config.BranchConfig(b)
1359
except NotBranchError:
1360
config = bzrlib.config.GlobalConfig()
1363
print config.user_email()
1365
print config.username()
1367
class cmd_nick(Command):
1369
Print or set the branch nickname.
1370
If unset, the tree root directory name is used as the nickname
1371
To print the current nickname, execute with no argument.
1373
takes_args = ['nickname?']
1374
def run(self, nickname=None):
1375
branch = Branch.open_containing(u'.')[0]
1376
if nickname is None:
1377
self.printme(branch)
1379
branch.nick = nickname
1382
def printme(self, branch):
1385
class cmd_selftest(Command):
1386
"""Run internal test suite.
1388
This creates temporary test directories in the working directory,
1389
but not existing data is affected. These directories are deleted
1390
if the tests pass, or left behind to help in debugging if they
1391
fail and --keep-output is specified.
1393
If arguments are given, they are regular expressions that say
1394
which tests should run.
1396
# TODO: --list should give a list of all available tests
1398
takes_args = ['testspecs*']
1399
takes_options = ['verbose',
1400
Option('one', help='stop when one test fails'),
1401
Option('keep-output',
1402
help='keep output directories when tests fail')
1405
def run(self, testspecs_list=None, verbose=False, one=False,
1408
from bzrlib.tests import selftest
1409
# we don't want progress meters from the tests to go to the
1410
# real output; and we don't want log messages cluttering up
1412
save_ui = bzrlib.ui.ui_factory
1413
bzrlib.trace.info('running tests...')
1415
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1416
if testspecs_list is not None:
1417
pattern = '|'.join(testspecs_list)
1420
result = selftest(verbose=verbose,
1422
stop_on_failure=one,
1423
keep_output=keep_output)
1425
bzrlib.trace.info('tests passed')
1427
bzrlib.trace.info('tests failed')
1428
return int(not result)
1430
bzrlib.ui.ui_factory = save_ui
1434
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1435
# is bzrlib itself in a branch?
1436
bzrrev = bzrlib.get_bzr_revision()
1438
print " (bzr checkout, revision %d {%s})" % bzrrev
1439
print bzrlib.__copyright__
1440
print "http://bazaar-ng.org/"
1442
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1443
print "you may use, modify and redistribute it under the terms of the GNU"
1444
print "General Public License version 2 or later."
1447
class cmd_version(Command):
1448
"""Show version of bzr."""
1453
class cmd_rocks(Command):
1454
"""Statement of optimism."""
1458
print "it sure does!"
1461
class cmd_find_merge_base(Command):
1462
"""Find and print a base revision for merging two branches.
1464
# TODO: Options to specify revisions on either side, as if
1465
# merging only part of the history.
1466
takes_args = ['branch', 'other']
1470
def run(self, branch, other):
1471
from bzrlib.revision import common_ancestor, MultipleRevisionSources
1473
branch1 = Branch.open_containing(branch)[0]
1474
branch2 = Branch.open_containing(other)[0]
1476
history_1 = branch1.revision_history()
1477
history_2 = branch2.revision_history()
1479
last1 = branch1.last_revision()
1480
last2 = branch2.last_revision()
1482
source = MultipleRevisionSources(branch1, branch2)
1484
base_rev_id = common_ancestor(last1, last2, source)
1486
print 'merge base is revision %s' % base_rev_id
1490
if base_revno is None:
1491
raise bzrlib.errors.UnrelatedBranches()
1493
print ' r%-6d in %s' % (base_revno, branch)
1495
other_revno = branch2.revision_id_to_revno(base_revid)
1497
print ' r%-6d in %s' % (other_revno, other)
1501
class cmd_merge(Command):
1502
"""Perform a three-way merge.
1504
The branch is the branch you will merge from. By default, it will
1505
merge the latest revision. If you specify a revision, that
1506
revision will be merged. If you specify two revisions, the first
1507
will be used as a BASE, and the second one as OTHER. Revision
1508
numbers are always relative to the specified branch.
1510
By default bzr will try to merge in all new work from the other
1511
branch, automatically determining an appropriate base. If this
1512
fails, you may need to give an explicit base.
1516
To merge the latest revision from bzr.dev
1517
bzr merge ../bzr.dev
1519
To merge changes up to and including revision 82 from bzr.dev
1520
bzr merge -r 82 ../bzr.dev
1522
To merge the changes introduced by 82, without previous changes:
1523
bzr merge -r 81..82 ../bzr.dev
1525
merge refuses to run if there are any uncommitted changes, unless
1528
takes_args = ['branch?']
1529
takes_options = ['revision', 'force', 'merge-type', 'reprocess',
1530
Option('show-base', help="Show base revision text in "
1533
def run(self, branch=None, revision=None, force=False, merge_type=None,
1534
show_base=False, reprocess=False):
1535
from bzrlib.merge import merge
1536
from bzrlib.merge_core import ApplyMerge3
1537
if merge_type is None:
1538
merge_type = ApplyMerge3
1540
branch = WorkingTree.open_containing(u'.')[0].branch.get_parent()
1542
raise BzrCommandError("No merge location known or specified.")
1544
print "Using saved location: %s" % branch
1545
if revision is None or len(revision) < 1:
1547
other = [branch, -1]
1549
if len(revision) == 1:
1551
other_branch = Branch.open_containing(branch)[0]
1552
revno = revision[0].in_history(other_branch).revno
1553
other = [branch, revno]
1555
assert len(revision) == 2
1556
if None in revision:
1557
raise BzrCommandError(
1558
"Merge doesn't permit that revision specifier.")
1559
b = Branch.open_containing(branch)[0]
1561
base = [branch, revision[0].in_history(b).revno]
1562
other = [branch, revision[1].in_history(b).revno]
1565
conflict_count = merge(other, base, check_clean=(not force),
1566
merge_type=merge_type, reprocess=reprocess,
1567
show_base=show_base)
1568
if conflict_count != 0:
1572
except bzrlib.errors.AmbiguousBase, e:
1573
m = ("sorry, bzr can't determine the right merge base yet\n"
1574
"candidates are:\n "
1575
+ "\n ".join(e.bases)
1577
"please specify an explicit base with -r,\n"
1578
"and (if you want) report this to the bzr developers\n")
1582
class cmd_remerge(Command):
1585
takes_args = ['file*']
1586
takes_options = ['merge-type', 'reprocess',
1587
Option('show-base', help="Show base revision text in "
1590
def run(self, file_list=None, merge_type=None, show_base=False,
1592
from bzrlib.merge import merge_inner, transform_tree
1593
from bzrlib.merge_core import ApplyMerge3
1594
if merge_type is None:
1595
merge_type = ApplyMerge3
1596
tree, file_list = tree_files(file_list)
1599
pending_merges = tree.pending_merges()
1600
if len(pending_merges) != 1:
1601
raise BzrCommandError("Sorry, remerge only works after normal"
1602
+ " merges. Not cherrypicking or"
1604
base_revision = common_ancestor(tree.branch.last_revision(),
1605
pending_merges[0], tree.branch)
1606
base_tree = tree.branch.revision_tree(base_revision)
1607
other_tree = tree.branch.revision_tree(pending_merges[0])
1608
interesting_ids = None
1609
if file_list is not None:
1610
interesting_ids = set()
1611
for filename in file_list:
1612
file_id = tree.path2id(filename)
1613
interesting_ids.add(file_id)
1614
if tree.kind(file_id) != "directory":
1617
for name, ie in tree.inventory.iter_entries(file_id):
1618
interesting_ids.add(ie.file_id)
1619
transform_tree(tree, tree.branch.basis_tree(), interesting_ids)
1620
if file_list is None:
1621
restore_files = list(tree.iter_conflicts())
1623
restore_files = file_list
1624
for filename in restore_files:
1626
restore(tree.abspath(filename))
1627
except NotConflicted:
1629
conflicts = merge_inner(tree.branch, other_tree, base_tree,
1630
interesting_ids = interesting_ids,
1631
other_rev_id=pending_merges[0],
1632
merge_type=merge_type,
1633
show_base=show_base,
1634
reprocess=reprocess)
1642
class cmd_revert(Command):
1643
"""Reverse all changes since the last commit.
1645
Only versioned files are affected. Specify filenames to revert only
1646
those files. By default, any files that are changed will be backed up
1647
first. Backup files have a '~' appended to their name.
1649
takes_options = ['revision', 'no-backup']
1650
takes_args = ['file*']
1651
aliases = ['merge-revert']
1653
def run(self, revision=None, no_backup=False, file_list=None):
1654
from bzrlib.merge import merge_inner
1655
from bzrlib.commands import parse_spec
1656
if file_list is not None:
1657
if len(file_list) == 0:
1658
raise BzrCommandError("No files specified")
1661
if revision is None:
1663
tree = WorkingTree.open_containing(u'.')[0]
1664
# FIXME should be tree.last_revision
1665
rev_id = tree.branch.last_revision()
1666
elif len(revision) != 1:
1667
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1669
tree, file_list = tree_files(file_list)
1670
rev_id = revision[0].in_history(tree.branch).rev_id
1671
tree.revert(file_list, tree.branch.revision_tree(rev_id),
1675
class cmd_assert_fail(Command):
1676
"""Test reporting of assertion failures"""
1679
assert False, "always fails"
1682
class cmd_help(Command):
1683
"""Show help on a command or other topic.
1685
For a list of all available commands, say 'bzr help commands'."""
1686
takes_options = ['long']
1687
takes_args = ['topic?']
1691
def run(self, topic=None, long=False):
1693
if topic is None and long:
1698
class cmd_shell_complete(Command):
1699
"""Show appropriate completions for context.
1701
For a list of all available commands, say 'bzr shell-complete'."""
1702
takes_args = ['context?']
1707
def run(self, context=None):
1708
import shellcomplete
1709
shellcomplete.shellcomplete(context)
1712
class cmd_fetch(Command):
1713
"""Copy in history from another branch but don't merge it.
1715
This is an internal method used for pull and merge."""
1717
takes_args = ['from_branch', 'to_branch']
1718
def run(self, from_branch, to_branch):
1719
from bzrlib.fetch import Fetcher
1720
from bzrlib.branch import Branch
1721
from_b = Branch.open(from_branch)
1722
to_b = Branch.open(to_branch)
1727
Fetcher(to_b, from_b)
1734
class cmd_missing(Command):
1735
"""What is missing in this branch relative to other branch.
1737
# TODO: rewrite this in terms of ancestry so that it shows only
1740
takes_args = ['remote?']
1741
aliases = ['mis', 'miss']
1742
takes_options = ['verbose']
1745
def run(self, remote=None, verbose=False):
1746
from bzrlib.errors import BzrCommandError
1747
from bzrlib.missing import show_missing
1749
if verbose and is_quiet():
1750
raise BzrCommandError('Cannot pass both quiet and verbose')
1752
tree = WorkingTree.open_containing(u'.')[0]
1753
parent = tree.branch.get_parent()
1756
raise BzrCommandError("No missing location known or specified.")
1759
print "Using last location: %s" % parent
1761
elif parent is None:
1762
# We only update parent if it did not exist, missing
1763
# should not change the parent
1764
tree.branch.set_parent(remote)
1765
br_remote = Branch.open_containing(remote)[0]
1766
return show_missing(tree.branch, br_remote, verbose=verbose,
1770
class cmd_plugins(Command):
1775
import bzrlib.plugin
1776
from inspect import getdoc
1777
for name, plugin in bzrlib.plugin.all_plugins().items():
1778
if hasattr(plugin, '__path__'):
1779
print plugin.__path__[0]
1780
elif hasattr(plugin, '__file__'):
1781
print plugin.__file__
1787
print '\t', d.split('\n')[0]
1790
class cmd_testament(Command):
1791
"""Show testament (signing-form) of a revision."""
1792
takes_options = ['revision', 'long']
1793
takes_args = ['branch?']
1795
def run(self, branch=u'.', revision=None, long=False):
1796
from bzrlib.testament import Testament
1797
b = WorkingTree.open_containing(branch)[0].branch
1800
if revision is None:
1801
rev_id = b.last_revision()
1803
rev_id = revision[0].in_history(b).rev_id
1804
t = Testament.from_revision(b, rev_id)
1806
sys.stdout.writelines(t.as_text_lines())
1808
sys.stdout.write(t.as_short_text())
1813
class cmd_annotate(Command):
1814
"""Show the origin of each line in a file.
1816
This prints out the given file with an annotation on the left side
1817
indicating which revision, author and date introduced the change.
1819
If the origin is the same for a run of consecutive lines, it is
1820
shown only at the top, unless the --all option is given.
1822
# TODO: annotate directories; showing when each file was last changed
1823
# TODO: annotate a previous version of a file
1824
# TODO: if the working copy is modified, show annotations on that
1825
# with new uncommitted lines marked
1826
aliases = ['blame', 'praise']
1827
takes_args = ['filename']
1828
takes_options = [Option('all', help='show annotations on all lines'),
1829
Option('long', help='show date in annotations'),
1833
def run(self, filename, all=False, long=False):
1834
from bzrlib.annotate import annotate_file
1835
tree, relpath = WorkingTree.open_containing(filename)
1836
branch = tree.branch
1839
file_id = tree.inventory.path2id(relpath)
1840
tree = branch.revision_tree(branch.last_revision())
1841
file_version = tree.inventory[file_id].revision
1842
annotate_file(branch, file_version, file_id, long, all, sys.stdout)
1847
class cmd_re_sign(Command):
1848
"""Create a digital signature for an existing revision."""
1849
# TODO be able to replace existing ones.
1851
hidden = True # is this right ?
1852
takes_args = ['revision_id?']
1853
takes_options = ['revision']
1855
def run(self, revision_id=None, revision=None):
1856
import bzrlib.config as config
1857
import bzrlib.gpg as gpg
1858
if revision_id is not None and revision is not None:
1859
raise BzrCommandError('You can only supply one of revision_id or --revision')
1860
if revision_id is None and revision is None:
1861
raise BzrCommandError('You must supply either --revision or a revision_id')
1862
b = WorkingTree.open_containing(u'.')[0].branch
1863
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1864
if revision_id is not None:
1865
b.sign_revision(revision_id, gpg_strategy)
1866
elif revision is not None:
1867
if len(revision) == 1:
1868
revno, rev_id = revision[0].in_history(b)
1869
b.sign_revision(rev_id, gpg_strategy)
1870
elif len(revision) == 2:
1871
# are they both on rh- if so we can walk between them
1872
# might be nice to have a range helper for arbitrary
1873
# revision paths. hmm.
1874
from_revno, from_revid = revision[0].in_history(b)
1875
to_revno, to_revid = revision[1].in_history(b)
1876
if to_revid is None:
1877
to_revno = b.revno()
1878
if from_revno is None or to_revno is None:
1879
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
1880
for revno in range(from_revno, to_revno + 1):
1881
b.sign_revision(b.get_rev_id(revno), gpg_strategy)
1883
raise BzrCommandError('Please supply either one revision, or a range.')
1886
class cmd_uncommit(bzrlib.commands.Command):
1887
"""Remove the last committed revision.
1889
By supplying the --all flag, it will not only remove the entry
1890
from revision_history, but also remove all of the entries in the
1893
--verbose will print out what is being removed.
1894
--dry-run will go through all the motions, but not actually
1897
In the future, uncommit will create a changeset, which can then
1900
takes_options = ['all', 'verbose', 'revision',
1901
Option('dry-run', help='Don\'t actually make changes'),
1902
Option('force', help='Say yes to all questions.')]
1903
takes_args = ['location?']
1906
def run(self, location=None, all=False,
1907
dry_run=False, verbose=False,
1908
revision=None, force=False):
1909
from bzrlib.branch import Branch
1910
from bzrlib.log import log_formatter
1912
from bzrlib.uncommit import uncommit
1914
if location is None:
1916
b, relpath = Branch.open_containing(location)
1918
if revision is None:
1920
rev_id = b.last_revision()
1922
revno, rev_id = revision[0].in_history(b)
1924
print 'No revisions to uncommit.'
1926
for r in range(revno, b.revno()+1):
1927
rev_id = b.get_rev_id(r)
1928
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
1929
lf.show(r, b.get_revision(rev_id), None)
1932
print 'Dry-run, pretending to remove the above revisions.'
1934
val = raw_input('Press <enter> to continue')
1936
print 'The above revision(s) will be removed.'
1938
val = raw_input('Are you sure [y/N]? ')
1939
if val.lower() not in ('y', 'yes'):
1943
uncommit(b, remove_files=all,
1944
dry_run=dry_run, verbose=verbose,
1948
# these get imported and then picked up by the scan for cmd_*
1949
# TODO: Some more consistent way to split command definitions across files;
1950
# we do need to load at least some information about them to know of
1952
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore