1
# Copyright (C) 2005 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
19
import traceback, socket, fnmatch, difflib, time
20
from binascii import hexlify
23
from inventory import Inventory
24
from trace import mutter, note
25
from tree import Tree, EmptyTree, RevisionTree
26
from inventory import InventoryEntry, Inventory
27
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
28
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
29
joinpath, sha_file, sha_string, file_kind, local_time_offset, appendpath
30
from store import ImmutableStore
31
from revision import Revision
32
from errors import BzrError
33
from textui import show_status
35
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
36
## TODO: Maybe include checks for common corruption of newlines, etc?
40
def find_branch(f, **args):
41
if f and (f.startswith('http://') or f.startswith('https://')):
43
return remotebranch.RemoteBranch(f, **args)
45
return Branch(f, **args)
48
def find_cached_branch(f, cache_root, **args):
49
from remotebranch import RemoteBranch
50
br = find_branch(f, **args)
51
def cacheify(br, store_name):
52
from meta_store import CachedStore
53
cache_path = os.path.join(cache_root, store_name)
55
new_store = CachedStore(getattr(br, store_name), cache_path)
56
setattr(br, store_name, new_store)
58
if isinstance(br, RemoteBranch):
59
cacheify(br, 'inventory_store')
60
cacheify(br, 'text_store')
61
cacheify(br, 'revision_store')
65
def _relpath(base, path):
66
"""Return path relative to base, or raise exception.
68
The path may be either an absolute path or a path relative to the
69
current working directory.
71
Lifted out of Branch.relpath for ease of testing.
73
os.path.commonprefix (python2.4) has a bad bug that it works just
74
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
75
avoids that problem."""
76
rp = os.path.abspath(path)
80
while len(head) >= len(base):
83
head, tail = os.path.split(head)
87
from errors import NotBranchError
88
raise NotBranchError("path %r is not within branch %r" % (rp, base))
93
def find_branch_root(f=None):
94
"""Find the branch root enclosing f, or pwd.
96
f may be a filename or a URL.
98
It is not necessary that f exists.
100
Basically we keep looking up until we find the control directory or
101
run into the root."""
104
elif hasattr(os.path, 'realpath'):
105
f = os.path.realpath(f)
107
f = os.path.abspath(f)
108
if not os.path.exists(f):
109
raise BzrError('%r does not exist' % f)
115
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
117
head, tail = os.path.split(f)
119
# reached the root, whatever that may be
120
raise BzrError('%r is not in a branch' % orig_f)
123
class DivergedBranches(Exception):
124
def __init__(self, branch1, branch2):
125
self.branch1 = branch1
126
self.branch2 = branch2
127
Exception.__init__(self, "These branches have diverged.")
130
class NoSuchRevision(BzrError):
131
def __init__(self, branch, revision):
133
self.revision = revision
134
msg = "Branch %s has no revision %d" % (branch, revision)
135
BzrError.__init__(self, msg)
138
######################################################################
141
class Branch(object):
142
"""Branch holding a history of revisions.
145
Base directory of the branch.
151
If _lock_mode is true, a positive count of the number of times the
155
Lock object from bzrlib.lock.
162
def __init__(self, base, init=False, find_root=True):
163
"""Create new branch object at a particular location.
165
base -- Base directory for the branch.
167
init -- If True, create new control files in a previously
168
unversioned directory. If False, the branch must already
171
find_root -- If true and init is false, find the root of the
172
existing branch containing base.
174
In the test suite, creation of new trees is tested using the
175
`ScratchBranch` class.
178
self.base = os.path.realpath(base)
181
self.base = find_branch_root(base)
183
self.base = os.path.realpath(base)
184
if not isdir(self.controlfilename('.')):
185
from errors import NotBranchError
186
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
187
['use "bzr init" to initialize a new working tree',
188
'current bzr can only operate from top-of-tree'])
191
self.text_store = ImmutableStore(self.controlfilename('text-store'))
192
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
193
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
197
return '%s(%r)' % (self.__class__.__name__, self.base)
204
if self._lock_mode or self._lock:
205
from warnings import warn
206
warn("branch %r was not explicitly unlocked" % self)
211
def lock_write(self):
213
if self._lock_mode != 'w':
214
from errors import LockError
215
raise LockError("can't upgrade to a write lock from %r" %
217
self._lock_count += 1
219
from bzrlib.lock import WriteLock
221
self._lock = WriteLock(self.controlfilename('branch-lock'))
222
self._lock_mode = 'w'
229
assert self._lock_mode in ('r', 'w'), \
230
"invalid lock mode %r" % self._lock_mode
231
self._lock_count += 1
233
from bzrlib.lock import ReadLock
235
self._lock = ReadLock(self.controlfilename('branch-lock'))
236
self._lock_mode = 'r'
242
if not self._lock_mode:
243
from errors import LockError
244
raise LockError('branch %r is not locked' % (self))
246
if self._lock_count > 1:
247
self._lock_count -= 1
251
self._lock_mode = self._lock_count = None
254
def abspath(self, name):
255
"""Return absolute filename for something in the branch"""
256
return os.path.join(self.base, name)
259
def relpath(self, path):
260
"""Return path relative to this branch of something inside it.
262
Raises an error if path is not in this branch."""
263
return _relpath(self.base, path)
266
def controlfilename(self, file_or_path):
267
"""Return location relative to branch."""
268
if isinstance(file_or_path, types.StringTypes):
269
file_or_path = [file_or_path]
270
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
273
def controlfile(self, file_or_path, mode='r'):
274
"""Open a control file for this branch.
276
There are two classes of file in the control directory: text
277
and binary. binary files are untranslated byte streams. Text
278
control files are stored with Unix newlines and in UTF-8, even
279
if the platform or locale defaults are different.
281
Controlfiles should almost never be opened in write mode but
282
rather should be atomically copied and replaced using atomicfile.
285
fn = self.controlfilename(file_or_path)
287
if mode == 'rb' or mode == 'wb':
288
return file(fn, mode)
289
elif mode == 'r' or mode == 'w':
290
# open in binary mode anyhow so there's no newline translation;
291
# codecs uses line buffering by default; don't want that.
293
return codecs.open(fn, mode + 'b', 'utf-8',
296
raise BzrError("invalid controlfile mode %r" % mode)
300
def _make_control(self):
301
os.mkdir(self.controlfilename([]))
302
self.controlfile('README', 'w').write(
303
"This is a Bazaar-NG control directory.\n"
304
"Do not change any files in this directory.\n")
305
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
306
for d in ('text-store', 'inventory-store', 'revision-store'):
307
os.mkdir(self.controlfilename(d))
308
for f in ('revision-history', 'merged-patches',
309
'pending-merged-patches', 'branch-name',
311
self.controlfile(f, 'w').write('')
312
mutter('created control directory in ' + self.base)
313
Inventory().write_xml(self.controlfile('inventory','w'))
316
def _check_format(self):
317
"""Check this branch format is supported.
319
The current tool only supports the current unstable format.
321
In the future, we might need different in-memory Branch
322
classes to support downlevel branches. But not yet.
324
# This ignores newlines so that we can open branches created
325
# on Windows from Linux and so on. I think it might be better
326
# to always make all internal files in unix format.
327
fmt = self.controlfile('branch-format', 'r').read()
328
fmt.replace('\r\n', '')
329
if fmt != BZR_BRANCH_FORMAT:
330
raise BzrError('sorry, branch format %r not supported' % fmt,
331
['use a different bzr version',
332
'or remove the .bzr directory and "bzr init" again'])
336
def read_working_inventory(self):
337
"""Read the working inventory."""
339
# ElementTree does its own conversion from UTF-8, so open in
343
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
344
mutter("loaded inventory of %d items in %f"
345
% (len(inv), time.time() - before))
351
def _write_inventory(self, inv):
352
"""Update the working inventory.
354
That is to say, the inventory describing changes underway, that
355
will be committed to the next revision.
359
from bzrlib.atomicfile import AtomicFile
361
f = AtomicFile(self.controlfilename('inventory'), 'wb')
370
mutter('wrote working inventory')
373
inventory = property(read_working_inventory, _write_inventory, None,
374
"""Inventory for the working copy.""")
377
def add(self, files, verbose=False, ids=None):
378
"""Make files versioned.
380
Note that the command line normally calls smart_add instead.
382
This puts the files in the Added state, so that they will be
383
recorded by the next commit.
386
List of paths to add, relative to the base of the tree.
389
If set, use these instead of automatically generated ids.
390
Must be the same length as the list of files, but may
391
contain None for ids that are to be autogenerated.
393
TODO: Perhaps have an option to add the ids even if the files do
396
TODO: Perhaps return the ids of the files? But then again it
397
is easy to retrieve them if they're needed.
399
TODO: Adding a directory should optionally recurse down and
400
add all non-ignored children. Perhaps do that in a
403
# TODO: Re-adding a file that is removed in the working copy
404
# should probably put it back with the previous ID.
405
if isinstance(files, types.StringTypes):
406
assert(ids is None or isinstance(ids, types.StringTypes))
412
ids = [None] * len(files)
414
assert(len(ids) == len(files))
418
inv = self.read_working_inventory()
419
for f,file_id in zip(files, ids):
420
if is_control_file(f):
421
raise BzrError("cannot add control file %s" % quotefn(f))
426
raise BzrError("cannot add top-level %r" % f)
428
fullpath = os.path.normpath(self.abspath(f))
431
kind = file_kind(fullpath)
433
# maybe something better?
434
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
436
if kind != 'file' and kind != 'directory':
437
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
440
file_id = gen_file_id(f)
441
inv.add_path(f, kind=kind, file_id=file_id)
444
print 'added', quotefn(f)
446
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
448
self._write_inventory(inv)
453
def print_file(self, file, revno):
454
"""Print `file` to stdout."""
457
tree = self.revision_tree(self.lookup_revision(revno))
458
# use inventory as it was in that revision
459
file_id = tree.inventory.path2id(file)
461
raise BzrError("%r is not present in revision %d" % (file, revno))
462
tree.print_file(file_id)
467
def remove(self, files, verbose=False):
468
"""Mark nominated files for removal from the inventory.
470
This does not remove their text. This does not run on
472
TODO: Refuse to remove modified files unless --force is given?
474
TODO: Do something useful with directories.
476
TODO: Should this remove the text or not? Tough call; not
477
removing may be useful and the user can just use use rm, and
478
is the opposite of add. Removing it is consistent with most
479
other tools. Maybe an option.
481
## TODO: Normalize names
482
## TODO: Remove nested loops; better scalability
483
if isinstance(files, types.StringTypes):
489
tree = self.working_tree()
492
# do this before any modifications
496
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
497
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
499
# having remove it, it must be either ignored or unknown
500
if tree.is_ignored(f):
504
show_status(new_status, inv[fid].kind, quotefn(f))
507
self._write_inventory(inv)
512
# FIXME: this doesn't need to be a branch method
513
def set_inventory(self, new_inventory_list):
515
for path, file_id, parent, kind in new_inventory_list:
516
name = os.path.basename(path)
519
inv.add(InventoryEntry(file_id, name, kind, parent))
520
self._write_inventory(inv)
524
"""Return all unknown files.
526
These are files in the working directory that are not versioned or
527
control files or ignored.
529
>>> b = ScratchBranch(files=['foo', 'foo~'])
530
>>> list(b.unknowns())
533
>>> list(b.unknowns())
536
>>> list(b.unknowns())
539
return self.working_tree().unknowns()
542
def append_revision(self, revision_id):
543
from bzrlib.atomicfile import AtomicFile
545
mutter("add {%s} to revision-history" % revision_id)
546
rev_history = self.revision_history() + [revision_id]
548
f = AtomicFile(self.controlfilename('revision-history'))
550
for rev_id in rev_history:
557
def get_revision(self, revision_id):
558
"""Return the Revision object for a named revision"""
559
if not revision_id or not isinstance(revision_id, basestring):
560
raise ValueError('invalid revision-id: %r' % revision_id)
561
r = Revision.read_xml(self.revision_store[revision_id])
562
assert r.revision_id == revision_id
565
def get_revision_sha1(self, revision_id):
566
"""Hash the stored value of a revision, and return it."""
567
# In the future, revision entries will be signed. At that
568
# point, it is probably best *not* to include the signature
569
# in the revision hash. Because that lets you re-sign
570
# the revision, (add signatures/remove signatures) and still
571
# have all hash pointers stay consistent.
572
# But for now, just hash the contents.
573
return sha_file(self.revision_store[revision_id])
576
def get_inventory(self, inventory_id):
577
"""Get Inventory object by hash.
579
TODO: Perhaps for this and similar methods, take a revision
580
parameter which can be either an integer revno or a
582
i = Inventory.read_xml(self.inventory_store[inventory_id])
585
def get_inventory_sha1(self, inventory_id):
586
"""Return the sha1 hash of the inventory entry
588
return sha_file(self.inventory_store[inventory_id])
591
def get_revision_inventory(self, revision_id):
592
"""Return inventory of a past revision."""
593
if revision_id == None:
596
return self.get_inventory(self.get_revision(revision_id).inventory_id)
599
def revision_history(self):
600
"""Return sequence of revision hashes on to this branch.
602
>>> ScratchBranch().revision_history()
607
return [l.rstrip('\r\n') for l in
608
self.controlfile('revision-history', 'r').readlines()]
613
def common_ancestor(self, other, self_revno=None, other_revno=None):
616
>>> sb = ScratchBranch(files=['foo', 'foo~'])
617
>>> sb.common_ancestor(sb) == (None, None)
619
>>> commit.commit(sb, "Committing first revision", verbose=False)
620
>>> sb.common_ancestor(sb)[0]
622
>>> clone = sb.clone()
623
>>> commit.commit(sb, "Committing second revision", verbose=False)
624
>>> sb.common_ancestor(sb)[0]
626
>>> sb.common_ancestor(clone)[0]
628
>>> commit.commit(clone, "Committing divergent second revision",
630
>>> sb.common_ancestor(clone)[0]
632
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
634
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
636
>>> clone2 = sb.clone()
637
>>> sb.common_ancestor(clone2)[0]
639
>>> sb.common_ancestor(clone2, self_revno=1)[0]
641
>>> sb.common_ancestor(clone2, other_revno=1)[0]
644
my_history = self.revision_history()
645
other_history = other.revision_history()
646
if self_revno is None:
647
self_revno = len(my_history)
648
if other_revno is None:
649
other_revno = len(other_history)
650
indices = range(min((self_revno, other_revno)))
653
if my_history[r] == other_history[r]:
654
return r+1, my_history[r]
657
def enum_history(self, direction):
658
"""Return (revno, revision_id) for history of branch.
661
'forward' is from earliest to latest
662
'reverse' is from latest to earliest
664
rh = self.revision_history()
665
if direction == 'forward':
670
elif direction == 'reverse':
676
raise ValueError('invalid history direction', direction)
680
"""Return current revision number for this branch.
682
That is equivalent to the number of revisions committed to
685
return len(self.revision_history())
688
def last_patch(self):
689
"""Return last patch hash, or None if no history.
691
ph = self.revision_history()
698
def missing_revisions(self, other, stop_revision=None):
700
If self and other have not diverged, return a list of the revisions
701
present in other, but missing from self.
703
>>> from bzrlib.commit import commit
704
>>> bzrlib.trace.silent = True
705
>>> br1 = ScratchBranch()
706
>>> br2 = ScratchBranch()
707
>>> br1.missing_revisions(br2)
709
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
710
>>> br1.missing_revisions(br2)
712
>>> br2.missing_revisions(br1)
714
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
715
>>> br1.missing_revisions(br2)
717
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
718
>>> br1.missing_revisions(br2)
720
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
721
>>> br1.missing_revisions(br2)
722
Traceback (most recent call last):
723
DivergedBranches: These branches have diverged.
725
self_history = self.revision_history()
726
self_len = len(self_history)
727
other_history = other.revision_history()
728
other_len = len(other_history)
729
common_index = min(self_len, other_len) -1
730
if common_index >= 0 and \
731
self_history[common_index] != other_history[common_index]:
732
raise DivergedBranches(self, other)
734
if stop_revision is None:
735
stop_revision = other_len
736
elif stop_revision > other_len:
737
raise NoSuchRevision(self, stop_revision)
739
return other_history[self_len:stop_revision]
742
def update_revisions(self, other, stop_revision=None):
743
"""Pull in all new revisions from other branch.
745
>>> from bzrlib.commit import commit
746
>>> bzrlib.trace.silent = True
747
>>> br1 = ScratchBranch(files=['foo', 'bar'])
750
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
751
>>> br2 = ScratchBranch()
752
>>> br2.update_revisions(br1)
756
>>> br2.revision_history()
758
>>> br2.update_revisions(br1)
762
>>> br1.text_store.total_size() == br2.text_store.total_size()
765
from bzrlib.progress import ProgressBar
769
pb.update('comparing histories')
770
revision_ids = self.missing_revisions(other, stop_revision)
772
if hasattr(other.revision_store, "prefetch"):
773
other.revision_store.prefetch(revision_ids)
774
if hasattr(other.inventory_store, "prefetch"):
775
inventory_ids = [other.get_revision(r).inventory_id
776
for r in revision_ids]
777
other.inventory_store.prefetch(inventory_ids)
780
needed_texts = sets.Set()
782
for rev_id in revision_ids:
784
pb.update('fetching revision', i, len(revision_ids))
785
rev = other.get_revision(rev_id)
786
revisions.append(rev)
787
inv = other.get_inventory(str(rev.inventory_id))
788
for key, entry in inv.iter_entries():
789
if entry.text_id is None:
791
if entry.text_id not in self.text_store:
792
needed_texts.add(entry.text_id)
796
count = self.text_store.copy_multi(other.text_store, needed_texts)
797
print "Added %d texts." % count
798
inventory_ids = [ f.inventory_id for f in revisions ]
799
count = self.inventory_store.copy_multi(other.inventory_store,
801
print "Added %d inventories." % count
802
revision_ids = [ f.revision_id for f in revisions]
803
count = self.revision_store.copy_multi(other.revision_store,
805
for revision_id in revision_ids:
806
self.append_revision(revision_id)
807
print "Added %d revisions." % count
810
def commit(self, *args, **kw):
811
from bzrlib.commit import commit
812
commit(self, *args, **kw)
815
def lookup_revision(self, revno):
816
"""Return revision hash for revision number."""
821
# list is 0-based; revisions are 1-based
822
return self.revision_history()[revno-1]
824
raise BzrError("no such revision %s" % revno)
827
def revision_tree(self, revision_id):
828
"""Return Tree for a revision on this branch.
830
`revision_id` may be None for the null revision, in which case
831
an `EmptyTree` is returned."""
832
# TODO: refactor this to use an existing revision object
833
# so we don't need to read it in twice.
834
if revision_id == None:
837
inv = self.get_revision_inventory(revision_id)
838
return RevisionTree(self.text_store, inv)
841
def working_tree(self):
842
"""Return a `Tree` for the working copy."""
843
from workingtree import WorkingTree
844
return WorkingTree(self.base, self.read_working_inventory())
847
def basis_tree(self):
848
"""Return `Tree` object for last revision.
850
If there are no revisions yet, return an `EmptyTree`.
852
r = self.last_patch()
856
return RevisionTree(self.text_store, self.get_revision_inventory(r))
860
def rename_one(self, from_rel, to_rel):
863
This can change the directory or the filename or both.
867
tree = self.working_tree()
869
if not tree.has_filename(from_rel):
870
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
871
if tree.has_filename(to_rel):
872
raise BzrError("can't rename: new working file %r already exists" % to_rel)
874
file_id = inv.path2id(from_rel)
876
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
878
if inv.path2id(to_rel):
879
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
881
to_dir, to_tail = os.path.split(to_rel)
882
to_dir_id = inv.path2id(to_dir)
883
if to_dir_id == None and to_dir != '':
884
raise BzrError("can't determine destination directory id for %r" % to_dir)
886
mutter("rename_one:")
887
mutter(" file_id {%s}" % file_id)
888
mutter(" from_rel %r" % from_rel)
889
mutter(" to_rel %r" % to_rel)
890
mutter(" to_dir %r" % to_dir)
891
mutter(" to_dir_id {%s}" % to_dir_id)
893
inv.rename(file_id, to_dir_id, to_tail)
895
print "%s => %s" % (from_rel, to_rel)
897
from_abs = self.abspath(from_rel)
898
to_abs = self.abspath(to_rel)
900
os.rename(from_abs, to_abs)
902
raise BzrError("failed to rename %r to %r: %s"
903
% (from_abs, to_abs, e[1]),
904
["rename rolled back"])
906
self._write_inventory(inv)
911
def move(self, from_paths, to_name):
914
to_name must exist as a versioned directory.
916
If to_name exists and is a directory, the files are moved into
917
it, keeping their old names. If it is a directory,
919
Note that to_name is only the last component of the new name;
920
this doesn't change the directory.
924
## TODO: Option to move IDs only
925
assert not isinstance(from_paths, basestring)
926
tree = self.working_tree()
928
to_abs = self.abspath(to_name)
929
if not isdir(to_abs):
930
raise BzrError("destination %r is not a directory" % to_abs)
931
if not tree.has_filename(to_name):
932
raise BzrError("destination %r not in working directory" % to_abs)
933
to_dir_id = inv.path2id(to_name)
934
if to_dir_id == None and to_name != '':
935
raise BzrError("destination %r is not a versioned directory" % to_name)
936
to_dir_ie = inv[to_dir_id]
937
if to_dir_ie.kind not in ('directory', 'root_directory'):
938
raise BzrError("destination %r is not a directory" % to_abs)
940
to_idpath = inv.get_idpath(to_dir_id)
943
if not tree.has_filename(f):
944
raise BzrError("%r does not exist in working tree" % f)
945
f_id = inv.path2id(f)
947
raise BzrError("%r is not versioned" % f)
948
name_tail = splitpath(f)[-1]
949
dest_path = appendpath(to_name, name_tail)
950
if tree.has_filename(dest_path):
951
raise BzrError("destination %r already exists" % dest_path)
952
if f_id in to_idpath:
953
raise BzrError("can't move %r to a subdirectory of itself" % f)
955
# OK, so there's a race here, it's possible that someone will
956
# create a file in this interval and then the rename might be
957
# left half-done. But we should have caught most problems.
960
name_tail = splitpath(f)[-1]
961
dest_path = appendpath(to_name, name_tail)
962
print "%s => %s" % (f, dest_path)
963
inv.rename(inv.path2id(f), to_dir_id, name_tail)
965
os.rename(self.abspath(f), self.abspath(dest_path))
967
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
968
["rename rolled back"])
970
self._write_inventory(inv)
975
def revert(self, filenames, old_tree=None, backups=True):
976
"""Restore selected files to the versions from a previous tree.
979
If true (default) backups are made of files before
982
from bzrlib.errors import NotVersionedError, BzrError
983
from bzrlib.atomicfile import AtomicFile
984
from bzrlib.osutils import backup_file
986
inv = self.read_working_inventory()
988
old_tree = self.basis_tree()
989
old_inv = old_tree.inventory
993
file_id = inv.path2id(fn)
995
raise NotVersionedError("not a versioned file", fn)
996
if not old_inv.has_id(file_id):
997
raise BzrError("file not present in old tree", fn, file_id)
998
nids.append((fn, file_id))
1000
# TODO: Rename back if it was previously at a different location
1002
# TODO: If given a directory, restore the entire contents from
1003
# the previous version.
1005
# TODO: Make a backup to a temporary file.
1007
# TODO: If the file previously didn't exist, delete it?
1008
for fn, file_id in nids:
1011
f = AtomicFile(fn, 'wb')
1013
f.write(old_tree.get_file(file_id).read())
1020
class ScratchBranch(Branch):
1021
"""Special test class: a branch that cleans up after itself.
1023
>>> b = ScratchBranch()
1031
def __init__(self, files=[], dirs=[], base=None):
1032
"""Make a test branch.
1034
This creates a temporary directory and runs init-tree in it.
1036
If any files are listed, they are created in the working copy.
1040
base = tempfile.mkdtemp()
1042
Branch.__init__(self, base, init=init)
1044
os.mkdir(self.abspath(d))
1047
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1052
>>> orig = ScratchBranch(files=["file1", "file2"])
1053
>>> clone = orig.clone()
1054
>>> os.path.samefile(orig.base, clone.base)
1056
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1059
base = tempfile.mkdtemp()
1061
shutil.copytree(self.base, base, symlinks=True)
1062
return ScratchBranch(base=base)
1068
"""Destroy the test branch, removing the scratch directory."""
1071
mutter("delete ScratchBranch %s" % self.base)
1072
shutil.rmtree(self.base)
1074
# Work around for shutil.rmtree failing on Windows when
1075
# readonly files are encountered
1076
mutter("hit exception in destroying ScratchBranch: %s" % e)
1077
for root, dirs, files in os.walk(self.base, topdown=False):
1079
os.chmod(os.path.join(root, name), 0700)
1080
shutil.rmtree(self.base)
1085
######################################################################
1089
def is_control_file(filename):
1090
## FIXME: better check
1091
filename = os.path.normpath(filename)
1092
while filename != '':
1093
head, tail = os.path.split(filename)
1094
## mutter('check %r for control file' % ((head, tail), ))
1095
if tail == bzrlib.BZRDIR:
1097
if filename == head:
1104
def gen_file_id(name):
1105
"""Return new file id.
1107
This should probably generate proper UUIDs, but for the moment we
1108
cope with just randomness because running uuidgen every time is
1112
# get last component
1113
idx = name.rfind('/')
1115
name = name[idx+1 : ]
1116
idx = name.rfind('\\')
1118
name = name[idx+1 : ]
1120
# make it not a hidden file
1121
name = name.lstrip('.')
1123
# remove any wierd characters; we don't escape them but rather
1124
# just pull them out
1125
name = re.sub(r'[^\w.]', '', name)
1127
s = hexlify(rand_bytes(8))
1128
return '-'.join((name, compact_date(time.time()), s))