/brz/remove-bazaar

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