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