25
25
from inventory import Inventory
26
26
from trace import mutter, note
27
from tree import Tree, EmptyTree, RevisionTree
27
from tree import Tree, EmptyTree, RevisionTree, WorkingTree
28
28
from inventory import InventoryEntry, Inventory
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, chomp, \
30
30
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
31
joinpath, sha_string, file_kind, local_time_offset, appendpath
32
32
from store import ImmutableStore
33
33
from revision import Revision
34
34
from errors import bailout, BzrError
35
35
from textui import show_status
36
from diff import diff_trees
37
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
38
39
## TODO: Maybe include checks for common corruption of newlines, etc?
42
def find_branch(f, **args):
43
if f and (f.startswith('http://') or f.startswith('https://')):
45
return remotebranch.RemoteBranch(f, **args)
47
return Branch(f, **args)
50
43
def find_branch_root(f=None):
51
44
"""Find the branch root enclosing f, or pwd.
53
f may be a filename or a URL.
55
46
It is not necessary that f exists.
57
48
Basically we keep looking up until we find the control directory or
86
74
"""Branch holding a history of revisions.
89
Base directory of the branch.
76
:todo: Perhaps use different stores for different classes of object,
77
so that we can keep track of how much space each one uses,
78
or garbage-collect them.
80
:todo: Add a RemoteBranch subclass. For the basic case of read-only
81
HTTP access this should be very easy by,
82
just redirecting controlfile access into HTTP requests.
83
We would need a RemoteStore working similarly.
85
:todo: Keep the on-disk branch locked while the object exists.
87
:todo: mkdir() method.
93
def __init__(self, base, init=False, find_root=True, lock_mode='w'):
89
def __init__(self, base, init=False, find_root=True):
94
90
"""Create new branch object at a particular location.
96
base -- Base directory for the branch.
92
:param base: Base directory for the branch.
98
init -- If True, create new control files in a previously
94
:param init: If True, create new control files in a previously
99
95
unversioned directory. If False, the branch must already
102
find_root -- If true and init is false, find the root of the
98
:param find_root: If true and init is false, find the root of the
103
99
existing branch containing base.
105
101
In the test suite, creation of new trees is tested using the
131
126
__repr__ = __str__
135
def lock(self, mode='w'):
136
"""Lock the on-disk branch, excluding other processes."""
142
om = os.O_WRONLY | os.O_CREAT
147
raise BzrError("invalid locking mode %r" % mode)
150
lockfile = os.open(self.controlfilename('branch-lock'), om)
152
if e.errno == errno.ENOENT:
153
# might not exist on branches from <0.0.4
154
self.controlfile('branch-lock', 'w').close()
155
lockfile = os.open(self.controlfilename('branch-lock'), om)
159
fcntl.lockf(lockfile, lm)
161
fcntl.lockf(lockfile, fcntl.LOCK_UN)
163
self._lockmode = None
165
self._lockmode = mode
167
warning("please write a locking method for platform %r" % sys.platform)
169
self._lockmode = None
171
self._lockmode = mode
174
def _need_readlock(self):
175
if self._lockmode not in ['r', 'w']:
176
raise BzrError('need read lock on branch, only have %r' % self._lockmode)
178
def _need_writelock(self):
179
if self._lockmode not in ['w']:
180
raise BzrError('need write lock on branch, only have %r' % self._lockmode)
183
129
def abspath(self, name):
184
130
"""Return absolute filename for something in the branch"""
185
131
return os.path.join(self.base, name)
303
222
"""Inventory for the working copy.""")
306
def add(self, files, verbose=False, ids=None):
225
def add(self, files, verbose=False):
307
226
"""Make files versioned.
309
Note that the command line normally calls smart_add instead.
311
228
This puts the files in the Added state, so that they will be
312
229
recorded by the next commit.
314
TODO: Perhaps have an option to add the ids even if the files do
231
:todo: Perhaps have an option to add the ids even if the files do
317
TODO: Perhaps return the ids of the files? But then again it
234
:todo: Perhaps return the ids of the files? But then again it
318
235
is easy to retrieve them if they're needed.
320
TODO: Option to specify file id.
237
:todo: Option to specify file id.
322
TODO: Adding a directory should optionally recurse down and
239
:todo: Adding a directory should optionally recurse down and
323
240
add all non-ignored children. Perhaps do that in a
324
241
higher-level method.
243
>>> b = ScratchBranch(files=['foo'])
244
>>> 'foo' in b.unknowns()
249
>>> 'foo' in b.unknowns()
251
>>> bool(b.inventory.path2id('foo'))
257
Traceback (most recent call last):
259
BzrError: ('foo is already versioned', [])
261
>>> b.add(['nothere'])
262
Traceback (most recent call last):
263
BzrError: ('cannot add: not a regular file or directory: nothere', [])
326
self._need_writelock()
328
266
# TODO: Re-adding a file that is removed in the working copy
329
267
# should probably put it back with the previous ID.
330
268
if isinstance(files, types.StringTypes):
331
assert(ids is None or isinstance(ids, types.StringTypes))
337
ids = [None] * len(files)
339
assert(len(ids) == len(files))
341
271
inv = self.read_working_inventory()
342
for f,file_id in zip(files, ids):
343
273
if is_control_file(f):
344
274
bailout("cannot add control file %s" % quotefn(f))
388
316
This does not remove their text. This does not run on
390
TODO: Refuse to remove modified files unless --force is given?
392
TODO: Do something useful with directories.
394
TODO: Should this remove the text or not? Tough call; not
318
:todo: Refuse to remove modified files unless --force is given?
320
>>> b = ScratchBranch(files=['foo'])
322
>>> b.inventory.has_filename('foo')
325
>>> b.working_tree().has_filename('foo')
327
>>> b.inventory.has_filename('foo')
330
>>> b = ScratchBranch(files=['foo'])
335
>>> b.inventory.has_filename('foo')
337
>>> b.basis_tree().has_filename('foo')
339
>>> b.working_tree().has_filename('foo')
342
:todo: Do something useful with directories.
344
:todo: Should this remove the text or not? Tough call; not
395
345
removing may be useful and the user can just use use rm, and
396
346
is the opposite of add. Removing it is consistent with most
397
347
other tools. Maybe an option.
399
349
## TODO: Normalize names
400
350
## TODO: Remove nested loops; better scalability
401
self._need_writelock()
403
352
if isinstance(files, types.StringTypes):
452
392
return self.working_tree().unknowns()
455
def append_revision(self, revision_id):
456
mutter("add {%s} to revision-history" % revision_id)
457
rev_history = self.revision_history()
459
tmprhname = self.controlfilename('revision-history.tmp')
460
rhname = self.controlfilename('revision-history')
462
f = file(tmprhname, 'wt')
463
rev_history.append(revision_id)
464
f.write('\n'.join(rev_history))
395
def commit(self, message, timestamp=None, timezone=None,
398
"""Commit working copy as a new revision.
400
The basic approach is to add all the file texts into the
401
store, then the inventory, then make a new revision pointing
402
to that inventory and store that.
404
This is not quite safe if the working copy changes during the
405
commit; for the moment that is simply not allowed. A better
406
approach is to make a temporary copy of the files before
407
computing their hashes, and then add those hashes in turn to
408
the inventory. This should mean at least that there are no
409
broken hash pointers. There is no way we can get a snapshot
410
of the whole directory at an instant. This would also have to
411
be robust against files disappearing, moving, etc. So the
412
whole thing is a bit hard.
414
:param timestamp: if not None, seconds-since-epoch for a
415
postdated/predated commit.
418
## TODO: Show branch names
420
# TODO: Don't commit if there are no changes, unless forced?
422
# First walk over the working inventory; and both update that
423
# and also build a new revision inventory. The revision
424
# inventory needs to hold the text-id, sha1 and size of the
425
# actual file versions committed in the revision. (These are
426
# not present in the working inventory.) We also need to
427
# detect missing/deleted files, and remove them from the
430
work_inv = self.read_working_inventory()
432
basis = self.basis_tree()
433
basis_inv = basis.inventory
435
for path, entry in work_inv.iter_entries():
436
## TODO: Cope with files that have gone missing.
438
## TODO: Check that the file kind has not changed from the previous
439
## revision of this file (if any).
443
p = self.abspath(path)
444
file_id = entry.file_id
445
mutter('commit prep file %s, id %r ' % (p, file_id))
447
if not os.path.exists(p):
448
mutter(" file is missing, removing from inventory")
450
show_status('D', entry.kind, quotefn(path))
451
missing_ids.append(file_id)
454
# TODO: Handle files that have been deleted
456
# TODO: Maybe a special case for empty files? Seems a
457
# waste to store them many times.
461
if basis_inv.has_id(file_id):
462
old_kind = basis_inv[file_id].kind
463
if old_kind != entry.kind:
464
bailout("entry %r changed kind from %r to %r"
465
% (file_id, old_kind, entry.kind))
467
if entry.kind == 'directory':
469
bailout("%s is entered as directory but not a directory" % quotefn(p))
470
elif entry.kind == 'file':
472
bailout("%s is entered as file but is not a file" % quotefn(p))
474
content = file(p, 'rb').read()
476
entry.text_sha1 = sha_string(content)
477
entry.text_size = len(content)
479
old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
481
and (old_ie.text_size == entry.text_size)
482
and (old_ie.text_sha1 == entry.text_sha1)):
483
## assert content == basis.get_file(file_id).read()
484
entry.text_id = basis_inv[file_id].text_id
485
mutter(' unchanged from previous text_id {%s}' %
489
entry.text_id = gen_file_id(entry.name)
490
self.text_store.add(content, entry.text_id)
491
mutter(' stored with text_id {%s}' % entry.text_id)
495
elif (old_ie.name == entry.name
496
and old_ie.parent_id == entry.parent_id):
501
show_status(state, entry.kind, quotefn(path))
503
for file_id in missing_ids:
504
# have to do this later so we don't mess up the iterator.
505
# since parents may be removed before their children we
508
# FIXME: There's probably a better way to do this; perhaps
509
# the workingtree should know how to filter itself.
510
if work_inv.has_id(file_id):
511
del work_inv[file_id]
514
inv_id = rev_id = _gen_revision_id(time.time())
516
inv_tmp = tempfile.TemporaryFile()
517
inv.write_xml(inv_tmp)
519
self.inventory_store.add(inv_tmp, inv_id)
520
mutter('new inventory_id is {%s}' % inv_id)
522
self._write_inventory(work_inv)
524
if timestamp == None:
525
timestamp = time.time()
527
if committer == None:
528
committer = username()
531
timezone = local_time_offset()
533
mutter("building commit log message")
534
rev = Revision(timestamp=timestamp,
537
precursor = self.last_patch(),
542
rev_tmp = tempfile.TemporaryFile()
543
rev.write_xml(rev_tmp)
545
self.revision_store.add(rev_tmp, rev_id)
546
mutter("new revision_id is {%s}" % rev_id)
548
## XXX: Everything up to here can simply be orphaned if we abort
549
## the commit; it will leave junk files behind but that doesn't
552
## TODO: Read back the just-generated changeset, and make sure it
553
## applies and recreates the right state.
555
## TODO: Also calculate and store the inventory SHA1
556
mutter("committing patch r%d" % (self.revno() + 1))
558
mutter("append to revision-history")
559
f = self.controlfile('revision-history', 'at')
560
f.write(rev_id + '\n')
468
if sys.platform == 'win32':
470
os.rename(tmprhname, rhname)
564
note("commited r%d" % self.revno())
474
567
def get_revision(self, revision_id):
475
568
"""Return the Revision object for a named revision"""
476
self._need_readlock()
477
569
r = Revision.read_xml(self.revision_store[revision_id])
478
570
assert r.revision_id == revision_id
683
def write_log(self, show_timezone='original'):
684
"""Write out human-readable log of commits to this branch
686
:param utc: If true, show dates in universal time, not local time."""
687
## TODO: Option to choose either original, utc or local timezone
690
for p in self.revision_history():
692
print 'revno:', revno
693
## TODO: Show hash if --id is given.
694
##print 'revision-hash:', p
695
rev = self.get_revision(p)
696
print 'committer:', rev.committer
697
print 'timestamp: %s' % (format_date(rev.timestamp, rev.timezone or 0,
700
## opportunistic consistency check, same as check_patch_chaining
701
if rev.precursor != precursor:
702
bailout("mismatched precursor!")
706
print ' (no message)'
708
for l in rev.message.split('\n'):
603
715
def rename_one(self, from_rel, to_rel):
606
This can change the directory or the filename or both.
608
self._need_writelock()
609
716
tree = self.working_tree()
610
717
inv = tree.inventory
611
718
if not tree.has_filename(from_rel):
820
def show_status(self, show_all=False):
821
"""Display single-line status for non-ignored working files.
823
The list is show sorted in order by file name.
825
>>> b = ScratchBranch(files=['foo', 'foo~'])
831
>>> b.commit("add foo")
833
>>> os.unlink(b.abspath('foo'))
838
:todo: Get state for single files.
840
:todo: Perhaps show a slash at the end of directory names.
844
# We have to build everything into a list first so that it can
845
# sorted by name, incorporating all the different sources.
847
# FIXME: Rather than getting things in random order and then sorting,
848
# just step through in order.
850
# Interesting case: the old ID for a file has been removed,
851
# but a new file has been created under that name.
853
old = self.basis_tree()
854
new = self.working_tree()
856
for fs, fid, oldname, newname, kind in diff_trees(old, new):
858
show_status(fs, kind,
859
oldname + ' => ' + newname)
860
elif fs == 'A' or fs == 'M':
861
show_status(fs, kind, newname)
863
show_status(fs, kind, oldname)
866
show_status(fs, kind, newname)
869
show_status(fs, kind, newname)
871
show_status(fs, kind, newname)
873
bailout("wierd file state %r" % ((fs, fid),))
715
877
class ScratchBranch(Branch):
716
878
"""Special test class: a branch that cleans up after itself.