/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: John Arbash Meinel
  • Date: 2005-09-29 20:34:25 UTC
  • mfrom: (1185.11.24)
  • mto: (1393.1.12)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: john@arbash-meinel.com-20050929203425-7fc2ea87f449dfe8
Merged in split-storage-2 branch. Need to cleanup a little bit more still.

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