/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

Fix formatting, remove catch-all for exceptions when opening local repositories.

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