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