/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-09-22 05:18:24 UTC
  • Revision ID: mbp@sourcefrog.net-20050922051824-263a54b20d3c54a4
- store control weaves in .bzr/, not mixed in with file weaves

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
 
 
18
import sys
 
19
import os
 
20
from cStringIO import StringIO
 
21
 
 
22
import bzrlib
 
23
from bzrlib.trace import mutter, note
 
24
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
 
25
     splitpath, \
 
26
     sha_file, appendpath, file_kind
 
27
 
 
28
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
29
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
30
                           LockError)
 
31
from bzrlib.textui import show_status
 
32
from bzrlib.revision import Revision, validate_revision_id
 
33
from bzrlib.delta import compare_trees
 
34
from bzrlib.tree import EmptyTree, RevisionTree
 
35
from bzrlib.inventory import Inventory
 
36
from bzrlib.weavestore import WeaveStore
 
37
from bzrlib.store import ImmutableStore
 
38
import bzrlib.xml5
 
39
import bzrlib.ui
 
40
 
 
41
 
 
42
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
43
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
44
## TODO: Maybe include checks for common corruption of newlines, etc?
 
45
 
 
46
 
 
47
# TODO: Some operations like log might retrieve the same revisions
 
48
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
49
# cache in memory to make this faster.  In general anything can be
 
50
# cached in memory between lock and unlock operations.
 
51
 
 
52
# TODO: please move the revision-string syntax stuff out of the branch
 
53
# object; it's clutter
 
54
 
 
55
 
 
56
def find_branch(f, **args):
 
57
    if f and (f.startswith('http://') or f.startswith('https://')):
 
58
        import remotebranch 
 
59
        return remotebranch.RemoteBranch(f, **args)
 
60
    else:
 
61
        return Branch(f, **args)
 
62
 
 
63
 
 
64
def find_cached_branch(f, cache_root, **args):
 
65
    from remotebranch import RemoteBranch
 
66
    br = find_branch(f, **args)
 
67
    def cacheify(br, store_name):
 
68
        from meta_store import CachedStore
 
69
        cache_path = os.path.join(cache_root, store_name)
 
70
        os.mkdir(cache_path)
 
71
        new_store = CachedStore(getattr(br, store_name), cache_path)
 
72
        setattr(br, store_name, new_store)
 
73
 
 
74
    if isinstance(br, RemoteBranch):
 
75
        cacheify(br, 'inventory_store')
 
76
        cacheify(br, 'text_store')
 
77
        cacheify(br, 'revision_store')
 
78
    return br
 
79
 
 
80
 
 
81
def _relpath(base, path):
 
82
    """Return path relative to base, or raise exception.
 
83
 
 
84
    The path may be either an absolute path or a path relative to the
 
85
    current working directory.
 
86
 
 
87
    Lifted out of Branch.relpath for ease of testing.
 
88
 
 
89
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
90
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
91
    avoids that problem."""
 
92
    rp = os.path.abspath(path)
 
93
 
 
94
    s = []
 
95
    head = rp
 
96
    while len(head) >= len(base):
 
97
        if head == base:
 
98
            break
 
99
        head, tail = os.path.split(head)
 
100
        if tail:
 
101
            s.insert(0, tail)
 
102
    else:
 
103
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
 
104
 
 
105
    return os.sep.join(s)
 
106
        
 
107
 
 
108
def find_branch_root(f=None):
 
109
    """Find the branch root enclosing f, or pwd.
 
110
 
 
111
    f may be a filename or a URL.
 
112
 
 
113
    It is not necessary that f exists.
 
114
 
 
115
    Basically we keep looking up until we find the control directory or
 
116
    run into the root.  If there isn't one, raises NotBranchError.
 
117
    """
 
118
    if f == None:
 
119
        f = os.getcwd()
 
120
    elif hasattr(os.path, 'realpath'):
 
121
        f = os.path.realpath(f)
 
122
    else:
 
123
        f = os.path.abspath(f)
 
124
    if not os.path.exists(f):
 
125
        raise BzrError('%r does not exist' % f)
 
126
        
 
127
 
 
128
    orig_f = f
 
129
 
 
130
    while True:
 
131
        if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
 
132
            return f
 
133
        head, tail = os.path.split(f)
 
134
        if head == f:
 
135
            # reached the root, whatever that may be
 
136
            raise NotBranchError('%s is not in a branch' % orig_f)
 
137
        f = head
 
138
 
 
139
 
 
140
 
 
141
# XXX: move into bzrlib.errors; subclass BzrError    
 
142
class DivergedBranches(Exception):
 
143
    def __init__(self, branch1, branch2):
 
144
        self.branch1 = branch1
 
145
        self.branch2 = branch2
 
146
        Exception.__init__(self, "These branches have diverged.")
 
147
 
 
148
 
 
149
######################################################################
 
150
# branch objects
 
151
 
 
152
class Branch(object):
 
153
    """Branch holding a history of revisions.
 
154
 
 
155
    base
 
156
        Base directory of the branch.
 
157
 
 
158
    _lock_mode
 
159
        None, or 'r' or 'w'
 
160
 
 
161
    _lock_count
 
162
        If _lock_mode is true, a positive count of the number of times the
 
163
        lock has been taken.
 
164
 
 
165
    _lock
 
166
        Lock object from bzrlib.lock.
 
167
    """
 
168
    base = None
 
169
    _lock_mode = None
 
170
    _lock_count = None
 
171
    _lock = None
 
172
    _inventory_weave = None
 
173
    
 
174
    # Map some sort of prefix into a namespace
 
175
    # stuff like "revno:10", "revid:", etc.
 
176
    # This should match a prefix with a function which accepts
 
177
    REVISION_NAMESPACES = {}
 
178
 
 
179
    def __init__(self, base, init=False, find_root=True,
 
180
                 relax_version_check=False):
 
181
        """Create new branch object at a particular location.
 
182
 
 
183
        base -- Base directory for the branch.
 
184
        
 
185
        init -- If True, create new control files in a previously
 
186
             unversioned directory.  If False, the branch must already
 
187
             be versioned.
 
188
 
 
189
        find_root -- If true and init is false, find the root of the
 
190
             existing branch containing base.
 
191
 
 
192
        relax_version_check -- If true, the usual check for the branch
 
193
            version is not applied.  This is intended only for
 
194
            upgrade/recovery type use; it's not guaranteed that
 
195
            all operations will work on old format branches.
 
196
 
 
197
        In the test suite, creation of new trees is tested using the
 
198
        `ScratchBranch` class.
 
199
        """
 
200
        if init:
 
201
            self.base = os.path.realpath(base)
 
202
            self._make_control()
 
203
        elif find_root:
 
204
            self.base = find_branch_root(base)
 
205
        else:
 
206
            self.base = os.path.realpath(base)
 
207
            if not isdir(self.controlfilename('.')):
 
208
                raise NotBranchError('not a bzr branch: %s' % quotefn(base),
 
209
                                     ['use "bzr init" to initialize a '
 
210
                                      'new working tree'])
 
211
        self._check_format(relax_version_check)
 
212
        cfn = self.controlfilename
 
213
        if self._branch_format == 4:
 
