~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

[merge] jaq

Show diffs side-by-side

added added

removed removed

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