15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
from warnings import warn
22
from cStringIO import StringIO
20
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
21
import traceback, socket, fnmatch, difflib, time
22
from binascii import hexlify
25
from inventory import Inventory
26
from trace import mutter, note
27
from tree import Tree, EmptyTree, RevisionTree, WorkingTree
28
from inventory import InventoryEntry, Inventory
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
30
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
joinpath, sha_string, file_kind, local_time_offset, appendpath
32
from store import ImmutableStore
33
from revision import Revision
34
from errors import bailout, BzrError
35
from textui import show_status
36
from diff import diff_trees
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
26
from bzrlib.inventory import InventoryEntry
27
import bzrlib.inventory as inventory
28
from bzrlib.trace import mutter, note
29
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes,
30
rename, splitpath, sha_file, appendpath,
32
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
33
NoSuchRevision, HistoryMissing, NotBranchError,
34
DivergedBranches, LockError, UnlistableStore,
35
UnlistableBranch, NoSuchFile)
36
from bzrlib.textui import show_status
37
from bzrlib.revision import Revision
38
from bzrlib.delta import compare_trees
39
from bzrlib.tree import EmptyTree, RevisionTree
40
from bzrlib.inventory import Inventory
41
from bzrlib.store import copy_all
42
from bzrlib.store.compressed_text import CompressedTextStore
43
from bzrlib.store.text import TextStore
44
from bzrlib.store.weave import WeaveStore
45
from bzrlib.transport import Transport, get_transport
50
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
51
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
39
52
## TODO: Maybe include checks for common corruption of newlines, etc?
43
def find_branch_root(f=None):
44
"""Find the branch root enclosing f, or pwd.
46
It is not necessary that f exists.
55
# TODO: Some operations like log might retrieve the same revisions
56
# repeatedly to calculate deltas. We could perhaps have a weakref
57
# cache in memory to make this faster. In general anything can be
58
# cached in memory between lock and unlock operations.
60
def find_branch(*ignored, **ignored_too):
61
# XXX: leave this here for about one release, then remove it
62
raise NotImplementedError('find_branch() is not supported anymore, '
63
'please use one of the new branch constructors')
64
def _relpath(base, path):
65
"""Return path relative to base, or raise exception.
67
The path may be either an absolute path or a path relative to the
68
current working directory.
70
Lifted out of Branch.relpath for ease of testing.
72
os.path.commonprefix (python2.4) has a bad bug that it works just
73
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
74
avoids that problem."""
75
rp = os.path.abspath(path)
79
while len(head) >= len(base):
82
head, tail = os.path.split(head)
86
raise NotBranchError("path %r is not within branch %r" % (rp, base))
91
def find_branch_root(t):
92
"""Find the branch root enclosing the transport's base.
94
t is a Transport object.
96
It is not necessary that the base of t exists.
48
98
Basically we keep looking up until we find the control directory or
52
elif hasattr(os.path, 'realpath'):
53
f = os.path.realpath(f)
55
f = os.path.abspath(f)
99
run into the root. If there isn't one, raises NotBranchError.
60
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
62
head, tail = os.path.split(f)
103
if t.has(bzrlib.BZRDIR):
105
new_t = t.clone('..')
106
if new_t.base == t.base:
64
107
# reached the root, whatever that may be
65
raise BzrError('%r is not in a branch' % orig_f)
108
raise NotBranchError('%s is not in a branch' % orig_base)
70
112
######################################################################
115
class Branch(object):
74
116
"""Branch holding a history of revisions.
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.
89
def __init__(self, base, init=False, find_root=True):
119
Base directory/url of the branch.
123
def __init__(self, *ignored, **ignored_too):
124
raise NotImplementedError('The Branch class is abstract')
127
def open_downlevel(base):
128
"""Open a branch which may be of an old format.
130
Only local branches are supported."""
131
return _Branch(get_transport(base), relax_version_check=True)
135
"""Open an existing branch, rooted at 'base' (url)"""
136
t = get_transport(base)
140
def open_containing(url):
141
"""Open an existing branch which contains url.
143
This probes for a branch at url, and searches upwards from there.
145
t = get_transport(url)
146
t = find_branch_root(t)
150
def initialize(base):
151
"""Create a new branch, rooted at 'base' (url)"""
152
t = get_transport(base)
153
return _Branch(t, init=True)
155
def setup_caching(self, cache_root):
156
"""Subclasses that care about caching should override this, and set
157
up cached stores located under cache_root.
159
self.cache_root = cache_root
162
class _Branch(Branch):
163
"""A branch stored in the actual filesystem.
165
Note that it's "local" in the context of the filesystem; it doesn't
166
really matter if it's on an nfs/smb/afs/coda/... share, as long as
167
it's writable, and can be accessed via the normal filesystem API.
173
If _lock_mode is true, a positive count of the number of times the
177
Lock object from bzrlib.lock.
179
# We actually expect this class to be somewhat short-lived; part of its
180
# purpose is to try to isolate what bits of the branch logic are tied to
181
# filesystem access, so that in a later step, we can extricate them to
182
# a separarte ("storage") class.
186
_inventory_weave = None
188
# Map some sort of prefix into a namespace
189
# stuff like "revno:10", "revid:", etc.
190
# This should match a prefix with a function which accepts
191
REVISION_NAMESPACES = {}
193
def push_stores(self, branch_to):
194
"""Copy the content of this branches store to branch_to."""
195
if (self._branch_format != branch_to._branch_format
196
or self._branch_format != 4):
197
from bzrlib.fetch import greedy_fetch
198
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
199
self, self._branch_format, branch_to, branch_to._branch_format)
200
greedy_fetch(to_branch=branch_to, from_branch=self,
201
revision=self.last_revision())
204
store_pairs = ((self.text_store, branch_to.text_store),
205
(self.inventory_store, branch_to.inventory_store),
206
(self.revision_store, branch_to.revision_store))
208
for from_store, to_store in store_pairs:
209
copy_all(from_store, to_store)
210
except UnlistableStore:
211
raise UnlistableBranch(from_store)
213
def __init__(self, transport, init=False,
214
relax_version_check=False):
90
215
"""Create new branch object at a particular location.
92
base -- Base directory for the branch.
217
transport -- A Transport object, defining how to access files.
218
(If a string, transport.transport() will be used to
219
create a Transport object)
94
221
init -- If True, create new control files in a previously
95
222
unversioned directory. If False, the branch must already
98
find_root -- If true and init is false, find the root of the
99
existing branch containing base.
225
relax_version_check -- If true, the usual check for the branch
226
version is not applied. This is intended only for
227
upgrade/recovery type use; it's not guaranteed that
228
all operations will work on old format branches.
101
230
In the test suite, creation of new trees is tested using the
102
231
`ScratchBranch` class.
233
assert isinstance(transport, Transport), \
234
"%r is not a Transport" % transport
235
self._transport = transport
105
self.base = os.path.realpath(base)
106
237
self._make_control()
108
self.base = find_branch_root(base)
110
self.base = os.path.realpath(base)
111
if not isdir(self.controlfilename('.')):
112
bailout("not a bzr branch: %s" % quotefn(base),
113
['use "bzr init" to initialize a new working tree',
114
'current bzr can only operate from top-of-tree'])
117
self.text_store = ImmutableStore(self.controlfilename('text-store'))
118
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
119
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
238
self._check_format(relax_version_check)
240
def get_store(name, compressed=True):
241
# FIXME: This approach of assuming stores are all entirely compressed
242
# or entirely uncompressed is tidy, but breaks upgrade from
243
# some existing branches where there's a mixture; we probably
244
# still want the option to look for both.
245
relpath = self._rel_controlfilename(name)
247
store = CompressedTextStore(self._transport.clone(relpath))
249
store = TextStore(self._transport.clone(relpath))
250
#if self._transport.should_cache():
251
# cache_path = os.path.join(self.cache_root, name)
252
# os.mkdir(cache_path)
253
# store = bzrlib.store.CachedStore(store, cache_path)
256
relpath = self._rel_controlfilename(name)
257
ws = WeaveStore(self._transport.clone(relpath))
258
if self._transport.should_cache():
259
ws.enable_cache = True
262
if self._branch_format == 4:
263
self.inventory_store = get_store('inventory-store')
264
self.text_store = get_store('text-store')
265
self.revision_store = get_store('revision-store')
266
elif self._branch_format == 5:
267
self.control_weaves = get_weave([])
268
self.weave_store = get_weave('weaves')
269
self.revision_store = get_store('revision-store', compressed=False)
122
271
def __str__(self):
123
return '%s(%r)' % (self.__class__.__name__, self.base)
272
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
126
275
__repr__ = __str__
279
if self._lock_mode or self._lock:
280
# XXX: This should show something every time, and be suitable for
281
# headless operation and embedding
282
warn("branch %r was not explicitly unlocked" % self)
285
# TODO: It might be best to do this somewhere else,
286
# but it is nice for a Branch object to automatically
287
# cache it's information.
288
# Alternatively, we could have the Transport objects cache requests
289
# See the earlier discussion about how major objects (like Branch)
290
# should never expect their __del__ function to run.
291
if hasattr(self, 'cache_root') and self.cache_root is not None:
294
shutil.rmtree(self.cache_root)
297
self.cache_root = None
301
return self._transport.base
304
base = property(_get_base)
307
def lock_write(self):
308
# TODO: Upgrade locking to support using a Transport,
309
# and potentially a remote locking protocol
311
if self._lock_mode != 'w':
312
raise LockError("can't upgrade to a write lock from %r" %
314
self._lock_count += 1
316
self._lock = self._transport.lock_write(
317
self._rel_controlfilename('branch-lock'))
318
self._lock_mode = 'w'
324
assert self._lock_mode in ('r', 'w'), \
325
"invalid lock mode %r" % self._lock_mode
326
self._lock_count += 1
328
self._lock = self._transport.lock_read(
329
self._rel_controlfilename('branch-lock'))
330
self._lock_mode = 'r'
334
if not self._lock_mode:
335
raise LockError('branch %r is not locked' % (self))
337
if self._lock_count > 1:
338
self._lock_count -= 1
342
self._lock_mode = self._lock_count = None
129
344
def abspath(self, name):
130
345
"""Return absolute filename for something in the branch"""
131
return os.path.join(self.base, name)
346
return self._transport.abspath(name)
134
348
def relpath(self, path):
135
349
"""Return path relative to this branch of something inside it.
137
351
Raises an error if path is not in this branch."""
138
rp = os.path.realpath(path)
140
if not rp.startswith(self.base):
141
bailout("path %r is not within branch %r" % (rp, self.base))
142
rp = rp[len(self.base):]
143
rp = rp.lstrip(os.sep)
352
return self._transport.relpath(path)
355
def _rel_controlfilename(self, file_or_path):
356
if isinstance(file_or_path, basestring):
357
file_or_path = [file_or_path]
358
return [bzrlib.BZRDIR] + file_or_path
147
360
def controlfilename(self, file_or_path):
148
361
"""Return location relative to branch."""
149
if isinstance(file_or_path, types.StringTypes):
150
file_or_path = [file_or_path]
151
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
362
return self._transport.abspath(self._rel_controlfilename(file_or_path))
154
365
def controlfile(self, file_or_path, mode='r'):
158
369
and binary. binary files are untranslated byte streams. Text
159
370
control files are stored with Unix newlines and in UTF-8, even
160
371
if the platform or locale defaults are different.
373
Controlfiles should almost never be opened in write mode but
374
rather should be atomically copied and replaced using atomicfile.
163
fn = self.controlfilename(file_or_path)
165
if mode == 'rb' or mode == 'wb':
166
return file(fn, mode)
167
elif mode == 'r' or mode == 'w':
168
# open in binary mode anyhow so there's no newline translation;
169
# codecs uses line buffering by default; don't want that.
171
return codecs.open(fn, mode + 'b', 'utf-8',
378
relpath = self._rel_controlfilename(file_or_path)
379
#TODO: codecs.open() buffers linewise, so it was overloaded with
380
# a much larger buffer, do we need to do the same for getreader/getwriter?
382
return self._transport.get(relpath)
384
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
386
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
388
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
174
390
raise BzrError("invalid controlfile mode %r" % mode)
392
def put_controlfile(self, path, f, encode=True):
393
"""Write an entry as a controlfile.
395
:param path: The path to put the file, relative to the .bzr control
397
:param f: A file-like or string object whose contents should be copied.
398
:param encode: If true, encode the contents as utf-8
400
self.put_controlfiles([(path, f)], encode=encode)
402
def put_controlfiles(self, files, encode=True):
403
"""Write several entries as controlfiles.
405
:param files: A list of [(path, file)] pairs, where the path is the directory
406
underneath the bzr control directory
407
:param encode: If true, encode the contents as utf-8
411
for path, f in files:
413
if isinstance(f, basestring):
414
f = f.encode('utf-8', 'replace')
416
f = codecs.getwriter('utf-8')(f, errors='replace')
417
path = self._rel_controlfilename(path)
418
ctrl_files.append((path, f))
419
self._transport.put_multi(ctrl_files)
178
421
def _make_control(self):
179
os.mkdir(self.controlfilename([]))
180
self.controlfile('README', 'w').write(
422
from bzrlib.inventory import Inventory
423
from bzrlib.weavefile import write_weave_v5
424
from bzrlib.weave import Weave
426
# Create an empty inventory
428
# if we want per-tree root ids then this is the place to set
429
# them; they're not needed for now and so ommitted for
431
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
432
empty_inv = sio.getvalue()
434
bzrlib.weavefile.write_weave_v5(Weave(), sio)
435
empty_weave = sio.getvalue()
437
dirs = [[], 'revision-store', 'weaves']
181
439
"This is a Bazaar-NG control directory.\n"
182
"Do not change any files in this directory.")
183
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
184
for d in ('text-store', 'inventory-store', 'revision-store'):
185
os.mkdir(self.controlfilename(d))
186
for f in ('revision-history', 'merged-patches',
187
'pending-merged-patches', 'branch-name'):
188
self.controlfile(f, 'w').write('')
189
mutter('created control directory in ' + self.base)
190
Inventory().write_xml(self.controlfile('inventory','w'))
193
def _check_format(self):
440
"Do not change any files in this directory.\n"),
441
('branch-format', BZR_BRANCH_FORMAT_5),
442
('revision-history', ''),
445
('pending-merges', ''),
446
('inventory', empty_inv),
447
('inventory.weave', empty_weave),
448
('ancestry.weave', empty_weave)
450
cfn = self._rel_controlfilename
451
self._transport.mkdir_multi([cfn(d) for d in dirs])
452
self.put_controlfiles(files)
453
mutter('created control directory in ' + self._transport.base)
455
def _check_format(self, relax_version_check):
194
456
"""Check this branch format is supported.
196
The current tool only supports the current unstable format.
458
The format level is stored, as an integer, in
459
self._branch_format for code that needs to check it later.
198
461
In the future, we might need different in-memory Branch
199
462
classes to support downlevel branches. But not yet.
201
# This ignores newlines so that we can open branches created
202
# on Windows from Linux and so on. I think it might be better
203
# to always make all internal files in unix format.
204
fmt = self.controlfile('branch-format', 'r').read()
205
fmt.replace('\r\n', '')
206
if fmt != BZR_BRANCH_FORMAT:
207
bailout('sorry, branch format %r not supported' % fmt,
208
['use a different bzr version',
209
'or remove the .bzr directory and "bzr init" again'])
465
fmt = self.controlfile('branch-format', 'r').read()
467
raise NotBranchError(self.base)
469
if fmt == BZR_BRANCH_FORMAT_5:
470
self._branch_format = 5
471
elif fmt == BZR_BRANCH_FORMAT_4:
472
self._branch_format = 4
474
if (not relax_version_check
475
and self._branch_format != 5):
476
raise BzrError('sorry, branch format %r not supported' % fmt,
477
['use a different bzr version',
478
'or remove the .bzr directory'
479
' and "bzr init" again'])
481
def get_root_id(self):
482
"""Return the id of this branches root"""
483
inv = self.read_working_inventory()
484
return inv.root.file_id
486
def set_root_id(self, file_id):
487
inv = self.read_working_inventory()
488
orig_root_id = inv.root.file_id
489
del inv._byid[inv.root.file_id]
490
inv.root.file_id = file_id
491
inv._byid[inv.root.file_id] = inv.root
494
if entry.parent_id in (None, orig_root_id):
495
entry.parent_id = inv.root.file_id
496
self._write_inventory(inv)
212
498
def read_working_inventory(self):
213
499
"""Read the working inventory."""
215
# ElementTree does its own conversion from UTF-8, so open in
217
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
218
mutter("loaded inventory of %d items in %f"
219
% (len(inv), time.time() - before))
502
# ElementTree does its own conversion from UTF-8, so open in
504
f = self.controlfile('inventory', 'rb')
505
return bzrlib.xml5.serializer_v5.read_inventory(f)
223
510
def _write_inventory(self, inv):
224
511
"""Update the working inventory.
226
513
That is to say, the inventory describing changes underway, that
227
514
will be committed to the next revision.
229
## TODO: factor out to atomicfile? is rename safe on windows?
230
## TODO: Maybe some kind of clean/dirty marker on inventory?
231
tmpfname = self.controlfilename('inventory.tmp')
232
tmpf = file(tmpfname, 'wb')
235
inv_fname = self.controlfilename('inventory')
236
if sys.platform == 'win32':
238
os.rename(tmpfname, inv_fname)
516
from cStringIO import StringIO
520
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
522
# Transport handles atomicity
523
self.put_controlfile('inventory', sio)
239
527
mutter('wrote working inventory')
242
529
inventory = property(read_working_inventory, _write_inventory, None,
243
530
"""Inventory for the working copy.""")
246
def add(self, files, verbose=False):
532
def add(self, files, ids=None):
247
533
"""Make files versioned.
249
Note that the command line normally calls smart_add instead.
535
Note that the command line normally calls smart_add instead,
536
which can automatically recurse.
251
538
This puts the files in the Added state, so that they will be
252
539
recorded by the next commit.
542
List of paths to add, relative to the base of the tree.
545
If set, use these instead of automatically generated ids.
546
Must be the same length as the list of files, but may
547
contain None for ids that are to be autogenerated.
254
549
TODO: Perhaps have an option to add the ids even if the files do
257
TODO: Perhaps return the ids of the files? But then again it
258
is easy to retrieve them if they're needed.
260
TODO: Option to specify file id.
262
TODO: Adding a directory should optionally recurse down and
263
add all non-ignored children. Perhaps do that in a
266
>>> b = ScratchBranch(files=['foo'])
267
>>> 'foo' in b.unknowns()
272
>>> 'foo' in b.unknowns()
274
>>> bool(b.inventory.path2id('foo'))
280
Traceback (most recent call last):
282
BzrError: ('foo is already versioned', [])
284
>>> b.add(['nothere'])
285
Traceback (most recent call last):
286
BzrError: ('cannot add: not a regular file or directory: nothere', [])
552
TODO: Perhaps yield the ids and paths as they're added.
289
554
# TODO: Re-adding a file that is removed in the working copy
290
555
# should probably put it back with the previous ID.
291
if isinstance(files, types.StringTypes):
556
if isinstance(files, basestring):
557
assert(ids is None or isinstance(ids, basestring))
294
inv = self.read_working_inventory()
296
if is_control_file(f):
297
bailout("cannot add control file %s" % quotefn(f))
302
bailout("cannot add top-level %r" % f)
304
fullpath = os.path.normpath(self.abspath(f))
307
kind = file_kind(fullpath)
309
# maybe something better?
310
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
312
if kind != 'file' and kind != 'directory':
313
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
315
file_id = gen_file_id(f)
316
inv.add_path(f, kind=kind, file_id=file_id)
319
show_status('A', kind, quotefn(f))
321
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
323
self._write_inventory(inv)
563
ids = [None] * len(files)
565
assert(len(ids) == len(files))
569
inv = self.read_working_inventory()
570
for f,file_id in zip(files, ids):
571
if is_control_file(f):
572
raise BzrError("cannot add control file %s" % quotefn(f))
577
raise BzrError("cannot add top-level %r" % f)
579
fullpath = os.path.normpath(self.abspath(f))
582
kind = file_kind(fullpath)
584
# maybe something better?
585
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
587
if not InventoryEntry.versionable_kind(kind):
588
raise BzrError('cannot add: not a versionable file ('
589
'i.e. regular file, symlink or directory): %s' % quotefn(f))
592
file_id = gen_file_id(f)
593
inv.add_path(f, kind=kind, file_id=file_id)
595
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
597
self._write_inventory(inv)
326
602
def print_file(self, file, revno):
327
603
"""Print `file` to stdout."""
328
tree = self.revision_tree(self.lookup_revision(revno))
329
# use inventory as it was in that revision
330
file_id = tree.inventory.path2id(file)
332
bailout("%r is not present in revision %d" % (file, revno))
333
tree.print_file(file_id)
606
tree = self.revision_tree(self.get_rev_id(revno))
607
# use inventory as it was in that revision
608
file_id = tree.inventory.path2id(file)
610
raise BzrError("%r is not present in revision %s" % (file, revno))
611
tree.print_file(file_id)
336
616
def remove(self, files, verbose=False):
337
617
"""Mark nominated files for removal from the inventory.
415
695
return self.working_tree().unknowns()
418
def commit(self, message, timestamp=None, timezone=None,
421
"""Commit working copy as a new revision.
423
The basic approach is to add all the file texts into the
424
store, then the inventory, then make a new revision pointing
425
to that inventory and store that.
427
This is not quite safe if the working copy changes during the
428
commit; for the moment that is simply not allowed. A better
429
approach is to make a temporary copy of the files before
430
computing their hashes, and then add those hashes in turn to
431
the inventory. This should mean at least that there are no
432
broken hash pointers. There is no way we can get a snapshot
433
of the whole directory at an instant. This would also have to
434
be robust against files disappearing, moving, etc. So the
435
whole thing is a bit hard.
437
timestamp -- if not None, seconds-since-epoch for a
438
postdated/predated commit.
441
## TODO: Show branch names
443
# TODO: Don't commit if there are no changes, unless forced?
445
# First walk over the working inventory; and both update that
446
# and also build a new revision inventory. The revision
447
# inventory needs to hold the text-id, sha1 and size of the
448
# actual file versions committed in the revision. (These are
449
# not present in the working inventory.) We also need to
450
# detect missing/deleted files, and remove them from the
453
work_inv = self.read_working_inventory()
455
basis = self.basis_tree()
456
basis_inv = basis.inventory
458
for path, entry in work_inv.iter_entries():
459
## TODO: Cope with files that have gone missing.
461
## TODO: Check that the file kind has not changed from the previous
462
## revision of this file (if any).
466
p = self.abspath(path)
467
file_id = entry.file_id
468
mutter('commit prep file %s, id %r ' % (p, file_id))
470
if not os.path.exists(p):
471
mutter(" file is missing, removing from inventory")
473
show_status('D', entry.kind, quotefn(path))
474
missing_ids.append(file_id)
477
# TODO: Handle files that have been deleted
479
# TODO: Maybe a special case for empty files? Seems a
480
# waste to store them many times.
484
if basis_inv.has_id(file_id):
485
old_kind = basis_inv[file_id].kind
486
if old_kind != entry.kind:
487
bailout("entry %r changed kind from %r to %r"
488
% (file_id, old_kind, entry.kind))
490
if entry.kind == 'directory':
492
bailout("%s is entered as directory but not a directory" % quotefn(p))
493
elif entry.kind == 'file':
495
bailout("%s is entered as file but is not a file" % quotefn(p))
497
content = file(p, 'rb').read()
499
entry.text_sha1 = sha_string(content)
500
entry.text_size = len(content)
502
old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
504
and (old_ie.text_size == entry.text_size)
505
and (old_ie.text_sha1 == entry.text_sha1)):
506
## assert content == basis.get_file(file_id).read()
507
entry.text_id = basis_inv[file_id].text_id
508
mutter(' unchanged from previous text_id {%s}' %
512
entry.text_id = gen_file_id(entry.name)
513
self.text_store.add(content, entry.text_id)
514
mutter(' stored with text_id {%s}' % entry.text_id)
518
elif (old_ie.name == entry.name
519
and old_ie.parent_id == entry.parent_id):
524
show_status(state, entry.kind, quotefn(path))
526
for file_id in missing_ids:
527
# have to do this later so we don't mess up the iterator.
528
# since parents may be removed before their children we
531
# FIXME: There's probably a better way to do this; perhaps
532
# the workingtree should know how to filter itself.
533
if work_inv.has_id(file_id):
534
del work_inv[file_id]
537
inv_id = rev_id = _gen_revision_id(time.time())
539
inv_tmp = tempfile.TemporaryFile()
540
inv.write_xml(inv_tmp)
542
self.inventory_store.add(inv_tmp, inv_id)
543
mutter('new inventory_id is {%s}' % inv_id)
545
self._write_inventory(work_inv)
547
if timestamp == None:
548
timestamp = time.time()
550
if committer == None:
551
committer = username()
554
timezone = local_time_offset()
556
mutter("building commit log message")
557
rev = Revision(timestamp=timestamp,
560
precursor = self.last_patch(),
565
rev_tmp = tempfile.TemporaryFile()
566
rev.write_xml(rev_tmp)
568
self.revision_store.add(rev_tmp, rev_id)
569
mutter("new revision_id is {%s}" % rev_id)
571
## XXX: Everything up to here can simply be orphaned if we abort
572
## the commit; it will leave junk files behind but that doesn't
575
## TODO: Read back the just-generated changeset, and make sure it
576
## applies and recreates the right state.
578
## TODO: Also calculate and store the inventory SHA1
579
mutter("committing patch r%d" % (self.revno() + 1))
582
self.append_revision(rev_id)
585
note("commited r%d" % self.revno())
588
def append_revision(self, revision_id):
589
mutter("add {%s} to revision-history" % revision_id)
590
rev_history = self.revision_history()
592
tmprhname = self.controlfilename('revision-history.tmp')
593
rhname = self.controlfilename('revision-history')
595
f = file(tmprhname, 'wt')
596
rev_history.append(revision_id)
597
f.write('\n'.join(rev_history))
601
if sys.platform == 'win32':
603
os.rename(tmprhname, rhname)
698
def append_revision(self, *revision_ids):
699
for revision_id in revision_ids:
700
mutter("add {%s} to revision-history" % revision_id)
703
rev_history = self.revision_history()
704
rev_history.extend(revision_ids)
705
self.put_controlfile('revision-history', '\n'.join(rev_history))
709
def has_revision(self, revision_id):
710
"""True if this branch has a copy of the revision.
712
This does not necessarily imply the revision is merge
713
or on the mainline."""
714
return (revision_id is None
715
or revision_id in self.revision_store)
717
def get_revision_xml_file(self, revision_id):
718
"""Return XML file object for revision object."""
719
if not revision_id or not isinstance(revision_id, basestring):
720
raise InvalidRevisionId(revision_id)
725
return self.revision_store[revision_id]
726
except (IndexError, KeyError):
727
raise bzrlib.errors.NoSuchRevision(self, revision_id)
732
get_revision_xml = get_revision_xml_file
734
def get_revision_xml(self, revision_id):
735
return self.get_revision_xml_file(revision_id).read()
607
738
def get_revision(self, revision_id):
608
739
"""Return the Revision object for a named revision"""
609
r = Revision.read_xml(self.revision_store[revision_id])
740
xml_file = self.get_revision_xml_file(revision_id)
743
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
744
except SyntaxError, e:
745
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
749
assert r.revision_id == revision_id
614
def get_inventory(self, inventory_id):
615
"""Get Inventory object by hash.
617
TODO: Perhaps for this and similar methods, take a revision
618
parameter which can be either an integer revno or a
620
i = Inventory.read_xml(self.inventory_store[inventory_id])
752
def get_revision_delta(self, revno):
753
"""Return the delta for one revision.
755
The delta is relative to its mainline predecessor, or the
756
empty tree for revision 1.
758
assert isinstance(revno, int)
759
rh = self.revision_history()
760
if not (1 <= revno <= len(rh)):
761
raise InvalidRevisionNumber(revno)
763
# revno is 1-based; list is 0-based
765
new_tree = self.revision_tree(rh[revno-1])
767
old_tree = EmptyTree()
769
old_tree = self.revision_tree(rh[revno-2])
771
return compare_trees(old_tree, new_tree)
773
def get_revision_sha1(self, revision_id):
774
"""Hash the stored value of a revision, and return it."""
775
# In the future, revision entries will be signed. At that
776
# point, it is probably best *not* to include the signature
777
# in the revision hash. Because that lets you re-sign
778
# the revision, (add signatures/remove signatures) and still
779
# have all hash pointers stay consistent.
780
# But for now, just hash the contents.
781
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
783
def get_ancestry(self, revision_id):
784
"""Return a list of revision-ids integrated by a revision.
786
This currently returns a list, but the ordering is not guaranteed:
789
if revision_id is None:
791
w = self.control_weaves.get_weave('inventory')
792
return [None] + map(w.idx_to_name,
793
w.inclusions([w.lookup(revision_id)]))
795
def get_inventory_weave(self):
796
return self.control_weaves.get_weave('inventory')
798
def get_inventory(self, revision_id):
799
"""Get Inventory object by hash."""
800
xml = self.get_inventory_xml(revision_id)
801
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
803
def get_inventory_xml(self, revision_id):
804
"""Get inventory XML as a file object."""
806
assert isinstance(revision_id, basestring), type(revision_id)
807
iw = self.get_inventory_weave()
808
return iw.get_text(iw.lookup(revision_id))
810
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
812
def get_inventory_sha1(self, revision_id):
813
"""Return the sha1 hash of the inventory entry
815
return self.get_revision(revision_id).inventory_sha1
624
817
def get_revision_inventory(self, revision_id):
625
818
"""Return inventory of a past revision."""
819
# TODO: Unify this with get_inventory()
820
# bzr 0.0.6 and later imposes the constraint that the inventory_id
821
# must be the same as its revision, so this is trivial.
626
822
if revision_id == None:
823
return Inventory(self.get_root_id())
629
return self.get_inventory(self.get_revision(revision_id).inventory_id)
825
return self.get_inventory(revision_id)
632
827
def revision_history(self):
633
"""Return sequence of revision hashes on to this branch.
828
"""Return sequence of revision hashes on to this branch."""
831
return [l.rstrip('\r\n') for l in
832
self.controlfile('revision-history', 'r').readlines()]
635
>>> ScratchBranch().revision_history()
638
return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
836
def common_ancestor(self, other, self_revno=None, other_revno=None):
838
>>> from bzrlib.commit import commit
839
>>> sb = ScratchBranch(files=['foo', 'foo~'])
840
>>> sb.common_ancestor(sb) == (None, None)
842
>>> commit(sb, "Committing first revision", verbose=False)
843
>>> sb.common_ancestor(sb)[0]
845
>>> clone = sb.clone()
846
>>> commit(sb, "Committing second revision", verbose=False)
847
>>> sb.common_ancestor(sb)[0]
849
>>> sb.common_ancestor(clone)[0]
851
>>> commit(clone, "Committing divergent second revision",
853
>>> sb.common_ancestor(clone)[0]
855
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
857
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
859
>>> clone2 = sb.clone()
860
>>> sb.common_ancestor(clone2)[0]
862
>>> sb.common_ancestor(clone2, self_revno=1)[0]
864
>>> sb.common_ancestor(clone2, other_revno=1)[0]
867
my_history = self.revision_history()
868
other_history = other.revision_history()
869
if self_revno is None:
870
self_revno = len(my_history)
871
if other_revno is None:
872
other_revno = len(other_history)
873
indices = range(min((self_revno, other_revno)))
876
if my_history[r] == other_history[r]:
877
return r+1, my_history[r]
644
884
That is equivalent to the number of revisions committed to
647
>>> b = ScratchBranch()
650
>>> b.commit('no foo')
654
887
return len(self.revision_history())
657
def last_patch(self):
890
def last_revision(self):
658
891
"""Return last patch hash, or None if no history.
660
>>> ScratchBranch().last_patch() == None
663
893
ph = self.revision_history()
900
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
901
"""Return a list of new revisions that would perfectly fit.
670
def lookup_revision(self, revno):
671
"""Return revision hash for revision number."""
903
If self and other have not diverged, return a list of the revisions
904
present in other, but missing from self.
906
>>> from bzrlib.commit import commit
907
>>> bzrlib.trace.silent = True
908
>>> br1 = ScratchBranch()
909
>>> br2 = ScratchBranch()
910
>>> br1.missing_revisions(br2)
912
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
913
>>> br1.missing_revisions(br2)
915
>>> br2.missing_revisions(br1)
917
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
918
>>> br1.missing_revisions(br2)
920
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
921
>>> br1.missing_revisions(br2)
923
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
924
>>> br1.missing_revisions(br2)
925
Traceback (most recent call last):
926
DivergedBranches: These branches have diverged.
928
# FIXME: If the branches have diverged, but the latest
929
# revision in this branch is completely merged into the other,
930
# then we should still be able to pull.
931
self_history = self.revision_history()
932
self_len = len(self_history)
933
other_history = other.revision_history()
934
other_len = len(other_history)
935
common_index = min(self_len, other_len) -1
936
if common_index >= 0 and \
937
self_history[common_index] != other_history[common_index]:
938
raise DivergedBranches(self, other)
940
if stop_revision is None:
941
stop_revision = other_len
943
assert isinstance(stop_revision, int)
944
if stop_revision > other_len:
945
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
946
return other_history[self_len:stop_revision]
948
def update_revisions(self, other, stop_revision=None):
949
"""Pull in new perfect-fit revisions."""
950
from bzrlib.fetch import greedy_fetch
951
from bzrlib.revision import get_intervening_revisions
952
if stop_revision is None:
953
stop_revision = other.last_revision()
954
greedy_fetch(to_branch=self, from_branch=other,
955
revision=stop_revision)
956
pullable_revs = self.missing_revisions(
957
other, other.revision_id_to_revno(stop_revision))
959
greedy_fetch(to_branch=self,
961
revision=pullable_revs[-1])
962
self.append_revision(*pullable_revs)
965
def commit(self, *args, **kw):
966
from bzrlib.commit import Commit
967
Commit().commit(self, *args, **kw)
969
def revision_id_to_revno(self, revision_id):
970
"""Given a revision id, return its revno"""
971
if revision_id is None:
973
history = self.revision_history()
975
return history.index(revision_id) + 1
977
raise bzrlib.errors.NoSuchRevision(self, revision_id)
979
def get_rev_id(self, revno, history=None):
980
"""Find the revision id of the specified revno."""
676
# list is 0-based; revisions are 1-based
677
return self.revision_history()[revno-1]
679
raise BzrError("no such revision %s" % revno)
984
history = self.revision_history()
985
elif revno <= 0 or revno > len(history):
986
raise bzrlib.errors.NoSuchRevision(self, revno)
987
return history[revno - 1]
682
989
def revision_tree(self, revision_id):
683
990
"""Return Tree for a revision on this branch.
685
992
`revision_id` may be None for the null revision, in which case
686
993
an `EmptyTree` is returned."""
994
# TODO: refactor this to use an existing revision object
995
# so we don't need to read it in twice.
688
996
if revision_id == None:
689
997
return EmptyTree()
691
999
inv = self.get_revision_inventory(revision_id)
692
return RevisionTree(self.text_store, inv)
1000
return RevisionTree(self.weave_store, inv, revision_id)
695
1003
def working_tree(self):
696
1004
"""Return a `Tree` for the working copy."""
697
return WorkingTree(self.base, self.read_working_inventory())
1005
from bzrlib.workingtree import WorkingTree
1006
# TODO: In the future, WorkingTree should utilize Transport
1007
# RobertCollins 20051003 - I don't think it should - working trees are
1008
# much more complex to keep consistent than our careful .bzr subset.
1009
# instead, we should say that working trees are local only, and optimise
1011
return WorkingTree(self._transport.base, self.read_working_inventory())
700
1014
def basis_tree(self):
701
1015
"""Return `Tree` object for last revision.
703
1017
If there are no revisions yet, return an `EmptyTree`.
705
>>> b = ScratchBranch(files=['foo'])
706
>>> b.basis_tree().has_filename('foo')
708
>>> b.working_tree().has_filename('foo')
711
>>> b.commit('add foo')
712
>>> b.basis_tree().has_filename('foo')
715
r = self.last_patch()
719
return RevisionTree(self.text_store, self.get_revision_inventory(r))
723
def write_log(self, show_timezone='original', verbose=False):
724
"""Write out human-readable log of commits to this branch
726
utc -- If true, show dates in universal time, not local time."""
727
## TODO: Option to choose either original, utc or local timezone
730
for p in self.revision_history():
732
print 'revno:', revno
733
## TODO: Show hash if --id is given.
734
##print 'revision-hash:', p
735
rev = self.get_revision(p)
736
print 'committer:', rev.committer
737
print 'timestamp: %s' % (format_date(rev.timestamp, rev.timezone or 0,
740
## opportunistic consistency check, same as check_patch_chaining
741
if rev.precursor != precursor:
742
bailout("mismatched precursor!")
746
print ' (no message)'
748
for l in rev.message.split('\n'):
751
if verbose == True and precursor != None:
752
print 'changed files:'
753
tree = self.revision_tree(p)
754
prevtree = self.revision_tree(precursor)
756
for file_state, fid, old_name, new_name, kind in \
757
diff_trees(prevtree, tree, ):
758
if file_state == 'A' or file_state == 'M':
759
show_status(file_state, kind, new_name)
760
elif file_state == 'D':
761
show_status(file_state, kind, old_name)
762
elif file_state == 'R':
763
show_status(file_state, kind,
764
old_name + ' => ' + new_name)
1019
return self.revision_tree(self.last_revision())
770
1022
def rename_one(self, from_rel, to_rel):
771
1023
"""Rename one file.
773
1025
This can change the directory or the filename or both.
775
tree = self.working_tree()
777
if not tree.has_filename(from_rel):
778
bailout("can't rename: old working file %r does not exist" % from_rel)
779
if tree.has_filename(to_rel):
780
bailout("can't rename: new working file %r already exists" % to_rel)
782
file_id = inv.path2id(from_rel)
784
bailout("can't rename: old name %r is not versioned" % from_rel)
786
if inv.path2id(to_rel):
787
bailout("can't rename: new name %r is already versioned" % to_rel)
789
to_dir, to_tail = os.path.split(to_rel)
790
to_dir_id = inv.path2id(to_dir)
791
if to_dir_id == None and to_dir != '':
792
bailout("can't determine destination directory id for %r" % to_dir)
794
mutter("rename_one:")
795
mutter(" file_id {%s}" % file_id)
796
mutter(" from_rel %r" % from_rel)
797
mutter(" to_rel %r" % to_rel)
798
mutter(" to_dir %r" % to_dir)
799
mutter(" to_dir_id {%s}" % to_dir_id)
801
inv.rename(file_id, to_dir_id, to_tail)
803
print "%s => %s" % (from_rel, to_rel)
805
from_abs = self.abspath(from_rel)
806
to_abs = self.abspath(to_rel)
808
os.rename(from_abs, to_abs)
810
bailout("failed to rename %r to %r: %s"
811
% (from_abs, to_abs, e[1]),
812
["rename rolled back"])
814
self._write_inventory(inv)
1029
tree = self.working_tree()
1030
inv = tree.inventory
1031
if not tree.has_filename(from_rel):
1032
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1033
if tree.has_filename(to_rel):
1034
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1036
file_id = inv.path2id(from_rel)
1038
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1040
if inv.path2id(to_rel):
1041
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1043
to_dir, to_tail = os.path.split(to_rel)
1044
to_dir_id = inv.path2id(to_dir)
1045
if to_dir_id == None and to_dir != '':
1046
raise BzrError("can't determine destination directory id for %r" % to_dir)
1048
mutter("rename_one:")
1049
mutter(" file_id {%s}" % file_id)
1050
mutter(" from_rel %r" % from_rel)
1051
mutter(" to_rel %r" % to_rel)
1052
mutter(" to_dir %r" % to_dir)
1053
mutter(" to_dir_id {%s}" % to_dir_id)
1055
inv.rename(file_id, to_dir_id, to_tail)
1057
from_abs = self.abspath(from_rel)
1058
to_abs = self.abspath(to_rel)
1060
rename(from_abs, to_abs)
1062
raise BzrError("failed to rename %r to %r: %s"
1063
% (from_abs, to_abs, e[1]),
1064
["rename rolled back"])
1066
self._write_inventory(inv)
818
1071
def move(self, from_paths, to_name):
826
1079
Note that to_name is only the last component of the new name;
827
1080
this doesn't change the directory.
829
## TODO: Option to move IDs only
830
assert not isinstance(from_paths, basestring)
831
tree = self.working_tree()
833
to_abs = self.abspath(to_name)
834
if not isdir(to_abs):
835
bailout("destination %r is not a directory" % to_abs)
836
if not tree.has_filename(to_name):
837
bailout("destination %r not in working directory" % to_abs)
838
to_dir_id = inv.path2id(to_name)
839
if to_dir_id == None and to_name != '':
840
bailout("destination %r is not a versioned directory" % to_name)
841
to_dir_ie = inv[to_dir_id]
842
if to_dir_ie.kind not in ('directory', 'root_directory'):
843
bailout("destination %r is not a directory" % to_abs)
845
to_idpath = Set(inv.get_idpath(to_dir_id))
848
if not tree.has_filename(f):
849
bailout("%r does not exist in working tree" % f)
850
f_id = inv.path2id(f)
852
bailout("%r is not versioned" % f)
853
name_tail = splitpath(f)[-1]
854
dest_path = appendpath(to_name, name_tail)
855
if tree.has_filename(dest_path):
856
bailout("destination %r already exists" % dest_path)
857
if f_id in to_idpath:
858
bailout("can't move %r to a subdirectory of itself" % f)
860
# OK, so there's a race here, it's possible that someone will
861
# create a file in this interval and then the rename might be
862
# left half-done. But we should have caught most problems.
865
name_tail = splitpath(f)[-1]
866
dest_path = appendpath(to_name, name_tail)
867
print "%s => %s" % (f, dest_path)
868
inv.rename(inv.path2id(f), to_dir_id, name_tail)
870
os.rename(self.abspath(f), self.abspath(dest_path))
872
bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
873
["rename rolled back"])
875
self._write_inventory(inv)
879
def show_status(self, show_all=False):
880
"""Display single-line status for non-ignored working files.
882
The list is show sorted in order by file name.
884
>>> b = ScratchBranch(files=['foo', 'foo~'])
890
>>> b.commit("add foo")
892
>>> os.unlink(b.abspath('foo'))
896
TODO: Get state for single files.
899
# We have to build everything into a list first so that it can
900
# sorted by name, incorporating all the different sources.
902
# FIXME: Rather than getting things in random order and then sorting,
903
# just step through in order.
905
# Interesting case: the old ID for a file has been removed,
906
# but a new file has been created under that name.
908
old = self.basis_tree()
909
new = self.working_tree()
911
for fs, fid, oldname, newname, kind in diff_trees(old, new):
913
show_status(fs, kind,
914
oldname + ' => ' + newname)
915
elif fs == 'A' or fs == 'M':
916
show_status(fs, kind, newname)
918
show_status(fs, kind, oldname)
921
show_status(fs, kind, newname)
924
show_status(fs, kind, newname)
926
show_status(fs, kind, newname)
928
bailout("weird file state %r" % ((fs, fid),))
932
class ScratchBranch(Branch):
1082
This returns a list of (from_path, to_path) pairs for each
1083
entry that is moved.
1088
## TODO: Option to move IDs only
1089
assert not isinstance(from_paths, basestring)
1090
tree = self.working_tree()
1091
inv = tree.inventory
1092
to_abs = self.abspath(to_name)
1093
if not isdir(to_abs):
1094
raise BzrError("destination %r is not a directory" % to_abs)
1095
if not tree.has_filename(to_name):
1096
raise BzrError("destination %r not in working directory" % to_abs)
1097
to_dir_id = inv.path2id(to_name)
1098
if to_dir_id == None and to_name != '':
1099
raise BzrError("destination %r is not a versioned directory" % to_name)
1100
to_dir_ie = inv[to_dir_id]
1101
if to_dir_ie.kind not in ('directory', 'root_directory'):
1102
raise BzrError("destination %r is not a directory" % to_abs)
1104
to_idpath = inv.get_idpath(to_dir_id)
1106
for f in from_paths:
1107
if not tree.has_filename(f):
1108
raise BzrError("%r does not exist in working tree" % f)
1109
f_id = inv.path2id(f)
1111
raise BzrError("%r is not versioned" % f)
1112
name_tail = splitpath(f)[-1]
1113
dest_path = appendpath(to_name, name_tail)
1114
if tree.has_filename(dest_path):
1115
raise BzrError("destination %r already exists" % dest_path)
1116
if f_id in to_idpath:
1117
raise BzrError("can't move %r to a subdirectory of itself" % f)
1119
# OK, so there's a race here, it's possible that someone will
1120
# create a file in this interval and then the rename might be
1121
# left half-done. But we should have caught most problems.
1123
for f in from_paths:
1124
name_tail = splitpath(f)[-1]
1125
dest_path = appendpath(to_name, name_tail)
1126
result.append((f, dest_path))
1127
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1129
rename(self.abspath(f), self.abspath(dest_path))
1131
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1132
["rename rolled back"])
1134
self._write_inventory(inv)
1141
def revert(self, filenames, old_tree=None, backups=True):
1142
"""Restore selected files to the versions from a previous tree.
1145
If true (default) backups are made of files before
1148
from bzrlib.errors import NotVersionedError, BzrError
1149
from bzrlib.atomicfile import AtomicFile
1150
from bzrlib.osutils import backup_file
1152
inv = self.read_working_inventory()
1153
if old_tree is None:
1154
old_tree = self.basis_tree()
1155
old_inv = old_tree.inventory
1158
for fn in filenames:
1159
file_id = inv.path2id(fn)
1161
raise NotVersionedError("not a versioned file", fn)
1162
if not old_inv.has_id(file_id):
1163
raise BzrError("file not present in old tree", fn, file_id)
1164
nids.append((fn, file_id))
1166
# TODO: Rename back if it was previously at a different location
1168
# TODO: If given a directory, restore the entire contents from
1169
# the previous version.
1171
# TODO: Make a backup to a temporary file.
1173
# TODO: If the file previously didn't exist, delete it?
1174
for fn, file_id in nids:
1177
f = AtomicFile(fn, 'wb')
1179
f.write(old_tree.get_file(file_id).read())
1185
def pending_merges(self):
1186
"""Return a list of pending merges.
1188
These are revisions that have been merged into the working
1189
directory but not yet committed.
1191
cfn = self._rel_controlfilename('pending-merges')
1192
if not self._transport.has(cfn):
1195
for l in self.controlfile('pending-merges', 'r').readlines():
1196
p.append(l.rstrip('\n'))
1200
def add_pending_merge(self, *revision_ids):
1201
# TODO: Perhaps should check at this point that the
1202
# history of the revision is actually present?
1203
p = self.pending_merges()
1205
for rev_id in revision_ids:
1211
self.set_pending_merges(p)
1213
def set_pending_merges(self, rev_list):
1216
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1221
def get_parent(self):
1222
"""Return the parent location of the branch.
1224
This is the default location for push/pull/missing. The usual
1225
pattern is that the user can override it by specifying a
1229
_locs = ['parent', 'pull', 'x-pull']
1232
return self.controlfile(l, 'r').read().strip('\n')
1234
if e.errno != errno.ENOENT:
1239
def set_parent(self, url):
1240
# TODO: Maybe delete old location files?
1241
from bzrlib.atomicfile import AtomicFile
1244
f = AtomicFile(self.controlfilename('parent'))
1253
def check_revno(self, revno):
1255
Check whether a revno corresponds to any revision.
1256
Zero (the NULL revision) is considered valid.
1259
self.check_real_revno(revno)
1261
def check_real_revno(self, revno):
1263
Check whether a revno corresponds to a real revision.
1264
Zero (the NULL revision) is considered invalid
1266
if revno < 1 or revno > self.revno():
1267
raise InvalidRevisionNumber(revno)
1273
class ScratchBranch(_Branch):
933
1274
"""Special test class: a branch that cleans up after itself.
935
1276
>>> b = ScratchBranch()
936
1277
>>> isdir(b.base)
943
def __init__(self, files=[], dirs=[]):
1284
def __init__(self, files=[], dirs=[], base=None):
944
1285
"""Make a test branch.
946
1287
This creates a temporary directory and runs init-tree in it.
948
1289
If any files are listed, they are created in the working copy.
950
Branch.__init__(self, tempfile.mkdtemp(), init=True)
1291
from tempfile import mkdtemp
1296
if isinstance(base, basestring):
1297
base = get_transport(base)
1298
_Branch.__init__(self, base, init=init)
952
os.mkdir(self.abspath(d))
1300
self._transport.mkdir(d)
955
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1303
self._transport.put(f, 'content of %s' % f)
1308
>>> orig = ScratchBranch(files=["file1", "file2"])
1309
>>> clone = orig.clone()
1310
>>> if os.name != 'nt':
1311
... os.path.samefile(orig.base, clone.base)
1313
... orig.base == clone.base
1316
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1319
from shutil import copytree
1320
from tempfile import mkdtemp
1323
copytree(self.base, base, symlinks=True)
1324
return ScratchBranch(base=base)
958
1326
def __del__(self):
959
1330
"""Destroy the test branch, removing the scratch directory."""
1331
from shutil import rmtree
961
shutil.rmtree(self.base)
1334
mutter("delete ScratchBranch %s" % self.base)
963
1337
# Work around for shutil.rmtree failing on Windows when
964
1338
# readonly files are encountered
1339
mutter("hit exception in destroying ScratchBranch: %s" % e)
965
1340
for root, dirs, files in os.walk(self.base, topdown=False):
966
1341
for name in files:
967
1342
os.chmod(os.path.join(root, name), 0700)
968
shutil.rmtree(self.base)
1344
self._transport = None