214
            self.inventory_store = ImmutableStore(cfn('inventory-store'))
 
215
            self.text_store = ImmutableStore(cfn('text-store'))
 
216
        elif self._branch_format == 5:
 
217
            self.control_weaves = WeaveStore(cfn([]))
 
218
            self.weave_store = WeaveStore(cfn('weaves'))
 
219
        self.revision_store = ImmutableStore(cfn('revision-store'))
 
220
 
 
221
 
 
222
    def __str__(self):
 
223
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
224
 
 
225
 
 
226
    __repr__ = __str__
 
227
 
 
228
 
 
229
    def __del__(self):
 
230
        if self._lock_mode or self._lock:
 
231
            from warnings import warn
 
232
            warn("branch %r was not explicitly unlocked" % self)
 
233
            self._lock.unlock()
 
234
 
 
235
 
 
236
    def lock_write(self):
 
237
        if self._lock_mode:
 
238
            if self._lock_mode != 'w':
 
239
                raise LockError("can't upgrade to a write lock from %r" %
 
240
                                self._lock_mode)
 
241
            self._lock_count += 1
 
242
        else:
 
243
            from bzrlib.lock import WriteLock
 
244
 
 
245
            self._lock = WriteLock(self.controlfilename('branch-lock'))
 
246
            self._lock_mode = 'w'
 
247
            self._lock_count = 1
 
248
 
 
249
 
 
250
    def lock_read(self):
 
251
        if self._lock_mode:
 
252
            assert self._lock_mode in ('r', 'w'), \
 
253
                   "invalid lock mode %r" % self._lock_mode
 
254
            self._lock_count += 1
 
255
        else:
 
256
            from bzrlib.lock import ReadLock
 
257
 
 
258
            self._lock = ReadLock(self.controlfilename('branch-lock'))
 
259
            self._lock_mode = 'r'
 
260
            self._lock_count = 1
 
261
                        
 
262
    def unlock(self):
 
263
        if not self._lock_mode:
 
264
            raise LockError('branch %r is not locked' % (self))
 
265
 
 
266
        if self._lock_count > 1:
 
267
            self._lock_count -= 1
 
268
        else:
 
269
            self._lock.unlock()
 
270
            self._lock = None
 
271
            self._lock_mode = self._lock_count = None
 
272
 
 
273
    def abspath(self, name):
 
274
        """Return absolute filename for something in the branch"""
 
275
        return os.path.join(self.base, name)
 
276
 
 
277
    def relpath(self, path):
 
278
        """Return path relative to this branch of something inside it.
 
279
 
 
280
        Raises an error if path is not in this branch."""
 
281
        return _relpath(self.base, path)
 
282
 
 
283
    def controlfilename(self, file_or_path):
 
284
        """Return location relative to branch."""
 
285
        if isinstance(file_or_path, basestring):
 
286
            file_or_path = [file_or_path]
 
287
        return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
 
288
 
 
289
 
 
290
    def controlfile(self, file_or_path, mode='r'):
 
291
        """Open a control file for this branch.
 
292
 
 
293
        There are two classes of file in the control directory: text
 
294
        and binary.  binary files are untranslated byte streams.  Text
 
295
        control files are stored with Unix newlines and in UTF-8, even
 
296
        if the platform or locale defaults are different.
 
297
 
 
298
        Controlfiles should almost never be opened in write mode but
 
299
        rather should be atomically copied and replaced using atomicfile.
 
300
        """
 
301
 
 
302
        fn = self.controlfilename(file_or_path)
 
303
 
 
304
        if mode == 'rb' or mode == 'wb':
 
305
            return file(fn, mode)
 
306
        elif mode == 'r' or mode == 'w':
 
307
            # open in binary mode anyhow so there's no newline translation;
 
308
            # codecs uses line buffering by default; don't want that.
 
309
            import codecs
 
310
            return codecs.open(fn, mode + 'b', 'utf-8',
 
311
                               buffering=60000)
 
312
        else:
 
313
            raise BzrError("invalid controlfile mode %r" % mode)
 
314
 
 
315
    def _make_control(self):
 
316
        os.mkdir(self.controlfilename([]))
 
317
        self.controlfile('README', 'w').write(
 
318
            "This is a Bazaar-NG control directory.\n"
 
319
            "Do not change any files in this directory.\n")
 
320
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
321
        for d in ('text-store', 'revision-store',
 
322
                  'weaves'):
 
323
            os.mkdir(self.controlfilename(d))
 
324
        for f in ('revision-history', 'merged-patches',
 
325
                  'pending-merged-patches', 'branch-name',
 
326
                  'branch-lock',
 
327
                  'pending-merges'):
 
328
            self.controlfile(f, 'w').write('')
 
329
        mutter('created control directory in ' + self.base)
 
330
 
 
331
        # if we want per-tree root ids then this is the place to set
 
332
        # them; they're not needed for now and so ommitted for
 
333
        # simplicity.
 
334
        f = self.controlfile('inventory','w')
 
335
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
336
        
 
337
 
 
338
 
 
339
    def _check_format(self, relax_version_check):
 
340
        """Check this branch format is supported.
 
341
 
 
342
        The format level is stored, as an integer, in
 
343
        self._branch_format for code that needs to check it later.
 
344
 
 
345
        In the future, we might need different in-memory Branch
 
346
        classes to support downlevel branches.  But not yet.
 
347
        """
 
348
        fmt = self.controlfile('branch-format', 'r').read()
 
349
        if fmt == BZR_BRANCH_FORMAT_5:
 
350
            self._branch_format = 5
 
351
        elif fmt == BZR_BRANCH_FORMAT_4:
 
352
            self._branch_format = 4
 
353
 
 
354
        if (not relax_version_check
 
355
            and self._branch_format != 5):
 
356
            raise BzrError('sorry, branch format "%s" not supported; ' 
 
357
                           'use a different bzr version, '
 
358
                           'or run "bzr upgrade"'
 
359
                           % fmt.rstrip('\n\r'))
 
360
        
 
361
 
 
362
    def get_root_id(self):
 
363
        """Return the id of this branches root"""
 
364
        inv = self.read_working_inventory()
 
365
        return inv.root.file_id
 
366
 
 
367
    def set_root_id(self, file_id):
 
368
        inv = self.read_working_inventory()
 
369
        orig_root_id = inv.root.file_id
 
370
        del inv._byid[inv.root.file_id]
 
371
        inv.root.file_id = file_id
 
372
        inv._byid[inv.root.file_id] = inv.root
 
373
        for fid in inv:
 
374
            entry = inv[fid]
 
375
            if entry.parent_id in (None, orig_root_id):
 
376
                entry.parent_id = inv.root.file_id
 
377
        self._write_inventory(inv)
 
378
 
 
379
    def read_working_inventory(self):
 
380
        """Read the working inventory."""
 
381
        self.lock_read()
 
382
        try:
 
383
            # ElementTree does its own conversion from UTF-8, so open in
 
384
            # binary.
 
385
            f = self.controlfile('inventory', 'rb')
 
386
            return bzrlib.xml5.serializer_v5.read_inventory(f)
 
387
        finally:
 
