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