/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Lalo Martins
  • Date: 2005-09-07 13:17:26 UTC
  • mto: (1185.1.22)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: lalo@exoweb.net-20050907131726-8d8d4ab45a390a9f
splitting a "LocalBranch" class off from Branch

Show diffs side-by-side

added added

removed removed

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