388
            self.unlock()
 
389
            
 
390
 
 
391
    def _write_inventory(self, inv):
 
392
        """Update the working inventory.
 
393
 
 
394
        That is to say, the inventory describing changes underway, that
 
395
        will be committed to the next revision.
 
396
        """
 
397
        from bzrlib.atomicfile import AtomicFile
 
398
        
 
399
        self.lock_write()
 
400
        try:
 
401
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
 
402
            try:
 
403
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
 
404
                f.commit()
 
405
            finally:
 
406
                f.close()
 
407
        finally:
 
408
            self.unlock()
 
409
        
 
410
        mutter('wrote working inventory')
 
411
            
 
412
 
 
413
    inventory = property(read_working_inventory, _write_inventory, None,
 
414
                         """Inventory for the working copy.""")
 
415
 
 
416
 
 
417
    def add(self, files, ids=None):
 
418
        """Make files versioned.
 
419
 
 
420
        Note that the command line normally calls smart_add instead,
 
421
        which can automatically recurse.
 
422
 
 
423
        This puts the files in the Added state, so that they will be
 
424
        recorded by the next commit.
 
425
 
 
426
        files
 
427
            List of paths to add, relative to the base of the tree.
 
428
 
 
429
        ids
 
430
            If set, use these instead of automatically generated ids.
 
431
            Must be the same length as the list of files, but may
 
432
            contain None for ids that are to be autogenerated.
 
433
 
 
434
        TODO: Perhaps have an option to add the ids even if the files do
 
435
              not (yet) exist.
 
436
 
 
437
        TODO: Perhaps yield the ids and paths as they're added.
 
438
        """
 
439
        # TODO: Re-adding a file that is removed in the working copy
 
440
        # should probably put it back with the previous ID.
 
441
        if isinstance(files, basestring):
 
442
            assert(ids is None or isinstance(ids, basestring))
 
443
            files = [files]
 
444
            if ids is not None:
 
445
                ids = [ids]
 
446
 
 
447
        if ids is None:
 
448
            ids = [None] * len(files)
 
449
        else:
 
450
            assert(len(ids) == len(files))
 
451
 
 
452
        self.lock_write()
 
453
        try:
 
454
            inv = self.read_working_inventory()
 
455
            for f,file_id in zip(files, ids):
 
456
                if is_control_file(f):
 
457
                    raise BzrError("cannot add control file %s" % quotefn(f))
 
458
 
 
459
                fp = splitpath(f)
 
460
 
 
461
                if len(fp) == 0:
 
462
                    raise BzrError("cannot add top-level %r" % f)
 
463
 
 
464
                fullpath = os.path.normpath(self.abspath(f))
 
465
 
 
466
                try:
 
467
                    kind = file_kind(fullpath)
 
468
                except OSError:
 
469
                    # maybe something better?
 
470
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
471
 
 
472
                if kind != 'file' and kind != 'directory':
 
473
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
474
 
 
475
                if file_id is None:
 
476
                    file_id = gen_file_id(f)
 
477
                inv.add_path(f, kind=kind, file_id=file_id)
 
478
 
 
479
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
480
 
 
481
            self._write_inventory(inv)
 
482
        finally:
 
483
            self.unlock()
 
484
            
 
485
 
 
486
    def print_file(self, file, revno):
 
487
        """Print `file` to stdout."""
 
488
        self.lock_read()
 
489
        try:
 
490
            tree = self.revision_tree(self.lookup_revision(revno))
 
491
            # use inventory as it was in that revision
 
492
            file_id = tree.inventory.path2id(file)
 
493
            if not file_id:
 
494
                raise BzrError("%r is not present in revision %s" % (file, revno))
 
495
            tree.print_file(file_id)
 
496
        finally:
 
497
            self.unlock()
 
498
 
 
499
 
 
500
    def remove(self, files, verbose=False):
 
501
        """Mark nominated files for removal from the inventory.
 
502
 
 
503
        This does not remove their text.  This does not run on 
 
504
 
 
505
        TODO: Refuse to remove modified files unless --force is given?
 
506
 
 
507
        TODO: Do something useful with directories.
 
508
 
 
509
        TODO: Should this remove the text or not?  Tough call; not
 
510
        removing may be useful and the user can just use use rm, and
 
511
        is the opposite of add.  Removing it is consistent with most
 
512
        other tools.  Maybe an option.
 
513
        """
 
514
        ## TODO: Normalize names
 
515
        ## TODO: Remove nested loops; better scalability
 
516
        if isinstance(files, basestring):
 
517
            files = [files]
 
518
 
 
519
        self.lock_write()
 
520
 
 
521
        try:
 
522
            tree = self.working_tree()
 
523
            inv = tree.inventory
 
524
 
 
525
            # do this before any modifications
 
526
            for f in files:
 
527
                fid = inv.path2id(f)
 
528
                if not fid:
 
529
                    raise BzrError("cannot remove unversioned file %s" % quotefn(f))
 
530
                mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
531
                if verbose:
 
532
                    # having remove it, it must be either ignored or unknown
 
533
                    if tree.is_ignored(f):
 
534
                        new_status = 'I'
 
535
                    else:
 
536
                        new_status = '?'
 
537
                    show_status(new_status, inv[fid].kind, quotefn(f))
 
538
                del inv[fid]
 
539
 
 
540
            self._write_inventory(inv)
 
541
        finally:
 
542
            self.unlock()
 
543
 
 
544
 
 
545
    # FIXME: this doesn't need to be a branch method
 
546
    def set_inventory(self, new_inventory_list):
 
547
        from bzrlib.inventory import Inventory, InventoryEntry
 
548
        inv = Inventory(self.get_root_id())
 
549
        for path, file_id, parent, kind in new_inventory_list:
 
550
            name = os.path.basename(path)
 
551
            if name == "":
 
552
                continue
 
553
            inv.add(InventoryEntry(file_id, name, kind, parent))
 
554
        self._write_inventory(inv)
 
555
 
 
556
 
 
557
    def unknowns(self):
 
558
        """Return all unknown files.
 
559
 
 
560
        These are files in the working directory that are not versioned or
 
561
        control files or ignored.
 
562
        
 
563
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
564
        >>> list(b.unknowns())
 
565
        ['foo']
 
566
        >>> b.add('foo')
 
567
        >>> list(b.unknowns())
 
568
        []
 
569
        >>> b.remove('foo')
 
570
        >>> list(b.unknowns())
 
571
        ['foo']
 
572
        """
 
573
        return self.working_tree().unknowns()
 
574
 
 
575
 
 
576
    def append_revision(self, *revision_ids):
 
577
        from bzrlib.atomicfile import AtomicFile
 
578
 
 
579
        for revision_id in revision_ids:
 
580
            mutter("add {%s} to revision-history" % revision_id)
 
581
 
 
582
        rev_history = self.revision_history()
 
583
        rev_history.extend(revision_ids)
 
584
 
 
585
        f = AtomicFile(self.controlfilename('revision-history'))
 
586
        try:
 
587
            for rev_id in rev_history:
 
588
                print >>f, rev_id
 
589
            f.commit()
 
590
        finally:
 
