~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2005-10-11 02:52:47 UTC
  • mfrom: (1417.1.13)
  • Revision ID: robertc@robertcollins.net-20051011025247-4b95466bb6509385
merge in revision-history caching, and tuning of fetch to not retrieve more data than needed when nothing needs to be pulled

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
import sys, os
 
18
import sys
 
19
import os
 
20
import errno
 
21
from warnings import warn
 
22
from cStringIO import StringIO
 
23
 
19
24
 
20
25
import bzrlib
 
26
from bzrlib.inventory import InventoryEntry
 
27
import bzrlib.inventory as inventory
21
28
from bzrlib.trace import mutter, note
22
 
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
23
 
     sha_file, appendpath, file_kind
24
 
from bzrlib.errors import BzrError
25
 
 
26
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
29
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes, 
 
30
                            rename, splitpath, sha_file, appendpath, 
 
31
                            file_kind)
 
32
import bzrlib.errors as errors
 
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
34
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
35
                           DivergedBranches, LockError, UnlistableStore,
 
36
                           UnlistableBranch, NoSuchFile)
 
37
from bzrlib.textui import show_status
 
38
from bzrlib.revision import Revision
 
39
from bzrlib.delta import compare_trees
 
40
from bzrlib.tree import EmptyTree, RevisionTree
 
41
from bzrlib.inventory import Inventory
 
42
from bzrlib.store import copy_all
 
43
from bzrlib.store.compressed_text import CompressedTextStore
 
44
from bzrlib.store.text import TextStore
 
45
from bzrlib.store.weave import WeaveStore
 
46
import bzrlib.transactions as transactions
 
47
from bzrlib.transport import Transport, get_transport
 
48
import bzrlib.xml5
 
49
import bzrlib.ui
 
50
 
 
51
 
 
52
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
53
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
54
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
27
55
## TODO: Maybe include checks for common corruption of newlines, etc?
28
56
 
29
57
 
30
 
 
31
 
def find_branch(f, **args):
32
 
    if f and (f.startswith('http://') or f.startswith('https://')):
33
 
        import remotebranch 
34
 
        return remotebranch.RemoteBranch(f, **args)
35
 
    else:
36
 
        return Branch(f, **args)
37
 
 
38
 
 
39
 
def find_cached_branch(f, cache_root, **args):
40
 
    from remotebranch import RemoteBranch
41
 
    br = find_branch(f, **args)
42
 
    def cacheify(br, store_name):
43
 
        from meta_store import CachedStore
44
 
        cache_path = os.path.join(cache_root, store_name)
45
 
        os.mkdir(cache_path)
46
 
        new_store = CachedStore(getattr(br, store_name), cache_path)
47
 
        setattr(br, store_name, new_store)
48
 
 
49
 
    if isinstance(br, RemoteBranch):
50
 
        cacheify(br, 'inventory_store')
51
 
        cacheify(br, 'text_store')
52
 
        cacheify(br, 'revision_store')
53
 
    return br
54
 
 
55
 
 
 
58
# TODO: Some operations like log might retrieve the same revisions
 
59
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
60
# cache in memory to make this faster.  In general anything can be
 
61
# cached in memory between lock and unlock operations.
 
62
 
 
63
def find_branch(*ignored, **ignored_too):
 
64
    # XXX: leave this here for about one release, then remove it
 
65
    raise NotImplementedError('find_branch() is not supported anymore, '
 
66
                              'please use one of the new branch constructors')
56
67
def _relpath(base, path):
57
68
    """Return path relative to base, or raise exception.
58
69
 
75
86
        if tail:
76
87
            s.insert(0, tail)
77
88
    else:
78
 
        from errors import NotBranchError
79
89
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
80
90
 
81
91
    return os.sep.join(s)
82
92
        
83
93
 
84
 
def find_branch_root(f=None):
85
 
    """Find the branch root enclosing f, or pwd.
86
 
 
87
 
    f may be a filename or a URL.
88
 
 
89
 
    It is not necessary that f exists.
 
94
def find_branch_root(t):
 
95
    """Find the branch root enclosing the transport's base.
 
96
 
 
97
    t is a Transport object.
 
98
 
 
99
    It is not necessary that the base of t exists.
90
100
 
91
101
    Basically we keep looking up until we find the control directory or
92
 
    run into the root."""
93
 
    if f == None:
94
 
        f = os.getcwd()
95
 
    elif hasattr(os.path, 'realpath'):
96
 
        f = os.path.realpath(f)
97
 
    else:
98
 
        f = os.path.abspath(f)
99
 
    if not os.path.exists(f):
100
 
        raise BzrError('%r does not exist' % f)
101
 
        
102
 
 
103
 
    orig_f = f
104
 
 
 
102
    run into the root.  If there isn't one, raises NotBranchError.
 
103
    """
 
104
    orig_base = t.base
105
105
    while True:
106
 
        if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
107
 
            return f
108
 
        head, tail = os.path.split(f)
109
 
        if head == f:
 
106
        if t.has(bzrlib.BZRDIR):
 
107
            return t
 
108
        new_t = t.clone('..')
 
109
        if new_t.base == t.base:
110
110
            # reached the root, whatever that may be
111
 
            raise BzrError('%r is not in a branch' % orig_f)
112
 
        f = head
113
 
    
114
 
class DivergedBranches(Exception):
115
 
    def __init__(self, branch1, branch2):
116
 
        self.branch1 = branch1
117
 
        self.branch2 = branch2
118
 
        Exception.__init__(self, "These branches have diverged.")
119
 
 
120
 
 
121
 
class NoSuchRevision(BzrError):
122
 
    def __init__(self, branch, revision):
123
 
        self.branch = branch
124
 
        self.revision = revision
125
 
        msg = "Branch %s has no revision %d" % (branch, revision)
126
 
        BzrError.__init__(self, msg)
 
111
            raise NotBranchError('%s is not in a branch' % orig_base)
 
112
        t = new_t
127
113
 
128
114
 
129
115
######################################################################
133
119
    """Branch holding a history of revisions.
134
120
 
135
121
    base
136
 
        Base directory of the branch.
 
122
        Base directory/url of the branch.
 
123
    """
 
124
    base = None
 
125
 
 
126
    def __init__(self, *ignored, **ignored_too):
 
127
        raise NotImplementedError('The Branch class is abstract')
 
128
 
 
129
    @staticmethod
 
130
    def open_downlevel(base):
 
131
        """Open a branch which may be of an old format.
 
132
        
 
133
        Only local branches are supported."""
 
134
        return _Branch(get_transport(base), relax_version_check=True)
 
135
        
 
136
    @staticmethod
 
137
    def open(base):
 
138
        """Open an existing branch, rooted at 'base' (url)"""
 
139
        t = get_transport(base)
 
140
        mutter("trying to open %r with transport %r", base, t)
 
141
        return _Branch(t)
 
142
 
 
143
    @staticmethod
 
144
    def open_containing(url):
 
145
        """Open an existing branch which contains url.
 
146
        
 
147
        This probes for a branch at url, and searches upwards from there.
 
148
        """
 
149
        t = get_transport(url)
 
150
        t = find_branch_root(t)
 
151
        return _Branch(t)
 
152
 
 
153
    @staticmethod
 
154
    def initialize(base):
 
155
        """Create a new branch, rooted at 'base' (url)"""
 
156
        t = get_transport(base)
 
157
        return _Branch(t, init=True)
 
158
 
 
159
    def setup_caching(self, cache_root):
 
160
        """Subclasses that care about caching should override this, and set
 
161
        up cached stores located under cache_root.
 
162
        """
 
163
        self.cache_root = cache_root
 
164
 
 
165
 
 
166
class _Branch(Branch):
 
167
    """A branch stored in the actual filesystem.
 
168
 
 
169
    Note that it's "local" in the context of the filesystem; it doesn't
 
