965
1425
If there is a repository in a parent directory of the location, then
966
1426
the history of the branch will be stored in the repository. Otherwise
967
init creates a standalone branch which carries its own history in
1427
init creates a standalone branch which carries its own history
1428
in the .bzr directory.
970
1430
If there is already a branch at the location but it has no working tree,
971
1431
the tree can be populated with 'bzr checkout'.
973
Recipe for importing a tree of files:
1433
Recipe for importing a tree of files::
978
bzr commit -m 'imported project'
1439
bzr commit -m "imported project"
1442
_see_also = ['init-repository', 'branch', 'checkout']
980
1443
takes_args = ['location?']
981
1444
takes_options = [
983
help='Specify a format for this branch. Current'
984
' formats are: default, knit, metaweave and'
985
' weave. Default is knit; metaweave and'
986
' weave are deprecated',
987
type=get_format_type),
989
def run(self, location=None, format=None):
990
from bzrlib.branch import Branch
1445
Option('create-prefix',
1446
help='Create the path leading up to the branch '
1447
'if it does not already exist.'),
1448
RegistryOption('format',
1449
help='Specify a format for this branch. '
1450
'See "help formats".',
1451
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1452
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1453
value_switches=True,
1454
title="Branch Format",
1456
Option('append-revisions-only',
1457
help='Never change revnos or the existing log.'
1458
' Append revisions to it only.')
1460
def run(self, location=None, format=None, append_revisions_only=False,
1461
create_prefix=False):
991
1462
if format is None:
992
format = get_format_type('default')
1463
format = bzrdir.format_registry.make_bzrdir('default')
993
1464
if location is None:
996
# The path has to exist to initialize a
997
# branch inside of it.
998
# Just using os.mkdir, since I don't
999
# believe that we want to create a bunch of
1000
# locations if the user supplies an extended path
1001
if not os.path.exists(location):
1004
existing_bzrdir = bzrdir.BzrDir.open(location)
1005
except NotBranchError:
1467
to_transport = transport.get_transport(location)
1469
# The path has to exist to initialize a
1470
# branch inside of it.
1471
# Just using os.mkdir, since I don't
1472
# believe that we want to create a bunch of
1473
# locations if the user supplies an extended path
1475
to_transport.ensure_base()
1476
except errors.NoSuchFile:
1477
if not create_prefix:
1478
raise errors.BzrCommandError("Parent directory of %s"
1480
"\nYou may supply --create-prefix to create all"
1481
" leading parent directories."
1483
_create_prefix(to_transport)
1486
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1487
except errors.NotBranchError:
1006
1488
# really a NotBzrDir error...
1007
bzrdir.BzrDir.create_branch_convenience(location, format=format)
1489
create_branch = bzrdir.BzrDir.create_branch_convenience
1490
branch = create_branch(to_transport.base, format=format,
1491
possible_transports=[to_transport])
1492
a_bzrdir = branch.bzrdir
1009
if existing_bzrdir.has_branch():
1010
if existing_bzrdir.has_workingtree():
1011
raise errors.AlreadyBranchError(location)
1013
raise errors.BranchExistsWithoutWorkingTree(location)
1015
existing_bzrdir.create_branch()
1016
existing_bzrdir.create_workingtree()
1494
from bzrlib.transport.local import LocalTransport
1495
if a_bzrdir.has_branch():
1496
if (isinstance(to_transport, LocalTransport)
1497
and not a_bzrdir.has_workingtree()):
1498
raise errors.BranchExistsWithoutWorkingTree(location)
1499
raise errors.AlreadyBranchError(location)
1500
branch = a_bzrdir.create_branch()
1501
a_bzrdir.create_workingtree()
1502
if append_revisions_only:
1504
branch.set_append_revisions_only(True)
1505
except errors.UpgradeRequired:
1506
raise errors.BzrCommandError('This branch format cannot be set'
1507
' to append-revisions-only. Try --experimental-branch6')
1509
from bzrlib.info import describe_layout, describe_format
1511
tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
1512
except (errors.NoWorkingTree, errors.NotLocalUrl):
1514
repository = branch.repository
1515
layout = describe_layout(repository, branch, tree).lower()
1516
format = describe_format(a_bzrdir, repository, branch, tree)
1517
self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1518
if repository.is_shared():
1519
#XXX: maybe this can be refactored into transport.path_or_url()
1520
url = repository.bzrdir.root_transport.external_url()
1522
url = urlutils.local_path_from_url(url)
1523
except errors.InvalidURL:
1525
self.outf.write("Using shared repository: %s\n" % url)
1019
1528
class cmd_init_repository(Command):
1020
1529
"""Create a shared repository to hold branches.
1022
New branches created under the repository directory will store their revisions
1023
in the repository, not in the branch directory, if the branch format supports
1029
bzr checkout --lightweight repo/trunk trunk-checkout
1531
New branches created under the repository directory will store their
1532
revisions in the repository, not in the branch directory.
1534
If the --no-trees option is used then the branches in the repository
1535
will not have working trees by default.
1538
Create a shared repositories holding just branches::
1540
bzr init-repo --no-trees repo
1543
Make a lightweight checkout elsewhere::
1545
bzr checkout --lightweight repo/trunk trunk-checkout
1033
takes_args = ["location"]
1034
takes_options = [Option('format',
1035
help='Specify a format for this repository.'
1036
' Current formats are: default, knit,'
1037
' metaweave and weave. Default is knit;'
1038
' metaweave and weave are deprecated',
1039
type=get_format_type),
1041
help='Allows branches in repository to have'
1550
_see_also = ['init', 'branch', 'checkout', 'repositories']
1551
takes_args = ["location"]
1552
takes_options = [RegistryOption('format',
1553
help='Specify a format for this repository. See'
1554
' "bzr help formats" for details.',
1555
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1556
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1557
value_switches=True, title='Repository format'),
1559
help='Branches in the repository will default to'
1560
' not having a working tree.'),
1043
1562
aliases = ["init-repo"]
1044
def run(self, location, format=None, trees=False):
1045
from bzrlib.transport import get_transport
1564
def run(self, location, format=None, no_trees=False):
1046
1565
if format is None:
1047
format = get_format_type('default')
1048
transport = get_transport(location)
1049
if not transport.has('.'):
1051
newdir = format.initialize_on_transport(transport)
1566
format = bzrdir.format_registry.make_bzrdir('default')
1568
if location is None:
1571
to_transport = transport.get_transport(location)
1572
to_transport.ensure_base()
1574
newdir = format.initialize_on_transport(to_transport)
1052
1575
repo = newdir.create_repository(shared=True)
1053
repo.set_make_working_trees(trees)
1576
repo.set_make_working_trees(not no_trees)
1578
from bzrlib.info import show_bzrdir_info
1579
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1056
1582
class cmd_diff(Command):
1057
"""Show differences in working tree.
1583
"""Show differences in the working tree, between revisions or branches.
1059
If files are listed, only the changes in those files are listed.
1060
Otherwise, all changes for the tree are listed.
1585
If no arguments are given, all changes for the current tree are listed.
1586
If files are given, only the changes in those files are listed.
1587
Remote and multiple branches can be compared by using the --old and
1588
--new options. If not provided, the default for both is derived from
1589
the first argument, if any, or the current tree if no arguments are
1062
1592
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1063
1593
produces patches suitable for "patch -p1".
1069
bzr diff --diff-prefix old/:new/
1070
bzr diff bzr.mine bzr.dev
1597
2 - unrepresentable changes
1602
Shows the difference in the working tree versus the last commit::
1606
Difference between the working tree and revision 1::
1610
Difference between revision 2 and revision 1::
1614
Difference between revision 2 and revision 1 for branch xxx::
1618
Show just the differences for file NEWS::
1622
Show the differences in working tree xxx for file NEWS::
1626
Show the differences from branch xxx to this working tree:
1630
Show the differences between two branches for file NEWS::
1632
bzr diff --old xxx --new yyy NEWS
1634
Same as 'bzr diff' but prefix paths with old/ and new/::
1636
bzr diff --prefix old/:new/
1073
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1074
# or a graphical diff.
1076
# TODO: Python difflib is not exactly the same as unidiff; should
1077
# either fix it up or prefer to use an external diff.
1079
# TODO: Selected-file diff is inefficient and doesn't show you
1082
# TODO: This probably handles non-Unix newlines poorly.
1638
_see_also = ['status']
1084
1639
takes_args = ['file*']
1085
takes_options = ['revision', 'diff-options', 'prefix']
1641
Option('diff-options', type=str,
1642
help='Pass these options to the external diff program.'),
1643
Option('prefix', type=str,
1645
help='Set prefixes added to old and new filenames, as '
1646
'two values separated by a colon. (eg "old/:new/").'),
1648
help='Branch/tree to compare from.',
1652
help='Branch/tree to compare to.',
1658
help='Use this command to compare files.',
1086
1662
aliases = ['di', 'dif']
1087
1663
encoding_type = 'exact'
1089
1665
@display_command
1090
1666
def run(self, revision=None, file_list=None, diff_options=None,
1092
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1667
prefix=None, old=None, new=None, using=None):
1668
from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1094
1670
if (prefix is None) or (prefix == '0'):
1095
1671
# diff -p0 format
1348
1986
def run(self, filename):
1349
1987
tree, relpath = WorkingTree.open_containing(filename)
1350
1988
b = tree.branch
1351
inv = tree.read_working_inventory()
1352
file_id = inv.path2id(relpath)
1353
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1989
file_id = tree.path2id(relpath)
1990
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1354
1991
self.outf.write("%6d %s\n" % (revno, what))
1357
1994
class cmd_ls(Command):
1358
1995
"""List files in a tree.
1998
_see_also = ['status', 'cat']
1999
takes_args = ['path?']
1360
2000
# TODO: Take a revision or remote path and list that tree instead.
1362
takes_options = ['verbose', 'revision',
1363
Option('non-recursive',
1364
help='don\'t recurse into sub-directories'),
1366
help='Print all paths from the root of the branch.'),
1367
Option('unknown', help='Print unknown files'),
1368
Option('versioned', help='Print versioned files'),
1369
Option('ignored', help='Print ignored files'),
1371
Option('null', help='Null separate the files'),
2004
Option('non-recursive',
2005
help='Don\'t recurse into subdirectories.'),
2007
help='Print paths relative to the root of the branch.'),
2008
Option('unknown', help='Print unknown files.'),
2009
Option('versioned', help='Print versioned files.',
2011
Option('ignored', help='Print ignored files.'),
2013
help='Write an ascii NUL (\\0) separator '
2014
'between files rather than a newline.'),
2016
help='List entries of a particular kind: file, directory, symlink.',
1373
2020
@display_command
1374
def run(self, revision=None, verbose=False,
2021
def run(self, revision=None, verbose=False,
1375
2022
non_recursive=False, from_root=False,
1376
2023
unknown=False, versioned=False, ignored=False,
2024
null=False, kind=None, show_ids=False, path=None):
2026
if kind and kind not in ('file', 'directory', 'symlink'):
2027
raise errors.BzrCommandError('invalid kind specified')
1379
2029
if verbose and null:
1380
raise BzrCommandError('Cannot set both --verbose and --null')
2030
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1381
2031
all = not (unknown or versioned or ignored)
1383
2033
selection = {'I':ignored, '?':unknown, 'V':versioned}
1385
tree, relpath = WorkingTree.open_containing(u'.')
2040
raise errors.BzrCommandError('cannot specify both --from-root'
2044
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1390
if revision is not None:
1391
tree = tree.branch.repository.revision_tree(
1392
revision[0].in_history(tree.branch).rev_id)
2050
if revision is not None or tree is None:
2051
tree = _get_one_revision_tree('ls', revision, branch=branch)
1394
for fp, fc, kind, fid, entry in tree.list_files():
1395
if fp.startswith(relpath):
1396
fp = fp[len(relpath):]
1397
if non_recursive and '/' in fp:
1399
if not all and not selection[fc]:
2055
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2056
if fp.startswith(relpath):
2057
fp = osutils.pathjoin(prefix, fp[len(relpath):])
2058
if non_recursive and '/' in fp:
2060
if not all and not selection[fc]:
2062
if kind is not None and fkind != kind:
1402
2064
kindch = entry.kind_character()
1403
self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1405
self.outf.write(fp + '\0')
1408
self.outf.write(fp + '\n')
2065
outstring = fp + kindch
2067
outstring = '%-8s %s' % (fc, outstring)
2068
if show_ids and fid is not None:
2069
outstring = "%-50s %s" % (outstring, fid)
2070
self.outf.write(outstring + '\n')
2072
self.outf.write(fp + '\0')
2075
self.outf.write(fid)
2076
self.outf.write('\0')
2084
self.outf.write('%-50s %s\n' % (outstring, my_id))
2086
self.outf.write(outstring + '\n')
1411
2091
class cmd_unknowns(Command):
1412
"""List unknown files."""
2092
"""List unknown files.
1413
2098
@display_command
1415
from bzrlib.osutils import quotefn
1416
2100
for f in WorkingTree.open_containing(u'.')[0].unknowns():
1417
self.outf.write(quotefn(f) + '\n')
2101
self.outf.write(osutils.quotefn(f) + '\n')
1420
2104
class cmd_ignore(Command):
1421
"""Ignore a command or pattern.
2105
"""Ignore specified files or patterns.
2107
See ``bzr help patterns`` for details on the syntax of patterns.
1423
2109
To remove patterns from the ignore list, edit the .bzrignore file.
1425
If the pattern contains a slash, it is compared to the whole path
1426
from the branch root. Otherwise, it is compared to only the last
1427
component of the path. To match a file only in the root directory,
1430
Ignore patterns are case-insensitive on case-insensitive systems.
1432
Note: wildcards must be quoted from the shell on Unix.
1435
bzr ignore ./Makefile
1436
bzr ignore '*.class'
2110
After adding, editing or deleting that file either indirectly by
2111
using this command or directly by using an editor, be sure to commit
2114
Note: ignore patterns containing shell wildcards must be quoted from
2118
Ignore the top level Makefile::
2120
bzr ignore ./Makefile
2122
Ignore class files in all directories::
2124
bzr ignore "*.class"
2126
Ignore .o files under the lib directory::
2128
bzr ignore "lib/**/*.o"
2130
Ignore .o files under the lib directory::
2132
bzr ignore "RE:lib/.*\.o"
2134
Ignore everything but the "debian" toplevel directory::
2136
bzr ignore "RE:(?!debian/).*"
1438
# TODO: Complain if the filename is absolute
1439
takes_args = ['name_pattern']
2139
_see_also = ['status', 'ignored', 'patterns']
2140
takes_args = ['name_pattern*']
2142
Option('old-default-rules',
2143
help='Write out the ignore rules bzr < 0.9 always used.')
1441
def run(self, name_pattern):
1442
from bzrlib.atomicfile import AtomicFile
2146
def run(self, name_pattern_list=None, old_default_rules=None):
2147
from bzrlib import ignores
2148
if old_default_rules is not None:
2149
# dump the rules and exit
2150
for pattern in ignores.OLD_DEFAULTS:
2153
if not name_pattern_list:
2154
raise errors.BzrCommandError("ignore requires at least one "
2155
"NAME_PATTERN or --old-default-rules")
2156
name_pattern_list = [globbing.normalize_pattern(p)
2157
for p in name_pattern_list]
2158
for name_pattern in name_pattern_list:
2159
if (name_pattern[0] == '/' or
2160
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2161
raise errors.BzrCommandError(
2162
"NAME_PATTERN should not be an absolute path")
1445
2163
tree, relpath = WorkingTree.open_containing(u'.')
1446
ifn = tree.abspath('.bzrignore')
1448
if os.path.exists(ifn):
1451
igns = f.read().decode('utf-8')
1457
# TODO: If the file already uses crlf-style termination, maybe
1458
# we should use that for the newly added lines?
1460
if igns and igns[-1] != '\n':
1462
igns += name_pattern + '\n'
1464
f = AtomicFile(ifn, 'wt')
1466
f.write(igns.encode('utf-8'))
1471
inv = tree.inventory
1472
if inv.path2id('.bzrignore'):
1473
mutter('.bzrignore is already versioned')
1475
mutter('need to make new .bzrignore file versioned')
1476
tree.add(['.bzrignore'])
2164
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2165
ignored = globbing.Globster(name_pattern_list)
2168
for entry in tree.list_files():
2172
if ignored.match(filename):
2173
matches.append(filename.encode('utf-8'))
2175
if len(matches) > 0:
2176
print "Warning: the following files are version controlled and" \
2177
" match your ignore pattern:\n%s" % ("\n".join(matches),)
1479
2180
class cmd_ignored(Command):
1480
2181
"""List ignored files and the patterns that matched them.
1482
See also: bzr ignore"""
2183
List all the ignored files and the ignore pattern that caused the file to
2186
Alternatively, to list just the files::
2191
encoding_type = 'replace'
2192
_see_also = ['ignore', 'ls']
1483
2194
@display_command
1485
2196
tree = WorkingTree.open_containing(u'.')[0]
1486
for path, file_class, kind, file_id, entry in tree.list_files():
1487
if file_class != 'I':
1489
## XXX: Slightly inefficient since this was already calculated
1490
pat = tree.is_ignored(path)
1491
print '%-50s %s' % (path, pat)
2199
for path, file_class, kind, file_id, entry in tree.list_files():
2200
if file_class != 'I':
2202
## XXX: Slightly inefficient since this was already calculated
2203
pat = tree.is_ignored(path)
2204
self.outf.write('%-50s %s\n' % (path, pat))
1494
2209
class cmd_lookup_revision(Command):
1495
2210
"""Lookup the revision-id from a revision-number
1498
2213
bzr lookup-revision 33
1833
2828
return FakeNFSServer
1834
2829
msg = "No known transport type %s. Supported types are: sftp\n" %\
1836
raise BzrCommandError(msg)
2831
raise errors.BzrCommandError(msg)
1839
2834
takes_args = ['testspecs*']
1840
2835
takes_options = ['verbose',
1841
Option('one', help='stop when one test fails'),
1842
Option('keep-output',
1843
help='keep output directories when tests fail'),
2837
help='Stop when one test fails.',
1845
2841
help='Use a different transport by default '
1846
2842
'throughout the test suite.',
1847
2843
type=get_transport_type),
1848
Option('benchmark', help='run the bzr bencharks.'),
2845
help='Run the benchmarks rather than selftests.'),
1849
2846
Option('lsprof-timed',
1850
help='generate lsprof output for benchmarked'
2847
help='Generate lsprof output for benchmarked'
1851
2848
' sections of code.'),
2849
Option('cache-dir', type=str,
2850
help='Cache intermediate benchmark output in this '
2853
help='Run all tests, but run specified tests first.',
2857
help='List the tests instead of running them.'),
2858
Option('randomize', type=str, argname="SEED",
2859
help='Randomize the order of tests using the given'
2860
' seed or "now" for the current time.'),
2861
Option('exclude', type=str, argname="PATTERN",
2863
help='Exclude tests that match this regular'
2865
Option('strict', help='Fail on missing dependencies or '
2867
Option('load-list', type=str, argname='TESTLISTFILE',
2868
help='Load a test id list from a text file.'),
2869
ListOption('debugflag', type=str, short_name='E',
2870
help='Turn on a selftest debug flag.'),
2871
ListOption('starting-with', type=str, argname='TESTID',
2872
param_name='starting_with', short_name='s',
2874
'Load only the tests starting with TESTID.'),
2876
encoding_type = 'replace'
1854
def run(self, testspecs_list=None, verbose=None, one=False,
1855
keep_output=False, transport=None, benchmark=None,
2878
def run(self, testspecs_list=None, verbose=False, one=False,
2879
transport=None, benchmark=None,
2880
lsprof_timed=None, cache_dir=None,
2881
first=False, list_only=False,
2882
randomize=None, exclude=None, strict=False,
2883
load_list=None, debugflag=None, starting_with=None):
1858
2884
from bzrlib.tests import selftest
1859
2885
import bzrlib.benchmarks as benchmarks
1860
# we don't want progress meters from the tests to go to the
1861
# real output; and we don't want log messages cluttering up
1863
save_ui = bzrlib.ui.ui_factory
1864
print '%10s: %s' % ('bzr', bzrlib.osutils.realpath(sys.argv[0]))
1865
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
2886
from bzrlib.benchmarks import tree_creator
2888
# Make deprecation warnings visible, unless -Werror is set
2889
symbol_versioning.activate_deprecation_warnings(override=False)
2891
if cache_dir is not None:
2892
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2894
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2895
print ' %s (%s python%s)' % (
2897
bzrlib.version_string,
2898
bzrlib._format_version_tuple(sys.version_info),
1867
bzrlib.trace.info('running tests...')
2901
if testspecs_list is not None:
2902
pattern = '|'.join(testspecs_list)
2906
test_suite_factory = benchmarks.test_suite
2907
# Unless user explicitly asks for quiet, be verbose in benchmarks
2908
verbose = not is_quiet()
2909
# TODO: should possibly lock the history file...
2910
benchfile = open(".perf_history", "at", buffering=1)
2912
test_suite_factory = None
1869
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1870
if testspecs_list is not None:
1871
pattern = '|'.join(testspecs_list)
1875
test_suite_factory = benchmarks.test_suite
1879
test_suite_factory = None
1882
result = selftest(verbose=verbose,
2915
result = selftest(verbose=verbose,
1883
2916
pattern=pattern,
1884
stop_on_failure=one,
1885
keep_output=keep_output,
2917
stop_on_failure=one,
1886
2918
transport=transport,
1887
2919
test_suite_factory=test_suite_factory,
1888
lsprof_timed=lsprof_timed)
1890
bzrlib.trace.info('tests passed')
1892
bzrlib.trace.info('tests failed')
1893
return int(not result)
2920
lsprof_timed=lsprof_timed,
2921
bench_history=benchfile,
2922
matching_tests_first=first,
2923
list_only=list_only,
2924
random_seed=randomize,
2925
exclude_pattern=exclude,
2927
load_list=load_list,
2928
debug_flags=debugflag,
2929
starting_with=starting_with,
1895
bzrlib.ui.ui_factory = save_ui
1898
def _get_bzr_branch():
1899
"""If bzr is run from a branch, return Branch or None"""
1900
import bzrlib.errors
1901
from bzrlib.branch import Branch
1902
from bzrlib.osutils import abspath
1903
from os.path import dirname
1906
branch = Branch.open(dirname(abspath(dirname(__file__))))
1908
except bzrlib.errors.BzrError:
1913
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1914
# is bzrlib itself in a branch?
1915
branch = _get_bzr_branch()
1917
rh = branch.revision_history()
1919
print " bzr checkout, revision %d" % (revno,)
1920
print " nick: %s" % (branch.nick,)
1922
print " revid: %s" % (rh[-1],)
1923
print "Using python interpreter:", sys.executable
1925
print "Using python standard library:", os.path.dirname(site.__file__)
1926
print "Using bzrlib:",
1927
if len(bzrlib.__path__) > 1:
1928
# print repr, which is a good enough way of making it clear it's
1929
# more than one element (eg ['/foo/bar', '/foo/bzr'])
1930
print repr(bzrlib.__path__)
1932
print bzrlib.__path__[0]
1935
print bzrlib.__copyright__
1936
print "http://bazaar-vcs.org/"
1938
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1939
print "you may use, modify and redistribute it under the terms of the GNU"
1940
print "General Public License version 2 or later."
2932
if benchfile is not None:
2935
note('tests passed')
2937
note('tests failed')
2938
return int(not result)
1943
2941
class cmd_version(Command):
1944
2942
"""Show version of bzr."""
2944
encoding_type = 'replace'
2946
Option("short", help="Print just the version number."),
1945
2949
@display_command
2950
def run(self, short=False):
2951
from bzrlib.version import show_version
2953
self.outf.write(bzrlib.version_string + '\n')
2955
show_version(to_file=self.outf)
1949
2958
class cmd_rocks(Command):
1950
2959
"""Statement of optimism."""
1952
2963
@display_command
1954
print "it sure does!"
2965
print "It sure does!"
1957
2968
class cmd_find_merge_base(Command):
1958
"""Find and print a base revision for merging two branches.
2969
"""Find and print a base revision for merging two branches."""
1960
2970
# TODO: Options to specify revisions on either side, as if
1961
2971
# merging only part of the history.
1962
2972
takes_args = ['branch', 'other']
2018
3024
If there is no default branch set, the first merge will set it. After
2019
3025
that, you can omit the branch to use the default. To change the
2020
default, use --remember.
2024
To merge the latest revision from bzr.dev
2025
bzr merge ../bzr.dev
2027
To merge changes up to and including revision 82 from bzr.dev
2028
bzr merge -r 82 ../bzr.dev
2030
To merge the changes introduced by 82, without previous changes:
2031
bzr merge -r 81..82 ../bzr.dev
3026
default, use --remember. The value will only be saved if the remote
3027
location can be accessed.
3029
The results of the merge are placed into the destination working
3030
directory, where they can be reviewed (with bzr diff), tested, and then
3031
committed to record the result of the merge.
2033
3033
merge refuses to run if there are any uncommitted changes, unless
2034
3034
--force is given.
2036
The following merge types are available:
3037
To merge the latest revision from bzr.dev::
3039
bzr merge ../bzr.dev
3041
To merge changes up to and including revision 82 from bzr.dev::
3043
bzr merge -r 82 ../bzr.dev
3045
To merge the changes introduced by 82, without previous changes::
3047
bzr merge -r 81..82 ../bzr.dev
3049
To apply a merge directive contained in in /tmp/merge:
3051
bzr merge /tmp/merge
2038
takes_args = ['branch?']
2039
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
2040
Option('show-base', help="Show base revision text in "
2044
from merge import merge_type_help
2045
from inspect import getdoc
2046
return getdoc(self) + '\n' + merge_type_help()
2048
def run(self, branch=None, revision=None, force=False, merge_type=None,
2049
show_base=False, reprocess=False, remember=False):
3054
encoding_type = 'exact'
3055
_see_also = ['update', 'remerge', 'status-flags']
3056
takes_args = ['location?']
3061
help='Merge even if the destination tree has uncommitted changes.'),
3065
Option('show-base', help="Show base revision text in "
3067
Option('uncommitted', help='Apply uncommitted changes'
3068
' from a working copy, instead of branch changes.'),
3069
Option('pull', help='If the destination is already'
3070
' completely merged into the source, pull from the'
3071
' source rather than merging. When this happens,'
3072
' you do not need to commit the result.'),
3074
help='Branch to merge into, '
3075
'rather than the one containing the working directory.',
3079
Option('preview', help='Instead of merging, show a diff of the merge.')
3082
def run(self, location=None, revision=None, force=False,
3083
merge_type=None, show_base=False, reprocess=None, remember=False,
3084
uncommitted=False, pull=False,
2050
3088
if merge_type is None:
2051
merge_type = Merge3Merger
2053
tree = WorkingTree.open_containing(u'.')[0]
3089
merge_type = _mod_merge.Merge3Merger
3091
if directory is None: directory = u'.'
3092
possible_transports = []
3094
allow_pending = True
3095
verified = 'inapplicable'
3096
tree = WorkingTree.open_containing(directory)[0]
3097
change_reporter = delta._ChangeReporter(
3098
unversioned_filter=tree.is_ignored)
3101
pb = ui.ui_factory.nested_progress_bar()
3102
cleanups.append(pb.finished)
3104
cleanups.append(tree.unlock)
3105
if location is not None:
3107
mergeable = bundle.read_mergeable_from_url(location,
3108
possible_transports=possible_transports)
3109
except errors.NotABundle:
3113
raise errors.BzrCommandError('Cannot use --uncommitted'
3114
' with bundles or merge directives.')
3116
if revision is not None:
3117
raise errors.BzrCommandError(
3118
'Cannot use -r with merge directives or bundles')
3119
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3122
if merger is None and uncommitted:
3123
if revision is not None and len(revision) > 0:
3124
raise errors.BzrCommandError('Cannot use --uncommitted and'
3125
' --revision at the same time.')
3126
location = self._select_branch_location(tree, location)[0]
3127
other_tree, other_path = WorkingTree.open_containing(location)
3128
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3130
allow_pending = False
3131
if other_path != '':
3132
merger.interesting_files = [other_path]
3135
merger, allow_pending = self._get_merger_from_branch(tree,
3136
location, revision, remember, possible_transports, pb)
3138
merger.merge_type = merge_type
3139
merger.reprocess = reprocess
3140
merger.show_base = show_base
3141
self.sanity_check_merger(merger)
3142
if (merger.base_rev_id == merger.other_rev_id and
3143
merger.other_rev_id is not None):
3144
note('Nothing to do.')
3147
if merger.interesting_files is not None:
3148
raise errors.BzrCommandError('Cannot pull individual files')
3149
if (merger.base_rev_id == tree.last_revision()):
3150
result = tree.pull(merger.other_branch, False,
3151
merger.other_rev_id)
3152
result.report(self.outf)
3154
merger.check_basis(not force)
3156
return self._do_preview(merger)
3158
return self._do_merge(merger, change_reporter, allow_pending,
3161
for cleanup in reversed(cleanups):
3164
def _do_preview(self, merger):
3165
from bzrlib.diff import show_diff_trees
3166
tree_merger = merger.make_merger()
3167
tt = tree_merger.make_preview_transform()
3169
result_tree = tt.get_preview_tree()
3170
show_diff_trees(merger.this_tree, result_tree, self.outf,
3171
old_label='', new_label='')
3175
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3176
merger.change_reporter = change_reporter
3177
conflict_count = merger.do_merge()
3179
merger.set_pending()
3180
if verified == 'failed':
3181
warning('Preview patch does not match changes')
3182
if conflict_count != 0:
3187
def sanity_check_merger(self, merger):
3188
if (merger.show_base and
3189
not merger.merge_type is _mod_merge.Merge3Merger):
3190
raise errors.BzrCommandError("Show-base is not supported for this"
3191
" merge type. %s" % merger.merge_type)
3192
if merger.reprocess is None:
3193
if merger.show_base:
3194
merger.reprocess = False
3196
# Use reprocess if the merger supports it
3197
merger.reprocess = merger.merge_type.supports_reprocess
3198
if merger.reprocess and not merger.merge_type.supports_reprocess:
3199
raise errors.BzrCommandError("Conflict reduction is not supported"
3200
" for merge type %s." %
3202
if merger.reprocess and merger.show_base:
3203
raise errors.BzrCommandError("Cannot do conflict reduction and"
3206
def _get_merger_from_branch(self, tree, location, revision, remember,
3207
possible_transports, pb):
3208
"""Produce a merger from a location, assuming it refers to a branch."""
3209
from bzrlib.tag import _merge_tags_if_possible
3210
# find the branch locations
3211
other_loc, user_location = self._select_branch_location(tree, location,
3213
if revision is not None and len(revision) == 2:
3214
base_loc, _unused = self._select_branch_location(tree,
3215
location, revision, 0)
3217
base_loc = other_loc
3219
other_branch, other_path = Branch.open_containing(other_loc,
3220
possible_transports)
3221
if base_loc == other_loc:
3222
base_branch = other_branch
3224
base_branch, base_path = Branch.open_containing(base_loc,
3225
possible_transports)
3226
# Find the revision ids
3227
if revision is None or len(revision) < 1 or revision[-1] is None:
3228
other_revision_id = _mod_revision.ensure_null(
3229
other_branch.last_revision())
3231
other_revision_id = revision[-1].as_revision_id(other_branch)
3232
if (revision is not None and len(revision) == 2
3233
and revision[0] is not None):
3234
base_revision_id = revision[0].as_revision_id(base_branch)
3236
base_revision_id = None
3237
# Remember where we merge from
3238
if ((remember or tree.branch.get_submit_branch() is None) and
3239
user_location is not None):
3240
tree.branch.set_submit_branch(other_branch.base)
3241
_merge_tags_if_possible(other_branch, tree.branch)
3242
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3243
other_revision_id, base_revision_id, other_branch, base_branch)
3244
if other_path != '':
3245
allow_pending = False
3246
merger.interesting_files = [other_path]
3248
allow_pending = True
3249
return merger, allow_pending
3251
def _select_branch_location(self, tree, user_location, revision=None,
3253
"""Select a branch location, according to possible inputs.
3255
If provided, branches from ``revision`` are preferred. (Both
3256
``revision`` and ``index`` must be supplied.)
3258
Otherwise, the ``location`` parameter is used. If it is None, then the
3259
``submit`` or ``parent`` location is used, and a note is printed.
3261
:param tree: The working tree to select a branch for merging into
3262
:param location: The location entered by the user
3263
:param revision: The revision parameter to the command
3264
:param index: The index to use for the revision parameter. Negative
3265
indices are permitted.
3266
:return: (selected_location, user_location). The default location
3267
will be the user-entered location.
3269
if (revision is not None and index is not None
3270
and revision[index] is not None):
3271
branch = revision[index].get_branch()
2056
3272
if branch is not None:
2057
reader = BundleReader(file(branch, 'rb'))
2061
if e.errno not in (errno.ENOENT, errno.EISDIR):
2066
if reader is not None:
2067
conflicts = merge_bundle(reader, tree, not force, merge_type,
2068
reprocess, show_base)
2074
branch = self._get_remembered_parent(tree, branch, 'Merging from')
2076
if revision is None or len(revision) < 1:
2078
other = [branch, -1]
2079
other_branch, path = Branch.open_containing(branch)
2081
if len(revision) == 1:
2083
other_branch, path = Branch.open_containing(branch)
2084
revno = revision[0].in_history(other_branch).revno
2085
other = [branch, revno]
2087
assert len(revision) == 2
2088
if None in revision:
2089
raise BzrCommandError(
2090
"Merge doesn't permit that revision specifier.")
2091
other_branch, path = Branch.open_containing(branch)
2093
base = [branch, revision[0].in_history(other_branch).revno]
2094
other = [branch, revision[1].in_history(other_branch).revno]
2096
if tree.branch.get_parent() is None or remember:
2097
tree.branch.set_parent(other_branch.base)
2100
interesting_files = [path]
2102
interesting_files = None
2103
pb = bzrlib.ui.ui_factory.nested_progress_bar()
2106
conflict_count = merge(other, base, check_clean=(not force),
2107
merge_type=merge_type,
2108
reprocess=reprocess,
2109
show_base=show_base,
2110
pb=pb, file_list=interesting_files)
2113
if conflict_count != 0:
2117
except bzrlib.errors.AmbiguousBase, e:
2118
m = ("sorry, bzr can't determine the right merge base yet\n"
2119
"candidates are:\n "
2120
+ "\n ".join(e.bases)
2122
"please specify an explicit base with -r,\n"
2123
"and (if you want) report this to the bzr developers\n")
2126
# TODO: move up to common parent; this isn't merge-specific anymore.
2127
def _get_remembered_parent(self, tree, supplied_location, verb_string):
3273
return branch, branch
3274
if user_location is None:
3275
location = self._get_remembered(tree, 'Merging from')
3277
location = user_location
3278
return location, user_location
3280
def _get_remembered(self, tree, verb_string):
2128
3281
"""Use tree.branch's parent if none was supplied.
2130
3283
Report if the remembered location was used.
2132
if supplied_location is not None:
2133
return supplied_location
2134
stored_location = tree.branch.get_parent()
3285
stored_location = tree.branch.get_submit_branch()
3286
stored_location_type = "submit"
3287
if stored_location is None:
3288
stored_location = tree.branch.get_parent()
3289
stored_location_type = "parent"
2135
3290
mutter("%s", stored_location)
2136
3291
if stored_location is None:
2137
raise BzrCommandError("No location specified or remembered")
2138
display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2139
self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
3292
raise errors.BzrCommandError("No location specified or remembered")
3293
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3294
note(u"%s remembered %s location %s", verb_string,
3295
stored_location_type, display_url)
2140
3296
return stored_location
2650
# command-line interpretation helper for merge-related commands
2651
def merge(other_revision, base_revision,
2652
check_clean=True, ignore_zero=False,
2653
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2654
file_list=None, show_base=False, reprocess=False,
2655
pb=DummyProgress()):
2656
"""Merge changes into a tree.
2659
list(path, revno) Base for three-way merge.
2660
If [None, None] then a base will be automatically determined.
2662
list(path, revno) Other revision for three-way merge.
2664
Directory to merge changes into; '.' by default.
2666
If true, this_dir must have no uncommitted changes before the
2668
ignore_zero - If true, suppress the "zero conflicts" message when
2669
there are no conflicts; should be set when doing something we expect
2670
to complete perfectly.
2671
file_list - If supplied, merge only changes to selected files.
2673
All available ancestors of other_revision and base_revision are
2674
automatically pulled into the branch.
2676
The revno may be -1 to indicate the last revision on the branch, which is
2679
This function is intended for use from the command line; programmatic
2680
clients might prefer to call merge.merge_inner(), which has less magic
2683
from bzrlib.merge import Merger
2684
if this_dir is None:
2686
this_tree = WorkingTree.open_containing(this_dir)[0]
2687
if show_base and not merge_type is Merge3Merger:
2688
raise BzrCommandError("Show-base is not supported for this merge"
2689
" type. %s" % merge_type)
2690
if reprocess and not merge_type.supports_reprocess:
2691
raise BzrCommandError("Conflict reduction is not supported for merge"
2692
" type %s." % merge_type)
2693
if reprocess and show_base:
2694
raise BzrCommandError("Cannot do conflict reduction and show base.")
2696
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2697
merger.pp = ProgressPhase("Merge phase", 5, pb)
2698
merger.pp.next_phase()
2699
merger.check_basis(check_clean)
2700
merger.set_other(other_revision)
2701
merger.pp.next_phase()
2702
merger.set_base(base_revision)
2703
if merger.base_rev_id == merger.other_rev_id:
2704
note('Nothing to do.')
4045
class cmd_wait_until_signalled(Command):
4046
"""Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4048
This just prints a line to signal when it is ready, then blocks on stdin.
4054
sys.stdout.write("running\n")
4056
sys.stdin.readline()
4059
class cmd_serve(Command):
4060
"""Run the bzr server."""
4062
aliases = ['server']
4066
help='Serve on stdin/out for use from inetd or sshd.'),
4068
help='Listen for connections on nominated port of the form '
4069
'[hostname:]portnumber. Passing 0 as the port number will '
4070
'result in a dynamically allocated port. The default port is '
4074
help='Serve contents of this directory.',
4076
Option('allow-writes',
4077
help='By default the server is a readonly server. Supplying '
4078
'--allow-writes enables write access to the contents of '
4079
'the served directory and below.'
4083
def run(self, port=None, inet=False, directory=None, allow_writes=False):
4084
from bzrlib import lockdir
4085
from bzrlib.smart import medium, server
4086
from bzrlib.transport import get_transport
4087
from bzrlib.transport.chroot import ChrootServer
4088
if directory is None:
4089
directory = os.getcwd()
4090
url = urlutils.local_path_to_url(directory)
4091
if not allow_writes:
4092
url = 'readonly+' + url
4093
chroot_server = ChrootServer(get_transport(url))
4094
chroot_server.setUp()
4095
t = get_transport(chroot_server.get_url())
4097
smart_server = medium.SmartServerPipeStreamMedium(
4098
sys.stdin, sys.stdout, t)
4100
host = medium.BZR_DEFAULT_INTERFACE
4102
port = medium.BZR_DEFAULT_PORT
4105
host, port = port.split(':')
4107
smart_server = server.SmartTCPServer(t, host=host, port=port)
4108
print 'listening on port: ', smart_server.port
4110
# for the duration of this server, no UI output is permitted.
4111
# note that this may cause problems with blackbox tests. This should
4112
# be changed with care though, as we dont want to use bandwidth sending
4113
# progress over stderr to smart server clients!
4114
old_factory = ui.ui_factory
4115
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4117
ui.ui_factory = ui.SilentUIFactory()
4118
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4119
smart_server.serve()
4121
ui.ui_factory = old_factory
4122
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4125
class cmd_join(Command):
4126
"""Combine a subtree into its containing tree.
4128
This command is for experimental use only. It requires the target tree
4129
to be in dirstate-with-subtree format, which cannot be converted into
4132
The TREE argument should be an independent tree, inside another tree, but
4133
not part of it. (Such trees can be produced by "bzr split", but also by
4134
running "bzr branch" with the target inside a tree.)
4136
The result is a combined tree, with the subtree no longer an independant
4137
part. This is marked as a merge of the subtree into the containing tree,
4138
and all history is preserved.
4140
If --reference is specified, the subtree retains its independence. It can
4141
be branched by itself, and can be part of multiple projects at the same
4142
time. But operations performed in the containing tree, such as commit
4143
and merge, will recurse into the subtree.
4146
_see_also = ['split']
4147
takes_args = ['tree']
4149
Option('reference', help='Join by reference.'),
4153
def run(self, tree, reference=False):
4154
sub_tree = WorkingTree.open(tree)
4155
parent_dir = osutils.dirname(sub_tree.basedir)
4156
containing_tree = WorkingTree.open_containing(parent_dir)[0]
4157
repo = containing_tree.branch.repository
4158
if not repo.supports_rich_root():
4159
raise errors.BzrCommandError(
4160
"Can't join trees because %s doesn't support rich root data.\n"
4161
"You can use bzr upgrade on the repository."
4165
containing_tree.add_reference(sub_tree)
4166
except errors.BadReferenceTarget, e:
4167
# XXX: Would be better to just raise a nicely printable
4168
# exception from the real origin. Also below. mbp 20070306
4169
raise errors.BzrCommandError("Cannot join %s. %s" %
4173
containing_tree.subsume(sub_tree)
4174
except errors.BadSubsumeSource, e:
4175
raise errors.BzrCommandError("Cannot join %s. %s" %
4179
class cmd_split(Command):
4180
"""Split a subdirectory of a tree into a separate tree.
4182
This command will produce a target tree in a format that supports
4183
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
4184
converted into earlier formats like 'dirstate-tags'.
4186
The TREE argument should be a subdirectory of a working tree. That
4187
subdirectory will be converted into an independent tree, with its own
4188
branch. Commits in the top-level tree will not apply to the new subtree.
4191
# join is not un-hidden yet
4192
#_see_also = ['join']
4193
takes_args = ['tree']
4195
def run(self, tree):
4196
containing_tree, subdir = WorkingTree.open_containing(tree)
4197
sub_id = containing_tree.path2id(subdir)
4199
raise errors.NotVersionedError(subdir)
4201
containing_tree.extract(sub_id)
4202
except errors.RootNotRich:
4203
raise errors.UpgradeRequired(containing_tree.branch.base)
4206
class cmd_merge_directive(Command):
4207
"""Generate a merge directive for auto-merge tools.
4209
A directive requests a merge to be performed, and also provides all the
4210
information necessary to do so. This means it must either include a
4211
revision bundle, or the location of a branch containing the desired
4214
A submit branch (the location to merge into) must be supplied the first
4215
time the command is issued. After it has been supplied once, it will
4216
be remembered as the default.
4218
A public branch is optional if a revision bundle is supplied, but required
4219
if --diff or --plain is specified. It will be remembered as the default
4220
after the first use.
4223
takes_args = ['submit_branch?', 'public_branch?']
4227
_see_also = ['send']
4230
RegistryOption.from_kwargs('patch-type',
4231
'The type of patch to include in the directive.',
4233
value_switches=True,
4235
bundle='Bazaar revision bundle (default).',
4236
diff='Normal unified diff.',
4237
plain='No patch, just directive.'),
4238
Option('sign', help='GPG-sign the directive.'), 'revision',
4239
Option('mail-to', type=str,
4240
help='Instead of printing the directive, email to this address.'),
4241
Option('message', type=str, short_name='m',
4242
help='Message to use when committing this merge.')
4245
encoding_type = 'exact'
4247
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4248
sign=False, revision=None, mail_to=None, message=None):
4249
from bzrlib.revision import ensure_null, NULL_REVISION
4250
include_patch, include_bundle = {
4251
'plain': (False, False),
4252
'diff': (True, False),
4253
'bundle': (True, True),
4255
branch = Branch.open('.')
4256
stored_submit_branch = branch.get_submit_branch()
4257
if submit_branch is None:
4258
submit_branch = stored_submit_branch
4260
if stored_submit_branch is None:
4261
branch.set_submit_branch(submit_branch)
4262
if submit_branch is None:
4263
submit_branch = branch.get_parent()
4264
if submit_branch is None:
4265
raise errors.BzrCommandError('No submit branch specified or known')
4267
stored_public_branch = branch.get_public_branch()
4268
if public_branch is None:
4269
public_branch = stored_public_branch
4270
elif stored_public_branch is None:
4271
branch.set_public_branch(public_branch)
4272
if not include_bundle and public_branch is None:
4273
raise errors.BzrCommandError('No public branch specified or'
4275
base_revision_id = None
4276
if revision is not None:
4277
if len(revision) > 2:
4278
raise errors.BzrCommandError('bzr merge-directive takes '
4279
'at most two one revision identifiers')
4280
revision_id = revision[-1].as_revision_id(branch)
4281
if len(revision) == 2:
4282
base_revision_id = revision[0].as_revision_id(branch)
4284
revision_id = branch.last_revision()
4285
revision_id = ensure_null(revision_id)
4286
if revision_id == NULL_REVISION:
4287
raise errors.BzrCommandError('No revisions to bundle.')
4288
directive = merge_directive.MergeDirective2.from_objects(
4289
branch.repository, revision_id, time.time(),
4290
osutils.local_time_offset(), submit_branch,
4291
public_branch=public_branch, include_patch=include_patch,
4292
include_bundle=include_bundle, message=message,
4293
base_revision_id=base_revision_id)
4296
self.outf.write(directive.to_signed(branch))
4298
self.outf.writelines(directive.to_lines())
4300
message = directive.to_email(mail_to, branch, sign)
4301
s = SMTPConnection(branch.get_config())
4302
s.send_email(message)
4305
class cmd_send(Command):
4306
"""Mail or create a merge-directive for submitting changes.
4308
A merge directive provides many things needed for requesting merges:
4310
* A machine-readable description of the merge to perform
4312
* An optional patch that is a preview of the changes requested
4314
* An optional bundle of revision data, so that the changes can be applied
4315
directly from the merge directive, without retrieving data from a
4318
If --no-bundle is specified, then public_branch is needed (and must be
4319
up-to-date), so that the receiver can perform the merge using the
4320
public_branch. The public_branch is always included if known, so that
4321
people can check it later.
4323
The submit branch defaults to the parent, but can be overridden. Both
4324
submit branch and public branch will be remembered if supplied.
4326
If a public_branch is known for the submit_branch, that public submit
4327
branch is used in the merge instructions. This means that a local mirror
4328
can be used as your actual submit branch, once you have set public_branch
4331
Mail is sent using your preferred mail program. This should be transparent
4332
on Windows (it uses MAPI). On Linux, it requires the xdg-email utility.
4333
If the preferred client can't be found (or used), your editor will be used.
4335
To use a specific mail program, set the mail_client configuration option.
4336
(For Thunderbird 1.5, this works around some bugs.) Supported values for
4337
specific clients are "claws", "evolution", "kmail", "mutt", and
4338
"thunderbird"; generic options are "default", "editor", "emacsclient",
4339
"mapi", and "xdg-email". Plugins may also add supported clients.
4341
If mail is being sent, a to address is required. This can be supplied
4342
either on the commandline, by setting the submit_to configuration
4343
option in the branch itself or the child_submit_to configuration option
4344
in the submit branch.
4346
Two formats are currently supported: "4" uses revision bundle format 4 and
4347
merge directive format 2. It is significantly faster and smaller than
4348
older formats. It is compatible with Bazaar 0.19 and later. It is the
4349
default. "0.9" uses revision bundle format 0.9 and merge directive
4350
format 1. It is compatible with Bazaar 0.12 - 0.18.
4352
Merge directives are applied using the merge command or the pull command.
4355
encoding_type = 'exact'
4357
_see_also = ['merge', 'pull']
4359
takes_args = ['submit_branch?', 'public_branch?']
4363
help='Do not include a bundle in the merge directive.'),
4364
Option('no-patch', help='Do not include a preview patch in the merge'
4367
help='Remember submit and public branch.'),
4369
help='Branch to generate the submission from, '
4370
'rather than the one containing the working directory.',
4373
Option('output', short_name='o',
4374
help='Write merge directive to this file; '
4375
'use - for stdout.',
4377
Option('mail-to', help='Mail the request to this address.',
4381
RegistryOption.from_kwargs('format',
4382
'Use the specified output format.',
4383
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4384
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4387
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4388
no_patch=False, revision=None, remember=False, output=None,
4389
format='4', mail_to=None, message=None, **kwargs):
4390
return self._run(submit_branch, revision, public_branch, remember,
4391
format, no_bundle, no_patch, output,
4392
kwargs.get('from', '.'), mail_to, message)
4394
def _run(self, submit_branch, revision, public_branch, remember, format,
4395
no_bundle, no_patch, output, from_, mail_to, message):
4396
from bzrlib.revision import NULL_REVISION
4397
branch = Branch.open_containing(from_)[0]
4399
outfile = cStringIO.StringIO()
4403
outfile = open(output, 'wb')
4404
# we may need to write data into branch's repository to calculate
4409
config = branch.get_config()
4411
mail_to = config.get_user_option('submit_to')
4412
mail_client = config.get_mail_client()
4413
if remember and submit_branch is None:
4414
raise errors.BzrCommandError(
4415
'--remember requires a branch to be specified.')
4416
stored_submit_branch = branch.get_submit_branch()
4417
remembered_submit_branch = None
4418
if submit_branch is None:
4419
submit_branch = stored_submit_branch
4420
remembered_submit_branch = "submit"
4422
if stored_submit_branch is None or remember:
4423
branch.set_submit_branch(submit_branch)
4424
if submit_branch is None:
4425
submit_branch = branch.get_parent()
4426
remembered_submit_branch = "parent"
4427
if submit_branch is None:
4428
raise errors.BzrCommandError('No submit branch known or'
4430
if remembered_submit_branch is not None:
4431
note('Using saved %s location "%s" to determine what '
4432
'changes to submit.', remembered_submit_branch,
4436
submit_config = Branch.open(submit_branch).get_config()
4437
mail_to = submit_config.get_user_option("child_submit_to")
4439
stored_public_branch = branch.get_public_branch()
4440
if public_branch is None:
4441
public_branch = stored_public_branch
4442
elif stored_public_branch is None or remember:
4443
branch.set_public_branch(public_branch)
4444
if no_bundle and public_branch is None:
4445
raise errors.BzrCommandError('No public branch specified or'
4447
base_revision_id = None
4449
if revision is not None:
4450
if len(revision) > 2:
4451
raise errors.BzrCommandError('bzr send takes '
4452
'at most two one revision identifiers')
4453
revision_id = revision[-1].as_revision_id(branch)
4454
if len(revision) == 2:
4455
base_revision_id = revision[0].as_revision_id(branch)
4456
if revision_id is None:
4457
revision_id = branch.last_revision()
4458
if revision_id == NULL_REVISION:
4459
raise errors.BzrCommandError('No revisions to submit.')
4461
directive = merge_directive.MergeDirective2.from_objects(
4462
branch.repository, revision_id, time.time(),
4463
osutils.local_time_offset(), submit_branch,
4464
public_branch=public_branch, include_patch=not no_patch,
4465
include_bundle=not no_bundle, message=message,
4466
base_revision_id=base_revision_id)
4467
elif format == '0.9':
4470
patch_type = 'bundle'
4472
raise errors.BzrCommandError('Format 0.9 does not'
4473
' permit bundle with no patch')
4479
directive = merge_directive.MergeDirective.from_objects(
4480
branch.repository, revision_id, time.time(),
4481
osutils.local_time_offset(), submit_branch,
4482
public_branch=public_branch, patch_type=patch_type,
4485
outfile.writelines(directive.to_lines())
4487
subject = '[MERGE] '
4488
if message is not None:
4491
revision = branch.repository.get_revision(revision_id)
4492
subject += revision.get_summary()
4493
basename = directive.get_disk_name(branch)
4494
mail_client.compose_merge_request(mail_to, subject,
4495
outfile.getvalue(), basename)
4502
class cmd_bundle_revisions(cmd_send):
4504
"""Create a merge-directive for submitting changes.
4506
A merge directive provides many things needed for requesting merges:
4508
* A machine-readable description of the merge to perform
4510
* An optional patch that is a preview of the changes requested
4512
* An optional bundle of revision data, so that the changes can be applied
4513
directly from the merge directive, without retrieving data from a
4516
If --no-bundle is specified, then public_branch is needed (and must be
4517
up-to-date), so that the receiver can perform the merge using the
4518
public_branch. The public_branch is always included if known, so that
4519
people can check it later.
4521
The submit branch defaults to the parent, but can be overridden. Both
4522
submit branch and public branch will be remembered if supplied.
4524
If a public_branch is known for the submit_branch, that public submit
4525
branch is used in the merge instructions. This means that a local mirror
4526
can be used as your actual submit branch, once you have set public_branch
4529
Two formats are currently supported: "4" uses revision bundle format 4 and
4530
merge directive format 2. It is significantly faster and smaller than
4531
older formats. It is compatible with Bazaar 0.19 and later. It is the
4532
default. "0.9" uses revision bundle format 0.9 and merge directive
4533
format 1. It is compatible with Bazaar 0.12 - 0.18.
4538
help='Do not include a bundle in the merge directive.'),
4539
Option('no-patch', help='Do not include a preview patch in the merge'
4542
help='Remember submit and public branch.'),
4544
help='Branch to generate the submission from, '
4545
'rather than the one containing the working directory.',
4548
Option('output', short_name='o', help='Write directive to this file.',
4551
RegistryOption.from_kwargs('format',
4552
'Use the specified output format.',
4553
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4554
'0.9': 'Bundle format 0.9, Merge Directive 1',})
4556
aliases = ['bundle']
4558
_see_also = ['send', 'merge']
4562
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4563
no_patch=False, revision=None, remember=False, output=None,
4564
format='4', **kwargs):
4567
return self._run(submit_branch, revision, public_branch, remember,
4568
format, no_bundle, no_patch, output,
4569
kwargs.get('from', '.'), None, None)
4572
class cmd_tag(Command):
4573
"""Create, remove or modify a tag naming a revision.
4575
Tags give human-meaningful names to revisions. Commands that take a -r
4576
(--revision) option can be given -rtag:X, where X is any previously
4579
Tags are stored in the branch. Tags are copied from one branch to another
4580
along when you branch, push, pull or merge.
4582
It is an error to give a tag name that already exists unless you pass
4583
--force, in which case the tag is moved to point to the new revision.
4585
To rename a tag (change the name but keep it on the same revsion), run ``bzr
4586
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4589
_see_also = ['commit', 'tags']
4590
takes_args = ['tag_name']
4593
help='Delete this tag rather than placing it.',
4596
help='Branch in which to place the tag.',
4601
help='Replace existing tags.',
4606
def run(self, tag_name,
4612
branch, relpath = Branch.open_containing(directory)
4616
branch.tags.delete_tag(tag_name)
4617
self.outf.write('Deleted tag %s.\n' % tag_name)
4620
if len(revision) != 1:
4621
raise errors.BzrCommandError(
4622
"Tags can only be placed on a single revision, "
4624
revision_id = revision[0].as_revision_id(branch)
4626
revision_id = branch.last_revision()
4627
if (not force) and branch.tags.has_tag(tag_name):
4628
raise errors.TagAlreadyExists(tag_name)
4629
branch.tags.set_tag(tag_name, revision_id)
4630
self.outf.write('Created tag %s.\n' % tag_name)
4635
class cmd_tags(Command):
4638
This command shows a table of tag names and the revisions they reference.
4644
help='Branch whose tags should be displayed.',
4648
RegistryOption.from_kwargs('sort',
4649
'Sort tags by different criteria.', title='Sorting',
4650
alpha='Sort tags lexicographically (default).',
4651
time='Sort tags chronologically.',
4664
branch, relpath = Branch.open_containing(directory)
4666
tags = branch.tags.get_tag_dict().items()
4673
graph = branch.repository.get_graph()
4674
rev1, rev2 = _get_revision_range(revision, branch, self.name())
4675
revid1, revid2 = rev1.rev_id, rev2.rev_id
4676
# only show revisions between revid1 and revid2 (inclusive)
4677
tags = [(tag, revid) for tag, revid in tags if
4679
graph.is_ancestor(revid, revid2)) and
4681
graph.is_ancestor(revid1, revid))]
4686
elif sort == 'time':
4688
for tag, revid in tags:
4690
revobj = branch.repository.get_revision(revid)
4691
except errors.NoSuchRevision:
4692
timestamp = sys.maxint # place them at the end
4694
timestamp = revobj.timestamp
4695
timestamps[revid] = timestamp
4696
tags.sort(key=lambda x: timestamps[x[1]])
4698
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4699
revno_map = branch.get_revision_id_to_revno_map()
4700
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4701
for tag, revid in tags ]
4702
for tag, revspec in tags:
4703
self.outf.write('%-20s %s\n' % (tag, revspec))
4706
class cmd_reconfigure(Command):
4707
"""Reconfigure the type of a bzr directory.
4709
A target configuration must be specified.
4711
For checkouts, the bind-to location will be auto-detected if not specified.
4712
The order of preference is
4713
1. For a lightweight checkout, the current bound location.
4714
2. For branches that used to be checkouts, the previously-bound location.
4715
3. The push location.
4716
4. The parent location.
4717
If none of these is available, --bind-to must be specified.
4720
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4721
takes_args = ['location?']
4722
takes_options = [RegistryOption.from_kwargs('target_type',
4723
title='Target type',
4724
help='The type to reconfigure the directory to.',
4725
value_switches=True, enum_switch=False,
4726
branch='Reconfigure to be an unbound branch '
4727
'with no working tree.',
4728
tree='Reconfigure to be an unbound branch '
4729
'with a working tree.',
4730
checkout='Reconfigure to be a bound branch '
4731
'with a working tree.',
4732
lightweight_checkout='Reconfigure to be a lightweight'
4733
' checkout (with no local history).',
4734
standalone='Reconfigure to be a standalone branch '
4735
'(i.e. stop using shared repository).',
4736
use_shared='Reconfigure to use a shared repository.'),
4737
Option('bind-to', help='Branch to bind checkout to.',
4740
help='Perform reconfiguration even if local changes'
4744
def run(self, location=None, target_type=None, bind_to=None, force=False):
4745
directory = bzrdir.BzrDir.open(location)
4746
if target_type is None:
4747
raise errors.BzrCommandError('No target configuration specified')
4748
elif target_type == 'branch':
4749
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4750
elif target_type == 'tree':
4751
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4752
elif target_type == 'checkout':
4753
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4755
elif target_type == 'lightweight-checkout':
4756
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4758
elif target_type == 'use-shared':
4759
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4760
elif target_type == 'standalone':
4761
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4762
reconfiguration.apply(force)
4765
class cmd_switch(Command):
4766
"""Set the branch of a checkout and update.
4768
For lightweight checkouts, this changes the branch being referenced.
4769
For heavyweight checkouts, this checks that there are no local commits
4770
versus the current bound branch, then it makes the local branch a mirror
4771
of the new location and binds to it.
4773
In both cases, the working tree is updated and uncommitted changes
4774
are merged. The user can commit or revert these as they desire.
4776
Pending merges need to be committed or reverted before using switch.
4778
The path to the branch to switch to can be specified relative to the parent
4779
directory of the current branch. For example, if you are currently in a
4780
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4783
Bound branches use the nickname of its master branch unless it is set
4784
locally, in which case switching will update the the local nickname to be
4788
takes_args = ['to_location']
4789
takes_options = [Option('force',
4790
help='Switch even if local commits will be lost.')
4793
def run(self, to_location, force=False):
4794
from bzrlib import switch
4796
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4797
branch = control_dir.open_branch()
4799
to_branch = Branch.open(to_location)
4800
except errors.NotBranchError:
4801
this_branch = control_dir.open_branch()
4802
# This may be a heavy checkout, where we want the master branch
4803
this_url = this_branch.get_bound_location()
4804
# If not, use a local sibling
4805
if this_url is None:
4806
this_url = this_branch.base
4807
to_branch = Branch.open(
4808
urlutils.join(this_url, '..', to_location))
4809
switch.switch(control_dir, to_branch, force)
4810
if branch.get_config().has_explicit_nickname():
4811
branch = control_dir.open_branch() #get the new branch!
4812
branch.nick = to_branch.nick
4813
note('Switched to branch: %s',
4814
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4817
class cmd_hooks(Command):
4818
"""Show a branch's currently registered hooks.
4822
takes_args = ['path?']
4824
def run(self, path=None):
4827
branch_hooks = Branch.open(path).hooks
4828
for hook_type in branch_hooks:
4829
hooks = branch_hooks[hook_type]
4830
self.outf.write("%s:\n" % (hook_type,))
4833
self.outf.write(" %s\n" %
4834
(branch_hooks.get_hook_name(hook),))
4836
self.outf.write(" <no hooks installed>\n")
4839
class cmd_shelve(Command):
4840
"""Temporarily set aside some changes from the current tree.
4842
Shelve allows you to temporarily put changes you've made "on the shelf",
4843
ie. out of the way, until a later time when you can bring them back from
4844
the shelf with the 'unshelve' command.
4846
If shelve --list is specified, previously-shelved changes are listed.
4848
Shelve is intended to help separate several sets of changes that have
4849
been inappropriately mingled. If you just want to get rid of all changes
4850
and you don't need to restore them later, use revert. If you want to
4851
shelve all text changes at once, use shelve --all.
4853
If filenames are specified, only the changes to those files will be
4854
shelved. Other files will be left untouched.
4856
If a revision is specified, changes since that revision will be shelved.
4858
You can put multiple items on the shelf, and by default, 'unshelve' will
4859
restore the most recently shelved changes.
4862
takes_args = ['file*']
4866
Option('all', help='Shelve all changes.'),
4868
RegistryOption('writer', 'Method to use for writing diffs.',
4869
bzrlib.option.diff_writer_registry,
4870
value_switches=True, enum_switch=False),
4872
Option('list', help='List shelved changes.'),
4874
_see_also = ['unshelve']
4876
def run(self, revision=None, all=False, file_list=None, message=None,
4877
writer=None, list=False):
4879
return self.run_for_list()
4880
from bzrlib.shelf_ui import Shelver
4882
writer = bzrlib.option.diff_writer_registry.get()
4884
Shelver.from_args(writer(sys.stdout), revision, all, file_list,
4886
except errors.UserAbort:
2706
merger.backup_files = backup_files
2707
merger.merge_type = merge_type
2708
merger.set_interesting_files(file_list)
2709
merger.show_base = show_base
2710
merger.reprocess = reprocess
2711
conflicts = merger.do_merge()
2712
if file_list is None:
2713
merger.set_pending()
4889
def run_for_list(self):
4890
tree = WorkingTree.open_containing('.')[0]
4893
manager = tree.get_shelf_manager()
4894
shelves = manager.active_shelves()
4895
if len(shelves) == 0:
4896
note('No shelved changes.')
4898
for shelf_id in reversed(shelves):
4899
message = manager.get_metadata(shelf_id).get('message')
4901
message = '<no message>'
4902
self.outf.write('%3d: %s\n' % (shelf_id, message))
4908
class cmd_unshelve(Command):
4909
"""Restore shelved changes.
4911
By default, the most recently shelved changes are restored. However if you
4912
specify a patch by name those changes will be restored instead. This
4913
works best when the changes don't depend on each other.
4916
takes_args = ['shelf_id?']
4918
RegistryOption.from_kwargs(
4919
'action', help="The action to perform.",
4920
enum_switch=False, value_switches=True,
4921
apply="Apply changes and remove from the shelf.",
4922
dry_run="Show changes, but do not apply or remove them.",
4923
delete_only="Delete changes without applying them."
4926
_see_also = ['shelve']
4928
def run(self, shelf_id=None, action='apply'):
4929
from bzrlib.shelf_ui import Unshelver
4930
Unshelver.from_args(shelf_id, action).run()
4933
def _create_prefix(cur_transport):
4934
needed = [cur_transport]
4935
# Recurse upwards until we can create a directory successfully
4937
new_transport = cur_transport.clone('..')
4938
if new_transport.base == cur_transport.base:
4939
raise errors.BzrCommandError(
4940
"Failed to create path prefix for %s."
4941
% cur_transport.base)
4943
new_transport.mkdir('.')
4944
except errors.NoSuchFile:
4945
needed.append(new_transport)
4946
cur_transport = new_transport
4949
# Now we only need to create child directories
4951
cur_transport = needed.pop()
4952
cur_transport.ensure_base()
2719
4955
# these get imported and then picked up by the scan for cmd_*