591
            f.close()
 
592
 
 
593
 
 
594
    def has_revision(self, revision_id):
 
595
        """True if this branch has a copy of the revision.
 
596
 
 
597
        This does not necessarily imply the revision is merge
 
598
        or on the mainline."""
 
599
        return revision_id in self.revision_store
 
600
 
 
601
 
 
602
    def get_revision_xml_file(self, revision_id):
 
603
        """Return XML file object for revision object."""
 
604
        if not revision_id or not isinstance(revision_id, basestring):
 
605
            raise InvalidRevisionId(revision_id)
 
606
 
 
607
        self.lock_read()
 
608
        try:
 
609
            try:
 
610
                return self.revision_store[revision_id]
 
611
            except IndexError:
 
612
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
613
        finally:
 
614
            self.unlock()
 
615
 
 
616
 
 
617
    def get_revision_xml(self, revision_id):
 
618
        return self.get_revision_xml_file(revision_id).read()
 
619
 
 
620
 
 
621
    def get_revision(self, revision_id):
 
622
        """Return the Revision object for a named revision"""
 
623
        xml_file = self.get_revision_xml_file(revision_id)
 
624
 
 
625
        try:
 
626
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
 
627
        except SyntaxError, e:
 
628
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
629
                                         [revision_id,
 
630
                                          str(e)])
 
631
            
 
632
        assert r.revision_id == revision_id
 
633
        return r
 
634
 
 
635
 
 
636
    def get_revision_delta(self, revno):
 
637
        """Return the delta for one revision.
 
638
 
 
639
        The delta is relative to its mainline predecessor, or the
 
640
        empty tree for revision 1.
 
641
        """
 
642
        assert isinstance(revno, int)
 
643
        rh = self.revision_history()
 
644
        if not (1 <= revno <= len(rh)):
 
645
            raise InvalidRevisionNumber(revno)
 
646
 
 
647
        # revno is 1-based; list is 0-based
 
648
 
 
649
        new_tree = self.revision_tree(rh[revno-1])
 
650
        if revno == 1:
 
651
            old_tree = EmptyTree()
 
652
        else:
 
653
            old_tree = self.revision_tree(rh[revno-2])
 
654
 
 
655
        return compare_trees(old_tree, new_tree)
 
656
 
 
657
        
 
658
 
 
659
    def get_revision_sha1(self, revision_id):
 
660
        """Hash the stored value of a revision, and return it."""
 
661
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
662
 
 
663
 
 
664
    def _get_ancestry_weave(self):
 
665
        return self.control_weaves.get_weave('ancestry')
 
666
        
 
667
 
 
668
    def get_ancestry(self, revision_id):
 
669
        """Return a list of revision-ids integrated by a revision.
 
670
        """
 
671
        # strip newlines
 
672
        w = self._get_ancestry_weave()
 
673
        return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
674
 
 
675
 
 
676
    def get_inventory_weave(self):
 
677
        return self.control_weaves.get_weave('inventory')
 
678
 
 
679
 
 
680
    def get_inventory(self, revision_id):
 
681
        """Get Inventory object by hash."""
 
682
        # FIXME: The text gets passed around a lot coming from the weave.
 
683
        f = StringIO(self.get_inventory_xml(revision_id))
 
684
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
685
 
 
686
 
 
687
    def get_inventory_xml(self, revision_id):
 
688
        """Get inventory XML as a file object."""
 
689
        try:
 
690
            assert isinstance(revision_id, basestring), type(revision_id)
 
691
            iw = self.get_inventory_weave()
 
692
            return iw.get_text(iw.lookup(revision_id))
 
693
        except IndexError:
 
694
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
695
 
 
696
 
 
697
    def get_inventory_sha1(self, revision_id):
 
698
        """Return the sha1 hash of the inventory entry
 
699
        """
 
700
        return self.get_revision(revision_id).inventory_sha1
 
701
 
 
702
 
 
703
    def get_revision_inventory(self, revision_id):
 
704
        """Return inventory of a past revision."""
 
705
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
706
        # must be the same as its revision, so this is trivial.
 
707
        if revision_id == None:
 
708
            return Inventory(self.get_root_id())
 
709
        else:
 
710
            return self.get_inventory(revision_id)
 
711
 
 
712
 
 
713
    def revision_history(self):
 
714
        """Return sequence of revision hashes on to this branch."""
 
715
        self.lock_read()
 
716
        try:
 
717
            return [l.rstrip('\r\n') for l in
 
718
                    self.controlfile('revision-history', 'r').readlines()]
 
719
        finally:
 
720
            self.unlock()
 
721
 
 
722
 
 
723
    def common_ancestor(self, other, self_revno=None, other_revno=None):
 
724
        """
 
725
        >>> import commit
 
726
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
 
727
        >>> sb.common_ancestor(sb) == (None, None)
 
728
        True
 
729
        >>> commit.commit(sb, "Committing first revision")
 
730
        >>> sb.common_ancestor(sb)[0]
 
731
        1
 
732
        >>> clone = sb.clone()
 
733
        >>> commit.commit(sb, "Committing second revision")
 
734
        >>> sb.common_ancestor(sb)[0]
 
735
        2
 
736
        >>> sb.common_ancestor(clone)[0]
 
737
        1
 
738
        >>> commit.commit(clone, "Committing divergent second revision")
 
739
        >>> sb.common_ancestor(clone)[0]
 
740
        1
 
741
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
 
742
        True
 
743
        >>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
 
744
        True
 
745
        >>> clone2 = sb.clone()
 
746
        >>> sb.common_ancestor(clone2)[0]
 
747
        2
 
748
        >>> sb.common_ancestor(clone2, self_revno=1)[0]
 
749
        1
 
750
        >>> sb.common_ancestor(clone2, other_revno=1)[0]
 
751
        1
 
752
        """
 
753
        my_history = self.revision_history()
 
754
        other_history = other.revision_history()
 
755
        if self_revno is None:
 
756
            self_revno = len(my_history)
 
757
        if other_revno is None:
 
758
            other_revno = len(other_history)
 
759
        indices = range(min((self_revno, other_revno)))
 
760
        indices.reverse()
 
761
        for r in indices:
 
762
            if my_history[r] == other_history[r]:
 
763
                return r+1, my_history[r]
 
764
        return None, None
 
765
 
 
766
 
 
767
    def revno(self):
 
768
        """Return current revision number for this branch.
 
769
 
 
770
        That is equivalent to the number of revisions committed to
 
771
        this branch.
 
772
        """
 
773
        return len(self.revision_history())
 
774
 
 
775
 
 
776
    def last_revision(self):
 
777
        """Return last patch hash, or None if no history.
 
778
        """
 
779
        ph = self.revision_history()
 
780
        if ph:
 
781
            return ph[-1]
 
782
        else:
 
783
            return None
 