170
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
171
    it's writable, and can be accessed via the normal filesystem API.
137
172
 
138
173
    _lock_mode
139
174
        None, or 'r' or 'w'
145
180
    _lock
146
181
        Lock object from bzrlib.lock.
147
182
    """
148
 
    base = None
 
183
    # We actually expect this class to be somewhat short-lived; part of its
 
184
    # purpose is to try to isolate what bits of the branch logic are tied to
 
185
    # filesystem access, so that in a later step, we can extricate them to
 
186
    # a separarte ("storage") class.
149
187
    _lock_mode = None
150
188
    _lock_count = None
151
189
    _lock = None
 
190
    _inventory_weave = None
152
191
    
153
192
    # Map some sort of prefix into a namespace
154
193
    # stuff like "revno:10", "revid:", etc.
155
194
    # This should match a prefix with a function which accepts
156
195
    REVISION_NAMESPACES = {}
157
196
 
158
 
    def __init__(self, base, init=False, find_root=True):
 
197
    def push_stores(self, branch_to):
 
198
        """Copy the content of this branches store to branch_to."""
 
199
        if (self._branch_format != branch_to._branch_format
 
200
            or self._branch_format != 4):
 
201
            from bzrlib.fetch import greedy_fetch
 
202
            mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
 
203
                   self, self._branch_format, branch_to, branch_to._branch_format)
 
204
            greedy_fetch(to_branch=branch_to, from_branch=self,
 
205
                         revision=self.last_revision())
 
206
            return
 
207
 
 
208
        store_pairs = ((self.text_store,      branch_to.text_store),
 
209
                       (self.inventory_store, branch_to.inventory_store),
 
210
                       (self.revision_store,  branch_to.revision_store))
 
211
        try:
 
212
            for from_store, to_store in store_pairs: 
 
213
                copy_all(from_store, to_store)
 
214
        except UnlistableStore:
 
215
            raise UnlistableBranch(from_store)
 
216
 
 
217
    def __init__(self, transport, init=False,
 
218
                 relax_version_check=False):
159
219
        """Create new branch object at a particular location.
160
220
 
161
 
        base -- Base directory for the branch.
 
221
        transport -- A Transport object, defining how to access files.
 
222
                (If a string, transport.transport() will be used to
 
223
                create a Transport object)
162
224
        
163
225
        init -- If True, create new control files in a previously
164
226
             unversioned directory.  If False, the branch must already
165
227
             be versioned.
166
228
 
167
 
        find_root -- If true and init is false, find the root of the
168
 
             existing branch containing base.
 
229
        relax_version_check -- If true, the usual check for the branch
 
230
            version is not applied.  This is intended only for
 
231
            upgrade/recovery type use; it's not guaranteed that
 
232
            all operations will work on old format branches.
169
233
 
170
234
        In the test suite, creation of new trees is tested using the
171
235
        `ScratchBranch` class.
172
236
        """
173
 
        from bzrlib.store import ImmutableStore
 
237
        assert isinstance(transport, Transport), \
 
238
            "%r is not a Transport" % transport
 
239
        self._transport = transport
174
240
        if init:
175
 
            self.base = os.path.realpath(base)
176
241
            self._make_control()
177
 
        elif find_root:
178
 
            self.base = find_branch_root(base)
179
 
        else:
180
 
            self.base = os.path.realpath(base)
181
 
            if not isdir(self.controlfilename('.')):
182
 
                from errors import NotBranchError
183
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
184
 
                                     ['use "bzr init" to initialize a new working tree',
185
 
                                      'current bzr can only operate from top-of-tree'])
186
 
        self._check_format()
187
 
 
188
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
189
 
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
190
 
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
191
 
 
 
242
        self._check_format(relax_version_check)
 
243
 
 
244
        def get_store(name, compressed=True, prefixed=False):
 
245
            # FIXME: This approach of assuming stores are all entirely compressed
 
246
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
247
            # some existing branches where there's a mixture; we probably 
 
248
            # still want the option to look for both.
 
249
            relpath = self._rel_controlfilename(name)
 
250
            if compressed:
 
251
                store = CompressedTextStore(self._transport.clone(relpath),
 
252
                                            prefixed=prefixed)
 
253
            else:
 
254
                store = TextStore(self._transport.clone(relpath),
 
255
                                  prefixed=prefixed)
 
256
            #if self._transport.should_cache():
 
257
            #    cache_path = os.path.join(self.cache_root, name)
 
258
            #    os.mkdir(cache_path)
 
259
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
260
            return store
 
261
        def get_weave(name, prefixed=False):
 
262
            relpath = self._rel_controlfilename(name)
 
263
            ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
 
264
            if self._transport.should_cache():
 
265
                ws.enable_cache = True
 
266
            return ws
 
267
 
 
268
        if self._branch_format == 4:
 
269
            self.inventory_store = get_store('inventory-store')
 
270
            self.text_store = get_store('text-store')
 
271
            self.revision_store = get_store('revision-store')
 
272
        elif self._branch_format == 5:
 
273
            self.control_weaves = get_weave([])
 
274
            self.weave_store = get_weave('weaves')
 
275
            self.revision_store = get_store('revision-store', compressed=False)
 
276
        elif self._branch_format == 6:
 
277
            self.control_weaves = get_weave([])
 
278
            self.weave_store = get_weave('weaves', prefixed=True)
 
279
            self.revision_store = get_store('revision-store', compressed=False,
 
280
                                            prefixed=True)
 
281
        self._transaction = None
192
282
 
193
283
    def __str__(self):
194
 
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
284
        return '%s(%r)' % (self.__class__.__name__, self._transport.base)
195
285
 
196
286
 
197
287
    __repr__ = __str__
199
289
 
200
290
    def __del__(self):
201
291
        if self._lock_mode or self._lock:
202
 
            from warnings import warn
 
292
            # XXX: This should show something every time, and be suitable for
 
293
            # headless operation and embedding
203
294
            warn("branch %r was not explicitly unlocked" % self)
204
295
            self._lock.unlock()
205
296
 
206
 
 
 
297
        # TODO: It might be best to do this somewhere else,
 
298
        # but it is nice for a Branch object to automatically
 
299
        # cache it's information.
 
300
        # Alternatively, we could have the Transport objects cache requests
 
301
        # See the earlier discussion about how major objects (like Branch)
 
302
        # should never expect their __del__ function to run.
 
303
        if hasattr(self, 'cache_root') and self.cache_root is not None:
 
304
            try:
 
305
                import shutil
 
306
                shutil.rmtree(self.cache_root)
 
307
            except:
 
308
                pass
 
309
            self.cache_root = None
 
310
 
 
311
    def _get_base(self):
 
312
        if self._transport:
 
313
            return self._transport.base
 
314
        return None
 
315
 
 
316
    base = property(_get_base)
 
317
 
 
318
    def _finish_transaction(self):
 
319
        """Exit the current transaction."""
 
320
        if self._transaction is None:
 
321
            raise errors.LockError('Branch %s is not in a transaction' %
 
322
                                   self)
 
323
        transaction = self._transaction
 
324
        self._transaction = None
 
325
        transaction.finish()
 
326
 
 
327
    def get_transaction(self):
 
328
        """Return the current active transaction.
 
329
 
 
330
        If no transaction is active, this returns a passthrough object
 
331
        for which all data is immedaitely flushed and no caching happens.
 
