/brz/remove-bazaar

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