784
 
 
785
 
 
786
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
787
        """Return a list of new revisions that would perfectly fit.
 
788
        
 
789
        If self and other have not diverged, return a list of the revisions
 
790
        present in other, but missing from self.
 
791
 
 
792
        >>> from bzrlib.commit import commit
 
793
        >>> bzrlib.trace.silent = True
 
794
        >>> br1 = ScratchBranch()
 
795
        >>> br2 = ScratchBranch()
 
796
        >>> br1.missing_revisions(br2)
 
797
        []
 
798
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
 
799
        >>> br1.missing_revisions(br2)
 
800
        [u'REVISION-ID-1']
 
801
        >>> br2.missing_revisions(br1)
 
802
        []
 
803
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
 
804
        >>> br1.missing_revisions(br2)
 
805
        []
 
806
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
 
807
        >>> br1.missing_revisions(br2)
 
808
        [u'REVISION-ID-2A']
 
809
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
 
810
        >>> br1.missing_revisions(br2)
 
811
        Traceback (most recent call last):
 
812
        DivergedBranches: These branches have diverged.
 
813
        """
 
814
        # FIXME: If the branches have diverged, but the latest
 
815
        # revision in this branch is completely merged into the other,
 
816
        # then we should still be able to pull.
 
817
        self_history = self.revision_history()
 
818
        self_len = len(self_history)
 
819
        other_history = other.revision_history()
 
820
        other_len = len(other_history)
 
821
        common_index = min(self_len, other_len) -1
 
822
        if common_index >= 0 and \
 
823
            self_history[common_index] != other_history[common_index]:
 
824
            raise DivergedBranches(self, other)
 
825
 
 
826
        if stop_revision is None:
 
827
            stop_revision = other_len
 
828
        else:
 
829
            assert isinstance(stop_revision, int)
 
830
            if stop_revision > other_len:
 
831
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
832
        
 
833
        return other_history[self_len:stop_revision]
 
834
 
 
835
 
 
836
    def update_revisions(self, other, stop_revno=None):
 
837
        """Pull in new perfect-fit revisions.
 
838
        """
 
839
        from bzrlib.fetch import greedy_fetch
 
840
 
 
841
        if stop_revno:
 
842
            stop_revision = other.lookup_revision(stop_revno)
 
843
        else:
 
844
            stop_revision = None
 
845
        greedy_fetch(to_branch=self, from_branch=other,
 
846
                     revision=stop_revision)
 
847
 
 
848
        pullable_revs = self.missing_revisions(other, stop_revision)
 
849
 
 
850
        if pullable_revs:
 
851
            greedy_fetch(to_branch=self,
 
852
                         from_branch=other,
 
853
                         revision=pullable_revs[-1])
 
854
            self.append_revision(*pullable_revs)
 
855
 
 
856
 
 
857
    def commit(self, *args, **kw):
 
858
        from bzrlib.commit import Commit
 
859
        Commit().commit(self, *args, **kw)
 
860
        
 
861
 
 
862
    def lookup_revision(self, revision):
 
863
        """Return the revision identifier for a given revision information."""
 
864
        revno, info = self._get_revision_info(revision)
 
865
        return info
 
866
 
 
867
 
 
868
    def revision_id_to_revno(self, revision_id):
 
869
        """Given a revision id, return its revno"""
 
870
        history = self.revision_history()
 
871
        try:
 
872
            return history.index(revision_id) + 1
 
873
        except ValueError:
 
874
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
875
 
 
876
 
 
877
    def get_revision_info(self, revision):
 
878
        """Return (revno, revision id) for revision identifier.
 
879
 
 
880
        revision can be an integer, in which case it is assumed to be revno (though
 
881
            this will translate negative values into positive ones)
 
882
        revision can also be a string, in which case it is parsed for something like
 
883
            'date:' or 'revid:' etc.
 
884
        """
 
885
        revno, rev_id = self._get_revision_info(revision)
 
886
        if revno is None:
 
887
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
888
        return revno, rev_id
 
889
 
 
890
    def get_rev_id(self, revno, history=None):
 
891
        """Find the revision id of the specified revno."""
 
892
        if revno == 0:
 
893
            return None
 
894
        if history is None:
 
895
            history = self.revision_history()
 
896
        elif revno <= 0 or revno > len(history):
 
897
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
898
        return history[revno - 1]
 
899
 
 
900
    def _get_revision_info(self, revision):
 
901
        """Return (revno, revision id) for revision specifier.
 
902
 
 
903
        revision can be an integer, in which case it is assumed to be revno
 
904
        (though this will translate negative values into positive ones)
 
905
        revision can also be a string, in which case it is parsed for something
 
906
        like 'date:' or 'revid:' etc.
 
907
 
 
908
        A revid is always returned.  If it is None, the specifier referred to
 
909
        the null revision.  If the revid does not occur in the revision
 
910
        history, revno will be None.
 
911
        """
 
912
        
 
913
        if revision is None:
 
914
            return 0, None
 
915
        revno = None
 
916
        try:# Convert to int if possible
 
917
            revision = int(revision)
 
918
        except ValueError:
 
919
            pass
 
920
        revs = self.revision_history()
 
921
        if isinstance(revision, int):
 
922
            if revision < 0:
 
923
                revno = len(revs) + revision + 1
 
924
            else:
 
925
                revno = revision
 
926
            rev_id = self.get_rev_id(revno, revs)
 
927
        elif isinstance(revision, basestring):
 
928
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
 
929
                if revision.startswith(prefix):
 
930
                    result = func(self, revs, revision)
 
931
                    if len(result) > 1:
 
932
                        revno, rev_id = result
 
933
                    else:
 
934
                        revno = result[0]
 
935
                        rev_id = self.get_rev_id(revno, revs)
 
936
                    break
 
937
            else:
 
938
                raise BzrError('No namespace registered for string: %r' %
 
939
                               revision)
 
940
        else:
 
941
            raise TypeError('Unhandled revision type %s' % revision)
 
942
 
 
943
        if revno is None:
 
944
            if rev_id is None:
 
945
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
946
        return revno, rev_id
 
947
 
 
948
    def _namespace_revno(self, revs, revision):
 
949
        """Lookup a revision by revision number"""
 
950
        assert revision.startswith('revno:')
 
951
        try:
 
952
            return (int(revision[6:]),)
 
953
        except ValueError:
 
954
            return None
 
955
    REVISION_NAMESPACES['revno:'] = _namespace_revno
 
956
 
 
957
    def _namespace_revid(self, revs, revision):
 
958
        assert revision.startswith('revid:')
 
959
        rev_id = revision[len('revid:'):]
 
960
        try:
 
961
            return revs.index(rev_id) + 1, rev_id
 
962
        except ValueError:
 
963
            return None, rev_id
 
964
    REVISION_NAMESPACES['revid:'] = _namespace_revid
 
965
 
 
966
    def _namespace_last(self, revs, revision):
 
967
        assert revision.startswith('last:')
 
968
        try:
 
969
            offset = int(revision[5:])
 
970
        except ValueError:
 
971
            return (None,)
 
972
        else:
 
973
            if offset <= 0:
 
974
                raise BzrError('You must supply a positive value for --revision last:XXX')
 
975
            return (len(revs) - offset + 1,)
 
976
    REVISION_NAMESPACES['last:'] = _namespace_last
 
977
 
 
978
    def _namespace_tag(self, revs, revision):
 
979
        assert revision.startswith('tag:')
 
