25
25
sha_file, appendpath, file_kind
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
29
29
from bzrlib.textui import show_status
30
30
from bzrlib.revision import Revision
31
from bzrlib.xml import unpack_xml
31
32
from bzrlib.delta import compare_trees
32
33
from bzrlib.tree import EmptyTree, RevisionTree
50
50
def find_branch(f, **args):
51
51
if f and (f.startswith('http://') or f.startswith('https://')):
52
from bzrlib.remotebranch import RemoteBranch
53
return RemoteBranch(f, **args)
53
return remotebranch.RemoteBranch(f, **args)
55
55
return Branch(f, **args)
58
58
def find_cached_branch(f, cache_root, **args):
59
from bzrlib.remotebranch import RemoteBranch
59
from remotebranch import RemoteBranch
60
60
br = find_branch(f, **args)
61
61
def cacheify(br, store_name):
62
from bzrlib.meta_store import CachedStore
62
from meta_store import CachedStore
63
63
cache_path = os.path.join(cache_root, store_name)
64
64
os.mkdir(cache_path)
65
65
new_store = CachedStore(getattr(br, store_name), cache_path)
127
128
head, tail = os.path.split(f)
129
130
# reached the root, whatever that may be
130
raise NotBranchError('%s is not in a branch' % orig_f)
131
raise bzrlib.errors.NotBranchError('%s is not in a branch' % orig_f)
136
# XXX: move into bzrlib.errors; subclass BzrError
137
class DivergedBranches(Exception):
138
def __init__(self, branch1, branch2):
139
self.branch1 = branch1
140
self.branch2 = branch2
141
Exception.__init__(self, "These branches have diverged.")
136
144
######################################################################
165
173
def __init__(self, base, init=False, find_root=True):
166
174
"""Create new branch object at a particular location.
168
base -- Base directory for the branch. May be a file:// url.
176
base -- Base directory for the branch.
170
178
init -- If True, create new control files in a previously
171
179
unversioned directory. If False, the branch must already
185
193
self.base = find_branch_root(base)
187
if base.startswith("file://"):
189
195
self.base = os.path.realpath(base)
190
196
if not isdir(self.controlfilename('.')):
197
from errors import NotBranchError
191
198
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
192
199
['use "bzr init" to initialize a new working tree',
193
200
'current bzr can only operate from top-of-tree'])
208
215
def __del__(self):
209
216
if self._lock_mode or self._lock:
210
from bzrlib.warnings import warn
217
from warnings import warn
211
218
warn("branch %r was not explicitly unlocked" % self)
212
219
self._lock.unlock()
214
223
def lock_write(self):
215
224
if self._lock_mode:
216
225
if self._lock_mode != 'w':
217
from bzrlib.errors import LockError
226
from errors import LockError
218
227
raise LockError("can't upgrade to a write lock from %r" %
220
229
self._lock_count += 1
250
262
self._lock = None
251
263
self._lock_mode = self._lock_count = None
253
266
def abspath(self, name):
254
267
"""Return absolute filename for something in the branch"""
255
268
return os.path.join(self.base, name)
257
271
def relpath(self, path):
258
272
"""Return path relative to this branch of something inside it.
260
274
Raises an error if path is not in this branch."""
261
275
return _relpath(self.base, path)
263
278
def controlfilename(self, file_or_path):
264
279
"""Return location relative to branch."""
265
280
if isinstance(file_or_path, basestring):
293
308
raise BzrError("invalid controlfile mode %r" % mode)
295
312
def _make_control(self):
296
313
from bzrlib.inventory import Inventory
314
from bzrlib.xml import pack_xml
298
316
os.mkdir(self.controlfilename([]))
299
317
self.controlfile('README', 'w').write(
312
330
# if we want per-tree root ids then this is the place to set
313
331
# them; they're not needed for now and so ommitted for
315
f = self.controlfile('inventory','w')
316
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
333
pack_xml(Inventory(), self.controlfile('inventory','w'))
319
336
def _check_format(self):
328
345
# on Windows from Linux and so on. I think it might be better
329
346
# to always make all internal files in unix format.
330
347
fmt = self.controlfile('branch-format', 'r').read()
331
fmt = fmt.replace('\r\n', '\n')
348
fmt.replace('\r\n', '')
332
349
if fmt != BZR_BRANCH_FORMAT:
333
350
raise BzrError('sorry, branch format %r not supported' % fmt,
334
351
['use a different bzr version',
354
371
def read_working_inventory(self):
355
372
"""Read the working inventory."""
356
373
from bzrlib.inventory import Inventory
374
from bzrlib.xml import unpack_xml
375
from time import time
359
379
# ElementTree does its own conversion from UTF-8, so open in
361
f = self.controlfile('inventory', 'rb')
362
return bzrlib.xml.serializer_v4.read_inventory(f)
381
inv = unpack_xml(Inventory,
382
self.controlfile('inventory', 'rb'))
383
mutter("loaded inventory of %d items in %f"
384
% (len(inv), time() - before))
371
394
will be committed to the next revision.
373
396
from bzrlib.atomicfile import AtomicFile
397
from bzrlib.xml import pack_xml
375
399
self.lock_write()
377
401
f = AtomicFile(self.controlfilename('inventory'), 'wb')
379
bzrlib.xml.serializer_v4.write_inventory(inv, f)
390
414
"""Inventory for the working copy.""")
393
def add(self, files, ids=None):
417
def add(self, files, verbose=False, ids=None):
394
418
"""Make files versioned.
396
Note that the command line normally calls smart_add instead,
397
which can automatically recurse.
420
Note that the command line normally calls smart_add instead.
399
422
This puts the files in the Added state, so that they will be
400
423
recorded by the next commit.
410
433
TODO: Perhaps have an option to add the ids even if the files do
413
TODO: Perhaps yield the ids and paths as they're added.
436
TODO: Perhaps return the ids of the files? But then again it
437
is easy to retrieve them if they're needed.
439
TODO: Adding a directory should optionally recurse down and
440
add all non-ignored children. Perhaps do that in a
415
443
# TODO: Re-adding a file that is removed in the working copy
416
444
# should probably put it back with the previous ID.
452
480
file_id = gen_file_id(f)
453
481
inv.add_path(f, kind=kind, file_id=file_id)
484
print 'added', quotefn(f)
455
486
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
457
488
self._write_inventory(inv)
570
def get_revision_xml_file(self, revision_id):
601
def get_revision_xml(self, revision_id):
571
602
"""Return XML file object for revision object."""
572
603
if not revision_id or not isinstance(revision_id, basestring):
573
604
raise InvalidRevisionId(revision_id)
578
609
return self.revision_store[revision_id]
579
except (IndexError, KeyError):
580
611
raise bzrlib.errors.NoSuchRevision(self, revision_id)
586
get_revision_xml = get_revision_xml_file
589
616
def get_revision(self, revision_id):
590
617
"""Return the Revision object for a named revision"""
591
xml_file = self.get_revision_xml_file(revision_id)
618
xml_file = self.get_revision_xml(revision_id)
594
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
621
r = unpack_xml(Revision, xml_file)
595
622
except SyntaxError, e:
596
623
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
642
669
parameter which can be either an integer revno or a
644
671
from bzrlib.inventory import Inventory
672
from bzrlib.xml import unpack_xml
646
f = self.get_inventory_xml_file(inventory_id)
647
return bzrlib.xml.serializer_v4.read_inventory(f)
674
return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
650
677
def get_inventory_xml(self, inventory_id):
651
678
"""Get inventory XML as a file object."""
652
679
return self.inventory_store[inventory_id]
654
get_inventory_xml_file = get_inventory_xml
657
682
def get_inventory_sha1(self, inventory_id):
688
713
def common_ancestor(self, other, self_revno=None, other_revno=None):
690
>>> from bzrlib.commit import commit
691
716
>>> sb = ScratchBranch(files=['foo', 'foo~'])
692
717
>>> sb.common_ancestor(sb) == (None, None)
694
>>> commit(sb, "Committing first revision", verbose=False)
719
>>> commit.commit(sb, "Committing first revision", verbose=False)
695
720
>>> sb.common_ancestor(sb)[0]
697
722
>>> clone = sb.clone()
698
>>> commit(sb, "Committing second revision", verbose=False)
723
>>> commit.commit(sb, "Committing second revision", verbose=False)
699
724
>>> sb.common_ancestor(sb)[0]
701
726
>>> sb.common_ancestor(clone)[0]
703
>>> commit(clone, "Committing divergent second revision",
728
>>> commit.commit(clone, "Committing divergent second revision",
704
729
... verbose=False)
705
730
>>> sb.common_ancestor(clone)[0]
797
822
"""Pull in all new revisions from other branch.
799
824
from bzrlib.fetch import greedy_fetch
800
from bzrlib.revision import get_intervening_revisions
802
826
pb = bzrlib.ui.ui_factory.progress_bar()
803
827
pb.update('comparing histories')
804
if stop_revision is None:
805
other_revision = other.last_patch()
829
revision_ids = self.missing_revisions(other, stop_revision)
831
if len(revision_ids) > 0:
832
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
807
other_revision = other.lookup_revision(stop_revision)
808
count = greedy_fetch(self, other, other_revision, pb)[0]
810
revision_ids = self.missing_revisions(other, stop_revision)
811
except DivergedBranches, e:
813
revision_ids = get_intervening_revisions(self.last_patch(),
814
other_revision, self)
815
assert self.last_patch() not in revision_ids
816
except bzrlib.errors.NotAncestor:
819
835
self.append_revision(*revision_ids)
836
## note("Added %d revisions." % count)
822
839
def install_revisions(self, other, revision_ids, pb):
823
840
if hasattr(other.revision_store, "prefetch"):
824
841
other.revision_store.prefetch(revision_ids)
825
842
if hasattr(other.inventory_store, "prefetch"):
827
for rev_id in revision_ids:
829
revision = other.get_revision(rev_id).inventory_id
830
inventory_ids.append(revision)
831
except bzrlib.errors.NoSuchRevision:
843
inventory_ids = [other.get_revision(r).inventory_id
844
for r in revision_ids]
833
845
other.inventory_store.prefetch(inventory_ids)
861
873
count, cp_fail = self.text_store.copy_multi(other.text_store,
863
#print "Added %d texts." % count
875
print "Added %d texts." % count
864
876
inventory_ids = [ f.inventory_id for f in revisions ]
865
877
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
867
#print "Added %d inventories." % count
879
print "Added %d inventories." % count
868
880
revision_ids = [ f.revision_id for f in revisions]
870
882
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
882
894
def lookup_revision(self, revision):
883
895
"""Return the revision identifier for a given revision information."""
884
revno, info = self._get_revision_info(revision)
896
revno, info = self.get_revision_info(revision)
902
914
revision can also be a string, in which case it is parsed for something like
903
915
'date:' or 'revid:' etc.
905
revno, rev_id = self._get_revision_info(revision)
907
raise bzrlib.errors.NoSuchRevision(self, revision)
910
def get_rev_id(self, revno, history=None):
911
"""Find the revision id of the specified revno."""
915
history = self.revision_history()
916
elif revno <= 0 or revno > len(history):
917
raise bzrlib.errors.NoSuchRevision(self, revno)
918
return history[revno - 1]
920
def _get_revision_info(self, revision):
921
"""Return (revno, revision id) for revision specifier.
923
revision can be an integer, in which case it is assumed to be revno
924
(though this will translate negative values into positive ones)
925
revision can also be a string, in which case it is parsed for something
926
like 'date:' or 'revid:' etc.
928
A revid is always returned. If it is None, the specifier referred to
929
the null revision. If the revid does not occur in the revision
930
history, revno will be None.
933
917
if revision is None:
940
924
revs = self.revision_history()
941
925
if isinstance(revision, int):
928
# Mabye we should do this first, but we don't need it if revision == 0
943
930
revno = len(revs) + revision + 1
946
rev_id = self.get_rev_id(revno, revs)
947
933
elif isinstance(revision, basestring):
948
934
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
949
935
if revision.startswith(prefix):
950
result = func(self, revs, revision)
952
revno, rev_id = result
955
rev_id = self.get_rev_id(revno, revs)
936
revno = func(self, revs, revision)
958
raise BzrError('No namespace registered for string: %r' %
961
raise TypeError('Unhandled revision type %s' % revision)
939
raise BzrError('No namespace registered for string: %r' % revision)
965
raise bzrlib.errors.NoSuchRevision(self, revision)
941
if revno is None or revno <= 0 or revno > len(revs):
942
raise BzrError("no such revision %s" % revision)
943
return revno, revs[revno-1]
968
945
def _namespace_revno(self, revs, revision):
969
946
"""Lookup a revision by revision number"""
970
947
assert revision.startswith('revno:')
972
return (int(revision[6:]),)
949
return int(revision[6:])
973
950
except ValueError:
975
952
REVISION_NAMESPACES['revno:'] = _namespace_revno
977
954
def _namespace_revid(self, revs, revision):
978
955
assert revision.startswith('revid:')
979
rev_id = revision[len('revid:'):]
981
return revs.index(rev_id) + 1, rev_id
957
return revs.index(revision[6:]) + 1
982
958
except ValueError:
984
960
REVISION_NAMESPACES['revid:'] = _namespace_revid
986
962
def _namespace_last(self, revs, revision):
989
965
offset = int(revision[5:])
990
966
except ValueError:
994
970
raise BzrError('You must supply a positive value for --revision last:XXX')
995
return (len(revs) - offset + 1,)
971
return len(revs) - offset + 1
996
972
REVISION_NAMESPACES['last:'] = _namespace_last
998
974
def _namespace_tag(self, revs, revision):
1073
1049
# TODO: Handle timezone.
1074
1050
dt = datetime.datetime.fromtimestamp(r.timestamp)
1075
1051
if first >= dt and (last is None or dt >= last):
1078
1054
for i in range(len(revs)):
1079
1055
r = self.get_revision(revs[i])
1080
1056
# TODO: Handle timezone.
1081
1057
dt = datetime.datetime.fromtimestamp(r.timestamp)
1082
1058
if first <= dt and (last is None or dt <= last):
1084
1060
REVISION_NAMESPACES['date:'] = _namespace_date
1087
def _namespace_ancestor(self, revs, revision):
1088
from revision import common_ancestor, MultipleRevisionSources
1089
other_branch = find_branch(_trim_namespace('ancestor', revision))
1090
revision_a = self.last_patch()
1091
revision_b = other_branch.last_patch()
1092
for r, b in ((revision_a, self), (revision_b, other_branch)):
1094
raise bzrlib.errors.NoCommits(b)
1095
revision_source = MultipleRevisionSources(self, other_branch)
1096
result = common_ancestor(revision_a, revision_b, revision_source)
1098
revno = self.revision_id_to_revno(result)
1099
except bzrlib.errors.NoSuchRevision:
1104
REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
1106
1062
def revision_tree(self, revision_id):
1107
1063
"""Return Tree for a revision on this branch.
1120
1076
def working_tree(self):
1121
1077
"""Return a `Tree` for the working copy."""
1122
from bzrlib.workingtree import WorkingTree
1078
from workingtree import WorkingTree
1123
1079
return WorkingTree(self.base, self.read_working_inventory())
1172
1128
inv.rename(file_id, to_dir_id, to_tail)
1130
print "%s => %s" % (from_rel, to_rel)
1174
1132
from_abs = self.abspath(from_rel)
1175
1133
to_abs = self.abspath(to_rel)
1196
1154
Note that to_name is only the last component of the new name;
1197
1155
this doesn't change the directory.
1199
This returns a list of (from_path, to_path) pairs for each
1200
entry that is moved.
1203
1157
self.lock_write()
1205
1159
## TODO: Option to move IDs only
1240
1194
for f in from_paths:
1241
1195
name_tail = splitpath(f)[-1]
1242
1196
dest_path = appendpath(to_name, name_tail)
1243
result.append((f, dest_path))
1197
print "%s => %s" % (f, dest_path)
1244
1198
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1246
1200
os.rename(self.abspath(f), self.abspath(dest_path))
1344
def get_parent(self):
1345
"""Return the parent location of the branch.
1347
This is the default location for push/pull/missing. The usual
1348
pattern is that the user can override it by specifying a
1352
_locs = ['parent', 'pull', 'x-pull']
1355
return self.controlfile(l, 'r').read().strip('\n')
1357
if e.errno != errno.ENOENT:
1362
def set_parent(self, url):
1363
# TODO: Maybe delete old location files?
1364
from bzrlib.atomicfile import AtomicFile
1367
f = AtomicFile(self.controlfilename('parent'))
1376
def check_revno(self, revno):
1378
Check whether a revno corresponds to any revision.
1379
Zero (the NULL revision) is considered valid.
1382
self.check_real_revno(revno)
1384
def check_real_revno(self, revno):
1386
Check whether a revno corresponds to a real revision.
1387
Zero (the NULL revision) is considered invalid
1389
if revno < 1 or revno > self.revno():
1390
raise InvalidRevisionNumber(revno)
1395
1297
class ScratchBranch(Branch):
1396
1298
"""Special test class: a branch that cleans up after itself.
1515
1415
"""Return a new tree-root file id."""
1516
1416
return gen_file_id('TREE_ROOT')
1519
def copy_branch(branch_from, to_location, revision=None):
1520
"""Copy branch_from into the existing directory to_location.
1523
If not None, only revisions up to this point will be copied.
1524
The head of the new branch will be that revision.
1527
The name of a local directory that exists but is empty.
1529
from bzrlib.merge import merge
1531
assert isinstance(branch_from, Branch)
1532
assert isinstance(to_location, basestring)
1534
br_to = Branch(to_location, init=True)
1535
br_to.set_root_id(branch_from.get_root_id())
1536
if revision is None:
1537
revno = branch_from.revno()
1539
revno, rev_id = branch_from.get_revision_info(revision)
1540
br_to.update_revisions(branch_from, stop_revision=revno)
1541
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1542
check_clean=False, ignore_zero=True)
1543
br_to.set_parent(branch_from.base)
1546
def _trim_namespace(namespace, spec):
1547
full_namespace = namespace + ':'
1548
assert spec.startswith(full_namespace)
1549
return spec[len(full_namespace):]