/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-08-01 19:25:31 UTC
  • Revision ID: mbp@sourcefrog.net-20050801192531-d2918f319d08a380
- better str method for InvalidRevisionNumber exception

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