980
        raise BzrError('tag: namespace registered, but not implemented.')
 
981
    REVISION_NAMESPACES['tag:'] = _namespace_tag
 
982
 
 
983
    def _namespace_date(self, revs, revision):
 
984
        assert revision.startswith('date:')
 
985
        import datetime
 
986
        # Spec for date revisions:
 
987
        #   date:value
 
988
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
989
        #   it can also start with a '+/-/='. '+' says match the first
 
990
        #   entry after the given date. '-' is match the first entry before the date
 
991
        #   '=' is match the first entry after, but still on the given date.
 
992
        #
 
993
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
 
994
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
 
995
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
 
996
        #       May 13th, 2005 at 0:00
 
997
        #
 
998
        #   So the proper way of saying 'give me all entries for today' is:
 
999
        #       -r {date:+today}:{date:-tomorrow}
 
1000
        #   The default is '=' when not supplied
 
1001
        val = revision[5:]
 
1002
        match_style = '='
 
1003
        if val[:1] in ('+', '-', '='):
 
1004
            match_style = val[:1]
 
1005
            val = val[1:]
 
1006
 
 
1007
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
 
1008
        if val.lower() == 'yesterday':
 
1009
            dt = today - datetime.timedelta(days=1)
 
1010
        elif val.lower() == 'today':
 
1011
            dt = today
 
1012
        elif val.lower() == 'tomorrow':
 
1013
            dt = today + datetime.timedelta(days=1)
 
1014
        else:
 
1015
            import re
 
1016
            # This should be done outside the function to avoid recompiling it.
 
1017
            _date_re = re.compile(
 
1018
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
1019
                    r'(,|T)?\s*'
 
1020
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
1021
                )
 
1022
            m = _date_re.match(val)
 
1023
            if not m or (not m.group('date') and not m.group('time')):
 
1024
                raise BzrError('Invalid revision date %r' % revision)
 
1025
 
 
1026
            if m.group('date'):
 
1027
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
 
1028
            else:
 
1029
                year, month, day = today.year, today.month, today.day
 
1030
            if m.group('time'):
 
1031
                hour = int(m.group('hour'))
 
1032
                minute = int(m.group('minute'))
 
1033
                if m.group('second'):
 
1034
                    second = int(m.group('second'))
 
1035
                else:
 
1036
                    second = 0
 
1037
            else:
 
1038
                hour, minute, second = 0,0,0
 
1039
 
 
1040
            dt = datetime.datetime(year=year, month=month, day=day,
 
1041
                    hour=hour, minute=minute, second=second)
 
1042
        first = dt
 
1043
        last = None
 
1044
        reversed = False
 
1045
        if match_style == '-':
 
1046
            reversed = True
 
1047
        elif match_style == '=':
 
1048
            last = dt + datetime.timedelta(days=1)
 
1049
 
 
1050
        if reversed:
 
1051
            for i in range(len(revs)-1, -1, -1):
 
1052
                r = self.get_revision(revs[i])
 
1053
                # TODO: Handle timezone.
 
1054
                dt = datetime.datetime.fromtimestamp(r.timestamp)
 
1055
                if first >= dt and (last is None or dt >= last):
 
1056
                    return (i+1,)
 
1057
        else:
 
1058
            for i in range(len(revs)):
 
1059
                r = self.get_revision(revs[i])
 
1060
                # TODO: Handle timezone.
 
1061
                dt = datetime.datetime.fromtimestamp(r.timestamp)
 
1062
                if first <= dt and (last is None or dt <= last):
 
1063
                    return (i+1,)
 
1064
    REVISION_NAMESPACES['date:'] = _namespace_date
 
1065
 
 
1066
    def revision_tree(self, revision_id):
 
1067
        """Return Tree for a revision on this branch.
 
1068
 
 
1069
        `revision_id` may be None for the null revision, in which case
 
1070
        an `EmptyTree` is returned."""
 
1071
        # TODO: refactor this to use an existing revision object
 
1072
        # so we don't need to read it in twice.
 
1073
        if revision_id == None:
 
1074
            return EmptyTree()
 
1075
        else:
 
1076
            inv = self.get_revision_inventory(revision_id)
 
1077
            return RevisionTree(self.weave_store, inv, revision_id)
 
1078
 
 
1079
 
 
1080
    def working_tree(self):
 
1081
        """Return a `Tree` for the working copy."""
 
1082
        from workingtree import WorkingTree
 
1083
        return WorkingTree(self.base, self.read_working_inventory())
 
1084
 
 
1085
 
 
1086
    def basis_tree(self):
 
1087
        """Return `Tree` object for last revision.
 
1088
 
 
1089
        If there are no revisions yet, return an `EmptyTree`.
 
1090
        """
 
1091
        return self.revision_tree(self.last_revision())
 
1092
 
 
1093
 
 
1094
    def rename_one(self, from_rel, to_rel):
 
1095
        """Rename one file.
 
1096
 
 
1097
        This can change the directory or the filename or both.
 
1098
        """
 
1099
        self.lock_write()
 
1100
        try:
 
1101
            tree = self.working_tree()
 
1102
            inv = tree.inventory
 
1103
            if not tree.has_filename(from_rel):
 
1104
                raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
1105
            if tree.has_filename(to_rel):
 
1106
                raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
1107
 
 
1108
            file_id = inv.path2id(from_rel)
 
1109
            if file_id == None:
 
1110
                raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
1111
 
 
1112
            if inv.path2id(to_rel):
 
1113
                raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
1114
 
 
1115
            to_dir, to_tail = os.path.split(to_rel)
 
1116
            to_dir_id = inv.path2id(to_dir)
 
1117
            if to_dir_id == None and to_dir != '':
 
1118
                raise BzrError("can't determine destination directory id for %r" % to_dir)
 
1119
 
 
1120
            mutter("rename_one:")
 
1121
            mutter("  file_id    {%s}" % file_id)
 
1122
            mutter("  from_rel   %r" % from_rel)
 
1123
            mutter("  to_rel     %r" % to_rel)
 
1124
            mutter("  to_dir     %r" % to_dir)
 
1125
            mutter("  to_dir_id  {%s}" % to_dir_id)
 
1126
 
 
1127
            inv.rename(file_id, to_dir_id, to_tail)
 
1128
 
 
1129
            from_abs = self.abspath(from_rel)
 
1130
            to_abs = self.abspath(to_rel)
 
1131
            try:
 
1132
                os.rename(from_abs, to_abs)
 
1133
            except OSError, e:
 
1134
                raise BzrError("failed to rename %r to %r: %s"
 
1135
                        % (from_abs, to_abs, e[1]),
 
1136
                        ["rename rolled back"])
 
1137
 
 
1138
            self._write_inventory(inv)
 
1139
        finally:
 
1140
            self.unlock()
 
1141
 
 
1142
 
 
1143
    def move(self, from_paths, to_name):
 
1144
        """Rename files.
 
1145
 
 
1146
        to_name must exist as a versioned directory.
 
1147
 
 
1148
        If to_name exists and is a directory, the files are moved into
 
1149
        it, keeping their old names.  If it is a directory, 
 
1150
 
 
1151
        Note that to_name is only the last component of the new name;
 
1152
        this doesn't change the directory.
 
1153
 
 
1154
        This returns a list of (from_path, to_path) pairs for each
 
1155
        entry that is moved.
 
1156
        """
 
