/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: Robert Collins
  • Date: 2005-09-26 08:56:15 UTC
  • mto: (1092.3.4)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: robertc@robertcollins.net-20050926085615-99b8fb35f41b541d
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid

Show diffs side-by-side

added added

removed removed

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