/brz/remove-bazaar

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