/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: Lalo Martins
  • Date: 2005-09-09 11:37:44 UTC
  • mto: (1185.1.22)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: lalo@exoweb.net-20050909113744-22f870db25a9e5f5
getting rid of everything that calls the Branch constructor directly

Show diffs side-by-side

added added

removed removed

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