14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""builtin bzr commands"""
17
"""builtin brz commands"""
21
from bzrlib.lazy_import import lazy_import
22
lazy_import(globals(), """
30
from . import lazy_import
31
lazy_import.lazy_import(globals(), """
36
branch as _mod_branch,
42
config as _mod_config,
41
48
merge as _mod_merge,
49
mergeable as _mod_mergeable,
46
54
revision as _mod_revision,
55
from bzrlib.branch import Branch
56
from bzrlib.conflicts import ConflictList
57
from bzrlib.transport import memory
58
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
59
from bzrlib.smtp_connection import SMTPConnection
60
from bzrlib.workingtree import WorkingTree
63
from breezy.branch import Branch
64
from breezy.conflicts import ConflictList
65
from breezy.transport import memory
66
from breezy.smtp_connection import SMTPConnection
67
from breezy.workingtree import WorkingTree
68
from breezy.i18n import gettext, ngettext
63
from bzrlib.commands import (
71
from .commands import (
65
73
builtin_command_registry,
68
from bzrlib.option import (
73
81
_parse_revision_str,
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
81
return internal_tree_files(file_list, default_branch, canonicalize,
83
except errors.FileInWrongBranch, e:
84
raise errors.BzrCommandError("%s is not in the same branch as %s" %
85
(e.path, file_list[0]))
83
from .revisionspec import (
87
from .trace import mutter, note, warning, is_quiet, get_verbosity_level
90
def _get_branch_location(control_dir, possible_transports=None):
91
"""Return location of branch for this control dir."""
93
target = control_dir.get_branch_reference()
94
except errors.NotBranchError:
95
return control_dir.root_transport.base
96
if target is not None:
98
this_branch = control_dir.open_branch(
99
possible_transports=possible_transports)
100
# This may be a heavy checkout, where we want the master branch
101
master_location = this_branch.get_bound_location()
102
if master_location is not None:
103
return master_location
104
# If not, use a local sibling
105
return this_branch.base
108
def _is_colocated(control_dir, possible_transports=None):
109
"""Check if the branch in control_dir is colocated.
111
:param control_dir: Control directory
112
:return: Tuple with boolean indicating whether the branch is colocated
113
and the full URL to the actual branch
115
# This path is meant to be relative to the existing branch
116
this_url = _get_branch_location(
117
control_dir, possible_transports=possible_transports)
118
# Perhaps the target control dir supports colocated branches?
120
root = controldir.ControlDir.open(
121
this_url, possible_transports=possible_transports)
122
except errors.NotBranchError:
123
return (False, this_url)
126
control_dir.open_workingtree()
127
except (errors.NoWorkingTree, errors.NotLocalUrl):
128
return (False, this_url)
131
root._format.colocated_branches and
132
control_dir.control_url == root.control_url,
136
def lookup_new_sibling_branch(control_dir, location, possible_transports=None):
137
"""Lookup the location for a new sibling branch.
139
:param control_dir: Control directory to find sibling branches from
140
:param location: Name of the new branch
141
:return: Full location to the new branch
143
location = directory_service.directories.dereference(location)
144
if '/' not in location and '\\' not in location:
145
(colocated, this_url) = _is_colocated(control_dir, possible_transports)
148
return urlutils.join_segment_parameters(
149
this_url, {"branch": urlutils.escape(location)})
151
return urlutils.join(this_url, '..', urlutils.escape(location))
155
def open_sibling_branch(control_dir, location, possible_transports=None):
156
"""Open a branch, possibly a sibling of another.
158
:param control_dir: Control directory relative to which to lookup the
160
:param location: Location to look up
161
:return: branch to open
164
# Perhaps it's a colocated branch?
165
return control_dir.open_branch(
166
location, possible_transports=possible_transports)
167
except (errors.NotBranchError, errors.NoColocatedBranchSupport):
168
this_url = _get_branch_location(control_dir)
171
this_url, '..', urlutils.escape(location)))
174
def open_nearby_branch(near=None, location=None, possible_transports=None):
175
"""Open a nearby branch.
177
:param near: Optional location of container from which to open branch
178
:param location: Location of the branch
179
:return: Branch instance
186
location, possible_transports=possible_transports)
187
except errors.NotBranchError:
189
cdir = controldir.ControlDir.open(
190
near, possible_transports=possible_transports)
191
return open_sibling_branch(
192
cdir, location, possible_transports=possible_transports)
195
def iter_sibling_branches(control_dir, possible_transports=None):
196
"""Iterate over the siblings of a branch.
198
:param control_dir: Control directory for which to look up the siblings
199
:return: Iterator over tuples with branch name and branch object
202
reference = control_dir.get_branch_reference()
203
except errors.NotBranchError:
205
if reference is not None:
207
ref_branch = Branch.open(
208
reference, possible_transports=possible_transports)
209
except errors.NotBranchError:
213
if ref_branch is None or ref_branch.name:
214
if ref_branch is not None:
215
control_dir = ref_branch.controldir
216
for name, branch in control_dir.get_branches().items():
219
repo = ref_branch.controldir.find_repository()
220
for branch in repo.find_branches(using=True):
221
name = urlutils.relative_url(
222
repo.user_url, branch.user_url).rstrip("/")
88
226
def tree_files_for_add(file_list):
364
442
def run(self, revision_id=None, revision=None, directory=u'.'):
365
443
if revision_id is not None and revision is not None:
366
raise errors.BzrCommandError('You can only supply one of'
367
' revision_id or --revision')
444
raise errors.BzrCommandError(gettext('You can only supply one of'
445
' revision_id or --revision'))
368
446
if revision_id is None and revision is None:
369
raise errors.BzrCommandError('You must supply either'
370
' --revision or a revision_id')
371
b = WorkingTree.open_containing(directory)[0].branch
373
revisions = b.repository.revisions
447
raise errors.BzrCommandError(
448
gettext('You must supply either --revision or a revision_id'))
450
b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
452
revisions = getattr(b.repository, "revisions", None)
374
453
if revisions is None:
375
raise errors.BzrCommandError('Repository %r does not support '
376
'access to raw revision texts')
454
raise errors.BzrCommandError(
455
gettext('Repository %r does not support '
456
'access to raw revision texts') % b.repository)
378
b.repository.lock_read()
458
with b.repository.lock_read():
380
459
# TODO: jam 20060112 should cat-revision always output utf-8?
381
460
if revision_id is not None:
382
revision_id = osutils.safe_revision_id(revision_id, warn=False)
461
revision_id = cache_utf8.encode(revision_id)
384
463
self.print_revision(revisions, revision_id)
385
464
except errors.NoSuchRevision:
386
msg = "The repository %s contains no revision %s." % (
387
b.repository.base, revision_id)
466
"The repository {0} contains no revision {1}.").format(
467
b.repository.base, revision_id.decode('utf-8'))
388
468
raise errors.BzrCommandError(msg)
389
469
elif revision is not None:
390
470
for rev in revision:
392
472
raise errors.BzrCommandError(
393
'You cannot specify a NULL revision.')
473
gettext('You cannot specify a NULL revision.'))
394
474
rev_id = rev.as_revision_id(b)
395
475
self.print_revision(revisions, rev_id)
397
b.repository.unlock()
400
class cmd_dump_btree(Command):
401
__doc__ = """Dump the contents of a btree index file to stdout.
403
PATH is a btree index file, it can be any URL. This includes things like
404
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
406
By default, the tuples stored in the index file will be displayed. With
407
--raw, we will uncompress the pages, but otherwise display the raw bytes
411
# TODO: Do we want to dump the internal nodes as well?
412
# TODO: It would be nice to be able to dump the un-parsed information,
413
# rather than only going through iter_all_entries. However, this is
414
# good enough for a start
416
encoding_type = 'exact'
417
takes_args = ['path']
418
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
419
' rather than the parsed tuples.'),
422
def run(self, path, raw=False):
423
dirname, basename = osutils.split(path)
424
t = transport.get_transport(dirname)
426
self._dump_raw_bytes(t, basename)
428
self._dump_entries(t, basename)
430
def _get_index_and_bytes(self, trans, basename):
431
"""Create a BTreeGraphIndex and raw bytes."""
432
bt = btree_index.BTreeGraphIndex(trans, basename, None)
433
bytes = trans.get_bytes(basename)
434
bt._file = cStringIO.StringIO(bytes)
435
bt._size = len(bytes)
438
def _dump_raw_bytes(self, trans, basename):
441
# We need to parse at least the root node.
442
# This is because the first page of every row starts with an
443
# uncompressed header.
444
bt, bytes = self._get_index_and_bytes(trans, basename)
445
for page_idx, page_start in enumerate(xrange(0, len(bytes),
446
btree_index._PAGE_SIZE)):
447
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
448
page_bytes = bytes[page_start:page_end]
450
self.outf.write('Root node:\n')
451
header_end, data = bt._parse_header_from_bytes(page_bytes)
452
self.outf.write(page_bytes[:header_end])
454
self.outf.write('\nPage %d\n' % (page_idx,))
455
decomp_bytes = zlib.decompress(page_bytes)
456
self.outf.write(decomp_bytes)
457
self.outf.write('\n')
459
def _dump_entries(self, trans, basename):
461
st = trans.stat(basename)
462
except errors.TransportNotPossible:
463
# We can't stat, so we'll fake it because we have to do the 'get()'
465
bt, _ = self._get_index_and_bytes(trans, basename)
467
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
468
for node in bt.iter_all_entries():
469
# Node is made up of:
470
# (index, key, value, [references])
474
refs_as_tuples = None
476
refs_as_tuples = static_tuple.as_tuples(refs)
477
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
478
self.outf.write('%s\n' % (as_tuple,))
481
478
class cmd_remove_tree(Command):
484
481
Since a lightweight checkout is little more than a working tree
485
482
this will refuse to run against one.
487
To re-create the working tree, use "bzr checkout".
484
To re-create the working tree, use "brz checkout".
489
486
_see_also = ['checkout', 'working-trees']
490
487
takes_args = ['location*']
491
488
takes_options = [
493
490
help='Remove the working tree even if it has '
494
'uncommitted changes.'),
491
'uncommitted or shelved changes.'),
497
494
def run(self, location_list, force=False):
498
495
if not location_list:
496
location_list = ['.']
501
498
for location in location_list:
502
d = bzrdir.BzrDir.open(location)
499
d = controldir.ControlDir.open(location)
505
502
working = d.open_workingtree()
506
503
except errors.NoWorkingTree:
507
raise errors.BzrCommandError("No working tree to remove")
504
raise errors.BzrCommandError(
505
gettext("No working tree to remove"))
508
506
except errors.NotLocalUrl:
509
raise errors.BzrCommandError("You cannot remove the working tree"
507
raise errors.BzrCommandError(
508
gettext("You cannot remove the working tree"
509
" of a remote path"))
512
511
if (working.has_changes()):
513
512
raise errors.UncommittedChanges(working)
513
if working.get_shelf_manager().last_shelf() is not None:
514
raise errors.ShelvedChanges(working)
515
516
if working.user_url != working.branch.user_url:
516
raise errors.BzrCommandError("You cannot remove the working tree"
517
" from a lightweight checkout")
517
raise errors.BzrCommandError(
518
gettext("You cannot remove the working tree"
519
" from a lightweight checkout"))
519
521
d.destroy_workingtree()
524
class cmd_repair_workingtree(Command):
525
__doc__ = """Reset the working tree state file.
527
This is not meant to be used normally, but more as a way to recover from
528
filesystem corruption, etc. This rebuilds the working inventory back to a
529
'known good' state. Any new modifications (adding a file, renaming, etc)
530
will be lost, though modified files will still be detected as such.
532
Most users will want something more like "brz revert" or "brz update"
533
unless the state file has become corrupted.
535
By default this attempts to recover the current state by looking at the
536
headers of the state file. If the state file is too corrupted to even do
537
that, you can supply --revision to force the state of the tree.
541
'revision', 'directory',
543
help='Reset the tree even if it doesn\'t appear to be'
548
def run(self, revision=None, directory='.', force=False):
549
tree, _ = WorkingTree.open_containing(directory)
550
self.enter_context(tree.lock_tree_write())
554
except errors.BzrError:
555
pass # There seems to be a real error here, so we'll reset
558
raise errors.BzrCommandError(gettext(
559
'The tree does not appear to be corrupt. You probably'
560
' want "brz revert" instead. Use "--force" if you are'
561
' sure you want to reset the working tree.'))
565
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
567
tree.reset_state(revision_ids)
568
except errors.BzrError:
569
if revision_ids is None:
570
extra = gettext(', the header appears corrupt, try passing '
571
'-r -1 to set the state to the last commit')
574
raise errors.BzrCommandError(
575
gettext('failed to reset the tree state{0}').format(extra))
522
578
class cmd_revno(Command):
523
579
__doc__ = """Show current revision number.
747
858
takes_options = [
861
Option('include-root',
862
help='Include the entry for the root of the tree, if any.'),
751
help='List entries of a particular kind: file, directory, symlink.',
864
help='List entries of a particular kind: file, directory, '
754
868
takes_args = ['file*']
757
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
871
def run(self, revision=None, show_ids=False, kind=None, include_root=False,
758
873
if kind and kind not in ['file', 'directory', 'symlink']:
759
raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
874
raise errors.BzrCommandError(
875
gettext('invalid kind %r specified') % (kind,))
761
877
revision = _get_one_revision('inventory', revision)
762
work_tree, file_list = tree_files(file_list)
763
self.add_cleanup(work_tree.lock_read().unlock)
878
work_tree, file_list = WorkingTree.open_containing_paths(file_list)
879
self.enter_context(work_tree.lock_read())
764
880
if revision is not None:
765
881
tree = revision.as_tree(work_tree.branch)
767
883
extra_trees = [work_tree]
768
self.add_cleanup(tree.lock_read().unlock)
884
self.enter_context(tree.lock_read())
889
self.enter_context(tree.lock_read())
773
890
if file_list is not None:
774
file_ids = tree.paths2ids(file_list, trees=extra_trees,
775
require_versioned=True)
891
paths = tree.find_related_paths_across_trees(
892
file_list, extra_trees, require_versioned=True)
776
893
# find_ids_across_trees may include some paths that don't
777
894
# exist in 'tree'.
778
entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
779
for file_id in file_ids if file_id in tree)
895
entries = tree.iter_entries_by_dir(specific_files=paths)
781
entries = tree.inventory.entries()
897
entries = tree.iter_entries_by_dir()
784
for path, entry in entries:
899
for path, entry in sorted(entries):
785
900
if kind and kind != entry.kind:
902
if path == "" and not include_root:
788
self.outf.write('%-50s %s\n' % (path, entry.file_id))
905
self.outf.write('%-50s %s\n' % (
906
path, entry.file_id.decode('utf-8')))
790
908
self.outf.write(path)
791
909
self.outf.write('\n')
912
class cmd_cp(Command):
913
__doc__ = """Copy a file.
916
brz cp OLDNAME NEWNAME
918
brz cp SOURCE... DESTINATION
920
If the last argument is a versioned directory, all the other names
921
are copied into it. Otherwise, there must be exactly two arguments
922
and the file is copied to a new name.
924
Files cannot be copied between branches. Only files can be copied
928
takes_args = ['names*']
931
encoding_type = 'replace'
933
def run(self, names_list):
934
if names_list is None:
936
if len(names_list) < 2:
937
raise errors.BzrCommandError(gettext("missing file argument"))
938
tree, rel_names = WorkingTree.open_containing_paths(
939
names_list, canonicalize=False)
940
for file_name in rel_names[0:-1]:
942
raise errors.BzrCommandError(
943
gettext("can not copy root of branch"))
944
self.enter_context(tree.lock_tree_write())
945
into_existing = osutils.isdir(names_list[-1])
946
if not into_existing:
948
(src, dst) = rel_names
950
raise errors.BzrCommandError(
951
gettext('to copy multiple files the'
952
' destination must be a versioned'
957
(n, osutils.joinpath([rel_names[-1], osutils.basename(n)]))
958
for n in rel_names[:-1]]
960
for src, dst in pairs:
962
src_kind = tree.stored_kind(src)
963
except errors.NoSuchFile:
964
raise errors.BzrCommandError(
965
gettext('Could not copy %s => %s: %s is not versioned.')
968
raise errors.BzrCommandError(
969
gettext('Could not copy %s => %s . %s is not versioned\\.'
971
if src_kind == 'directory':
972
raise errors.BzrCommandError(
973
gettext('Could not copy %s => %s . %s is a directory.'
975
dst_parent = osutils.split(dst)[0]
978
dst_parent_kind = tree.stored_kind(dst_parent)
979
except errors.NoSuchFile:
980
raise errors.BzrCommandError(
981
gettext('Could not copy %s => %s: %s is not versioned.')
982
% (src, dst, dst_parent))
983
if dst_parent_kind != 'directory':
984
raise errors.BzrCommandError(
985
gettext('Could not copy to %s: %s is not a directory.')
986
% (dst_parent, dst_parent))
988
tree.copy_one(src, dst)
794
991
class cmd_mv(Command):
795
992
__doc__ = """Move or rename a file.
798
bzr mv OLDNAME NEWNAME
995
brz mv OLDNAME NEWNAME
800
bzr mv SOURCE... DESTINATION
997
brz mv SOURCE... DESTINATION
802
999
If the last argument is a versioned directory, all the other names
803
1000
are moved into it. Otherwise, there must be exactly two arguments
1060
1291
considered diverged if the destination branch's most recent commit is one
1061
1292
that has not been merged (directly or indirectly) by the source branch.
1063
If branches have diverged, you can use 'bzr push --overwrite' to replace
1294
If branches have diverged, you can use 'brz push --overwrite' to replace
1064
1295
the other branch completely, discarding its unmerged changes.
1066
1297
If you want to ensure you have the different changes in the other branch,
1067
do a merge (see bzr help merge) from the other branch, and commit that.
1298
do a merge (see brz help merge) from the other branch, and commit that.
1068
1299
After that you will be able to do a push without '--overwrite'.
1070
If there is no default push location set, the first push will set it.
1071
After that, you can omit the location to use the default. To change the
1072
default, use --remember. The value will only be saved if the remote
1073
location can be accessed.
1301
If there is no default push location set, the first push will set it (use
1302
--no-remember to avoid setting it). After that, you can omit the
1303
location to use the default. To change the default, use --remember. The
1304
value will only be saved if the remote location can be accessed.
1306
The --verbose option will display the revisions pushed using the log_format
1307
configuration option. You can use a different format by overriding it with
1308
-Olog_format=<other_format>.
1076
1311
_see_also = ['pull', 'update', 'working-trees']
1077
1312
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
1078
Option('create-prefix',
1079
help='Create the path leading up to the branch '
1080
'if it does not already exist.'),
1081
custom_help('directory',
1082
help='Branch to push from, '
1083
'rather than the one containing the working directory.'),
1084
Option('use-existing-dir',
1085
help='By default push will fail if the target'
1086
' directory exists, but does not already'
1087
' have a control directory. This flag will'
1088
' allow push to proceed.'),
1090
help='Create a stacked branch that references the public location '
1091
'of the parent branch.'),
1092
Option('stacked-on',
1093
help='Create a stacked branch that refers to another branch '
1094
'for the commit history. Only the work not present in the '
1095
'referenced branch is included in the branch created.',
1098
help='Refuse to push if there are uncommitted changes in'
1099
' the working tree, --no-strict disables the check.'),
1313
Option('create-prefix',
1314
help='Create the path leading up to the branch '
1315
'if it does not already exist.'),
1316
custom_help('directory',
1317
help='Branch to push from, '
1318
'rather than the one containing the working directory.'),
1319
Option('use-existing-dir',
1320
help='By default push will fail if the target'
1321
' directory exists, but does not already'
1322
' have a control directory. This flag will'
1323
' allow push to proceed.'),
1325
help='Create a stacked branch that references the public location '
1326
'of the parent branch.'),
1327
Option('stacked-on',
1328
help='Create a stacked branch that refers to another branch '
1329
'for the commit history. Only the work not present in the '
1330
'referenced branch is included in the branch created.',
1333
help='Refuse to push if there are uncommitted changes in'
1334
' the working tree, --no-strict disables the check.'),
1336
help="Don't populate the working tree, even for protocols"
1337
" that support it."),
1338
Option('overwrite-tags',
1339
help="Overwrite tags only."),
1340
Option('lossy', help="Allow lossy push, i.e. dropping metadata "
1341
"that can't be represented in the target.")
1101
1343
takes_args = ['location?']
1102
1344
encoding_type = 'replace'
1104
def run(self, location=None, remember=False, overwrite=False,
1105
create_prefix=False, verbose=False, revision=None,
1106
use_existing_dir=False, directory=None, stacked_on=None,
1107
stacked=False, strict=None):
1108
from bzrlib.push import _show_push_branch
1346
def run(self, location=None, remember=None, overwrite=False,
1347
create_prefix=False, verbose=False, revision=None,
1348
use_existing_dir=False, directory=None, stacked_on=None,
1349
stacked=False, strict=None, no_tree=False,
1350
overwrite_tags=False, lossy=False):
1351
from .location import location_to_url
1352
from .push import _show_push_branch
1355
overwrite = ["history", "tags"]
1356
elif overwrite_tags:
1357
overwrite = ["tags"]
1110
1361
if directory is None:
1111
1362
directory = '.'
1112
1363
# Get the source branch
1113
1364
(tree, br_from,
1114
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1365
_unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
1115
1366
# Get the tip's revision_id
1116
1367
revision = _get_one_revision('push', revision)
1117
1368
if revision is not None:
1176
1437
_see_also = ['checkout']
1177
1438
takes_args = ['from_location', 'to_location?']
1178
takes_options = ['revision', Option('hardlink',
1179
help='Hard-link working tree files where possible.'),
1181
help="Create a branch without a working-tree."),
1183
help="Switch the checkout in the current directory "
1184
"to the new branch."),
1186
help='Create a stacked branch referring to the source branch. '
1187
'The new branch will depend on the availability of the source '
1188
'branch for all operations.'),
1189
Option('standalone',
1190
help='Do not use a shared repository, even if available.'),
1191
Option('use-existing-dir',
1192
help='By default branch will fail if the target'
1193
' directory exists, but does not already'
1194
' have a control directory. This flag will'
1195
' allow branch to proceed.'),
1197
help="Bind new branch to from location."),
1199
aliases = ['get', 'clone']
1439
takes_options = ['revision',
1441
'hardlink', help='Hard-link working tree files where possible.'),
1442
Option('files-from', type=str,
1443
help="Get file contents from this tree."),
1445
help="Create a branch without a working-tree."),
1447
help="Switch the checkout in the current directory "
1448
"to the new branch."),
1450
help='Create a stacked branch referring to the source branch. '
1451
'The new branch will depend on the availability of the source '
1452
'branch for all operations.'),
1453
Option('standalone',
1454
help='Do not use a shared repository, even if available.'),
1455
Option('use-existing-dir',
1456
help='By default branch will fail if the target'
1457
' directory exists, but does not already'
1458
' have a control directory. This flag will'
1459
' allow branch to proceed.'),
1461
help="Bind new branch to from location."),
1462
Option('no-recurse-nested',
1463
help='Do not recursively check out nested trees.'),
1201
1466
def run(self, from_location, to_location=None, revision=None,
1202
1467
hardlink=False, stacked=False, standalone=False, no_tree=False,
1203
use_existing_dir=False, switch=False, bind=False):
1204
from bzrlib import switch as _mod_switch
1205
from bzrlib.tag import _merge_tags_if_possible
1206
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1468
use_existing_dir=False, switch=False, bind=False,
1469
files_from=None, no_recurse_nested=False):
1470
from breezy import switch as _mod_switch
1471
accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
1473
if no_recurse_nested:
1477
if not (hardlink or files_from):
1478
# accelerator_tree is usually slower because you have to read N
1479
# files (no readahead, lots of seeks, etc), but allow the user to
1480
# explicitly request it
1481
accelerator_tree = None
1482
if files_from is not None and files_from != from_location:
1483
accelerator_tree = WorkingTree.open(files_from)
1208
1484
revision = _get_one_revision('branch', revision)
1209
self.add_cleanup(br_from.lock_read().unlock)
1485
self.enter_context(br_from.lock_read())
1210
1486
if revision is not None:
1211
1487
revision_id = revision.as_revision_id(br_from)
1216
1492
revision_id = br_from.last_revision()
1217
1493
if to_location is None:
1218
1494
to_location = urlutils.derive_to_location(from_location)
1219
to_transport = transport.get_transport(to_location)
1495
to_transport = transport.get_transport(to_location, purpose='write')
1221
1497
to_transport.mkdir('.')
1222
1498
except errors.FileExists:
1223
if not use_existing_dir:
1224
raise errors.BzrCommandError('Target directory "%s" '
1225
'already exists.' % to_location)
1500
to_dir = controldir.ControlDir.open_from_transport(
1502
except errors.NotBranchError:
1503
if not use_existing_dir:
1504
raise errors.BzrCommandError(gettext('Target directory "%s" '
1505
'already exists.') % to_location)
1228
bzrdir.BzrDir.open_from_transport(to_transport)
1510
to_dir.open_branch()
1229
1511
except errors.NotBranchError:
1232
1514
raise errors.AlreadyBranchError(to_location)
1233
1515
except errors.NoSuchFile:
1234
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1516
raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
1237
# preserve whatever source format we have.
1238
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1239
possible_transports=[to_transport],
1240
accelerator_tree=accelerator_tree,
1241
hardlink=hardlink, stacked=stacked,
1242
force_new_repo=standalone,
1243
create_tree_if_local=not no_tree,
1244
source_branch=br_from)
1245
branch = dir.open_branch()
1246
except errors.NoSuchRevision:
1247
to_transport.delete_tree('.')
1248
msg = "The branch %s has no revision %s." % (from_location,
1250
raise errors.BzrCommandError(msg)
1251
_merge_tags_if_possible(br_from, branch)
1522
# preserve whatever source format we have.
1523
to_dir = br_from.controldir.sprout(
1524
to_transport.base, revision_id,
1525
possible_transports=[to_transport],
1526
accelerator_tree=accelerator_tree, hardlink=hardlink,
1527
stacked=stacked, force_new_repo=standalone,
1528
create_tree_if_local=not no_tree, source_branch=br_from,
1530
branch = to_dir.open_branch(
1531
possible_transports=[
1532
br_from.controldir.root_transport, to_transport])
1533
except errors.NoSuchRevision:
1534
to_transport.delete_tree('.')
1535
msg = gettext("The branch {0} has no revision {1}.").format(
1536
from_location, revision)
1537
raise errors.BzrCommandError(msg)
1540
to_repo = to_dir.open_repository()
1541
except errors.NoRepositoryPresent:
1542
to_repo = to_dir.create_repository()
1543
to_repo.fetch(br_from.repository, revision_id=revision_id)
1544
branch = br_from.sprout(
1545
to_dir, revision_id=revision_id)
1546
br_from.tags.merge_to(branch.tags)
1252
1548
# If the source branch is stacked, the new branch may
1253
1549
# be stacked whether we asked for that explicitly or not.
1254
1550
# We therefore need a try/except here and not just 'if stacked:'
1256
note('Created new stacked branch referring to %s.' %
1257
branch.get_stacked_on_url())
1258
except (errors.NotStacked, errors.UnstackableBranchFormat,
1259
errors.UnstackableRepositoryFormat), e:
1260
note('Branched %d revision(s).' % branch.revno())
1552
note(gettext('Created new stacked branch referring to %s.') %
1553
branch.get_stacked_on_url())
1554
except (errors.NotStacked, _mod_branch.UnstackableBranchFormat,
1555
errors.UnstackableRepositoryFormat) as e:
1556
revno = branch.revno()
1557
if revno is not None:
1558
note(ngettext('Branched %d revision.',
1559
'Branched %d revisions.',
1560
branch.revno()) % revno)
1562
note(gettext('Created new branch.'))
1262
1564
# Bind to the parent
1263
1565
parent_branch = Branch.open(from_location)
1264
1566
branch.bind(parent_branch)
1265
note('New branch bound to %s' % from_location)
1567
note(gettext('New branch bound to %s') % from_location)
1267
1569
# Switch to the new branch
1268
1570
wt, _ = WorkingTree.open_containing('.')
1269
_mod_switch.switch(wt.bzrdir, branch)
1270
note('Switched to branch: %s',
1271
urlutils.unescape_for_display(branch.base, 'utf-8'))
1571
_mod_switch.switch(wt.controldir, branch)
1572
note(gettext('Switched to branch: %s'),
1573
urlutils.unescape_for_display(branch.base, 'utf-8'))
1576
class cmd_branches(Command):
1577
__doc__ = """List the branches available at the current location.
1579
This command will print the names of all the branches at the current
1583
takes_args = ['location?']
1585
Option('recursive', short_name='R',
1586
help='Recursively scan for branches rather than '
1587
'just looking in the specified location.')]
1589
def run(self, location=".", recursive=False):
1591
t = transport.get_transport(location, purpose='read')
1592
if not t.listable():
1593
raise errors.BzrCommandError(
1594
"Can't scan this type of location.")
1595
for b in controldir.ControlDir.find_branches(t):
1596
self.outf.write("%s\n" % urlutils.unescape_for_display(
1597
urlutils.relative_url(t.base, b.base),
1598
self.outf.encoding).rstrip("/"))
1600
dir = controldir.ControlDir.open_containing(location)[0]
1602
active_branch = dir.open_branch(name="")
1603
except errors.NotBranchError:
1604
active_branch = None
1606
for name, branch in iter_sibling_branches(dir):
1609
active = (active_branch is not None and
1610
active_branch.user_url == branch.user_url)
1611
names[name] = active
1612
# Only mention the current branch explicitly if it's not
1613
# one of the colocated branches
1614
if not any(names.values()) and active_branch is not None:
1615
self.outf.write("* %s\n" % gettext("(default)"))
1616
for name in sorted(names):
1617
active = names[name]
1622
self.outf.write("%s %s\n" % (prefix, name))
1274
1625
class cmd_checkout(Command):
1275
1626
__doc__ = """Create a new checkout of an existing branch.
1277
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1278
the branch found in '.'. This is useful if you have removed the working tree
1279
or if it was never created - i.e. if you pushed the branch to its current
1280
location using SFTP.
1628
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree
1629
for the branch found in '.'. This is useful if you have removed the working
1630
tree or if it was never created - i.e. if you pushed the branch to its
1631
current location using SFTP.
1282
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1283
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1284
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1285
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1286
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1633
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION
1634
will be used. In other words, "checkout ../foo/bar" will attempt to create
1635
./bar. If the BRANCH_LOCATION has no / or path separator embedded, the
1636
TO_LOCATION is derived from the BRANCH_LOCATION by stripping a leading
1637
scheme or drive identifier, if any. For example, "checkout lp:foo-bar" will
1638
attempt to create ./foo-bar.
1289
1640
To retrieve the branch as of a particular revision, supply the --revision
1290
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1291
out of date [so you cannot commit] but it may be useful (i.e. to examine old
1641
parameter, as in "checkout foo/bar -r 5". Note that this will be
1642
immediately out of date [so you cannot commit] but it may be useful (i.e.
1643
to examine old code.)
1295
_see_also = ['checkouts', 'branch']
1646
_see_also = ['checkouts', 'branch', 'working-trees', 'remove-tree']
1296
1647
takes_args = ['branch_location?', 'to_location?']
1297
1648
takes_options = ['revision',
1298
1649
Option('lightweight',
1357
1707
@display_command
1358
1708
def run(self, dir=u'.'):
1359
1709
tree = WorkingTree.open_containing(dir)[0]
1360
self.add_cleanup(tree.lock_read().unlock)
1361
new_inv = tree.inventory
1710
self.enter_context(tree.lock_read())
1362
1711
old_tree = tree.basis_tree()
1363
self.add_cleanup(old_tree.lock_read().unlock)
1364
old_inv = old_tree.inventory
1712
self.enter_context(old_tree.lock_read())
1366
1714
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1367
for f, paths, c, v, p, n, k, e in iterator:
1368
if paths[0] == paths[1]:
1372
renames.append(paths)
1715
for change in iterator:
1716
if change.path[0] == change.path[1]:
1718
if None in change.path:
1720
renames.append(change.path)
1374
1722
for old_name, new_name in renames:
1375
1723
self.outf.write("%s => %s\n" % (old_name, new_name))
1378
1726
class cmd_update(Command):
1379
__doc__ = """Update a tree to have the latest code committed to its branch.
1381
This will perform a merge into the working tree, and may generate
1382
conflicts. If you have any local changes, you will still
1383
need to commit them after the update for the update to be complete.
1385
If you want to discard your local changes, you can just do a
1386
'bzr revert' instead of 'bzr commit' after the update.
1388
If the tree's branch is bound to a master branch, it will also update
1727
__doc__ = """Update a working tree to a new revision.
1729
This will perform a merge of the destination revision (the tip of the
1730
branch, or the specified revision) into the working tree, and then make
1731
that revision the basis revision for the working tree.
1733
You can use this to visit an older revision, or to update a working tree
1734
that is out of date from its branch.
1736
If there are any uncommitted changes in the tree, they will be carried
1737
across and remain as uncommitted changes after the update. To discard
1738
these changes, use 'brz revert'. The uncommitted changes may conflict
1739
with the changes brought in by the change in basis revision.
1741
If the tree's branch is bound to a master branch, brz will also update
1389
1742
the branch from the master.
1744
You cannot update just a single file or directory, because each Breezy
1745
working tree has just a single basis revision. If you want to restore a
1746
file that has been removed locally, use 'brz revert' instead of 'brz
1747
update'. If you want to restore a file to its state in a previous
1748
revision, use 'brz revert' with a '-r' option, or use 'brz cat' to write
1749
out the old content of that file to a new location.
1751
The 'dir' argument, if given, must be the location of the root of a
1752
working tree to update. By default, the working tree that contains the
1753
current working directory is used.
1392
1756
_see_also = ['pull', 'working-trees', 'status-flags']
1393
1757
takes_args = ['dir?']
1394
takes_options = ['revision']
1758
takes_options = ['revision',
1760
help="Show base revision text in conflicts."),
1395
1762
aliases = ['up']
1397
def run(self, dir='.', revision=None):
1764
def run(self, dir=None, revision=None, show_base=None):
1398
1765
if revision is not None and len(revision) != 1:
1399
raise errors.BzrCommandError(
1400
"bzr update --revision takes exactly one revision")
1401
tree = WorkingTree.open_containing(dir)[0]
1766
raise errors.BzrCommandError(gettext(
1767
"brz update --revision takes exactly one revision"))
1769
tree = WorkingTree.open_containing('.')[0]
1771
tree, relpath = WorkingTree.open_containing(dir)
1774
raise errors.BzrCommandError(gettext(
1775
"brz update can only update a whole tree, "
1776
"not a file or subdirectory"))
1402
1777
branch = tree.branch
1403
1778
possible_transports = []
1404
1779
master = branch.get_master_branch(
1405
1780
possible_transports=possible_transports)
1406
1781
if master is not None:
1407
1782
branch_location = master.base
1783
self.enter_context(tree.lock_write())
1410
1785
branch_location = tree.branch.base
1411
tree.lock_tree_write()
1412
self.add_cleanup(tree.unlock)
1786
self.enter_context(tree.lock_tree_write())
1413
1787
# get rid of the final '/' and be ready for display
1414
1788
branch_location = urlutils.unescape_for_display(
1415
1789
branch_location.rstrip('/'),
1500
1875
noise_level = get_verbosity_level()
1502
1877
noise_level = 0
1503
from bzrlib.info import show_bzrdir_info
1504
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1878
from .info import show_bzrdir_info
1879
show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
1505
1880
verbose=noise_level, outfile=self.outf)
1508
1883
class cmd_remove(Command):
1509
1884
__doc__ = """Remove files or directories.
1511
This makes bzr stop tracking changes to the specified files. bzr will delete
1512
them if they can easily be recovered using revert. If no options or
1513
parameters are given bzr will scan for files that are being tracked by bzr
1514
but missing in your tree and stop tracking them for you.
1886
This makes Breezy stop tracking changes to the specified files. Breezy will
1887
delete them if they can easily be recovered using revert otherwise they
1888
will be backed up (adding an extension of the form .~#~). If no options or
1889
parameters are given Breezy will scan for files that are being tracked by
1890
Breezy but missing in your tree and stop tracking them for you.
1516
1892
takes_args = ['file*']
1517
1893
takes_options = ['verbose',
1518
Option('new', help='Only remove files that have never been committed.'),
1519
RegistryOption.from_kwargs('file-deletion-strategy',
1520
'The file deletion mode to be used.',
1521
title='Deletion Strategy', value_switches=True, enum_switch=False,
1522
safe='Only delete files if they can be'
1523
' safely recovered (default).',
1524
keep='Delete from bzr but leave the working copy.',
1525
force='Delete all the specified files, even if they can not be '
1526
'recovered and even if they are non-empty directories.')]
1895
'new', help='Only remove files that have never been committed.'),
1896
RegistryOption.from_kwargs('file-deletion-strategy',
1897
'The file deletion mode to be used.',
1898
title='Deletion Strategy', value_switches=True, enum_switch=False,
1899
safe='Backup changed files (default).',
1900
keep='Delete from brz but leave the working copy.',
1901
no_backup='Don\'t backup changed files.'),
1527
1903
aliases = ['rm', 'del']
1528
1904
encoding_type = 'replace'
1530
1906
def run(self, file_list, verbose=False, new=False,
1531
file_deletion_strategy='safe'):
1532
tree, file_list = tree_files(file_list)
1907
file_deletion_strategy='safe'):
1909
tree, file_list = WorkingTree.open_containing_paths(file_list)
1534
1911
if file_list is not None:
1535
1912
file_list = [f for f in file_list]
1537
self.add_cleanup(tree.lock_write().unlock)
1914
self.enter_context(tree.lock_write())
1538
1915
# Heuristics should probably all move into tree.remove_smart or
1541
1918
added = tree.changes_from(tree.basis_tree(),
1542
specific_files=file_list).added
1543
file_list = sorted([f[0] for f in added], reverse=True)
1919
specific_files=file_list).added
1920
file_list = sorted([f.path[1] for f in added], reverse=True)
1544
1921
if len(file_list) == 0:
1545
raise errors.BzrCommandError('No matching files.')
1922
raise errors.BzrCommandError(gettext('No matching files.'))
1546
1923
elif file_list is None:
1547
1924
# missing files show up in iter_changes(basis) as
1548
1925
# versioned-with-no-kind.
1550
1927
for change in tree.iter_changes(tree.basis_tree()):
1551
1928
# Find paths in the working tree that have no kind:
1552
if change[1][1] is not None and change[6][1] is None:
1553
missing.append(change[1][1])
1929
if change.path[1] is not None and change.kind[1] is None:
1930
missing.append(change.path[1])
1554
1931
file_list = sorted(missing, reverse=True)
1555
1932
file_deletion_strategy = 'keep'
1556
1933
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1557
keep_files=file_deletion_strategy=='keep',
1558
force=file_deletion_strategy=='force')
1561
class cmd_file_id(Command):
1562
__doc__ = """Print file_id of a particular file or directory.
1564
The file_id is assigned when the file is first added and remains the
1565
same through all revisions where the file exists, even when it is
1570
_see_also = ['inventory', 'ls']
1571
takes_args = ['filename']
1574
def run(self, filename):
1575
tree, relpath = WorkingTree.open_containing(filename)
1576
i = tree.path2id(relpath)
1578
raise errors.NotVersionedError(filename)
1580
self.outf.write(i + '\n')
1583
class cmd_file_path(Command):
1584
__doc__ = """Print path of file_ids to a file or directory.
1586
This prints one line for each directory down to the target,
1587
starting at the branch root.
1591
takes_args = ['filename']
1594
def run(self, filename):
1595
tree, relpath = WorkingTree.open_containing(filename)
1596
fid = tree.path2id(relpath)
1598
raise errors.NotVersionedError(filename)
1599
segments = osutils.splitpath(relpath)
1600
for pos in range(1, len(segments) + 1):
1601
path = osutils.joinpath(segments[:pos])
1602
self.outf.write("%s\n" % tree.path2id(path))
1934
keep_files=file_deletion_strategy == 'keep',
1935
force=(file_deletion_strategy == 'no-backup'))
1605
1938
class cmd_reconcile(Command):
1606
__doc__ = """Reconcile bzr metadata in a branch.
1939
__doc__ = """Reconcile brz metadata in a branch.
1608
1941
This can correct data mismatches that may have been caused by
1609
previous ghost operations or bzr upgrades. You should only
1610
need to run this command if 'bzr check' or a bzr developer
1942
previous ghost operations or brz upgrades. You should only
1943
need to run this command if 'brz check' or a brz developer
1611
1944
advises you to run it.
1613
1946
If a second branch is provided, cross-branch reconciliation is
1614
1947
also attempted, which will check that data like the tree root
1615
id which was not present in very early bzr versions is represented
1948
id which was not present in very early brz versions is represented
1616
1949
correctly in both branches.
1618
1951
At the same time it is run it may recompress data resulting in
1730
2081
to_transport.ensure_base()
1731
2082
except errors.NoSuchFile:
1732
2083
if not create_prefix:
1733
raise errors.BzrCommandError("Parent directory of %s"
1735
"\nYou may supply --create-prefix to create all"
1736
" leading parent directories."
2084
raise errors.BzrCommandError(gettext("Parent directory of %s"
2086
"\nYou may supply --create-prefix to create all"
2087
" leading parent directories.")
1738
2089
to_transport.create_prefix()
1741
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
2092
a_controldir = controldir.ControlDir.open_from_transport(
1742
2094
except errors.NotBranchError:
1743
2095
# really a NotBzrDir error...
1744
create_branch = bzrdir.BzrDir.create_branch_convenience
2096
create_branch = controldir.ControlDir.create_branch_convenience
2098
force_new_tree = False
2100
force_new_tree = None
1745
2101
branch = create_branch(to_transport.base, format=format,
1746
possible_transports=[to_transport])
1747
a_bzrdir = branch.bzrdir
2102
possible_transports=[to_transport],
2103
force_new_tree=force_new_tree)
2104
a_controldir = branch.controldir
1749
from bzrlib.transport.local import LocalTransport
1750
if a_bzrdir.has_branch():
2106
from .transport.local import LocalTransport
2107
if a_controldir.has_branch():
1751
2108
if (isinstance(to_transport, LocalTransport)
1752
and not a_bzrdir.has_workingtree()):
1753
raise errors.BranchExistsWithoutWorkingTree(location)
2109
and not a_controldir.has_workingtree()):
2110
raise errors.BranchExistsWithoutWorkingTree(location)
1754
2111
raise errors.AlreadyBranchError(location)
1755
branch = a_bzrdir.create_branch()
1756
a_bzrdir.create_workingtree()
2112
branch = a_controldir.create_branch()
2113
if not no_tree and not a_controldir.has_workingtree():
2114
a_controldir.create_workingtree()
1757
2115
if append_revisions_only:
1759
2117
branch.set_append_revisions_only(True)
1760
2118
except errors.UpgradeRequired:
1761
raise errors.BzrCommandError('This branch format cannot be set'
1762
' to append-revisions-only. Try --default.')
2119
raise errors.BzrCommandError(gettext('This branch format cannot be set'
2120
' to append-revisions-only. Try --default.'))
1763
2121
if not is_quiet():
1764
from bzrlib.info import describe_layout, describe_format
2122
from .info import describe_layout, describe_format
1766
tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
2124
tree = a_controldir.open_workingtree(recommend_upgrade=False)
1767
2125
except (errors.NoWorkingTree, errors.NotLocalUrl):
1769
2127
repository = branch.repository
1770
2128
layout = describe_layout(repository, branch, tree).lower()
1771
format = describe_format(a_bzrdir, repository, branch, tree)
1772
self.outf.write("Created a %s (format: %s)\n" % (layout, format))
2129
format = describe_format(a_controldir, repository, branch, tree)
2130
self.outf.write(gettext("Created a {0} (format: {1})\n").format(
1773
2132
if repository.is_shared():
1774
#XXX: maybe this can be refactored into transport.path_or_url()
1775
url = repository.bzrdir.root_transport.external_url()
2133
# XXX: maybe this can be refactored into transport.path_or_url()
2134
url = repository.controldir.root_transport.external_url()
1777
2136
url = urlutils.local_path_from_url(url)
1778
except errors.InvalidURL:
2137
except urlutils.InvalidURL:
1780
self.outf.write("Using shared repository: %s\n" % url)
1783
class cmd_init_repository(Command):
2139
self.outf.write(gettext("Using shared repository: %s\n") % url)
2142
class cmd_init_shared_repository(Command):
1784
2143
__doc__ = """Create a shared repository for branches to share storage space.
1786
2145
New branches created under the repository directory will store their
1787
2146
revisions in the repository, not in the branch directory. For branches
1788
with shared history, this reduces the amount of storage needed and
2147
with shared history, this reduces the amount of storage needed and
1789
2148
speeds up the creation of new branches.
1791
2150
If the --no-trees option is given then the branches in the repository
1792
will not have working trees by default. They will still exist as
1793
directories on disk, but they will not have separate copies of the
2151
will not have working trees by default. They will still exist as
2152
directories on disk, but they will not have separate copies of the
1794
2153
files at a certain revision. This can be useful for repositories that
1795
2154
store branches which are interacted with through checkouts or remote
1796
2155
branches, such as on a server.
1920
2304
help='Set prefixes added to old and new filenames, as '
1921
2305
'two values separated by a colon. (eg "old/:new/").'),
1923
help='Branch/tree to compare from.',
2307
help='Branch/tree to compare from.',
1927
help='Branch/tree to compare to.',
2311
help='Branch/tree to compare to.',
1932
2316
Option('using',
1933
help='Use this command to compare files.',
2317
help='Use this command to compare files.',
1936
2320
RegistryOption('format',
1937
help='Diff format to use.',
1938
lazy_registry=('bzrlib.diff', 'format_registry'),
1939
value_switches=False, title='Diff format'),
2322
help='Diff format to use.',
2323
lazy_registry=('breezy.diff', 'format_registry'),
2324
title='Diff format'),
2326
help='How many lines of context to show.',
2329
RegistryOption.from_kwargs(
2331
help='Color mode to use.',
2332
title='Color Mode', value_switches=False, enum_switch=True,
2333
never='Never colorize output.',
2334
auto='Only colorize output if terminal supports it and STDOUT is a'
2336
always='Always colorize output (default).'),
2339
help=('Warn if trailing whitespace or spurious changes have been'
1941
2343
aliases = ['di', 'dif']
1942
2344
encoding_type = 'exact'
1944
2346
@display_command
1945
2347
def run(self, revision=None, file_list=None, diff_options=None,
1946
prefix=None, old=None, new=None, using=None, format=None):
1947
from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
2348
prefix=None, old=None, new=None, using=None, format=None,
2349
context=None, color='never'):
2350
from .diff import (get_trees_and_branches_to_diff_locked,
1950
if (prefix is None) or (prefix == '0'):
1951
2354
# diff -p0 format
2357
elif prefix == u'1' or prefix is None:
1955
2358
old_label = 'old/'
1956
2359
new_label = 'new/'
1958
old_label, new_label = prefix.split(":")
2360
elif u':' in prefix:
2361
old_label, new_label = prefix.split(u":")
1960
raise errors.BzrCommandError(
2363
raise errors.BzrCommandError(gettext(
1961
2364
'--prefix expects two values separated by a colon'
1962
' (eg "old/:new/")')
2365
' (eg "old/:new/")'))
1964
2367
if revision and len(revision) > 2:
1965
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1966
' one or two revision specifiers')
2368
raise errors.BzrCommandError(gettext('brz diff --revision takes exactly'
2369
' one or two revision specifiers'))
1968
2371
if using is not None and format is not None:
1969
raise errors.BzrCommandError('--using and --format are mutually '
2372
raise errors.BzrCommandError(gettext(
2373
'{0} and {1} are mutually exclusive').format(
2374
'--using', '--format'))
1972
2376
(old_tree, new_tree,
1973
2377
old_branch, new_branch,
1974
2378
specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1975
file_list, revision, old, new, self.add_cleanup, apply_view=True)
1976
return show_diff_trees(old_tree, new_tree, sys.stdout,
2379
file_list, revision, old, new, self._exit_stack, apply_view=True)
2380
# GNU diff on Windows uses ANSI encoding for filenames
2381
path_encoding = osutils.get_diff_header_encoding()
2384
from .terminal import has_ansi_colors
2385
if has_ansi_colors():
2389
if 'always' == color:
2390
from .colordiff import DiffWriter
2391
outf = DiffWriter(outf)
2392
return show_diff_trees(old_tree, new_tree, outf,
1977
2393
specific_files=specific_files,
1978
2394
external_diff_options=diff_options,
1979
2395
old_label=old_label, new_label=new_label,
1980
extra_trees=extra_trees, using=using,
2396
extra_trees=extra_trees,
2397
path_encoding=path_encoding,
2398
using=using, context=context,
1981
2399
format_cls=format)
2242
2663
takes_args = ['file*']
2243
2664
_see_also = ['log-formats', 'revisionspec']
2244
2665
takes_options = [
2246
help='Show from oldest to newest.'),
2248
custom_help('verbose',
2249
help='Show files changed in each revision.'),
2253
type=bzrlib.option._parse_revision_str,
2255
help='Show just the specified revision.'
2256
' See also "help revisionspec".'),
2258
RegistryOption('authors',
2259
'What names to list as authors - first, all or committer.',
2261
lazy_registry=('bzrlib.log', 'author_list_registry'),
2265
help='Number of levels to display - 0 for all, 1 for flat.',
2267
type=_parse_levels),
2667
help='Show from oldest to newest.'),
2669
custom_help('verbose',
2670
help='Show files changed in each revision.'),
2674
type=breezy.option._parse_revision_str,
2676
help='Show just the specified revision.'
2677
' See also "help revisionspec".'),
2679
RegistryOption('authors',
2680
'What names to list as authors - first, all or committer.',
2683
'breezy.log', 'author_list_registry'),
2687
help='Number of levels to display - 0 for all, 1 for flat.',
2689
type=_parse_levels),
2691
help='Show revisions whose message matches this '
2692
'regular expression.',
2697
help='Limit the output to the first N revisions.',
2702
help='Show changes made in each revision as a patch.'),
2703
Option('include-merged',
2704
help='Show merged revisions like --levels 0 does.'),
2705
Option('include-merges', hidden=True,
2706
help='Historical alias for --include-merged.'),
2707
Option('omit-merges',
2708
help='Do not report commits with more than one parent.'),
2709
Option('exclude-common-ancestry',
2710
help='Display only the revisions that are not part'
2711
' of both ancestries (require -rX..Y).'
2713
Option('signatures',
2714
help='Show digital signature validity.'),
2269
2716
short_name='m',
2717
help='Show revisions whose properties match this '
2720
ListOption('match-message',
2270
2721
help='Show revisions whose message matches this '
2271
'regular expression.',
2275
help='Limit the output to the first N revisions.',
2280
help='Show changes made in each revision as a patch.'),
2281
Option('include-merges',
2282
help='Show merged revisions like --levels 0 does.'),
2283
Option('exclude-common-ancestry',
2284
help='Display only the revisions that are not part'
2285
' of both ancestries (require -rX..Y)'
2724
ListOption('match-committer',
2725
help='Show revisions whose committer matches this '
2728
ListOption('match-author',
2729
help='Show revisions whose authors match this '
2732
ListOption('match-bugs',
2733
help='Show revisions whose bugs match this '
2288
2737
encoding_type = 'replace'
2290
2739
@display_command
2502
2983
_see_also = ['status', 'cat']
2503
2984
takes_args = ['path?']
2504
2985
takes_options = [
2507
Option('recursive', short_name='R',
2508
help='Recurse into subdirectories.'),
2510
help='Print paths relative to the root of the branch.'),
2511
Option('unknown', short_name='u',
2512
help='Print unknown files.'),
2513
Option('versioned', help='Print versioned files.',
2515
Option('ignored', short_name='i',
2516
help='Print ignored files.'),
2517
Option('kind', short_name='k',
2518
help='List entries of a particular kind: file, directory, symlink.',
2988
Option('recursive', short_name='R',
2989
help='Recurse into subdirectories.'),
2991
help='Print paths relative to the root of the branch.'),
2992
Option('unknown', short_name='u',
2993
help='Print unknown files.'),
2994
Option('versioned', help='Print versioned files.',
2996
Option('ignored', short_name='i',
2997
help='Print ignored files.'),
2998
Option('kind', short_name='k',
2999
help=('List entries of a particular kind: file, '
3000
'directory, symlink, tree-reference.'),
2524
3007
@display_command
2525
3008
def run(self, revision=None, verbose=False,
2526
3009
recursive=False, from_root=False,
2527
3010
unknown=False, versioned=False, ignored=False,
2528
3011
null=False, kind=None, show_ids=False, path=None, directory=None):
2530
if kind and kind not in ('file', 'directory', 'symlink'):
2531
raise errors.BzrCommandError('invalid kind specified')
3013
if kind and kind not in ('file', 'directory', 'symlink', 'tree-reference'):
3014
raise errors.BzrCommandError(gettext('invalid kind specified'))
2533
3016
if verbose and null:
2534
raise errors.BzrCommandError('Cannot set both --verbose and --null')
3017
raise errors.BzrCommandError(
3018
gettext('Cannot set both --verbose and --null'))
2535
3019
all = not (unknown or versioned or ignored)
2537
selection = {'I':ignored, '?':unknown, 'V':versioned}
3021
selection = {'I': ignored, '?': unknown, 'V': versioned}
2539
3023
if path is None:
2543
raise errors.BzrCommandError('cannot specify both --from-root'
3027
raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2546
3030
tree, branch, relpath = \
2547
3031
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2641
3125
After adding, editing or deleting that file either indirectly by
2642
3126
using this command or directly by using an editor, be sure to commit
2645
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2646
the global ignore file can be found in the application data directory as
2647
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
3129
Breezy also supports a global ignore file ~/.config/breezy/ignore. On
3130
Windows the global ignore file can be found in the application data
3132
C:\\Documents and Settings\\<user>\\Application Data\\Breezy\\3.0\\ignore.
2648
3133
Global ignores are not touched by this command. The global ignore file
2649
3134
can be edited directly using an editor.
2651
3136
Patterns prefixed with '!' are exceptions to ignore patterns and take
2652
3137
precedence over regular ignores. Such exceptions are used to specify
2653
3138
files that should be versioned which would otherwise be ignored.
2655
3140
Patterns prefixed with '!!' act as regular ignore patterns, but have
2656
3141
precedence over the '!' exception patterns.
2658
Note: ignore patterns containing shell wildcards must be quoted from
3145
* Ignore patterns containing shell wildcards must be quoted from
3148
* Ignore patterns starting with "#" act as comments in the ignore file.
3149
To ignore patterns that begin with that character, use the "RE:" prefix.
2662
3152
Ignore the top level Makefile::
2664
bzr ignore ./Makefile
3154
brz ignore ./Makefile
2666
3156
Ignore .class files in all directories...::
2668
bzr ignore "*.class"
3158
brz ignore "*.class"
2670
3160
...but do not ignore "special.class"::
2672
bzr ignore "!special.class"
2674
Ignore .o files under the lib directory::
2676
bzr ignore "lib/**/*.o"
2678
Ignore .o files under the lib directory::
2680
bzr ignore "RE:lib/.*\.o"
3162
brz ignore "!special.class"
3164
Ignore files whose name begins with the "#" character::
3168
Ignore .o files under the lib directory::
3170
brz ignore "lib/**/*.o"
3172
Ignore .o files under the lib directory::
3174
brz ignore "RE:lib/.*\\.o"
2682
3176
Ignore everything but the "debian" toplevel directory::
2684
bzr ignore "RE:(?!debian/).*"
3178
brz ignore "RE:(?!debian/).*"
2686
3180
Ignore everything except the "local" toplevel directory,
2687
but always ignore "*~" autosave files, even under local/::
2690
bzr ignore "!./local"
3181
but always ignore autosave files ending in ~, even under local/::
3184
brz ignore "!./local"
2694
3188
_see_also = ['status', 'ignored', 'patterns']
2695
3189
takes_args = ['name_pattern*']
2696
3190
takes_options = ['directory',
2697
Option('default-rules',
2698
help='Display the default ignore rules that bzr uses.')
3191
Option('default-rules',
3192
help='Display the default ignore rules that brz uses.')
2701
3195
def run(self, name_pattern_list=None, default_rules=None,
2702
3196
directory=u'.'):
2703
from bzrlib import ignores
3197
from breezy import ignores
2704
3198
if default_rules is not None:
2705
3199
# dump the default rules and exit
2706
3200
for pattern in ignores.USER_DEFAULTS:
2707
3201
self.outf.write("%s\n" % pattern)
2709
3203
if not name_pattern_list:
2710
raise errors.BzrCommandError("ignore requires at least one "
2711
"NAME_PATTERN or --default-rules.")
3204
raise errors.BzrCommandError(gettext("ignore requires at least one "
3205
"NAME_PATTERN or --default-rules."))
2712
3206
name_pattern_list = [globbing.normalize_pattern(p)
2713
3207
for p in name_pattern_list]
3209
bad_patterns_count = 0
3210
for p in name_pattern_list:
3211
if not globbing.Globster.is_pattern_valid(p):
3212
bad_patterns_count += 1
3213
bad_patterns += ('\n %s' % p)
3215
msg = (ngettext('Invalid ignore pattern found. %s',
3216
'Invalid ignore patterns found. %s',
3217
bad_patterns_count) % bad_patterns)
3218
ui.ui_factory.show_error(msg)
3219
raise lazy_regex.InvalidPattern('')
2714
3220
for name_pattern in name_pattern_list:
2715
3221
if (name_pattern[0] == '/' or
2716
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2717
raise errors.BzrCommandError(
2718
"NAME_PATTERN should not be an absolute path")
3222
(len(name_pattern) > 1 and name_pattern[1] == ':')):
3223
raise errors.BzrCommandError(gettext(
3224
"NAME_PATTERN should not be an absolute path"))
2719
3225
tree, relpath = WorkingTree.open_containing(directory)
2720
3226
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2721
3227
ignored = globbing.Globster(name_pattern_list)
2724
for entry in tree.list_files():
3229
self.enter_context(tree.lock_read())
3230
for filename, fc, fkind, entry in tree.list_files():
3231
id = getattr(entry, 'file_id', None)
2726
3232
if id is not None:
2728
3233
if ignored.match(filename):
2729
3234
matches.append(filename)
2731
3235
if len(matches) > 0:
2732
self.outf.write("Warning: the following files are version controlled and"
2733
" match your ignore pattern:\n%s"
2734
"\nThese files will continue to be version controlled"
2735
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
3236
self.outf.write(gettext("Warning: the following files are version "
3237
"controlled and match your ignore pattern:\n%s"
3238
"\nThese files will continue to be version controlled"
3239
" unless you 'brz remove' them.\n") % ("\n".join(matches),))
2738
3242
class cmd_ignored(Command):
2812
3317
================= =========================
3320
encoding_type = 'exact'
2814
3321
takes_args = ['dest', 'branch_or_subdir?']
2815
3322
takes_options = ['directory',
2817
help="Type of file to export to.",
2820
Option('filters', help='Apply content filters to export the '
2821
'convenient form.'),
2824
help="Name of the root directory inside the exported file."),
2825
Option('per-file-timestamps',
2826
help='Set modification time of files to that of the last '
2827
'revision in which it was changed.'),
3324
help="Type of file to export to.",
3327
Option('filters', help='Apply content filters to export the '
3328
'convenient form.'),
3331
help="Name of the root directory inside the exported file."),
3332
Option('per-file-timestamps',
3333
help='Set modification time of files to that of the last '
3334
'revision in which it was changed.'),
3335
Option('uncommitted',
3336
help='Export the working tree contents rather than that of the '
2829
3340
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2830
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2831
from bzrlib.export import export
3341
root=None, filters=False, per_file_timestamps=False, uncommitted=False,
3343
from .export import export, guess_format, get_root_name
2833
3345
if branch_or_subdir is None:
2834
tree = WorkingTree.open_containing(directory)[0]
2838
b, subdir = Branch.open_containing(branch_or_subdir)
2841
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
3346
branch_or_subdir = directory
3348
(tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
3350
if tree is not None:
3351
self.enter_context(tree.lock_read())
3355
raise errors.BzrCommandError(
3356
gettext("--uncommitted requires a working tree"))
3359
export_tree = _get_one_revision_tree(
3360
'export', revision, branch=b,
3364
format = guess_format(dest)
3367
root = get_root_name(dest)
3369
if not per_file_timestamps:
3370
force_mtime = time.time()
3375
from breezy.filter_tree import ContentFilterTree
3376
export_tree = ContentFilterTree(
3377
export_tree, export_tree._content_filter_stack)
2843
export(rev_tree, dest, format, root, subdir, filtered=filters,
3380
export(export_tree, dest, format, root, subdir,
2844
3381
per_file_timestamps=per_file_timestamps)
2845
except errors.NoSuchExportFormat, e:
2846
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3382
except errors.NoSuchExportFormat as e:
3383
raise errors.BzrCommandError(
3384
gettext('Unsupported export format: %s') % e.format)
2849
3387
class cmd_cat(Command):
2869
3408
def run(self, filename, revision=None, name_from_revision=False,
2870
3409
filters=False, directory=None):
2871
3410
if revision is not None and len(revision) != 1:
2872
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2873
" one revision specifier")
3411
raise errors.BzrCommandError(gettext("brz cat --revision takes exactly"
3412
" one revision specifier"))
2874
3413
tree, branch, relpath = \
2875
3414
_open_directory_or_containing_tree_or_branch(filename, directory)
2876
self.add_cleanup(branch.lock_read().unlock)
3415
self.enter_context(branch.lock_read())
2877
3416
return self._run(tree, branch, relpath, filename, revision,
2878
3417
name_from_revision, filters)
2880
3419
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2882
3422
if tree is None:
2883
3423
tree = b.basis_tree()
2884
3424
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2885
self.add_cleanup(rev_tree.lock_read().unlock)
2887
old_file_id = rev_tree.path2id(relpath)
3425
self.enter_context(rev_tree.lock_read())
2889
3427
if name_from_revision:
2890
3428
# Try in revision if requested
2891
if old_file_id is None:
2892
raise errors.BzrCommandError(
2893
"%r is not present in revision %s" % (
3429
if not rev_tree.is_versioned(relpath):
3430
raise errors.BzrCommandError(gettext(
3431
"{0!r} is not present in revision {1}").format(
2894
3432
filename, rev_tree.get_revision_id()))
2896
content = rev_tree.get_file_text(old_file_id)
3433
rev_tree_path = relpath
2898
cur_file_id = tree.path2id(relpath)
2900
if cur_file_id is not None:
2901
# Then try with the actual file id
2903
content = rev_tree.get_file_text(cur_file_id)
2905
except errors.NoSuchId:
2906
# The actual file id didn't exist at that time
2908
if not found and old_file_id is not None:
2909
# Finally try with the old file id
2910
content = rev_tree.get_file_text(old_file_id)
2913
# Can't be found anywhere
2914
raise errors.BzrCommandError(
2915
"%r is not present in revision %s" % (
2916
filename, rev_tree.get_revision_id()))
3436
rev_tree_path = _mod_tree.find_previous_path(
3437
tree, rev_tree, relpath)
3438
except errors.NoSuchFile:
3439
rev_tree_path = None
3441
if rev_tree_path is None:
3442
# Path didn't exist in working tree
3443
if not rev_tree.is_versioned(relpath):
3444
raise errors.BzrCommandError(gettext(
3445
"{0!r} is not present in revision {1}").format(
3446
filename, rev_tree.get_revision_id()))
3448
# Fall back to the same path in the basis tree, if present.
3449
rev_tree_path = relpath
2918
from bzrlib.filters import (
2919
ContentFilterContext,
2920
filtered_output_bytes,
2922
filters = rev_tree._content_filter_stack(relpath)
2923
chunks = content.splitlines(True)
2924
content = filtered_output_bytes(chunks, filters,
2925
ContentFilterContext(relpath, rev_tree))
2927
self.outf.writelines(content)
3452
from .filter_tree import ContentFilterTree
3453
filter_tree = ContentFilterTree(
3454
rev_tree, rev_tree._content_filter_stack)
3455
fileobj = filter_tree.get_file(rev_tree_path)
2930
self.outf.write(content)
3457
fileobj = rev_tree.get_file(rev_tree_path)
3458
shutil.copyfileobj(fileobj, self.outf)
2933
3462
class cmd_local_time_offset(Command):
2934
3463
__doc__ = """Show the offset in seconds from GMT to local time."""
2936
3466
@display_command
2938
3468
self.outf.write("%s\n" % osutils.local_time_offset())
2942
3471
class cmd_commit(Command):
2943
3472
__doc__ = """Commit changes into a new revision.
2975
3504
"John Doe <jdoe@example.com>". If there is more than one author of
2976
3505
the change you can specify the option multiple times, once for each
2981
3510
A common mistake is to forget to add a new file or directory before
2982
3511
running the commit command. The --strict option checks for unknown
2983
3512
files and aborts the commit if any are found. More advanced pre-commit
2984
checks can be implemented by defining hooks. See ``bzr help hooks``
3513
checks can be implemented by defining hooks. See ``brz help hooks``
2987
3516
:Things to note:
2989
If you accidentially commit the wrong changes or make a spelling
3518
If you accidentally commit the wrong changes or make a spelling
2990
3519
mistake in the commit message say, you can use the uncommit command
2991
to undo it. See ``bzr help uncommit`` for details.
3520
to undo it. See ``brz help uncommit`` for details.
2993
3522
Hooks can also be configured to run after a commit. This allows you
2994
3523
to trigger updates to external systems like bug trackers. The --fixes
2995
3524
option can be used to record the association between a revision and
2996
one or more bugs. See ``bzr help bugs`` for details.
2998
A selective commit may fail in some cases where the committed
2999
tree would be invalid. Consider::
3004
bzr commit foo -m "committing foo"
3005
bzr mv foo/bar foo/baz
3008
bzr commit foo/bar -m "committing bar but not baz"
3010
In the example above, the last commit will fail by design. This gives
3011
the user the opportunity to decide whether they want to commit the
3012
rename at the same time, separately first, or not at all. (As a general
3013
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3525
one or more bugs. See ``brz help bugs`` for details.
3015
# TODO: Run hooks on tree to-be-committed, and after commit.
3017
# TODO: Strict commit that fails if there are deleted files.
3018
# (what does "deleted files" mean ??)
3020
# TODO: Give better message for -s, --summary, used by tla people
3022
# XXX: verbose currently does nothing
3024
3528
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
3025
3529
takes_args = ['selected*']
3026
3530
takes_options = [
3027
ListOption('exclude', type=str, short_name='x',
3028
help="Do not consider changes made to a given path."),
3029
Option('message', type=unicode,
3031
help="Description of the new revision."),
3034
help='Commit even if nothing has changed.'),
3035
Option('file', type=str,
3038
help='Take commit message from this file.'),
3040
help="Refuse to commit if there are unknown "
3041
"files in the working tree."),
3042
Option('commit-time', type=str,
3043
help="Manually set a commit time using commit date "
3044
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3045
ListOption('fixes', type=str,
3046
help="Mark a bug as being fixed by this revision "
3047
"(see \"bzr help bugs\")."),
3048
ListOption('author', type=unicode,
3049
help="Set the author's name, if it's different "
3050
"from the committer."),
3052
help="Perform a local commit in a bound "
3053
"branch. Local commits are not pushed to "
3054
"the master branch until a normal commit "
3057
Option('show-diff', short_name='p',
3058
help='When no message is supplied, show the diff along'
3059
' with the status summary in the message editor.'),
3532
'exclude', type=str, short_name='x',
3533
help="Do not consider changes made to a given path."),
3534
Option('message', type=str,
3536
help="Description of the new revision."),
3539
help='Commit even if nothing has changed.'),
3540
Option('file', type=str,
3543
help='Take commit message from this file.'),
3545
help="Refuse to commit if there are unknown "
3546
"files in the working tree."),
3547
Option('commit-time', type=str,
3548
help="Manually set a commit time using commit date "
3549
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3552
help="Link to a related bug. (see \"brz help bugs\")."),
3555
help="Mark a bug as being fixed by this revision "
3556
"(see \"brz help bugs\")."),
3559
help="Set the author's name, if it's different "
3560
"from the committer."),
3562
help="Perform a local commit in a bound "
3563
"branch. Local commits are not pushed to "
3564
"the master branch until a normal commit "
3567
Option('show-diff', short_name='p',
3568
help='When no message is supplied, show the diff along'
3569
' with the status summary in the message editor.'),
3571
help='When committing to a foreign version control '
3572
'system do not push data that can not be natively '
3061
3574
aliases = ['ci', 'checkin']
3063
def _iter_bug_fix_urls(self, fixes, branch):
3576
def _iter_bug_urls(self, bugs, branch, status):
3577
default_bugtracker = None
3064
3578
# Configure the properties for bug fixing attributes.
3065
for fixed_bug in fixes:
3066
tokens = fixed_bug.split(':')
3067
if len(tokens) != 2:
3068
raise errors.BzrCommandError(
3580
tokens = bug.split(':')
3581
if len(tokens) == 1:
3582
if default_bugtracker is None:
3583
branch_config = branch.get_config_stack()
3584
default_bugtracker = branch_config.get(
3586
if default_bugtracker is None:
3587
raise errors.BzrCommandError(gettext(
3588
"No tracker specified for bug %s. Use the form "
3589
"'tracker:id' or specify a default bug tracker "
3590
"using the `bugtracker` option.\nSee "
3591
"\"brz help bugs\" for more information on this "
3592
"feature. Commit refused.") % bug)
3593
tag = default_bugtracker
3595
elif len(tokens) != 2:
3596
raise errors.BzrCommandError(gettext(
3069
3597
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3070
"See \"bzr help bugs\" for more information on this "
3071
"feature.\nCommit refused." % fixed_bug)
3072
tag, bug_id = tokens
3598
"See \"brz help bugs\" for more information on this "
3599
"feature.\nCommit refused.") % bug)
3601
tag, bug_id = tokens
3074
yield bugtracker.get_bug_url(tag, branch, bug_id)
3075
except errors.UnknownBugTrackerAbbreviation:
3076
raise errors.BzrCommandError(
3077
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3078
except errors.MalformedBugIdentifier, e:
3079
raise errors.BzrCommandError(
3080
"%s\nCommit refused." % (str(e),))
3603
yield bugtracker.get_bug_url(tag, branch, bug_id), status
3604
except bugtracker.UnknownBugTrackerAbbreviation:
3605
raise errors.BzrCommandError(gettext(
3606
'Unrecognized bug %s. Commit refused.') % bug)
3607
except bugtracker.MalformedBugIdentifier as e:
3608
raise errors.BzrCommandError(gettext(
3609
u"%s\nCommit refused.") % (e,))
3082
3611
def run(self, message=None, file=None, verbose=False, selected_list=None,
3083
unchanged=False, strict=False, local=False, fixes=None,
3084
author=None, show_diff=False, exclude=None, commit_time=None):
3085
from bzrlib.errors import (
3612
unchanged=False, strict=False, local=False, fixes=None, bugs=None,
3613
author=None, show_diff=False, exclude=None, commit_time=None,
3616
from .commit import (
3086
3617
PointlessCommit,
3619
from .errors import (
3087
3620
ConflictsInTree,
3088
3621
StrictCommitFailed
3090
from bzrlib.msgeditor import (
3623
from .msgeditor import (
3091
3624
edit_commit_message_encoded,
3092
3625
generate_commit_message_template,
3093
make_commit_message_template_encoded
3626
make_commit_message_template_encoded,
3096
3630
commit_stamp = offset = None
3097
3631
if commit_time is not None:
3099
3633
commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3100
except ValueError, e:
3101
raise errors.BzrCommandError(
3102
"Could not parse --commit-time: " + str(e))
3104
# TODO: Need a blackbox test for invoking the external editor; may be
3105
# slightly problematic to run this cross-platform.
3107
# TODO: do more checks that the commit will succeed before
3108
# spending the user's valuable time typing a commit message.
3634
except ValueError as e:
3635
raise errors.BzrCommandError(gettext(
3636
"Could not parse --commit-time: " + str(e)))
3110
3638
properties = {}
3112
tree, selected_list = tree_files(selected_list)
3640
tree, selected_list = WorkingTree.open_containing_paths(selected_list)
3113
3641
if selected_list == ['']:
3114
3642
# workaround - commit of root of tree should be exactly the same
3115
3643
# as just default commit in that tree, and succeed even though
3278
3821
class cmd_upgrade(Command):
3279
__doc__ = """Upgrade branch storage to current format.
3281
The check command or bzr developers may sometimes advise you to run
3282
this command. When the default format has changed you may also be warned
3283
during other operations to upgrade.
3822
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3824
When the default format has changed after a major new release of
3825
Bazaar/Breezy, you may be informed during certain operations that you
3826
should upgrade. Upgrading to a newer format may improve performance
3827
or make new features available. It may however limit interoperability
3828
with older repositories or with older versions of Bazaar or Breezy.
3830
If you wish to upgrade to a particular format rather than the
3831
current default, that can be specified using the --format option.
3832
As a consequence, you can use the upgrade command this way to
3833
"downgrade" to an earlier format, though some conversions are
3834
a one way process (e.g. changing from the 1.x default to the
3835
2.x default) so downgrading is not always possible.
3837
A backup.bzr.~#~ directory is created at the start of the conversion
3838
process (where # is a number). By default, this is left there on
3839
completion. If the conversion fails, delete the new .bzr directory
3840
and rename this one back in its place. Use the --clean option to ask
3841
for the backup.bzr directory to be removed on successful conversion.
3842
Alternatively, you can delete it by hand if everything looks good
3845
If the location given is a shared repository, dependent branches
3846
are also converted provided the repository converts successfully.
3847
If the conversion of a branch fails, remaining branches are still
3850
For more information on upgrades, see the Breezy Upgrade Guide,
3851
https://www.breezy-vcs.org/doc/en/upgrade-guide/.
3286
_see_also = ['check']
3854
_see_also = ['check', 'reconcile', 'formats']
3287
3855
takes_args = ['url?']
3288
3856
takes_options = [
3289
RegistryOption('format',
3290
help='Upgrade to a specific format. See "bzr help'
3291
' formats" for details.',
3292
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3293
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3294
value_switches=True, title='Branch format'),
3857
RegistryOption('format',
3858
help='Upgrade to a specific format. See "brz help'
3859
' formats" for details.',
3860
lazy_registry=('breezy.controldir', 'format_registry'),
3861
converter=lambda name: controldir.format_registry.make_controldir(
3863
value_switches=True, title='Branch format'),
3865
help='Remove the backup.bzr directory if successful.'),
3867
help="Show what would be done, but don't actually do anything."),
3297
def run(self, url='.', format=None):
3298
from bzrlib.upgrade import upgrade
3299
upgrade(url, format)
3870
def run(self, url='.', format=None, clean=False, dry_run=False):
3871
from .upgrade import upgrade
3872
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3874
if len(exceptions) == 1:
3875
# Compatibility with historical behavior
3302
3881
class cmd_whoami(Command):
3303
__doc__ = """Show or set bzr user id.
3882
__doc__ = """Show or set brz user id.
3306
3885
Show the email of the current user::
3310
3889
Set the current user::
3312
bzr whoami "Frank Chu <fchu@example.com>"
3891
brz whoami "Frank Chu <fchu@example.com>"
3314
takes_options = [ Option('email',
3315
help='Display email address only.'),
3317
help='Set identity for the current branch instead of '
3893
takes_options = ['directory',
3895
help='Display email address only.'),
3897
help='Set identity for the current branch instead of '
3320
3900
takes_args = ['name?']
3321
3901
encoding_type = 'replace'
3323
3903
@display_command
3324
def run(self, email=False, branch=False, name=None):
3904
def run(self, email=False, branch=False, name=None, directory=None):
3325
3905
if name is None:
3326
# use branch if we're inside one; otherwise global config
3328
c = Branch.open_containing('.')[0].get_config()
3329
except errors.NotBranchError:
3330
c = config.GlobalConfig()
3906
if directory is None:
3907
# use branch if we're inside one; otherwise global config
3909
c = Branch.open_containing(u'.')[0].get_config_stack()
3910
except errors.NotBranchError:
3911
c = _mod_config.GlobalStack()
3913
c = Branch.open(directory).get_config_stack()
3914
identity = c.get('email')
3332
self.outf.write(c.user_email() + '\n')
3916
self.outf.write(_mod_config.extract_email_address(identity)
3334
self.outf.write(c.username() + '\n')
3919
self.outf.write(identity + '\n')
3923
raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3337
3926
# display a warning if an email address isn't included in the given name.
3339
config.extract_email_address(name)
3340
except errors.NoEmailInUsername, e:
3928
_mod_config.extract_email_address(name)
3929
except _mod_config.NoEmailInUsername:
3341
3930
warning('"%s" does not seem to contain an email address. '
3342
3931
'This is allowed, but not recommended.', name)
3344
3933
# use global config unless --branch given
3346
c = Branch.open_containing('.')[0].get_config()
3935
if directory is None:
3936
c = Branch.open_containing(u'.')[0].get_config_stack()
3938
b = Branch.open(directory)
3939
self.enter_context(b.lock_write())
3940
c = b.get_config_stack()
3348
c = config.GlobalConfig()
3349
c.set_user_option('email', name)
3942
c = _mod_config.GlobalStack()
3943
c.set('email', name)
3352
3946
class cmd_nick(Command):
3353
3947
__doc__ = """Print or set the branch nickname.
3355
If unset, the tree root directory name is used as the nickname.
3356
To print the current nickname, execute with no argument.
3949
If unset, the colocated branch name is used for colocated branches, and
3950
the branch directory name is used for other branches. To print the
3951
current nickname, execute with no argument.
3358
3953
Bound branches use the nickname of its master branch unless it is set
3568
4171
def run(self, testspecs_list=None, verbose=False, one=False,
3569
4172
transport=None, benchmark=None,
3570
lsprof_timed=None, cache_dir=None,
3571
4174
first=False, list_only=False,
3572
4175
randomize=None, exclude=None, strict=False,
3573
load_list=None, debugflag=None, starting_with=None, subunit=False,
3574
parallel=None, lsprof_tests=False):
3575
from bzrlib.tests import selftest
3576
import bzrlib.benchmarks as benchmarks
3577
from bzrlib.benchmarks import tree_creator
3579
# Make deprecation warnings visible, unless -Werror is set
3580
symbol_versioning.activate_deprecation_warnings(override=False)
3582
if cache_dir is not None:
3583
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
4176
load_list=None, debugflag=None, starting_with=None, subunit1=False,
4177
subunit2=False, parallel=None, lsprof_tests=False, sync=False):
4179
# During selftest, disallow proxying, as it can cause severe
4180
# performance penalties and is only needed for thread
4181
# safety. The selftest command is assumed to not use threads
4182
# too heavily. The call should be as early as possible, as
4183
# error reporting for past duplicate imports won't have useful
4185
if sys.version_info[0] < 3:
4186
# TODO(pad.lv/1696545): Allow proxying on Python 3, since
4187
# disallowing it currently leads to failures in many places.
4188
lazy_import.disallow_proxying()
4193
raise errors.BzrCommandError("tests not available. Install the "
4194
"breezy tests to run the breezy testsuite.")
3584
4196
if testspecs_list is not None:
3585
4197
pattern = '|'.join(testspecs_list)
3590
from bzrlib.tests import SubUnitBzrRunner
4202
from .tests import SubUnitBzrRunnerv1
3591
4203
except ImportError:
3592
raise errors.BzrCommandError("subunit not available. subunit "
3593
"needs to be installed to use --subunit.")
3594
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
4204
raise errors.BzrCommandError(gettext(
4205
"subunit not available. subunit needs to be installed "
4206
"to use --subunit."))
4207
self.additional_selftest_args['runner_class'] = SubUnitBzrRunnerv1
3595
4208
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3596
# stdout, which would corrupt the subunit stream.
3597
if sys.platform == "win32" and sys.stdout.fileno() >= 0:
4209
# stdout, which would corrupt the subunit stream.
4210
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
4211
# following code can be deleted when it's sufficiently deployed
4212
# -- vila/mgz 20100514
4213
if (sys.platform == "win32"
4214
and getattr(sys.stdout, 'fileno', None) is not None):
3599
4216
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4219
from .tests import SubUnitBzrRunnerv2
4221
raise errors.BzrCommandError(gettext(
4222
"subunit not available. subunit "
4223
"needs to be installed to use --subunit2."))
4224
self.additional_selftest_args['runner_class'] = SubUnitBzrRunnerv2
3601
4227
self.additional_selftest_args.setdefault(
3602
4228
'suite_decorators', []).append(parallel)
3604
test_suite_factory = benchmarks.test_suite
3605
# Unless user explicitly asks for quiet, be verbose in benchmarks
3606
verbose = not is_quiet()
3607
# TODO: should possibly lock the history file...
3608
benchfile = open(".perf_history", "at", buffering=1)
3609
self.add_cleanup(benchfile.close)
4230
raise errors.BzrCommandError(gettext(
4231
"--benchmark is no longer supported from brz 2.2; "
4232
"use bzr-usertest instead"))
4233
test_suite_factory = None
4235
exclude_pattern = None
3611
test_suite_factory = None
4237
exclude_pattern = '(' + '|'.join(exclude) + ')'
4239
self._disable_fsync()
3613
4240
selftest_kwargs = {"verbose": verbose,
3615
"stop_on_failure": one,
3616
"transport": transport,
3617
"test_suite_factory": test_suite_factory,
3618
"lsprof_timed": lsprof_timed,
3619
"lsprof_tests": lsprof_tests,
3620
"bench_history": benchfile,
3621
"matching_tests_first": first,
3622
"list_only": list_only,
3623
"random_seed": randomize,
3624
"exclude_pattern": exclude,
3626
"load_list": load_list,
3627
"debug_flags": debugflag,
3628
"starting_with": starting_with
4242
"stop_on_failure": one,
4243
"transport": transport,
4244
"test_suite_factory": test_suite_factory,
4245
"lsprof_timed": lsprof_timed,
4246
"lsprof_tests": lsprof_tests,
4247
"matching_tests_first": first,
4248
"list_only": list_only,
4249
"random_seed": randomize,
4250
"exclude_pattern": exclude_pattern,
4252
"load_list": load_list,
4253
"debug_flags": debugflag,
4254
"starting_with": starting_with
3630
4256
selftest_kwargs.update(self.additional_selftest_args)
3631
result = selftest(**selftest_kwargs)
4258
# Make deprecation warnings visible, unless -Werror is set
4259
cleanup = symbol_versioning.activate_deprecation_warnings(
4262
result = tests.selftest(**selftest_kwargs)
3632
4265
return int(not result)
4267
def _disable_fsync(self):
4268
"""Change the 'os' functionality to not synchronize."""
4269
self._orig_fsync = getattr(os, 'fsync', None)
4270
if self._orig_fsync is not None:
4271
os.fsync = lambda filedes: None
4272
self._orig_fdatasync = getattr(os, 'fdatasync', None)
4273
if self._orig_fdatasync is not None:
4274
os.fdatasync = lambda filedes: None
3635
4277
class cmd_version(Command):
3636
__doc__ = """Show version of bzr."""
4278
__doc__ = """Show version of brz."""
3638
4280
encoding_type = 'replace'
3639
4281
takes_options = [
3689
4332
The source of the merge can be specified either in the form of a branch,
3690
4333
or in the form of a path to a file containing a merge directive generated
3691
with bzr send. If neither is specified, the default is the upstream branch
3692
or the branch most recently merged using --remember.
3694
When merging a branch, by default the tip will be merged. To pick a different
3695
revision, pass --revision. If you specify two values, the first will be used as
3696
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3697
available revisions, like this is commonly referred to as "cherrypicking".
3699
Revision numbers are always relative to the branch being merged.
3701
By default, bzr will try to merge in all new work from the other
3702
branch, automatically determining an appropriate base. If this
3703
fails, you may need to give an explicit base.
4334
with brz send. If neither is specified, the default is the upstream branch
4335
or the branch most recently merged using --remember. The source of the
4336
merge may also be specified in the form of a path to a file in another
4337
branch: in this case, only the modifications to that file are merged into
4338
the current working tree.
4340
When merging from a branch, by default brz will try to merge in all new
4341
work from the other branch, automatically determining an appropriate base
4342
revision. If this fails, you may need to give an explicit base.
4344
To pick a different ending revision, pass "--revision OTHER". brz will
4345
try to merge in all new work up to and including revision OTHER.
4347
If you specify two values, "--revision BASE..OTHER", only revisions BASE
4348
through OTHER, excluding BASE but including OTHER, will be merged. If this
4349
causes some revisions to be skipped, i.e. if the destination branch does
4350
not already contain revision BASE, such a merge is commonly referred to as
4351
a "cherrypick". Unlike a normal merge, Breezy does not currently track
4352
cherrypicks. The changes look like a normal commit, and the history of the
4353
changes from the other branch is not stored in the commit.
4355
Revision numbers are always relative to the source branch.
3705
4357
Merge will do its best to combine the changes in two branches, but there
3706
4358
are some kinds of problems only a human can fix. When it encounters those,
3707
4359
it will mark a conflict. A conflict means that you need to fix something,
3708
before you should commit.
3710
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
3712
If there is no default branch set, the first merge will set it. After
3713
that, you can omit the branch to use the default. To change the
3714
default, use --remember. The value will only be saved if the remote
3715
location can be accessed.
4360
before you can commit.
4362
Use brz resolve when you have fixed a problem. See also brz conflicts.
4364
If there is no default branch set, the first merge will set it (use
4365
--no-remember to avoid setting it). After that, you can omit the branch
4366
to use the default. To change the default, use --remember. The value will
4367
only be saved if the remote location can be accessed.
3717
4369
The results of the merge are placed into the destination working
3718
directory, where they can be reviewed (with bzr diff), tested, and then
4370
directory, where they can be reviewed (with brz diff), tested, and then
3719
4371
committed to record the result of the merge.
3721
4373
merge refuses to run if there are any uncommitted changes, unless
3722
--force is given. The --force option can also be used to create a
4374
--force is given. If --force is given, then the changes from the source
4375
will be merged with the current working tree, including any uncommitted
4376
changes in the tree. The --force option can also be used to create a
3723
4377
merge revision which has more than two parents.
3725
4379
If one would like to merge changes from the working tree of the other
3813
4467
change_reporter = delta._ChangeReporter(
3814
4468
unversioned_filter=tree.is_ignored, view_info=view_info)
3815
4469
pb = ui.ui_factory.nested_progress_bar()
3816
self.add_cleanup(pb.finished)
3817
self.add_cleanup(tree.lock_write().unlock)
4470
self.enter_context(pb)
4471
self.enter_context(tree.lock_write())
3818
4472
if location is not None:
3820
mergeable = bundle.read_mergeable_from_url(location,
3821
possible_transports=possible_transports)
4474
mergeable = _mod_mergeable.read_mergeable_from_url(
4475
location, possible_transports=possible_transports)
3822
4476
except errors.NotABundle:
3823
4477
mergeable = None
3825
4479
if uncommitted:
3826
raise errors.BzrCommandError('Cannot use --uncommitted'
3827
' with bundles or merge directives.')
4480
raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4481
' with bundles or merge directives.'))
3829
4483
if revision is not None:
3830
raise errors.BzrCommandError(
3831
'Cannot use -r with merge directives or bundles')
4484
raise errors.BzrCommandError(gettext(
4485
'Cannot use -r with merge directives or bundles'))
3832
4486
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3835
4489
if merger is None and uncommitted:
3836
4490
if revision is not None and len(revision) > 0:
3837
raise errors.BzrCommandError('Cannot use --uncommitted and'
3838
' --revision at the same time.')
4491
raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4492
' --revision at the same time.'))
3839
4493
merger = self.get_merger_from_uncommitted(tree, location, None)
3840
4494
allow_pending = False
3842
4496
if merger is None:
3843
4497
merger, allow_pending = self._get_merger_from_branch(tree,
3844
location, revision, remember, possible_transports, None)
4498
location, revision, remember, possible_transports, None)
3846
4500
merger.merge_type = merge_type
3847
4501
merger.reprocess = reprocess
3848
4502
merger.show_base = show_base
3849
4503
self.sanity_check_merger(merger)
3850
4504
if (merger.base_rev_id == merger.other_rev_id and
3851
merger.other_rev_id is not None):
3852
note('Nothing to do.')
4505
merger.other_rev_id is not None):
4506
# check if location is a nonexistent file (and not a branch) to
4507
# disambiguate the 'Nothing to do'
4508
if merger.interesting_files:
4509
if not merger.other_tree.has_filename(
4510
merger.interesting_files[0]):
4511
note(gettext("merger: ") + str(merger))
4512
raise errors.PathsDoNotExist([location])
4513
note(gettext('Nothing to do.'))
4515
if pull and not preview:
3855
4516
if merger.interesting_files is not None:
3856
raise errors.BzrCommandError('Cannot pull individual files')
4517
raise errors.BzrCommandError(
4518
gettext('Cannot pull individual files'))
3857
4519
if (merger.base_rev_id == tree.last_revision()):
3858
4520
result = tree.pull(merger.other_branch, False,
3859
4521
merger.other_rev_id)
3860
4522
result.report(self.outf)
3862
4524
if merger.this_basis is None:
3863
raise errors.BzrCommandError(
4525
raise errors.BzrCommandError(gettext(
3864
4526
"This branch has no commits."
3865
" (perhaps you would prefer 'bzr pull')")
4527
" (perhaps you would prefer 'brz pull')"))
3867
4529
return self._do_preview(merger)
3868
4530
elif interactive:
4055
4736
Re-do the merge of all conflicted files, and show the base text in
4056
4737
conflict regions, in addition to the usual THIS and OTHER texts::
4058
bzr remerge --show-base
4739
brz remerge --show-base
4060
4741
Re-do the merge of "foobar", using the weave merge algorithm, with
4061
4742
additional processing to reduce the size of conflict regions::
4063
bzr remerge --merge-type weave --reprocess foobar
4744
brz remerge --merge-type weave --reprocess foobar
4065
4746
takes_args = ['file*']
4066
4747
takes_options = [
4070
help="Show base revision text in conflicts."),
4751
help="Show base revision text in conflicts."),
4073
4754
def run(self, file_list=None, merge_type=None, show_base=False,
4074
4755
reprocess=False):
4075
from bzrlib.conflicts import restore
4756
from .conflicts import restore
4076
4757
if merge_type is None:
4077
4758
merge_type = _mod_merge.Merge3Merger
4078
tree, file_list = tree_files(file_list)
4079
self.add_cleanup(tree.lock_write().unlock)
4759
tree, file_list = WorkingTree.open_containing_paths(file_list)
4760
self.enter_context(tree.lock_write())
4080
4761
parents = tree.get_parent_ids()
4081
4762
if len(parents) != 2:
4082
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4083
" merges. Not cherrypicking or"
4085
repository = tree.branch.repository
4086
interesting_ids = None
4763
raise errors.BzrCommandError(
4764
gettext("Sorry, remerge only works after normal"
4765
" merges. Not cherrypicking or multi-merges."))
4766
interesting_files = None
4087
4767
new_conflicts = []
4088
4768
conflicts = tree.conflicts()
4089
4769
if file_list is not None:
4090
interesting_ids = set()
4770
interesting_files = set()
4091
4771
for filename in file_list:
4092
file_id = tree.path2id(filename)
4772
if not tree.is_versioned(filename):
4094
4773
raise errors.NotVersionedError(filename)
4095
interesting_ids.add(file_id)
4096
if tree.kind(file_id) != "directory":
4774
interesting_files.add(filename)
4775
if tree.kind(filename) != "directory":
4099
for name, ie in tree.inventory.iter_entries(file_id):
4100
interesting_ids.add(ie.file_id)
4778
for path, ie in tree.iter_entries_by_dir(
4779
specific_files=[filename]):
4780
interesting_files.add(path)
4101
4781
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4103
4783
# Remerge only supports resolving contents conflicts
4104
4784
allowed_conflicts = ('text conflict', 'contents conflict')
4105
4785
restore_files = [c.path for c in conflicts
4106
4786
if c.typestring in allowed_conflicts]
4107
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4787
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_files)
4108
4788
tree.set_conflicts(ConflictList(new_conflicts))
4109
4789
if file_list is not None:
4110
4790
restore_files = file_list
4555
5248
@display_command
4556
5249
def run(self, filename, all=False, long=False, revision=None,
4557
5250
show_ids=False, directory=None):
4558
from bzrlib.annotate import annotate_file, annotate_file_tree
5251
from .annotate import (
4559
5254
wt, branch, relpath = \
4560
5255
_open_directory_or_containing_tree_or_branch(filename, directory)
4561
5256
if wt is not None:
4562
self.add_cleanup(wt.lock_read().unlock)
5257
self.enter_context(wt.lock_read())
4564
self.add_cleanup(branch.lock_read().unlock)
5259
self.enter_context(branch.lock_read())
4565
5260
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4566
self.add_cleanup(tree.lock_read().unlock)
4568
file_id = wt.path2id(relpath)
4570
file_id = tree.path2id(relpath)
4572
raise errors.NotVersionedError(filename)
4573
file_version = tree.inventory[file_id].revision
5261
self.enter_context(tree.lock_read())
4574
5262
if wt is not None and revision is None:
5263
if not wt.is_versioned(relpath):
5264
raise errors.NotVersionedError(relpath)
4575
5265
# If there is a tree and we're not annotating historical
4576
5266
# versions, annotate the working tree's content.
4577
annotate_file_tree(wt, file_id, self.outf, long, all,
5267
annotate_file_tree(wt, relpath, self.outf, long, all,
4580
annotate_file(branch, file_version, file_id, long, all, self.outf,
5270
if not tree.is_versioned(relpath):
5271
raise errors.NotVersionedError(relpath)
5272
annotate_file_tree(tree, relpath, self.outf, long, all,
5273
show_ids=show_ids, branch=branch)
4584
5276
class cmd_re_sign(Command):
4585
5277
__doc__ = """Create a digital signature for an existing revision."""
4586
5278
# TODO be able to replace existing ones.
4588
hidden = True # is this right ?
5280
hidden = True # is this right ?
4589
5281
takes_args = ['revision_id*']
4590
5282
takes_options = ['directory', 'revision']
4592
5284
def run(self, revision_id_list=None, revision=None, directory=u'.'):
4593
5285
if revision_id_list is not None and revision is not None:
4594
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
5286
raise errors.BzrCommandError(
5287
gettext('You can only supply one of revision_id or --revision'))
4595
5288
if revision_id_list is None and revision is None:
4596
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
5289
raise errors.BzrCommandError(
5290
gettext('You must supply either --revision or a revision_id'))
4597
5291
b = WorkingTree.open_containing(directory)[0].branch
4598
self.add_cleanup(b.lock_write().unlock)
5292
self.enter_context(b.lock_write())
4599
5293
return self._run(b, revision_id_list, revision)
4601
5295
def _run(self, b, revision_id_list, revision):
4602
import bzrlib.gpg as gpg
4603
gpg_strategy = gpg.GPGStrategy(b.get_config())
5296
from .repository import WriteGroup
5297
gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
4604
5298
if revision_id_list is not None:
4605
b.repository.start_write_group()
5299
with WriteGroup(b.repository):
4607
5300
for revision_id in revision_id_list:
5301
revision_id = cache_utf8.encode(revision_id)
4608
5302
b.repository.sign_revision(revision_id, gpg_strategy)
4610
b.repository.abort_write_group()
4613
b.repository.commit_write_group()
4614
5303
elif revision is not None:
4615
5304
if len(revision) == 1:
4616
5305
revno, rev_id = revision[0].in_history(b)
4617
b.repository.start_write_group()
5306
with WriteGroup(b.repository):
4619
5307
b.repository.sign_revision(rev_id, gpg_strategy)
4621
b.repository.abort_write_group()
4624
b.repository.commit_write_group()
4625
5308
elif len(revision) == 2:
4626
5309
# are they both on rh- if so we can walk between them
4627
5310
# might be nice to have a range helper for arbitrary
4792
5478
end_revision=last_revno)
4795
self.outf.write('Dry-run, pretending to remove'
4796
' the above revisions.\n')
5481
self.outf.write(gettext('Dry-run, pretending to remove'
5482
' the above revisions.\n'))
4798
self.outf.write('The above revision(s) will be removed.\n')
5485
gettext('The above revision(s) will be removed.\n'))
4801
if not ui.ui_factory.get_boolean('Are you sure'):
4802
self.outf.write('Canceled')
5488
if not ui.ui_factory.confirm_action(
5489
gettext(u'Uncommit these revisions'),
5490
'breezy.builtins.uncommit',
5492
self.outf.write(gettext('Canceled\n'))
4805
5495
mutter('Uncommitting from {%s} to {%s}',
4806
5496
last_rev_id, rev_id)
4807
5497
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4808
revno=revno, local=local)
4809
self.outf.write('You can restore the old tip by running:\n'
4810
' bzr pull . -r revid:%s\n' % last_rev_id)
5498
revno=revno, local=local, keep_tags=keep_tags)
5501
gettext('You can restore the old tip by running:\n'
5502
' brz pull -d %s %s -r revid:%s\n')
5503
% (location, location, last_rev_id.decode('utf-8')))
5506
gettext('You can restore the old tip by running:\n'
5507
' brz pull . -r revid:%s\n')
5508
% last_rev_id.decode('utf-8'))
4813
5511
class cmd_break_lock(Command):
4814
__doc__ = """Break a dead lock on a repository, branch or working directory.
5512
__doc__ = """Break a dead lock.
5514
This command breaks a lock on a repository, branch, working directory or
4816
5517
CAUTION: Locks should only be broken when you are sure that the process
4817
5518
holding the lock has been stopped.
4819
You can get information on what locks are open via the 'bzr info
5520
You can get information on what locks are open via the 'brz info
4820
5521
[location]' command.
4824
bzr break-lock bzr+ssh://example.com/bzr/foo
5525
brz break-lock brz+ssh://example.com/brz/foo
5526
brz break-lock --conf ~/.config/breezy
4826
5529
takes_args = ['location?']
5532
help='LOCATION is the directory where the config lock is.'),
5534
help='Do not ask for confirmation before breaking the lock.'),
4828
def run(self, location=None, show=False):
5537
def run(self, location=None, config=False, force=False):
4829
5538
if location is None:
4830
5539
location = u'.'
4831
control, relpath = bzrdir.BzrDir.open_containing(location)
4833
control.break_lock()
4834
except NotImplementedError:
5541
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5543
{'breezy.lockdir.break': True})
5545
conf = _mod_config.LockableConfig(file_name=location)
5548
control, relpath = controldir.ControlDir.open_containing(location)
5550
control.break_lock()
5551
except NotImplementedError:
4838
5555
class cmd_wait_until_signalled(Command):
4839
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5556
__doc__ = """Test helper for test_start_and_stop_brz_subprocess_send_signal.
4841
5558
This just prints a line to signal when it is ready, then blocks on stdin.
4859
5576
help='Serve on stdin/out for use from inetd or sshd.'),
4860
5577
RegistryOption('protocol',
4861
help="Protocol to serve.",
4862
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4863
value_switches=True),
5578
help="Protocol to serve.",
5579
lazy_registry=('breezy.transport',
5580
'transport_server_registry'),
5581
value_switches=True),
5583
help='Listen for connections on nominated address.',
4865
help='Listen for connections on nominated port of the form '
4866
'[hostname:]portnumber. Passing 0 as the port number will '
4867
'result in a dynamically allocated port. The default port '
4868
'depends on the protocol.',
5586
help='Listen for connections on nominated port. Passing 0 as '
5587
'the port number will result in a dynamically allocated '
5588
'port. The default port depends on the protocol.',
4870
5590
custom_help('directory',
4871
help='Serve contents of this directory.'),
5591
help='Serve contents of this directory.'),
4872
5592
Option('allow-writes',
4873
5593
help='By default the server is a readonly server. Supplying '
4874
5594
'--allow-writes enables write access to the contents of '
4875
'the served directory and below. Note that ``bzr serve`` '
5595
'the served directory and below. Note that ``brz serve`` '
4876
5596
'does not perform authentication, so unless some form of '
4877
5597
'external authentication is arranged supplying this '
4878
5598
'option leads to global uncontrolled write access to your '
5601
Option('client-timeout', type=float,
5602
help='Override the default idle client timeout (5min).'),
4883
def get_host_and_port(self, port):
4884
"""Return the host and port to run the smart server on.
4886
If 'port' is None, None will be returned for the host and port.
4888
If 'port' has a colon in it, the string before the colon will be
4889
interpreted as the host.
4891
:param port: A string of the port to run the server on.
4892
:return: A tuple of (host, port), where 'host' is a host name or IP,
4893
and port is an integer TCP/IP port.
4896
if port is not None:
4898
host, port = port.split(':')
4902
def run(self, port=None, inet=False, directory=None, allow_writes=False,
4904
from bzrlib.transport import get_transport, transport_server_registry
5605
def run(self, listen=None, port=None, inet=False, directory=None,
5606
allow_writes=False, protocol=None, client_timeout=None):
5607
from . import location, transport
4905
5608
if directory is None:
4906
directory = os.getcwd()
5609
directory = osutils.getcwd()
4907
5610
if protocol is None:
4908
protocol = transport_server_registry.get()
4909
host, port = self.get_host_and_port(port)
4910
url = urlutils.local_path_to_url(directory)
5611
protocol = transport.transport_server_registry.get()
5612
url = location.location_to_url(directory)
4911
5613
if not allow_writes:
4912
5614
url = 'readonly+' + url
4913
transport = get_transport(url)
4914
protocol(transport, host, port, inet)
5615
t = transport.get_transport_from_url(url)
5616
protocol(t, listen, port, inet, client_timeout)
4917
5619
class cmd_join(Command):
5432
6155
takes_args = ['location?']
5433
6156
takes_options = [
5434
6157
RegistryOption.from_kwargs(
5436
title='Target type',
5437
help='The type to reconfigure the directory to.',
6160
help='The relation between branch and tree.',
5438
6161
value_switches=True, enum_switch=False,
5439
6162
branch='Reconfigure to be an unbound branch with no working tree.',
5440
6163
tree='Reconfigure to be an unbound branch with a working tree.',
5441
6164
checkout='Reconfigure to be a bound branch with a working tree.',
5442
6165
lightweight_checkout='Reconfigure to be a lightweight'
5443
' checkout (with no local history).',
6166
' checkout (with no local history).',
6168
RegistryOption.from_kwargs(
6170
title='Repository type',
6171
help='Location fo the repository.',
6172
value_switches=True, enum_switch=False,
5444
6173
standalone='Reconfigure to be a standalone branch '
5445
'(i.e. stop using shared repository).',
6174
'(i.e. stop using shared repository).',
5446
6175
use_shared='Reconfigure to use a shared repository.',
6177
RegistryOption.from_kwargs(
6179
title='Trees in Repository',
6180
help='Whether new branches in the repository have trees.',
6181
value_switches=True, enum_switch=False,
5447
6182
with_trees='Reconfigure repository to create '
5448
'working trees on branches by default.',
6183
'working trees on branches by default.',
5449
6184
with_no_trees='Reconfigure repository to not create '
5450
'working trees on branches by default.'
6185
'working trees on branches by default.'
5452
6187
Option('bind-to', help='Branch to bind checkout to.', type=str),
5453
6188
Option('force',
5454
help='Perform reconfiguration even if local changes'
6189
help='Perform reconfiguration even if local changes'
5456
6191
Option('stacked-on',
5457
help='Reconfigure a branch to be stacked on another branch.',
6192
help='Reconfigure a branch to be stacked on another branch.',
5460
6195
Option('unstacked',
5461
help='Reconfigure a branch to be unstacked. This '
5462
'may require copying substantial data into it.',
6196
help='Reconfigure a branch to be unstacked. This '
6197
'may require copying substantial data into it.',
5466
def run(self, location=None, target_type=None, bind_to=None, force=False,
5469
directory = bzrdir.BzrDir.open(location)
6201
def run(self, location=None, bind_to=None, force=False,
6202
tree_type=None, repository_type=None, repository_trees=None,
6203
stacked_on=None, unstacked=None):
6204
directory = controldir.ControlDir.open(location)
5470
6205
if stacked_on and unstacked:
5471
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
6206
raise errors.BzrCommandError(
6207
gettext("Can't use both --stacked-on and --unstacked"))
5472
6208
elif stacked_on is not None:
5473
6209
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5474
6210
elif unstacked:
5531
6278
takes_args = ['to_location?']
5532
takes_options = [Option('force',
5533
help='Switch even if local commits will be lost.'),
6279
takes_options = ['directory',
6281
help='Switch even if local commits will be lost.'),
5535
6283
Option('create-branch', short_name='b',
5536
help='Create the target branch from this one before'
5537
' switching to it.'),
6284
help='Create the target branch from this one before'
6285
' switching to it.'),
6287
help='Store and restore uncommitted changes in the'
5540
6291
def run(self, to_location=None, force=False, create_branch=False,
5542
from bzrlib import switch
6292
revision=None, directory=u'.', store=False):
6293
from . import switch
6294
tree_location = directory
5544
6295
revision = _get_one_revision('switch', revision)
5545
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
6296
control_dir = controldir.ControlDir.open_containing(tree_location)[0]
6297
possible_transports = [control_dir.root_transport]
5546
6298
if to_location is None:
5547
6299
if revision is None:
5548
raise errors.BzrCommandError('You must supply either a'
5549
' revision or a location')
6300
raise errors.BzrCommandError(gettext('You must supply either a'
6301
' revision or a location'))
6302
to_location = tree_location
5552
branch = control_dir.open_branch()
6304
branch = control_dir.open_branch(
6305
possible_transports=possible_transports)
5553
6306
had_explicit_nick = branch.get_config().has_explicit_nickname()
5554
6307
except errors.NotBranchError:
5556
6309
had_explicit_nick = False
6311
possible_transports.append(branch.user_transport)
5557
6312
if create_branch:
5558
6313
if branch is None:
5559
raise errors.BzrCommandError('cannot create branch without'
5561
to_location = directory_service.directories.dereference(
5563
if '/' not in to_location and '\\' not in to_location:
5564
# This path is meant to be relative to the existing branch
5565
this_url = self._get_branch_location(control_dir)
5566
to_location = urlutils.join(this_url, '..', to_location)
5567
to_branch = branch.bzrdir.sprout(to_location,
5568
possible_transports=[branch.bzrdir.root_transport],
5569
source_branch=branch).open_branch()
6314
raise errors.BzrCommandError(
6315
gettext('cannot create branch without source branch'))
6316
to_location = lookup_new_sibling_branch(
6317
control_dir, to_location,
6318
possible_transports=possible_transports)
6319
if revision is not None:
6320
revision = revision.as_revision_id(branch)
6321
to_branch = branch.controldir.sprout(
6323
possible_transports=possible_transports,
6324
revision_id=revision,
6325
source_branch=branch).open_branch()
5572
to_branch = Branch.open(to_location)
5573
except errors.NotBranchError:
5574
this_url = self._get_branch_location(control_dir)
5575
6328
to_branch = Branch.open(
5576
urlutils.join(this_url, '..', to_location))
5577
if revision is not None:
5578
revision = revision.as_revision_id(to_branch)
5579
switch.switch(control_dir, to_branch, force, revision_id=revision)
6329
to_location, possible_transports=possible_transports)
6330
except errors.NotBranchError:
6331
to_branch = open_sibling_branch(
6332
control_dir, to_location,
6333
possible_transports=possible_transports)
6334
if revision is not None:
6335
revision = revision.as_revision_id(to_branch)
6336
possible_transports.append(to_branch.user_transport)
6338
switch.switch(control_dir, to_branch, force, revision_id=revision,
6339
store_uncommitted=store,
6340
possible_transports=possible_transports)
6341
except controldir.BranchReferenceLoop:
6342
raise errors.BzrCommandError(
6343
gettext('switching would create a branch reference loop. '
6344
'Use the "bzr up" command to switch to a '
6345
'different revision.'))
5580
6346
if had_explicit_nick:
5581
branch = control_dir.open_branch() #get the new branch!
6347
branch = control_dir.open_branch() # get the new branch!
5582
6348
branch.nick = to_branch.nick
5583
note('Switched to branch: %s',
5584
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5586
def _get_branch_location(self, control_dir):
5587
"""Return location of branch for this control dir."""
5589
this_branch = control_dir.open_branch()
5590
# This may be a heavy checkout, where we want the master branch
5591
master_location = this_branch.get_bound_location()
5592
if master_location is not None:
5593
return master_location
5594
# If not, use a local sibling
5595
return this_branch.base
5596
except errors.NotBranchError:
5597
format = control_dir.find_branch_format()
5598
if getattr(format, 'get_reference', None) is not None:
5599
return format.get_reference(control_dir)
6350
if to_branch.controldir.control_url != control_dir.control_url:
6351
note(gettext('Switched to branch %s at %s'),
6352
to_branch.name, urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5601
return control_dir.root_transport.base
6354
note(gettext('Switched to branch %s'), to_branch.name)
6356
note(gettext('Switched to branch at %s'),
6357
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5604
6360
class cmd_view(Command):
5954
6744
takes_args = ['path?', 'location?']
6747
Option('force-unversioned',
6748
help='Set reference even if path is not versioned.'),
5956
def run(self, path=None, location=None):
5958
if path is not None:
5960
tree, branch, relpath =(
5961
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
5962
if path is not None:
6751
def run(self, path=None, directory='.', location=None, force_unversioned=False):
6752
tree, branch, relpath = (
6753
controldir.ControlDir.open_containing_tree_or_branch(directory))
5964
6754
if tree is None:
5965
6755
tree = branch.basis_tree()
5966
6756
if path is None:
5967
info = branch._get_all_reference_info().iteritems()
5968
self._display_reference_info(tree, branch, info)
6757
with tree.lock_read():
6759
(path, tree.get_reference_info(path, branch))
6760
for path in tree.iter_references()]
6761
self._display_reference_info(tree, branch, info)
5970
file_id = tree.path2id(path)
6763
if not tree.is_versioned(path) and not force_unversioned:
5972
6764
raise errors.NotVersionedError(path)
5973
6765
if location is None:
5974
info = [(file_id, branch.get_reference_info(file_id))]
6766
info = [(path, tree.get_reference_info(path, branch))]
5975
6767
self._display_reference_info(tree, branch, info)
5977
branch.set_reference_info(file_id, path, location)
6769
tree.set_reference_info(path, location)
5979
6771
def _display_reference_info(self, tree, branch, info):
5981
for file_id, (path, location) in info:
5983
path = tree.id2path(file_id)
5984
except errors.NoSuchId:
6773
for path, location in info:
5986
6774
ref_list.append((path, location))
5987
6775
for path, location in sorted(ref_list):
5988
6776
self.outf.write('%s %s\n' % (path, location))
6779
class cmd_export_pot(Command):
6780
__doc__ = """Export command helps and error messages in po format."""
6783
takes_options = [Option('plugin',
6784
help='Export help text from named command '
6785
'(defaults to all built in commands).',
6787
Option('include-duplicates',
6788
help='Output multiple copies of the same msgid '
6789
'string if it appears more than once.'),
6792
def run(self, plugin=None, include_duplicates=False):
6793
from .export_pot import export_pot
6794
export_pot(self.outf, plugin, include_duplicates)
6797
class cmd_import(Command):
6798
__doc__ = """Import sources from a directory, tarball or zip file
6800
This command will import a directory, tarball or zip file into a bzr
6801
tree, replacing any versioned files already present. If a directory is
6802
specified, it is used as the target. If the directory does not exist, or
6803
is not versioned, it is created.
6805
Tarballs may be gzip or bzip2 compressed. This is autodetected.
6807
If the tarball or zip has a single root directory, that directory is
6808
stripped when extracting the tarball. This is not done for directories.
6811
takes_args = ['source', 'tree?']
6813
def run(self, source, tree=None):
6814
from .upstream_import import do_import
6815
do_import(source, tree)
6818
class cmd_link_tree(Command):
6819
__doc__ = """Hardlink matching files to another tree.
6821
Only files with identical content and execute bit will be linked.
6824
takes_args = ['location']
6826
def run(self, location):
6827
from .transform import link_tree
6828
target_tree = WorkingTree.open_containing(".")[0]
6829
source_tree = WorkingTree.open(location)
6830
with target_tree.lock_write(), source_tree.lock_read():
6831
link_tree(target_tree, source_tree)
6834
class cmd_fetch_ghosts(Command):
6835
__doc__ = """Attempt to retrieve ghosts from another branch.
6837
If the other branch is not supplied, the last-pulled branch is used.
6841
aliases = ['fetch-missing']
6842
takes_args = ['branch?']
6843
takes_options = [Option('no-fix', help="Skip additional synchonization.")]
6845
def run(self, branch=None, no_fix=False):
6846
from .fetch_ghosts import GhostFetcher
6847
installed, failed = GhostFetcher.from_cmdline(branch).run()
6848
if len(installed) > 0:
6849
self.outf.write("Installed:\n")
6850
for rev in installed:
6851
self.outf.write(rev.decode('utf-8') + "\n")
6853
self.outf.write("Still missing:\n")
6855
self.outf.write(rev.decode('utf-8') + "\n")
6856
if not no_fix and len(installed) > 0:
6857
cmd_reconcile().run(".")
6860
class cmd_grep(Command):
6861
"""Print lines matching PATTERN for specified files and revisions.
6863
This command searches the specified files and revisions for a given
6864
pattern. The pattern is specified as a Python regular expressions[1].
6866
If the file name is not specified, the revisions starting with the
6867
current directory are searched recursively. If the revision number is
6868
not specified, the working copy is searched. To search the last committed
6869
revision, use the '-r -1' or '-r last:1' option.
6871
Unversioned files are not searched unless explicitly specified on the
6872
command line. Unversioned directores are not searched.
6874
When searching a pattern, the output is shown in the 'filepath:string'
6875
format. If a revision is explicitly searched, the output is shown as
6876
'filepath~N:string', where N is the revision number.
6878
--include and --exclude options can be used to search only (or exclude
6879
from search) files with base name matches the specified Unix style GLOB
6880
pattern. The GLOB pattern an use *, ?, and [...] as wildcards, and \\
6881
to quote wildcard or backslash character literally. Note that the glob
6882
pattern is not a regular expression.
6884
[1] http://docs.python.org/library/re.html#regular-expression-syntax
6887
encoding_type = 'replace'
6888
takes_args = ['pattern', 'path*']
6892
Option('color', type=str, argname='when',
6893
help='Show match in color. WHEN is never, always or auto.'),
6894
Option('diff', short_name='p',
6895
help='Grep for pattern in changeset for each revision.'),
6896
ListOption('exclude', type=str, argname='glob', short_name='X',
6897
help="Skip files whose base name matches GLOB."),
6898
ListOption('include', type=str, argname='glob', short_name='I',
6899
help="Search only files whose base name matches GLOB."),
6900
Option('files-with-matches', short_name='l',
6901
help='Print only the name of each input file in '
6902
'which PATTERN is found.'),
6903
Option('files-without-match', short_name='L',
6904
help='Print only the name of each input file in '
6905
'which PATTERN is not found.'),
6906
Option('fixed-string', short_name='F',
6907
help='Interpret PATTERN is a single fixed string (not regex).'),
6909
help='Search for pattern starting from the root of the branch. '
6910
'(implies --recursive)'),
6911
Option('ignore-case', short_name='i',
6912
help='Ignore case distinctions while matching.'),
6914
help='Number of levels to display - 0 for all, 1 for collapsed '
6917
type=_parse_levels),
6918
Option('line-number', short_name='n',
6919
help='Show 1-based line number.'),
6920
Option('no-recursive',
6921
help="Don't recurse into subdirectories. (default is --recursive)"),
6922
Option('null', short_name='Z',
6923
help='Write an ASCII NUL (\\0) separator '
6924
'between output lines rather than a newline.'),
6928
def run(self, verbose=False, ignore_case=False, no_recursive=False,
6929
from_root=False, null=False, levels=None, line_number=False,
6930
path_list=None, revision=None, pattern=None, include=None,
6931
exclude=None, fixed_string=False, files_with_matches=False,
6932
files_without_match=False, color=None, diff=False):
6933
from breezy import _termcolor
6936
if path_list is None:
6940
raise errors.BzrCommandError(
6941
'cannot specify both --from-root and PATH.')
6943
if files_with_matches and files_without_match:
6944
raise errors.BzrCommandError(
6945
'cannot specify both '
6946
'-l/--files-with-matches and -L/--files-without-matches.')
6948
global_config = _mod_config.GlobalConfig()
6951
color = global_config.get_user_option('grep_color')
6956
if color not in ['always', 'never', 'auto']:
6957
raise errors.BzrCommandError('Valid values for --color are '
6958
'"always", "never" or "auto".')
6964
if revision is not None or levels == 0:
6965
# print revision numbers as we may be showing multiple revisions
6972
if not ignore_case and grep.is_fixed_string(pattern):
6973
# if the pattern isalnum, implicitly use to -F for faster grep
6975
elif ignore_case and fixed_string:
6976
# GZ 2010-06-02: Fall back to regexp rather than lowercasing
6977
# pattern and text which will cause pain later
6978
fixed_string = False
6979
pattern = re.escape(pattern)
6982
re_flags = re.MULTILINE
6984
re_flags |= re.IGNORECASE
6986
if not fixed_string:
6987
patternc = grep.compile_pattern(
6988
pattern.encode(grep._user_encoding), re_flags)
6990
if color == 'always':
6992
elif color == 'never':
6994
elif color == 'auto':
6995
show_color = _termcolor.allow_color()
6997
opts = grep.GrepOptions()
6999
opts.verbose = verbose
7000
opts.ignore_case = ignore_case
7001
opts.no_recursive = no_recursive
7002
opts.from_root = from_root
7004
opts.levels = levels
7005
opts.line_number = line_number
7006
opts.path_list = path_list
7007
opts.revision = revision
7008
opts.pattern = pattern
7009
opts.include = include
7010
opts.exclude = exclude
7011
opts.fixed_string = fixed_string
7012
opts.files_with_matches = files_with_matches
7013
opts.files_without_match = files_without_match
7017
opts.eol_marker = eol_marker
7018
opts.print_revno = print_revno
7019
opts.patternc = patternc
7020
opts.recursive = not no_recursive
7021
opts.fixed_string = fixed_string
7022
opts.outf = self.outf
7023
opts.show_color = show_color
7027
# files_with_matches, files_without_match
7028
# levels(?), line_number, from_root
7030
# These are silently ignored.
7031
grep.grep_diff(opts)
7032
elif revision is None:
7033
grep.workingtree_grep(opts)
7035
grep.versioned_grep(opts)
7038
class cmd_patch(Command):
7039
"""Apply a named patch to the current tree.
7043
takes_args = ['filename?']
7044
takes_options = [Option('strip', type=int, short_name='p',
7045
help=("Strip the smallest prefix containing num "
7046
"leading slashes from filenames.")),
7047
Option('silent', help='Suppress chatter.')]
7049
def run(self, filename=None, strip=None, silent=False):
7050
from .patch import patch_tree
7051
wt = WorkingTree.open_containing('.')[0]
7055
if filename is None:
7056
my_file = getattr(sys.stdin, 'buffer', sys.stdin)
7058
my_file = open(filename, 'rb')
7059
patches = [my_file.read()]
7060
return patch_tree(wt, patches, strip, quiet=is_quiet(), out=self.outf)
7063
class cmd_resolve_location(Command):
7064
__doc__ = """Expand a location to a full URL.
7067
Look up a Launchpad URL.
7069
brz resolve-location lp:brz
7071
takes_args = ['location']
7074
def run(self, location):
7075
from .location import location_to_url
7076
url = location_to_url(location)
7077
display_url = urlutils.unescape_for_display(url, self.outf.encoding)
7078
self.outf.write('%s\n' % display_url)
5991
7081
def _register_lazy_builtins():
5992
7082
# register lazy builtins from other modules; called at startup and should
5993
7083
# be only called once.
5994
7084
for (name, aliases, module_name) in [
5995
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
5996
('cmd_dpush', [], 'bzrlib.foreign'),
5997
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
5998
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
5999
('cmd_conflicts', [], 'bzrlib.conflicts'),
6000
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
7085
('cmd_bisect', [], 'breezy.bisect'),
7086
('cmd_bundle_info', [], 'breezy.bzr.bundle.commands'),
7087
('cmd_config', [], 'breezy.config'),
7088
('cmd_dump_btree', [], 'breezy.bzr.debug_commands'),
7089
('cmd_file_id', [], 'breezy.bzr.debug_commands'),
7090
('cmd_file_path', [], 'breezy.bzr.debug_commands'),
7091
('cmd_version_info', [], 'breezy.cmd_version_info'),
7092
('cmd_resolve', ['resolved'], 'breezy.conflicts'),
7093
('cmd_conflicts', [], 'breezy.conflicts'),
7094
('cmd_ping', [], 'breezy.bzr.smart.ping'),
7095
('cmd_sign_my_commits', [], 'breezy.commit_signature_commands'),
7096
('cmd_verify_signatures', [], 'breezy.commit_signature_commands'),
7097
('cmd_test_script', [], 'breezy.cmd_test_script'),
6002
7099
builtin_command_registry.register_lazy(name, aliases, module_name)