332
        """
 
333
        if self._transaction is None:
 
334
            return transactions.PassThroughTransaction()
 
335
        else:
 
336
            return self._transaction
 
337
 
 
338
    def _set_transaction(self, new_transaction):
 
339
        """Set a new active transaction."""
 
340
        if self._transaction is not None:
 
341
            raise errors.LockError('Branch %s is in a transaction already.' %
 
342
                                   self)
 
343
        self._transaction = new_transaction
207
344
 
208
345
    def lock_write(self):
 
346
        mutter("lock write: %s (%s)", self, self._lock_count)
 
347
        # TODO: Upgrade locking to support using a Transport,
 
348
        # and potentially a remote locking protocol
209
349
        if self._lock_mode:
210
350
            if self._lock_mode != 'w':
211
 
                from errors import LockError
212
351
                raise LockError("can't upgrade to a write lock from %r" %
213
352
                                self._lock_mode)
214
353
            self._lock_count += 1
215
354
        else:
216
 
            from bzrlib.lock import WriteLock
217
 
 
218
 
            self._lock = WriteLock(self.controlfilename('branch-lock'))
 
355
            self._lock = self._transport.lock_write(
 
356
                    self._rel_controlfilename('branch-lock'))
219
357
            self._lock_mode = 'w'
220
358
            self._lock_count = 1
221
 
 
222
 
 
 
359
            self._set_transaction(transactions.PassThroughTransaction())
223
360
 
224
361
    def lock_read(self):
 
362
        mutter("lock read: %s (%s)", self, self._lock_count)
225
363
        if self._lock_mode:
226
364
            assert self._lock_mode in ('r', 'w'), \
227
365
                   "invalid lock mode %r" % self._lock_mode
228
366
            self._lock_count += 1
229
367
        else:
230
 
            from bzrlib.lock import ReadLock
231
 
 
232
 
            self._lock = ReadLock(self.controlfilename('branch-lock'))
 
368
            self._lock = self._transport.lock_read(
 
369
                    self._rel_controlfilename('branch-lock'))
233
370
            self._lock_mode = 'r'
234
371
            self._lock_count = 1
 
372
            self._set_transaction(transactions.ReadOnlyTransaction())
 
373
            # 5K may be excessive, but hey, its a knob.
 
374
            self.get_transaction().set_cache_size(5000)
235
375
                        
236
 
 
237
 
            
238
376
    def unlock(self):
 
377
        mutter("unlock: %s (%s)", self, self._lock_count)
239
378
        if not self._lock_mode:
240
 
            from errors import LockError
241
379
            raise LockError('branch %r is not locked' % (self))
242
380
 
243
381
        if self._lock_count > 1:
244
382
            self._lock_count -= 1
245
383
        else:
 
384
            self._finish_transaction()
246
385
            self._lock.unlock()
247
386
            self._lock = None
248
387
            self._lock_mode = self._lock_count = None
249
388
 
250
 
 
251
389
    def abspath(self, name):
252
390
        """Return absolute filename for something in the branch"""
253
 
        return os.path.join(self.base, name)
254
 
 
 
391
        return self._transport.abspath(name)
255
392
 
256
393
    def relpath(self, path):
257
394
        """Return path relative to this branch of something inside it.
258
395
 
259
396
        Raises an error if path is not in this branch."""
260
 
        return _relpath(self.base, path)
261
 
 
 
397
        return self._transport.relpath(path)
 
398
 
 
399
 
 
400
    def _rel_controlfilename(self, file_or_path):
 
401
        if isinstance(file_or_path, basestring):
 
402
            file_or_path = [file_or_path]
 
403
        return [bzrlib.BZRDIR] + file_or_path
262
404
 
263
405
    def controlfilename(self, file_or_path):
264
406
        """Return location relative to branch."""
265
 
        if isinstance(file_or_path, basestring):
266
 
            file_or_path = [file_or_path]
267
 
        return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
 
407
        return self._transport.abspath(self._rel_controlfilename(file_or_path))
268
408
 
269
409
 
270
410
    def controlfile(self, file_or_path, mode='r'):
278
418
        Controlfiles should almost never be opened in write mode but
279
419
        rather should be atomically copied and replaced using atomicfile.
280
420
        """
281
 
 
282
 
        fn = self.controlfilename(file_or_path)
283
 
 
284
 
        if mode == 'rb' or mode == 'wb':
285
 
            return file(fn, mode)
286
 
        elif mode == 'r' or mode == 'w':
287
 
            # open in binary mode anyhow so there's no newline translation;
288
 
            # codecs uses line buffering by default; don't want that.
289
 
            import codecs
290
 
            return codecs.open(fn, mode + 'b', 'utf-8',
291
 
                               buffering=60000)
 
421
        import codecs
 
422
 
 
423
        relpath = self._rel_controlfilename(file_or_path)
 
424
        #TODO: codecs.open() buffers linewise, so it was overloaded with
 
425
        # a much larger buffer, do we need to do the same for getreader/getwriter?
 
426
        if mode == 'rb': 
 
427
            return self._transport.get(relpath)
 
428
        elif mode == 'wb':
 
429
            raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
 
430
        elif mode == 'r':
 
431
            return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
 
432
        elif mode == 'w':
 
433
            raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
292
434
        else:
293
435
            raise BzrError("invalid controlfile mode %r" % mode)
294
436
 
295
 
 
 
437
    def put_controlfile(self, path, f, encode=True):
 
438
        """Write an entry as a controlfile.
 
439
 
 
440
        :param path: The path to put the file, relative to the .bzr control
 
441
                     directory
 
442
        :param f: A file-like or string object whose contents should be copied.
 
443
        :param encode:  If true, encode the contents as utf-8
 
444
        """
 
445
        self.put_controlfiles([(path, f)], encode=encode)
 
446
 
 
447
    def put_controlfiles(self, files, encode=True):
 
448
        """Write several entries as controlfiles.
 
449
 
 
450
        :param files: A list of [(path, file)] pairs, where the path is the directory
 
451
                      underneath the bzr control directory
 
452
        :param encode:  If true, encode the contents as utf-8
 
453
        """
 
454
        import codecs
 
455
        ctrl_files = []
 
456
        for path, f in files:
 
457
            if encode:
 
458
                if isinstance(f, basestring):
 
459
                    f = f.encode('utf-8', 'replace')
 
460
                else:
 
461
                    f = codecs.getwriter('utf-8')(f, errors='replace')
 
462
            path = self._rel_controlfilename(path)
 
463
            ctrl_files.append((path, f))
 
464
        self._transport.put_multi(ctrl_files)
296
465
 
297
466
    def _make_control(self):
298
467
        from bzrlib.inventory import Inventory
299
 
        from bzrlib.xml import pack_xml
 
468
        from bzrlib.weavefile import write_weave_v5
 
469
        from bzrlib.weave import Weave
300
470
        
301
 
        os.mkdir(self.controlfilename([]))
302
 
        self.controlfile('README', 'w').write(
 
471
        # Create an empty inventory
 
472
        sio = StringIO()
 
473
        # if we want per-tree root ids then this is the place to set
 
474
        # them; they're not needed for now and so ommitted for
 
475
        # simplicity.
 
476
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
 
477
        empty_inv = sio.getvalue()
 
478
        sio = StringIO()
 
479
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
 
480
        empty_weave = sio.getvalue()
 
481
 
 
482
        dirs = [[], 'revision-store', 'weaves']
 
483
        files = [('README', 
303
484
            "This is a Bazaar-NG control directory.\n"
304
 
            "Do not change any files in this directory.\n")
305
 
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
306
 
        for d in ('text-store', 'inventory-store', 'revision-store'):
307
 
            os.mkdir(self.controlfilename(d))
308
 
        for f in ('revision-history', 'merged-patches',
309
 
                  'pending-merged-patches', 'branch-name',
310
 
                  'branch-lock',
311
 
                  'pending-merges'):
312
 
            self.controlfile(f, 'w').write('')
313
 
        mutter('created control directory in ' + self.base)
314
 
 
315
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
316
 
 
317
 
 
318
 
    def _check_format(self):
 
485
            "Do not change any files in this directory.\n"),
 
486
            ('branch-format', BZR_BRANCH_FORMAT_6),
 
487
            ('revision-history', ''),
 
488
            ('branch-name', ''),
 
489
            ('branch-lock', ''),
 
490
            ('pending-merges', ''),
 
491
            ('inventory', empty_inv),
 
492
            ('inventory.weave', empty_weave),
 
493
            ('ancestry.weave', empty_weave)
 
494
        ]
 
