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