~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-09-13 23:08:19 UTC
  • Revision ID: mbp@sourcefrog.net-20050913230819-6ceae96050d32faa
ignore .bzr-shelf

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