495
        cfn = self._rel_controlfilename
 
496
        self._transport.mkdir_multi([cfn(d) for d in dirs])
 
497
        self.put_controlfiles(files)
 
498
        mutter('created control directory in ' + self._transport.base)
 
499
 
 
500
    def _check_format(self, relax_version_check):
319
501
        """Check this branch format is supported.
320
502
 
321
 
        The current tool only supports the current unstable format.
 
503
        The format level is stored, as an integer, in
 
504
        self._branch_format for code that needs to check it later.
322
505
 
323
506
        In the future, we might need different in-memory Branch
324
507
        classes to support downlevel branches.  But not yet.
325
508
        """
326
 
        # This ignores newlines so that we can open branches created
327
 
        # on Windows from Linux and so on.  I think it might be better
328
 
        # to always make all internal files in unix format.
329
 
        fmt = self.controlfile('branch-format', 'r').read()
330
 
        fmt.replace('\r\n', '')
331
 
        if fmt != BZR_BRANCH_FORMAT:
332
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
 
509
        try:
 
510
            fmt = self.controlfile('branch-format', 'r').read()
 
511
        except NoSuchFile:
 
512
            raise NotBranchError(self.base)
 
513
        mutter("got branch format %r", fmt)
 
514
        if fmt == BZR_BRANCH_FORMAT_6:
 
515
            self._branch_format = 6
 
516
        elif fmt == BZR_BRANCH_FORMAT_5:
 
517
            self._branch_format = 5
 
518
        elif fmt == BZR_BRANCH_FORMAT_4:
 
519
            self._branch_format = 4
 
520
 
 
521
        if (not relax_version_check
 
522
            and self._branch_format not in (5, 6)):
 
523
            raise errors.UnsupportedFormatError(
 
524
                           'sorry, branch format %r not supported' % fmt,
333
525
                           ['use a different bzr version',
334
 
                            'or remove the .bzr directory and "bzr init" again'])
 
526
                            'or remove the .bzr directory'
 
527
                            ' and "bzr init" again'])
335
528
 
336
529
    def get_root_id(self):
337
530
        """Return the id of this branches root"""
352
545
 
353
546
    def read_working_inventory(self):
354
547
        """Read the working inventory."""
355
 
        from bzrlib.inventory import Inventory
356
 
        from bzrlib.xml import unpack_xml
357
 
        from time import time
358
 
        before = time()
359
548
        self.lock_read()
360
549
        try:
361
550
            # ElementTree does its own conversion from UTF-8, so open in
362
551
            # binary.
363
 
            inv = unpack_xml(Inventory,
364
 
                             self.controlfile('inventory', 'rb'))
365
 
            mutter("loaded inventory of %d items in %f"
366
 
                   % (len(inv), time() - before))
367
 
            return inv
 
552
            f = self.controlfile('inventory', 'rb')
 
553
            return bzrlib.xml5.serializer_v5.read_inventory(f)
368
554
        finally:
369
555
            self.unlock()
370
556
            
375
561
        That is to say, the inventory describing changes underway, that
376
562
        will be committed to the next revision.
377
563
        """
378
 
        from bzrlib.atomicfile import AtomicFile
379
 
        from bzrlib.xml import pack_xml
380
 
        
 
564
        from cStringIO import StringIO
381
565
        self.lock_write()
382
566
        try:
383
 
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
384
 
            try:
385
 
                pack_xml(inv, f)
386
 
                f.commit()
387
 
            finally:
388
 
                f.close()
 
567
            sio = StringIO()
 
568
            bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
569
            sio.seek(0)
 
570
            # Transport handles atomicity
 
571
            self.put_controlfile('inventory', sio)
389
572
        finally:
390
573
            self.unlock()
391
574
        
392
575
        mutter('wrote working inventory')
393
576
            
394
 
 
395
577
    inventory = property(read_working_inventory, _write_inventory, None,
396
578
                         """Inventory for the working copy.""")
397
579
 
398
 
 
399
 
    def add(self, files, verbose=False, ids=None):
 
580
    def add(self, files, ids=None):
400
581
        """Make files versioned.
401
582
 
402
 
        Note that the command line normally calls smart_add instead.
 
583
        Note that the command line normally calls smart_add instead,
 
584
        which can automatically recurse.
403
585
 
404
586
        This puts the files in the Added state, so that they will be
405
587
        recorded by the next commit.
415
597
        TODO: Perhaps have an option to add the ids even if the files do
416
598
              not (yet) exist.
417
599
 
418
 
        TODO: Perhaps return the ids of the files?  But then again it
419
 
              is easy to retrieve them if they're needed.
420
 
 
421
 
        TODO: Adding a directory should optionally recurse down and
422
 
              add all non-ignored children.  Perhaps do that in a
423
 
              higher-level method.
 
600
        TODO: Perhaps yield the ids and paths as they're added.
424
601
        """
425
 
        from bzrlib.textui import show_status
426
602
        # TODO: Re-adding a file that is removed in the working copy
427
603
        # should probably put it back with the previous ID.
428
604
        if isinstance(files, basestring):
454
630
                    kind = file_kind(fullpath)
455
631
                except OSError:
456
632
                    # maybe something better?
457
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
633
                    raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
458
634
 
459
 
                if kind != 'file' and kind != 'directory':
460
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
635
                if not InventoryEntry.versionable_kind(kind):
 
636
                    raise BzrError('cannot add: not a versionable file ('
 
637
                                   'i.e. regular file, symlink or directory): %s' % quotefn(f))
461
638
 
462
639
                if file_id is None:
463
640
                    file_id = gen_file_id(f)
464
641
                inv.add_path(f, kind=kind, file_id=file_id)
465
642
 
466
 
                if verbose:
467
 
                    print 'added', quotefn(f)
468
 
 
469
643
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
470
644
 
471
645
            self._write_inventory(inv)
477
651
        """Print `file` to stdout."""
478
652
        self.lock_read()
479
653
        try:
480
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
654
            tree = self.revision_tree(self.get_rev_id(revno))
481
655
            # use inventory as it was in that revision
482
656
            file_id = tree.inventory.path2id(file)
483
657
            if not file_id:
501
675
        is the opposite of add.  Removing it is consistent with most
502
676
        other tools.  Maybe an option.
503
677
        """
504
 
        from bzrlib.textui import show_status
505
678
        ## TODO: Normalize names
506
679
        ## TODO: Remove nested loops; better scalability
507
680
        if isinstance(files, basestring):
532
705
        finally:
533
706
            self.unlock()
534
707
 
535
 
 
536
708
    # FIXME: this doesn't need to be a branch method
537
709
    def set_inventory(self, new_inventory_list):
538
710
        from bzrlib.inventory import Inventory, InventoryEntry
541
713
            name = os.path.basename(path)
542
714
            if name == "":
543
715
                continue
544
 
            inv.add(InventoryEntry(file_id, name, kind, parent))
 
716
            # fixme, there should be a factory function inv,add_?? 
 
717
            if kind == 'directory':
 
718
                inv.add(inventory.InventoryDirectory(file_id, name, parent))
 
719
            elif kind == 'file':
 
720
                inv.add(inventory.InventoryFile(file_id, name, parent))
 
721
            elif kind == 'symlink':
 
722
                inv.add(inventory.InventoryLink(file_id, name, parent))
 
723
            else:
 
724
                raise BzrError("unknown kind %r" % kind)