1157
        result = []
 
1158
        self.lock_write()
 
1159
        try:
 
1160
            ## TODO: Option to move IDs only
 
1161
            assert not isinstance(from_paths, basestring)
 
1162
            tree = self.working_tree()
 
1163
            inv = tree.inventory
 
1164
            to_abs = self.abspath(to_name)
 
1165
            if not isdir(to_abs):
 
1166
                raise BzrError("destination %r is not a directory" % to_abs)
 
1167
            if not tree.has_filename(to_name):
 
1168
                raise BzrError("destination %r not in working directory" % to_abs)
 
1169
            to_dir_id = inv.path2id(to_name)
 
1170
            if to_dir_id == None and to_name != '':
 
1171
                raise BzrError("destination %r is not a versioned directory" % to_name)
 
1172
            to_dir_ie = inv[to_dir_id]
 
1173
            if to_dir_ie.kind not in ('directory', 'root_directory'):
 
1174
                raise BzrError("destination %r is not a directory" % to_abs)
 
1175
 
 
1176
            to_idpath = inv.get_idpath(to_dir_id)
 
1177
 
 
1178
            for f in from_paths:
 
1179
                if not tree.has_filename(f):
 
1180
                    raise BzrError("%r does not exist in working tree" % f)
 
1181
                f_id = inv.path2id(f)
 
1182
                if f_id == None:
 
1183
                    raise BzrError("%r is not versioned" % f)
 
1184
                name_tail = splitpath(f)[-1]
 
1185
                dest_path = appendpath(to_name, name_tail)
 
1186
                if tree.has_filename(dest_path):
 
1187
                    raise BzrError("destination %r already exists" % dest_path)
 
1188
                if f_id in to_idpath:
 
1189
                    raise BzrError("can't move %r to a subdirectory of itself" % f)
 
1190
 
 
1191
            # OK, so there's a race here, it's possible that someone will
 
1192
            # create a file in this interval and then the rename might be
 
1193
            # left half-done.  But we should have caught most problems.
 
1194
 
 
1195
            for f in from_paths:
 
1196
                name_tail = splitpath(f)[-1]
 
1197
                dest_path = appendpath(to_name, name_tail)
 
1198
                result.append((f, dest_path))
 
1199
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
1200
                try:
 
1201
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1202
                except OSError, e:
 
1203
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
1204
                            ["rename rolled back"])
 
1205
 
 
1206
            self._write_inventory(inv)
 
1207
        finally:
 
1208
            self.unlock()
 
1209
 
 
1210
        return result
 
1211
 
 
1212
 
 
1213
    def revert(self, filenames, old_tree=None, backups=True):
 
1214
        """Restore selected files to the versions from a previous tree.
 
1215
 
 
1216
        backups
 
1217
            If true (default) backups are made of files before
 
1218
            they're renamed.
 
1219
        """
 
1220
        from bzrlib.errors import NotVersionedError, BzrError
 
1221
        from bzrlib.atomicfile import AtomicFile
 
1222
        from bzrlib.osutils import backup_file
 
1223
        
 
1224
        inv = self.read_working_inventory()
 
1225
        if old_tree is None:
 
1226
            old_tree = self.basis_tree()
 
1227
        old_inv = old_tree.inventory
 
1228
 
 
1229
        nids = []
 
1230
        for fn in filenames:
 
1231
            file_id = inv.path2id(fn)
 
1232
            if not file_id:
 
1233
                raise NotVersionedError("not a versioned file", fn)
 
1234
            if not old_inv.has_id(file_id):
 
1235
                raise BzrError("file not present in old tree", fn, file_id)
 
1236
            nids.append((fn, file_id))
 
1237
            
 
1238
        # TODO: Rename back if it was previously at a different location
 
1239
 
 
1240
        # TODO: If given a directory, restore the entire contents from
 
1241
        # the previous version.
 
1242
 
 
1243
        # TODO: Make a backup to a temporary file.
 
1244
 
 
1245
        # TODO: If the file previously didn't exist, delete it?
 
1246
        for fn, file_id in nids:
 
1247
            backup_file(fn)
 
1248
            
 
1249
            f = AtomicFile(fn, 'wb')
 
1250
            try:
 
1251
                f.write(old_tree.get_file(file_id).read())
 
1252
                f.commit()
 
1253
            finally:
 
1254
                f.close()
 
1255
 
 
1256
 
 
1257
    def pending_merges(self):
 
1258
        """Return a list of pending merges.
 
1259
 
 
1260
        These are revisions that have been merged into the working
 
1261
        directory but not yet committed.
 
1262
        """
 
1263
        cfn = self.controlfilename('pending-merges')
 
1264
        if not os.path.exists(cfn):
 
1265
            return []
 
1266
        p = []
 
1267
        for l in self.controlfile('pending-merges', 'r').readlines():
 
1268
            p.append(l.rstrip('\n'))
 
1269
        return p
 
1270
 
 
1271
 
 
1272
    def add_pending_merge(self, revision_id):
 
1273
        validate_revision_id(revision_id)
 
1274
        # TODO: Perhaps should check at this point that the
 
1275
        # history of the revision is actually present?
 
1276
        p = self.pending_merges()
 
1277
        if revision_id in p:
 
1278
            return
 
1279
        p.append(revision_id)
 
1280
        self.set_pending_merges(p)
 
1281
 
 
1282
 
 
1283
    def set_pending_merges(self, rev_list):
 
1284
        from bzrlib.atomicfile import AtomicFile
 
1285
        self.lock_write()
 
1286
        try:
 
1287
            f = AtomicFile(self.controlfilename('pending-merges'))
 
1288
            try:
 
1289
                for l in rev_list:
 
1290
                    print >>f, l
 
1291
                f.commit()
 
1292
            finally:
 
1293
                f.close()
 
1294
        finally:
 
1295
            self.unlock()
 
1296
 
 
1297
 
 
1298
    def get_parent(self):
 
1299
        """Return the parent location of the branch.
 
1300
 
 
1301
        This is the default location for push/pull/missing.  The usual
 
1302
        pattern is that the user can override it by specifying a
 
1303
        location.
 
1304
        """
 
1305
        import errno
 
1306
        _locs = ['parent', 'pull', 'x-pull']
 
1307
        for l in _locs:
 
1308
            try:
 
1309
                return self.controlfile(l, 'r').read().strip('\n')
 
1310
            except IOError, e:
 
1311
                if e.errno != errno.ENOENT:
 
1312
                    raise
 
1313
        return None
 
1314
 
 
1315
 
 
1316
    def set_parent(self, url):
 
1317
        # TODO: Maybe delete old location files?
 
1318
        from bzrlib.atomicfile import AtomicFile
 
1319
        self.lock_write()
 
1320
        try:
 
1321
            f = AtomicFile(self.controlfilename('parent'))
 
1322
            try:
 
1323
                f.write(url + '\n')
 
1324
                f.commit()
 
1325
            finally:
 