545
725
        self._write_inventory(inv)
546
726
 
547
 
 
548
727
    def unknowns(self):
549
728
        """Return all unknown files.
550
729
 
565
744
 
566
745
 
567
746
    def append_revision(self, *revision_ids):
568
 
        from bzrlib.atomicfile import AtomicFile
569
 
 
570
747
        for revision_id in revision_ids:
571
748
            mutter("add {%s} to revision-history" % revision_id)
572
 
 
573
 
        rev_history = self.revision_history()
574
 
        rev_history.extend(revision_ids)
575
 
 
576
 
        f = AtomicFile(self.controlfilename('revision-history'))
577
 
        try:
578
 
            for rev_id in rev_history:
579
 
                print >>f, rev_id
580
 
            f.commit()
581
 
        finally:
582
 
            f.close()
 
749
        self.lock_write()
 
750
        try:
 
751
            rev_history = self.revision_history()
 
752
            rev_history.extend(revision_ids)
 
753
            self.put_controlfile('revision-history', '\n'.join(rev_history))
 
754
        finally:
 
755
            self.unlock()
 
756
 
 
757
    def has_revision(self, revision_id):
 
758
        """True if this branch has a copy of the revision.
 
759
 
 
760
        This does not necessarily imply the revision is merge
 
761
        or on the mainline."""
 
762
        return (revision_id is None
 
763
                or revision_id in self.revision_store)
 
764
 
 
765
    def get_revision_xml_file(self, revision_id):
 
766
        """Return XML file object for revision object."""
 
767
        if not revision_id or not isinstance(revision_id, basestring):
 
768
            raise InvalidRevisionId(revision_id)
 
769
 
 
770
        self.lock_read()
 
771
        try:
 
772
            try:
 
773
                return self.revision_store[revision_id]
 
774
            except (IndexError, KeyError):
 
775
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
776
        finally:
 
777
            self.unlock()
 
778
 
 
779
    #deprecated
 
780
    get_revision_xml = get_revision_xml_file
 
781
 
 
782
    def get_revision_xml(self, revision_id):
 
783
        return self.get_revision_xml_file(revision_id).read()
583
784
 
584
785
 
585
786
    def get_revision(self, revision_id):
586
787
        """Return the Revision object for a named revision"""
587
 
        from bzrlib.revision import Revision
588
 
        from bzrlib.xml import unpack_xml
 
788
        xml_file = self.get_revision_xml_file(revision_id)
589
789
 
590
 
        self.lock_read()
591
790
        try:
592
 
            if not revision_id or not isinstance(revision_id, basestring):
593
 
                raise ValueError('invalid revision-id: %r' % revision_id)
594
 
            r = unpack_xml(Revision, self.revision_store[revision_id])
595
 
        finally:
596
 
            self.unlock()
 
791
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
 
792
        except SyntaxError, e:
 
793
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
794
                                         [revision_id,
 
795
                                          str(e)])
597
796
            
598
797
        assert r.revision_id == revision_id
599
798
        return r
600
 
        
 
799
 
 
800
    def get_revision_delta(self, revno):
 
801
        """Return the delta for one revision.
 
802
 
 
803
        The delta is relative to its mainline predecessor, or the
 
804
        empty tree for revision 1.
 
805
        """
 
806
        assert isinstance(revno, int)
 
807
        rh = self.revision_history()
 
808
        if not (1 <= revno <= len(rh)):
 
809
            raise InvalidRevisionNumber(revno)
 
810
 
 
811
        # revno is 1-based; list is 0-based
 
812
 
 
813
        new_tree = self.revision_tree(rh[revno-1])
 
814
        if revno == 1:
 
815
            old_tree = EmptyTree()
 
816
        else:
 
817
            old_tree = self.revision_tree(rh[revno-2])
 
818
 
 
819
        return compare_trees(old_tree, new_tree)
601
820
 
602
821
    def get_revision_sha1(self, revision_id):
603
822
        """Hash the stored value of a revision, and return it."""
607
826
        # the revision, (add signatures/remove signatures) and still
608
827
        # have all hash pointers stay consistent.
609
828
        # But for now, just hash the contents.
610
 
        return sha_file(self.revision_store[revision_id])
611
 
 
612
 
 
613
 
    def get_inventory(self, inventory_id):
614
 
        """Get Inventory object by hash.
615
 
 
616
 
        TODO: Perhaps for this and similar methods, take a revision
617
 
               parameter which can be either an integer revno or a
618
 
               string hash."""
619
 
        from bzrlib.inventory import Inventory
620
 
        from bzrlib.xml import unpack_xml
621
 
 
622
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
623
 
            
624
 
 
625
 
    def get_inventory_sha1(self, inventory_id):
 
829
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
830
 
 
831
    def get_ancestry(self, revision_id):
 
832
        """Return a list of revision-ids integrated by a revision.
 
833
        
 
834
        This currently returns a list, but the ordering is not guaranteed:
 
835
        treat it as a set.
 
836
        """
 
837
        if revision_id is None:
 
838
            return [None]
 
839
        w = self.get_inventory_weave()
 
840
        return [None] + map(w.idx_to_name,
 
841
                            w.inclusions([w.lookup(revision_id)]))
 
842
 
 
843
    def get_inventory_weave(self):
 
844
        return self.control_weaves.get_weave('inventory',
 
845
                                             self.get_transaction())
 
846
 
 
847
    def get_inventory(self, revision_id):
 
848
        """Get Inventory object by hash."""
 
849
        xml = self.get_inventory_xml(revision_id)
 
850
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
851
 
 
852
    def get_inventory_xml(self, revision_id):
 
853
        """Get inventory XML as a file object."""
 
854
        try:
 
855
            assert isinstance(revision_id, basestring), type(revision_id)
 
856
            iw = self.get_inventory_weave()
 
857
            return iw.get_text(iw.lookup(revision_id))
 
858
        except IndexError:
 
859
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
860
 
 
861
    def get_inventory_sha1(self, revision_id):
626
862
        """Return the sha1 hash of the inventory entry
627
863
        """
628
 
        return sha_file(self.inventory_store[inventory_id])
629
 
 
 
864
        return self.get_revision(revision_id).inventory_sha1
630
865
 
631
866
    def get_revision_inventory(self, revision_id):
632
867
        """Return inventory of a past revision."""
633
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
868
        # TODO: Unify this with get_inventory()
 
869
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
634
870
        # must be the same as its revision, so this is trivial.
635
871
        if revision_id == None:
636
 
            from bzrlib.inventory import Inventory
637
872
            return Inventory(self.get_root_id())
638
873
        else:
639
874
            return self.get_inventory(revision_id)
640
875
 
641
 
 
642
876
    def revision_history(self):
643
 
        """Return sequence of revision hashes on to this branch.
644
 
 
645
 
        >>> ScratchBranch().revision_history()
646
 
        []
647
 
        """
 
877
        """Return sequence of revision hashes on to this branch."""
648
878
        self.lock_read()
649
879
        try:
650
 
            return [l.rstrip('\r\n') for l in
 
880
            transaction = self.get_transaction()
 
881
            history = transaction.map.find_revision_history()
 
882
            if history is not None:
 
883
                mutter("cache hit for revision-history in %s", self)
 
884
                return list(history)
 
885
            history = [l.rstrip('\r\n') for l in
651
886
                    self.controlfile('revision-history', 'r').readlines()]
 
887
            transaction.map.add_revision_history(history)
 
888
            # this call is disabled because revision_history is 
 
889
            # not really an object yet, and the transaction is for objects.
 
890
            # transaction.register_clean(history, precious=True)
 
891
            return list(history)
652
892
        finally:
653
893
            self.unlock()
654
894
 
655
 
 
656
895
    def common_ancestor(self, other, self_revno=None, other_revno=None):
657
896
        """