1326
                f.close()
 
1327
        finally:
 
1328
            self.unlock()
 
1329
 
 
1330
    def check_revno(self, revno):
 
1331
        """\
 
1332
        Check whether a revno corresponds to any revision.
 
1333
        Zero (the NULL revision) is considered valid.
 
1334
        """
 
1335
        if revno != 0:
 
1336
            self.check_real_revno(revno)
 
1337
            
 
1338
    def check_real_revno(self, revno):
 
1339
        """\
 
1340
        Check whether a revno corresponds to a real revision.
 
1341
        Zero (the NULL revision) is considered invalid
 
1342
        """
 
1343
        if revno < 1 or revno > self.revno():
 
1344
            raise InvalidRevisionNumber(revno)
 
1345
        
 
1346
        
 
1347
 
 
1348
 
 
1349
class ScratchBranch(Branch):
 
1350
    """Special test class: a branch that cleans up after itself.
 
1351
 
 
1352
    >>> b = ScratchBranch()
 
1353
    >>> isdir(b.base)
 
1354
    True
 
1355
    >>> bd = b.base
 
1356
    >>> b.destroy()
 
1357
    >>> isdir(bd)
 
1358
    False
 
1359
    """
 
1360
    def __init__(self, files=[], dirs=[], base=None):
 
1361
        """Make a test branch.
 
1362
 
 
1363
        This creates a temporary directory and runs init-tree in it.
 
1364
 
 
1365
        If any files are listed, they are created in the working copy.
 
1366
        """
 
1367
        from tempfile import mkdtemp
 
1368
        init = False
 
1369
        if base is None:
 
1370
            base = mkdtemp()
 
1371
            init = True
 
1372
        Branch.__init__(self, base, init=init)
 
1373
        for d in dirs:
 
1374
            os.mkdir(self.abspath(d))
 
1375
            
 
1376
        for f in files:
 
1377
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
 
1378
 
 
1379
 
 
1380
    def clone(self):
 
1381
        """
 
1382
        >>> orig = ScratchBranch(files=["file1", "file2"])
 
1383
        >>> clone = orig.clone()
 
1384
        >>> os.path.samefile(orig.base, clone.base)
 
1385
        False
 
1386
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
 
1387
        True
 
1388
        """
 
1389
        from shutil import copytree
 
1390
        from tempfile import mkdtemp
 
1391
        base = mkdtemp()
 
1392
        os.rmdir(base)
 
1393
        copytree(self.base, base, symlinks=True)
 
1394
        return ScratchBranch(base=base)
 
1395
 
 
1396
 
 
1397
        
 
1398
    def __del__(self):
 
1399
        self.destroy()
 
1400
 
 
1401
    def destroy(self):
 
1402
        """Destroy the test branch, removing the scratch directory."""
 
1403
        from shutil import rmtree
 
1404
        try:
 
1405
            if self.base:
 
1406
                mutter("delete ScratchBranch %s" % self.base)
 
1407
                rmtree(self.base)
 
1408
        except OSError, e:
 
1409
            # Work around for shutil.rmtree failing on Windows when
 
1410
            # readonly files are encountered
 
1411
            mutter("hit exception in destroying ScratchBranch: %s" % e)
 
1412
            for root, dirs, files in os.walk(self.base, topdown=False):
 
1413
                for name in files:
 
1414
                    os.chmod(os.path.join(root, name), 0700)
 
1415
            rmtree(self.base)
 
1416
        self.base = None
 
1417
 
 
1418
    
 
1419
 
 
1420
######################################################################
 
1421
# predicates
 
1422
 
 
1423
 
 
1424
def is_control_file(filename):
 
1425
    ## FIXME: better check
 
1426
    filename = os.path.normpath(filename)
 
1427
    while filename != '':
 
1428
        head, tail = os.path.split(filename)
 
1429
        ## mutter('check %r for control file' % ((head, tail), ))
 
1430
        if tail == bzrlib.BZRDIR:
 
1431
            return True
 
1432
        if filename == head:
 
1433
            break
 
1434
        filename = head
 
1435
    return False
 
1436
 
 
1437
 
 
1438
 
 
1439
def gen_file_id(name):
 
1440
    """Return new file id.
 
1441
 
 
1442
    This should probably generate proper UUIDs, but for the moment we
 
1443
    cope with just randomness because running uuidgen every time is
 
1444
    slow."""
 
1445
    import re
 
1446
    from binascii import hexlify
 
1447
    from time import time
 
1448
 
 
1449
    # get last component
 
1450
    idx = name.rfind('/')
 
1451
    if idx != -1:
 
1452
        name = name[idx+1 : ]
 
1453
    idx = name.rfind('\\')
 
1454
    if idx != -1:
 
1455
        name = name[idx+1 : ]
 
1456
 
 
1457
    # make it not a hidden file
 
1458
    name = name.lstrip('.')
 
1459
 
 
1460
    # remove any wierd characters; we don't escape them but rather
 
1461
    # just pull them out
 
1462
    name = re.sub(r'[^\w.]', '', name)
 
1463
 
 
1464
    s = hexlify(rand_bytes(8))
 
1465
    return '-'.join((name, compact_date(time()), s))
 
1466
 
 
1467
 
 
1468
def gen_root_id():
 
1469
    """Return a new tree-root file id."""
 
1470
    return gen_file_id('TREE_ROOT')
 
1471
 
 
1472
 
 
1473
def pull_loc(branch):
 
1474
    # TODO: Should perhaps just make attribute be 'base' in
 
1475
    # RemoteBranch and Branch?
 
1476
    if hasattr(branch, "baseurl"):
 
1477
        return branch.baseurl
 
1478
    else:
 
1479
        return branch.base
 
1480
 
 
1481
 
 
1482
def copy_branch(branch_from, to_location, revision=None):
 
1483
    """Copy branch_from into the existing directory to_location.
 
1484
 
 
1485
    revision
 
1486
        If not None, only revisions up to this point will be copied.
 
1487
        The head of the new branch will be that revision.  Can be a
 
1488
        revno or revid.
 
1489
 
 
1490
    to_location
 
1491
        The name of a local directory that exists but is empty.
 
1492
    """
 
1493
    # TODO: This could be done *much* more efficiently by just copying
 
1494
    # all the whole weaves and revisions, rather than getting one
 
1495
    # revision at a time.
 
1496
    from bzrlib.merge import merge
 
1497
    from bzrlib.branch import Branch
 
1498
 
 
1499
    assert isinstance(branch_from, Branch)
 
1500
    assert isinstance(to_location, basestring)
 
1501
    
 
1502
    br_to = Branch(to_location, init=True)
 
1503
    br_to.set_root_id(branch_from.get_root_id())
 
1504
    if revision is None:
 
1505
        revno = None
 
1506
    else:
 
1507
        revno, rev_id = branch_from.get_revision_info(revision)
 
1508
    br_to.update_revisions(branch_from, stop_revno=revno)
 
1509
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1510
          check_clean=False, ignore_zero=True)
 
1511
    
 
1512
    from_location = pull_loc(branch_from)
 
1513
    br_to.set_parent(pull_loc(branch_from))
 
1514