658
 
        >>> import commit
 
897
        >>> from bzrlib.commit import commit
659
898
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
660
899
        >>> sb.common_ancestor(sb) == (None, None)
661
900
        True
662
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
901
        >>> commit(sb, "Committing first revision", verbose=False)
663
902
        >>> sb.common_ancestor(sb)[0]
664
903
        1
665
904
        >>> clone = sb.clone()
666
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
905
        >>> commit(sb, "Committing second revision", verbose=False)
667
906
        >>> sb.common_ancestor(sb)[0]
668
907
        2
669
908
        >>> sb.common_ancestor(clone)[0]
670
909
        1
671
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
910
        >>> commit(clone, "Committing divergent second revision", 
672
911
        ...               verbose=False)
673
912
        >>> sb.common_ancestor(clone)[0]
674
913
        1
697
936
                return r+1, my_history[r]
698
937
        return None, None
699
938
 
700
 
    def enum_history(self, direction):
701
 
        """Return (revno, revision_id) for history of branch.
702
 
 
703
 
        direction
704
 
            'forward' is from earliest to latest
705
 
            'reverse' is from latest to earliest
706
 
        """
707
 
        rh = self.revision_history()
708
 
        if direction == 'forward':
709
 
            i = 1
710
 
            for rid in rh:
711
 
                yield i, rid
712
 
                i += 1
713
 
        elif direction == 'reverse':
714
 
            i = len(rh)
715
 
            while i > 0:
716
 
                yield i, rh[i-1]
717
 
                i -= 1
718
 
        else:
719
 
            raise ValueError('invalid history direction', direction)
720
 
 
721
939
 
722
940
    def revno(self):
723
941
        """Return current revision number for this branch.
728
946
        return len(self.revision_history())
729
947
 
730
948
 
731
 
    def last_patch(self):
 
949
    def last_revision(self):
732
950
        """Return last patch hash, or None if no history.
733
951
        """
734
952
        ph = self.revision_history()
738
956
            return None
739
957
 
740
958
 
741
 
    def missing_revisions(self, other, stop_revision=None):
742
 
        """
 
959
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
960
        """Return a list of new revisions that would perfectly fit.
 
961
        
743
962
        If self and other have not diverged, return a list of the revisions
744
963
        present in other, but missing from self.
745
964
 
765
984
        Traceback (most recent call last):
766
985
        DivergedBranches: These branches have diverged.
767
986
        """
 
987
        # FIXME: If the branches have diverged, but the latest
 
988
        # revision in this branch is completely merged into the other,
 
989
        # then we should still be able to pull.
768
990
        self_history = self.revision_history()
769
991
        self_len = len(self_history)
770
992
        other_history = other.revision_history()
776
998
 
777
999
        if stop_revision is None:
778
1000
            stop_revision = other_len
779
 
        elif stop_revision > other_len:
780
 
            raise NoSuchRevision(self, stop_revision)
781
 
        
 
1001
        else:
 
1002
            assert isinstance(stop_revision, int)
 
1003
            if stop_revision > other_len:
 
1004
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
782
1005
        return other_history[self_len:stop_revision]
783
1006
 
784
 
 
785
1007
    def update_revisions(self, other, stop_revision=None):
786
 
        """Pull in all new revisions from other branch.
787
 
        
788
 
        >>> from bzrlib.commit import commit
789
 
        >>> bzrlib.trace.silent = True
790
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
791
 
        >>> br1.add('foo')
792
 
        >>> br1.add('bar')
793
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
794
 
        >>> br2 = ScratchBranch()
795
 
        >>> br2.update_revisions(br1)
796
 
        Added 2 texts.
797
 
        Added 1 inventories.
798
 
        Added 1 revisions.
799
 
        >>> br2.revision_history()
800
 
        [u'REVISION-ID-1']
801
 
        >>> br2.update_revisions(br1)
802
 
        Added 0 texts.
803
 
        Added 0 inventories.
804
 
        Added 0 revisions.
805
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
806
 
        True
807
 
        """
808
 
        from bzrlib.progress import ProgressBar
809
 
 
810
 
        pb = ProgressBar()
811
 
 
812
 
        pb.update('comparing histories')
813
 
        revision_ids = self.missing_revisions(other, stop_revision)
814
 
 
815
 
        if hasattr(other.revision_store, "prefetch"):
816
 
            other.revision_store.prefetch(revision_ids)
817
 
        if hasattr(other.inventory_store, "prefetch"):
818
 
            inventory_ids = [other.get_revision(r).inventory_id
819
 
                             for r in revision_ids]
820
 
            other.inventory_store.prefetch(inventory_ids)
821
 
                
822
 
        revisions = []
823
 
        needed_texts = set()
824
 
        i = 0
825
 
        for rev_id in revision_ids:
826
 
            i += 1
827
 
            pb.update('fetching revision', i, len(revision_ids))
828
 
            rev = other.get_revision(rev_id)
829
 
            revisions.append(rev)
830
 
            inv = other.get_inventory(str(rev.inventory_id))
831
 
            for key, entry in inv.iter_entries():
832
 
                if entry.text_id is None:
833
 
                    continue
834
 
                if entry.text_id not in self.text_store:
835
 
                    needed_texts.add(entry.text_id)
836
 
 
837
 
        pb.clear()
838
 
                    
839
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
840
 
        print "Added %d texts." % count 
841
 
        inventory_ids = [ f.inventory_id for f in revisions ]
842
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
843
 
                                                inventory_ids)
844
 
        print "Added %d inventories." % count 
845
 
        revision_ids = [ f.revision_id for f in revisions]
846
 
        count = self.revision_store.copy_multi(other.revision_store, 
847
 
                                               revision_ids)
848
 
        for revision_id in revision_ids:
849
 
            self.append_revision(revision_id)
850
 
        print "Added %d revisions." % count
851
 
                    
852
 
        
 
1008
        """Pull in new perfect-fit revisions."""
 
1009
        from bzrlib.fetch import greedy_fetch
 
1010
        from bzrlib.revision import get_intervening_revisions
 
1011
        if stop_revision is None:
 
1012
            stop_revision = other.last_revision()
 
1013
        greedy_fetch(to_branch=self, from_branch=other,
 
1014
                     revision=stop_revision)
 
1015
        pullable_revs = self.missing_revisions(
 
1016
            other, other.revision_id_to_revno(stop_revision))
 
1017
        if pullable_revs:
 
1018
            greedy_fetch(to_branch=self,
 
1019
                         from_branch=other,
 
1020
                         revision=pullable_revs[-1])
 
1021
            self.append_revision(*pullable_revs)
 
1022
    
 
1023
 
853
1024
    def commit(self, *args, **kw):
854
 
        from bzrlib.commit import commit
855
 
        commit(self, *args, **kw)
856
 
        
857
 
 
858
 
    def lookup_revision(self, revision):
859
 
        """Return the revision identifier for a given revision information."""
860
 
        revno, info = self.get_revision_info(revision)
861
 
        return info
862
 
 
863
 
    def get_revision_info(self, revision):
864
 
        """Return (revno, revision id) for revision identifier.
865
 
 
866
 
        revision can be an integer, in which case it is assumed to be revno (though
867
 
            this will translate negative values into positive ones)
868
 
        revision can also be a string, in which case it is parsed for something like
869
 
            'date:' or 'revid:' etc.
870
 
        """
871
 
        if revision is None:
872
 
            return 0, None
873
 
        revno = None
874
 
        try:# Convert to int if possible
875
 
            revision = int(revision)
876
 
        except ValueError:
877
 
            pass
878
 
        revs = self.revision_history()
879
 
        if isinstance(revision, int):
880
 
            if revision == 0:
881
 
                return 0, None
882
 
            # Mabye we should do this first, but we don't need it if revision == 0
883
 
            if revision < 0:
884
 
                revno = len(revs) + revision + 1
885
 
            else:
886
 
                revno = revision
887
 
        elif isinstance(revision, basestring):
888
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
889
 
                if revision.startswith(prefix):
890
 
                    revno = func(self, revs, revision)
891
 
                    break
892
 
            else:
893
 
                raise BzrError('No namespace registered for string: %r' % revision)
894
 
 
895
 
        if revno is None or revno <= 0 or revno > len(revs):
896
 
            raise BzrError("no such revision %s" % revision)
897
 
        return revno, revs[revno-1]
898
 
 
899
 
    def _namespace_revno(self, revs, revision):
900
 
        """Lookup a revision by revision number"""
901
 
        assert revision.startswith('revno:')
902
 
        try:
903
 
            return int(revision[6:])
904
 
        except ValueError:
905
 
            return None
906
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
907
 
 
908
 
    def _namespace_revid(self, revs, revision):
909
 
        assert revision.startswith('revid:')
910
 
        try:
911
 
            return revs.index(revision[6:]) + 1
912
 
        except ValueError:
913
 
            return None
914
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
915
 
 
916
 
    def _namespace_last(self, revs, revision):
917
 
        assert revision.startswith('last:')
918
 
        try:
919
 
            offset = int(revision[5:])
920
 
        except ValueError:
921
 
            return None
922
 
        else:
923
 
            if offset <= 0:
924
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
925
 
            return len(revs) - offset + 1
926
 
    REVISION_NAMESPACES['last:'] = _namespace_last
927
 
 
928
 
    def _namespace_tag(self, revs, revision):
929
 
        assert revision.startswith('tag:')
930
 
        raise BzrError('tag: namespace registered, but not implemented.')
931
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
932
 
 
933
 
    def _namespace_date(self, revs, revision):
934
 
        assert revision.startswith('date:')
935
 
        import datetime
936
 
        # Spec for date revisions:
937
 
        #   date:value
938
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
939
 
        #   it can also start with a '+/-/='. '+' says match the first
940
 
        #   entry after the given date. '-' is match the first entry before the date
941
 
        #   '=' is match the first entry after, but still on the given date.
942
 
        #
943
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
944
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
945
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
946
 
        #       May 13th, 2005 at 0:00
947
 
        #
948
 
        #   So the proper way of saying 'give me all entries for today' is:
949
 
        #       -r {date:+today}:{date:-tomorrow}
950
 
        #   The default is '=' when not supplied
951
 
        val = revision[5:]
952
 
        match_style = '='
953
 
        if val[:1] in ('+', '-', '='):
954
 
            match_style = val[:1]
955
 
            val = val[1:]
956
 
 
957
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
958
 
        if val.lower() == 'yesterday':
959
 
            dt = today - datetime.timedelta(days=1)
960
 
        elif val.lower() == 'today':
961
 
            dt = today
962
 
        elif val.lower() == 'tomorrow':
963
 
            dt = today + datetime.timedelta(days=1)
964
 
        else:
965
 
            import re
966
 
            # This should be done outside the function to avoid recompiling it.
967
 
            _date_re = re.compile(
968
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
969
 
                    r'(,|T)?\s*'
970
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
971
 
                )
972
 
            m = _date_re.match(val)
973
 
            if not m or (not m.group('date') and not m.group('time')):
974
 
                raise BzrError('Invalid revision date %r' % revision)
975
 
 
976
 
            if m.group('date'):
977
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
978
 
            else:
979
 
                year, month, day = today.year, today.month, today.day
980
 
            if m.group('time'):
981
 
                hour = int(m.group('hour'))
982
 
                minute = int(m.group('minute'))
983
 
                if m.group('second'):
984
 
                    second = int(m.group('second'))
985
 
                else:
986
 
                    second = 0
987
 
            else:
988
 
                hour, minute, second = 0,0,0
989
 
 
990
 
            dt = datetime.datetime(year=year, month=month, day=day,
991
 
                    hour=hour, minute=minute, second=second)
992
 
        first = dt
993
 
        last = None
994
 
        reversed = False
995
 
        if match_style == '-':
996
 
            reversed = True
997
 
        elif match_style == '=':
998
 
            last = dt + datetime.timedelta(days=1)
999
 
 
1000
 
        if reversed:
1001
 
            for i in range(len(revs)-1, -1, -1):
1002
 
                r = self.get_revision(revs[i])
1003
 
                # TODO: Handle timezone.
1004
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1005
 
                if first >= dt and (last is None or dt >= last):
1006
 
                    return i+1
1007
 
        else:
1008
 
            for i in range(len(revs)):
1009
 
                r = self.get_revision(revs[i])
1010
 
                # TODO: Handle timezone.
1011
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1012
 
                if first <= dt and (last is None or dt <= last):
1013
 
                    return i+1
1014
 
    REVISION_NAMESPACES['date:'] = _namespace_date
 
1025
        from bzrlib.commit import Commit
 
1026
        Commit().commit(self, *args, **kw)
 
1027
    
 
1028
    def revision_id_to_revno(self, revision_id):
 
1029
        """Given a revision id, return its revno"""
 
1030
        if revision_id is None:
 
1031
            return 0
 
1032
        history = self.revision_history()
 
1033
        try:
 
1034
            return history.index(revision_id) + 1
 
1035
        except ValueError:
 
1036
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
1037
 
 
1038
    def get_rev_id(self, revno, history=None):
 
1039
        """Find the revision id of the specified revno."""
 
1040
        if revno == 0:
 
1041
            return None
 
1042
        if history is None:
 
1043
            history = self.revision_history()
 
1044
        elif revno <= 0 or revno > len(history):
 
1045
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
1046
        return history[revno - 1]
1015
1047
 
1016
1048
    def revision_tree(self, revision_id):
1017
1049
        """Return Tree for a revision on this branch.
1018
1050
 
1019
1051
        `revision_id` may be None for the null revision, in which case
1020
1052
        an `EmptyTree` is returned."""
1021
 
        from bzrlib.tree import EmptyTree, RevisionTree
1022
1053
        # TODO: refactor this to use an existing revision object
1023
1054
        # so we don't need to read it in twice.
1024
1055
        if revision_id == None:
1025
 
            return EmptyTree(self.get_root_id())
 
1056
            return EmptyTree()
1026
1057
        else:
1027
1058
            inv = self.get_revision_inventory(revision_id)
1028
 
            return RevisionTree(self.text_store, inv)
 
1059
            return RevisionTree(self.weave_store, inv, revision_id)
1029
1060
 
1030
1061
 
1031
1062
    def working_tree(self):
1032
1063
        """Return a `Tree` for the working copy."""
1033
 
        from workingtree import WorkingTree
1034
 
        return WorkingTree(self.base, self.read_working_inventory())
 
1064
        from bzrlib.workingtree import WorkingTree
 
1065
        # TODO: In the future, WorkingTree should utilize Transport
 
1066
        # RobertCollins 20051003 - I don't think it should - working trees are
 
1067
        # much more complex to keep consistent than our careful .bzr subset.
 
1068
        # instead, we should say that working trees are local only, and optimise
 
1069
        # for that.
 
1070
        return WorkingTree(self._transport.base, self.read_working_inventory())
1035
1071
 
1036
1072
 
1037
1073
    def basis_tree(self):
1039
1075
 
1040
1076
        If there are no revisions yet, return an `EmptyTree`.
1041
1077
        """
1042
 
        from bzrlib.tree import EmptyTree, RevisionTree
1043
 
        r = self.last_patch()
1044
 
        if r == None:
1045
 
            return EmptyTree(self.get_root_id())
1046
 
        else:
1047
 
            return RevisionTree(self.text_store, self.get_revision_inventory(r))
1048
 
 
 
1078
        return self.revision_tree(self.last_revision())
1049
1079
 
1050
1080
 
1051
1081
    def rename_one(self, from_rel, to_rel):
1083
1113
 
1084
1114
            inv.rename(file_id, to_dir_id, to_tail)
1085
1115
 
1086
 
            print "%s => %s" % (from_rel, to_rel)
1087
 
 
1088
1116
            from_abs = self.abspath(from_rel)
1089
1117
            to_abs = self.abspath(to_rel)
1090
1118
            try:
1091
 
                os.rename(from_abs, to_abs)
 
1119
                rename(from_abs, to_abs)
1092
1120
            except OSError, e:
1093
1121
                raise BzrError("failed to rename %r to %r: %s"
1094
1122
                        % (from_abs, to_abs, e[1]),
1109
1137
 
1110
1138
        Note that to_name is only the last component of the new name;
1111
1139
        this doesn't change the directory.
 
1140
 
 
1141
        This returns a list of (from_path, to_path) pairs for each
 
1142
        entry that is moved.
1112
1143
        """
 
1144
        result = []
1113
1145
        self.lock_write()
1114
1146
        try:
1115
1147
            ## TODO: Option to move IDs only
1150
1182
            for f in from_paths:
1151
1183
                name_tail = splitpath(f)[-1]
1152
1184
                dest_path = appendpath(to_name, name_tail)
1153
 
                print "%s => %s" % (f, dest_path)
 
1185
                result.append((f, dest_path))
1154
1186
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1155
1187
                try:
1156
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1188
                    rename(self.abspath(f), self.abspath(dest_path))
1157
1189
                except OSError, e:
1158
1190
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1159
1191
                            ["rename rolled back"])
1162
1194
        finally:
1163
1195
            self.unlock()
1164
1196
 
 
1197
        return result
 
1198
 
1165
1199
 
1166
1200
    def revert(self, filenames, old_tree=None, backups=True):
1167
1201
        """Restore selected files to the versions from a previous tree.
1213
1247
        These are revisions that have been merged into the working
1214
1248
        directory but not yet committed.
1215
1249
        """
1216
 
        cfn = self.controlfilename('pending-merges')
1217
 
        if not os.path.exists(cfn):
 
1250
        cfn = self._rel_controlfilename('pending-merges')
 
1251
        if not self._transport.has(cfn):
1218
1252
            return []
1219
1253
        p = []
1220
1254
        for l in self.controlfile('pending-merges', 'r').readlines():
1222
1256
        return p
1223
1257
 
1224
1258
 
1225
 
    def add_pending_merge(self, revision_id):
1226
 
        from bzrlib.revision import validate_revision_id
1227
 
 
1228
 
        validate_revision_id(revision_id)
1229
 
 
 
1259
    def add_pending_merge(self, *revision_ids):
 
1260
        # TODO: Perhaps should check at this point that the
 
1261
        # history of the revision is actually present?
1230
1262
        p = self.pending_merges()
1231
 
        if revision_id in p:
1232
 
            return
1233
 
        p.append(revision_id)
1234
 
        self.set_pending_merges(p)
1235
 
 
 
1263
        updated = False
 
1264
        for rev_id in revision_ids:
 
1265
            if rev_id in p:
 
1266
                continue
 
1267
            p.append(rev_id)
 
1268
            updated = True
 
1269
        if updated:
 
1270
            self.set_pending_merges(p)
1236
1271
 
1237
1272
    def set_pending_merges(self, rev_list):
 
1273
        self.lock_write()
 
1274
        try:
 
1275
            self.put_controlfile('pending-merges', '\n'.join(rev_list))
 
1276
        finally:
 
1277
            self.unlock()
 
1278
 
 
1279
 
 
1280
    def get_parent(self):
 
1281
        """Return the parent location of the branch.
 
1282
 
 
1283
        This is the default location for push/pull/missing.  The usual
 
1284
        pattern is that the user can override it by specifying a
 
1285
        location.
 
1286
        """
 
1287
        import errno
 
1288
        _locs = ['parent', 'pull', 'x-pull']
 
1289
        for l in _locs:
 
1290
            try:
 
1291
                return self.controlfile(l, 'r').read().strip('\n')
 
1292
            except IOError, e:
 
1293
                if e.errno != errno.ENOENT:
 
1294
                    raise
 
1295
        return None
 
1296
 
 
1297
 
 
1298
    def set_parent(self, url):
 
1299
        # TODO: Maybe delete old location files?
1238
1300
        from bzrlib.atomicfile import AtomicFile
1239
1301
        self.lock_write()
1240
1302
        try:
1241
 
            f = AtomicFile(self.controlfilename('pending-merges'))
 
1303
            f = AtomicFile(self.controlfilename('parent'))
1242
1304
            try:
1243
 
                for l in rev_list:
1244
 
                    print >>f, l
 
1305
                f.write(url + '\n')
1245
1306
                f.commit()
1246
1307
            finally:
1247
1308
                f.close()
1248
1309
        finally:
1249
1310
            self.unlock()
1250
1311
 
1251
 
 
1252
 
 
1253
 
class ScratchBranch(Branch):
 
1312
    def check_revno(self, revno):
 
1313
        """\
 
1314
        Check whether a revno corresponds to any revision.
 
1315
        Zero (the NULL revision) is considered valid.
 
1316
        """
 
1317
        if revno != 0:
 
1318
            self.check_real_revno(revno)
 
1319
            
 
1320
    def check_real_revno(self, revno):
 
1321
        """\
 
1322
        Check whether a revno corresponds to a real revision.
 
1323
        Zero (the NULL revision) is considered invalid
 
1324
        """
 
1325
        if revno < 1 or revno > self.revno():
 
1326
            raise InvalidRevisionNumber(revno)
 
1327
        
 
1328
        
 
1329
        
 
1330
 
 
1331
 
 
1332
class ScratchBranch(_Branch):
1254
1333
    """Special test class: a branch that cleans up after itself.
1255
1334
 
1256
1335
    >>> b = ScratchBranch()
1273
1352
        if base is None:
1274
1353
            base = mkdtemp()
1275
1354
            init = True
1276
 
        Branch.__init__(self, base, init=init)
 
1355
        if isinstance(base, basestring):
 
1356
            base = get_transport(base)
 
1357
        _Branch.__init__(self, base, init=init)
1277
1358
        for d in dirs:
1278
 
            os.mkdir(self.abspath(d))
 
1359
            self._transport.mkdir(d)
1279
1360
            
1280
1361
        for f in files:
1281
 
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
 
1362
            self._transport.put(f, 'content of %s' % f)
1282
1363
 
1283
1364
 
1284
1365
    def clone(self):
1285
1366
        """
1286
1367
        >>> orig = ScratchBranch(files=["file1", "file2"])
1287
1368
        >>> clone = orig.clone()
1288
 
        >>> os.path.samefile(orig.base, clone.base)
 
1369
        >>> if os.name != 'nt':
 
1370
        ...   os.path.samefile(orig.base, clone.base)
 
1371
        ... else:
 
1372
        ...   orig.base == clone.base
 
1373
        ...
1289
1374
        False
1290
1375
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1291
1376
        True
1296
1381
        os.rmdir(base)
1297
1382
        copytree(self.base, base, symlinks=True)
1298
1383
        return ScratchBranch(base=base)
1299
 
        
 
1384
 
1300
1385
    def __del__(self):
1301
1386
        self.destroy()
1302
1387
 
1315
1400
                for name in files:
1316
1401
                    os.chmod(os.path.join(root, name), 0700)
1317
1402
            rmtree(self.base)
1318
 
        self.base = None
 
1403
        self._transport = None
1319
1404
 
1320
1405
    
1321
1406
 
1371
1456
    """Return a new tree-root file id."""
1372
1457
    return gen_file_id('TREE_ROOT')
1373
1458
 
 
1459