~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-05 06:38:18 UTC
  • Revision ID: mbp@sourcefrog.net-20050505063818-3eb3260343878325
- do upload CHANGELOG to web server, even though it's autogenerated

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
 
18
from sets import Set
 
19
 
18
20
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
19
21
import traceback, socket, fnmatch, difflib, time
20
22
from binascii import hexlify
22
24
import bzrlib
23
25
from inventory import Inventory
24
26
from trace import mutter, note
25
 
from tree import Tree, EmptyTree, RevisionTree
 
27
from tree import Tree, EmptyTree, RevisionTree, WorkingTree
26
28
from inventory import InventoryEntry, Inventory
27
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
28
30
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
29
31
     joinpath, sha_string, file_kind, local_time_offset, appendpath
30
32
from store import ImmutableStore
31
33
from revision import Revision
32
 
from errors import BzrError
 
34
from errors import bailout, BzrError
33
35
from textui import show_status
 
36
from diff import diff_trees
34
37
 
35
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
36
39
## TODO: Maybe include checks for common corruption of newlines, etc?
37
40
 
38
41
 
39
42
 
40
 
def find_branch(f, **args):
41
 
    if f and (f.startswith('http://') or f.startswith('https://')):
42
 
        import remotebranch 
43
 
        return remotebranch.RemoteBranch(f, **args)
44
 
    else:
45
 
        return Branch(f, **args)
46
 
 
47
 
 
48
 
 
49
 
def _relpath(base, path):
50
 
    """Return path relative to base, or raise exception.
51
 
 
52
 
    The path may be either an absolute path or a path relative to the
53
 
    current working directory.
54
 
 
55
 
    Lifted out of Branch.relpath for ease of testing.
56
 
 
57
 
    os.path.commonprefix (python2.4) has a bad bug that it works just
58
 
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
59
 
    avoids that problem."""
60
 
    rp = os.path.abspath(path)
61
 
 
62
 
    s = []
63
 
    head = rp
64
 
    while len(head) >= len(base):
65
 
        if head == base:
66
 
            break
67
 
        head, tail = os.path.split(head)
68
 
        if tail:
69
 
            s.insert(0, tail)
70
 
    else:
71
 
        from errors import NotBranchError
72
 
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
73
 
 
74
 
    return os.sep.join(s)
75
 
        
76
 
 
77
43
def find_branch_root(f=None):
78
44
    """Find the branch root enclosing f, or pwd.
79
45
 
80
 
    f may be a filename or a URL.
81
 
 
82
46
    It is not necessary that f exists.
83
47
 
84
48
    Basically we keep looking up until we find the control directory or
89
53
        f = os.path.realpath(f)
90
54
    else:
91
55
        f = os.path.abspath(f)
92
 
    if not os.path.exists(f):
93
 
        raise BzrError('%r does not exist' % f)
94
 
        
95
56
 
96
57
    orig_f = f
97
58
 
104
65
            raise BzrError('%r is not in a branch' % orig_f)
105
66
        f = head
106
67
    
107
 
class DivergedBranches(Exception):
108
 
    def __init__(self, branch1, branch2):
109
 
        self.branch1 = branch1
110
 
        self.branch2 = branch2
111
 
        Exception.__init__(self, "These branches have diverged.")
 
68
 
112
69
 
113
70
######################################################################
114
71
# branch objects
115
72
 
116
 
class Branch(object):
 
73
class Branch:
117
74
    """Branch holding a history of revisions.
118
75
 
119
76
    base
120
77
        Base directory of the branch.
121
 
 
122
 
    _lock_mode
123
 
        None, or 'r' or 'w'
124
 
 
125
 
    _lock_count
126
 
        If _lock_mode is true, a positive count of the number of times the
127
 
        lock has been taken.
128
 
 
129
 
    _lock
130
 
        Lock object from bzrlib.lock.
131
78
    """
132
 
    base = None
133
 
    _lock_mode = None
134
 
    _lock_count = None
135
 
    _lock = None
 
79
    _lockmode = None
136
80
    
137
 
    def __init__(self, base, init=False, find_root=True):
 
81
    def __init__(self, base, init=False, find_root=True, lock_mode='w'):
138
82
        """Create new branch object at a particular location.
139
83
 
140
84
        base -- Base directory for the branch.
157
101
        else:
158
102
            self.base = os.path.realpath(base)
159
103
            if not isdir(self.controlfilename('.')):
160
 
                from errors import NotBranchError
161
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
162
 
                                     ['use "bzr init" to initialize a new working tree',
163
 
                                      'current bzr can only operate from top-of-tree'])
 
104
                bailout("not a bzr branch: %s" % quotefn(base),
 
105
                        ['use "bzr init" to initialize a new working tree',
 
106
                         'current bzr can only operate from top-of-tree'])
164
107
        self._check_format()
 
108
        self.lock(lock_mode)
165
109
 
166
110
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
167
111
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
175
119
    __repr__ = __str__
176
120
 
177
121
 
178
 
    def __del__(self):
179
 
        if self._lock_mode or self._lock:
180
 
            from warnings import warn
181
 
            warn("branch %r was not explicitly unlocked" % self)
182
 
            self._lock.unlock()
183
 
 
184
 
 
185
 
 
186
 
    def lock_write(self):
187
 
        if self._lock_mode:
188
 
            if self._lock_mode != 'w':
189
 
                from errors import LockError
190
 
                raise LockError("can't upgrade to a write lock from %r" %
191
 
                                self._lock_mode)
192
 
            self._lock_count += 1
193
 
        else:
194
 
            from bzrlib.lock import WriteLock
195
 
 
196
 
            self._lock = WriteLock(self.controlfilename('branch-lock'))
197
 
            self._lock_mode = 'w'
198
 
            self._lock_count = 1
199
 
 
200
 
 
201
 
 
202
 
    def lock_read(self):
203
 
        if self._lock_mode:
204
 
            assert self._lock_mode in ('r', 'w'), \
205
 
                   "invalid lock mode %r" % self._lock_mode
206
 
            self._lock_count += 1
207
 
        else:
208
 
            from bzrlib.lock import ReadLock
209
 
 
210
 
            self._lock = ReadLock(self.controlfilename('branch-lock'))
211
 
            self._lock_mode = 'r'
212
 
            self._lock_count = 1
213
 
                        
214
 
 
215
 
            
216
 
    def unlock(self):
217
 
        if not self._lock_mode:
218
 
            from errors import LockError
219
 
            raise LockError('branch %r is not locked' % (self))
220
 
 
221
 
        if self._lock_count > 1:
222
 
            self._lock_count -= 1
223
 
        else:
224
 
            self._lock.unlock()
225
 
            self._lock = None
226
 
            self._lock_mode = self._lock_count = None
 
122
 
 
123
    def lock(self, mode='w'):
 
124
        """Lock the on-disk branch, excluding other processes."""
 
125
        try:
 
126
            import fcntl
 
127
 
 
128
            if mode == 'w':
 
129
                lm = fcntl.LOCK_EX
 
130
                om = os.O_WRONLY | os.O_CREAT
 
131
            elif mode == 'r':
 
132
                lm = fcntl.LOCK_SH
 
133
                om = os.O_RDONLY
 
134
            else:
 
135
                raise BzrError("invalid locking mode %r" % mode)
 
136
 
 
137
            # XXX: Old branches might not have the lock file, and
 
138
            # won't get one until someone does a write-mode command on
 
139
            # them or creates it by hand.
 
140
 
 
141
            lockfile = os.open(self.controlfilename('branch-lock'), om)
 
142
            fcntl.lockf(lockfile, lm)
 
143
            def unlock():
 
144
                fcntl.lockf(lockfile, fcntl.LOCK_UN)
 
145
                os.close(lockfile)
 
146
                self._lockmode = None
 
147
            self.unlock = unlock
 
148
            self._lockmode = mode
 
149
        except ImportError:
 
150
            warning("please write a locking method for platform %r" % sys.platform)
 
151
            def unlock():
 
152
                self._lockmode = None
 
153
            self.unlock = unlock
 
154
            self._lockmode = mode
 
155
 
 
156
 
 
157
    def _need_readlock(self):
 
158
        if self._lockmode not in ['r', 'w']:
 
159
            raise BzrError('need read lock on branch, only have %r' % self._lockmode)
 
160
 
 
161
    def _need_writelock(self):
 
162
        if self._lockmode not in ['w']:
 
163
            raise BzrError('need write lock on branch, only have %r' % self._lockmode)
227
164
 
228
165
 
229
166
    def abspath(self, name):
235
172
        """Return path relative to this branch of something inside it.
236
173
 
237
174
        Raises an error if path is not in this branch."""
238
 
        return _relpath(self.base, path)
 
175
        rp = os.path.realpath(path)
 
176
        # FIXME: windows
 
177
        if not rp.startswith(self.base):
 
178
            bailout("path %r is not within branch %r" % (rp, self.base))
 
179
        rp = rp[len(self.base):]
 
180
        rp = rp.lstrip(os.sep)
 
181
        return rp
239
182
 
240
183
 
241
184
    def controlfilename(self, file_or_path):
252
195
        and binary.  binary files are untranslated byte streams.  Text
253
196
        control files are stored with Unix newlines and in UTF-8, even
254
197
        if the platform or locale defaults are different.
255
 
 
256
 
        Controlfiles should almost never be opened in write mode but
257
 
        rather should be atomically copied and replaced using atomicfile.
258
198
        """
259
199
 
260
200
        fn = self.controlfilename(file_or_path)
302
242
        fmt = self.controlfile('branch-format', 'r').read()
303
243
        fmt.replace('\r\n', '')
304
244
        if fmt != BZR_BRANCH_FORMAT:
305
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
306
 
                           ['use a different bzr version',
307
 
                            'or remove the .bzr directory and "bzr init" again'])
308
 
 
 
245
            bailout('sorry, branch format %r not supported' % fmt,
 
246
                    ['use a different bzr version',
 
247
                     'or remove the .bzr directory and "bzr init" again'])
309
248
 
310
249
 
311
250
    def read_working_inventory(self):
312
251
        """Read the working inventory."""
 
252
        self._need_readlock()
313
253
        before = time.time()
314
254
        # ElementTree does its own conversion from UTF-8, so open in
315
255
        # binary.
316
 
        self.lock_read()
317
 
        try:
318
 
            inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
319
 
            mutter("loaded inventory of %d items in %f"
320
 
                   % (len(inv), time.time() - before))
321
 
            return inv
322
 
        finally:
323
 
            self.unlock()
324
 
            
 
256
        inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
 
257
        mutter("loaded inventory of %d items in %f"
 
258
               % (len(inv), time.time() - before))
 
259
        return inv
 
260
 
325
261
 
326
262
    def _write_inventory(self, inv):
327
263
        """Update the working inventory.
329
265
        That is to say, the inventory describing changes underway, that
330
266
        will be committed to the next revision.
331
267
        """
 
268
        self._need_writelock()
332
269
        ## TODO: factor out to atomicfile?  is rename safe on windows?
333
270
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
334
271
        tmpfname = self.controlfilename('inventory.tmp')
340
277
            os.remove(inv_fname)
341
278
        os.rename(tmpfname, inv_fname)
342
279
        mutter('wrote working inventory')
343
 
            
 
280
 
344
281
 
345
282
    inventory = property(read_working_inventory, _write_inventory, None,
346
283
                         """Inventory for the working copy.""")
347
284
 
348
285
 
349
 
    def add(self, files, verbose=False, ids=None):
 
286
    def add(self, files, verbose=False):
350
287
        """Make files versioned.
351
288
 
352
289
        Note that the command line normally calls smart_add instead.
354
291
        This puts the files in the Added state, so that they will be
355
292
        recorded by the next commit.
356
293
 
357
 
        files
358
 
            List of paths to add, relative to the base of the tree.
359
 
 
360
 
        ids
361
 
            If set, use these instead of automatically generated ids.
362
 
            Must be the same length as the list of files, but may
363
 
            contain None for ids that are to be autogenerated.
364
 
 
365
294
        TODO: Perhaps have an option to add the ids even if the files do
366
 
              not (yet) exist.
 
295
               not (yet) exist.
367
296
 
368
297
        TODO: Perhaps return the ids of the files?  But then again it
369
 
              is easy to retrieve them if they're needed.
 
298
               is easy to retrieve them if they're needed.
 
299
 
 
300
        TODO: Option to specify file id.
370
301
 
371
302
        TODO: Adding a directory should optionally recurse down and
372
 
              add all non-ignored children.  Perhaps do that in a
373
 
              higher-level method.
 
303
               add all non-ignored children.  Perhaps do that in a
 
304
               higher-level method.
 
305
 
 
306
        >>> b = ScratchBranch(files=['foo'])
 
307
        >>> 'foo' in b.unknowns()
 
308
        True
 
309
        >>> b.show_status()
 
310
        ?       foo
 
311
        >>> b.add('foo')
 
312
        >>> 'foo' in b.unknowns()
 
313
        False
 
314
        >>> bool(b.inventory.path2id('foo'))
 
315
        True
 
316
        >>> b.show_status()
 
317
        A       foo
 
318
 
 
319
        >>> b.add('foo')
 
320
        Traceback (most recent call last):
 
321
        ...
 
322
        BzrError: ('foo is already versioned', [])
 
323
 
 
324
        >>> b.add(['nothere'])
 
325
        Traceback (most recent call last):
 
326
        BzrError: ('cannot add: not a regular file or directory: nothere', [])
374
327
        """
 
328
        self._need_writelock()
 
329
 
375
330
        # TODO: Re-adding a file that is removed in the working copy
376
331
        # should probably put it back with the previous ID.
377
332
        if isinstance(files, types.StringTypes):
378
 
            assert(ids is None or isinstance(ids, types.StringTypes))
379
333
            files = [files]
380
 
            if ids is not None:
381
 
                ids = [ids]
382
 
 
383
 
        if ids is None:
384
 
            ids = [None] * len(files)
385
 
        else:
386
 
            assert(len(ids) == len(files))
387
 
 
388
 
        self.lock_write()
389
 
        try:
390
 
            inv = self.read_working_inventory()
391
 
            for f,file_id in zip(files, ids):
392
 
                if is_control_file(f):
393
 
                    raise BzrError("cannot add control file %s" % quotefn(f))
394
 
 
395
 
                fp = splitpath(f)
396
 
 
397
 
                if len(fp) == 0:
398
 
                    raise BzrError("cannot add top-level %r" % f)
399
 
 
400
 
                fullpath = os.path.normpath(self.abspath(f))
401
 
 
402
 
                try:
403
 
                    kind = file_kind(fullpath)
404
 
                except OSError:
405
 
                    # maybe something better?
406
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
407
 
 
408
 
                if kind != 'file' and kind != 'directory':
409
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
410
 
 
411
 
                if file_id is None:
412
 
                    file_id = gen_file_id(f)
413
 
                inv.add_path(f, kind=kind, file_id=file_id)
414
 
 
415
 
                if verbose:
416
 
                    show_status('A', kind, quotefn(f))
417
 
 
418
 
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
419
 
 
420
 
            self._write_inventory(inv)
421
 
        finally:
422
 
            self.unlock()
423
 
            
 
334
        
 
335
        inv = self.read_working_inventory()
 
336
        for f in files:
 
337
            if is_control_file(f):
 
338
                bailout("cannot add control file %s" % quotefn(f))
 
339
 
 
340
            fp = splitpath(f)
 
341
 
 
342
            if len(fp) == 0:
 
343
                bailout("cannot add top-level %r" % f)
 
344
                
 
345
            fullpath = os.path.normpath(self.abspath(f))
 
346
 
 
347
            try:
 
348
                kind = file_kind(fullpath)
 
349
            except OSError:
 
350
                # maybe something better?
 
351
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
352
            
 
353
            if kind != 'file' and kind != 'directory':
 
354
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
355
 
 
356
            file_id = gen_file_id(f)
 
357
            inv.add_path(f, kind=kind, file_id=file_id)
 
358
 
 
359
            if verbose:
 
360
                show_status('A', kind, quotefn(f))
 
361
                
 
362
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
363
            
 
364
        self._write_inventory(inv)
 
365
 
424
366
 
425
367
    def print_file(self, file, revno):
426
368
        """Print `file` to stdout."""
427
 
        self.lock_read()
428
 
        try:
429
 
            tree = self.revision_tree(self.lookup_revision(revno))
430
 
            # use inventory as it was in that revision
431
 
            file_id = tree.inventory.path2id(file)
432
 
            if not file_id:
433
 
                raise BzrError("%r is not present in revision %d" % (file, revno))
434
 
            tree.print_file(file_id)
435
 
        finally:
436
 
            self.unlock()
437
 
 
 
369
        self._need_readlock()
 
370
        tree = self.revision_tree(self.lookup_revision(revno))
 
371
        # use inventory as it was in that revision
 
372
        file_id = tree.inventory.path2id(file)
 
373
        if not file_id:
 
374
            bailout("%r is not present in revision %d" % (file, revno))
 
375
        tree.print_file(file_id)
 
376
        
438
377
 
439
378
    def remove(self, files, verbose=False):
440
379
        """Mark nominated files for removal from the inventory.
443
382
 
444
383
        TODO: Refuse to remove modified files unless --force is given?
445
384
 
 
385
        >>> b = ScratchBranch(files=['foo'])
 
386
        >>> b.add('foo')
 
387
        >>> b.inventory.has_filename('foo')
 
388
        True
 
389
        >>> b.remove('foo')
 
390
        >>> b.working_tree().has_filename('foo')
 
391
        True
 
392
        >>> b.inventory.has_filename('foo')
 
393
        False
 
394
        
 
395
        >>> b = ScratchBranch(files=['foo'])
 
396
        >>> b.add('foo')
 
397
        >>> b.commit('one')
 
398
        >>> b.remove('foo')
 
399
        >>> b.commit('two')
 
400
        >>> b.inventory.has_filename('foo') 
 
401
        False
 
402
        >>> b.basis_tree().has_filename('foo') 
 
403
        False
 
404
        >>> b.working_tree().has_filename('foo') 
 
405
        True
 
406
 
446
407
        TODO: Do something useful with directories.
447
408
 
448
409
        TODO: Should this remove the text or not?  Tough call; not
452
413
        """
453
414
        ## TODO: Normalize names
454
415
        ## TODO: Remove nested loops; better scalability
 
416
        self._need_writelock()
 
417
 
455
418
        if isinstance(files, types.StringTypes):
456
419
            files = [files]
457
 
 
458
 
        self.lock_write()
459
 
 
460
 
        try:
461
 
            tree = self.working_tree()
462
 
            inv = tree.inventory
463
 
 
464
 
            # do this before any modifications
465
 
            for f in files:
466
 
                fid = inv.path2id(f)
467
 
                if not fid:
468
 
                    raise BzrError("cannot remove unversioned file %s" % quotefn(f))
469
 
                mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
470
 
                if verbose:
471
 
                    # having remove it, it must be either ignored or unknown
472
 
                    if tree.is_ignored(f):
473
 
                        new_status = 'I'
474
 
                    else:
475
 
                        new_status = '?'
476
 
                    show_status(new_status, inv[fid].kind, quotefn(f))
477
 
                del inv[fid]
478
 
 
479
 
            self._write_inventory(inv)
480
 
        finally:
481
 
            self.unlock()
482
 
 
483
 
 
484
 
    # FIXME: this doesn't need to be a branch method
485
 
    def set_inventory(self, new_inventory_list):
486
 
        inv = Inventory()
487
 
        for path, file_id, parent, kind in new_inventory_list:
488
 
            name = os.path.basename(path)
489
 
            if name == "":
490
 
                continue
491
 
            inv.add(InventoryEntry(file_id, name, kind, parent))
 
420
        
 
421
        tree = self.working_tree()
 
422
        inv = tree.inventory
 
423
 
 
424
        # do this before any modifications
 
425
        for f in files:
 
426
            fid = inv.path2id(f)
 
427
            if not fid:
 
428
                bailout("cannot remove unversioned file %s" % quotefn(f))
 
429
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
430
            if verbose:
 
431
                # having remove it, it must be either ignored or unknown
 
432
                if tree.is_ignored(f):
 
433
                    new_status = 'I'
 
434
                else:
 
435
                    new_status = '?'
 
436
                show_status(new_status, inv[fid].kind, quotefn(f))
 
437
            del inv[fid]
 
438
 
492
439
        self._write_inventory(inv)
493
440
 
494
441
 
511
458
        return self.working_tree().unknowns()
512
459
 
513
460
 
 
461
    def commit(self, message, timestamp=None, timezone=None,
 
462
               committer=None,
 
463
               verbose=False):
 
464
        """Commit working copy as a new revision.
 
465
        
 
466
        The basic approach is to add all the file texts into the
 
467
        store, then the inventory, then make a new revision pointing
 
468
        to that inventory and store that.
 
469
        
 
470
        This is not quite safe if the working copy changes during the
 
471
        commit; for the moment that is simply not allowed.  A better
 
472
        approach is to make a temporary copy of the files before
 
473
        computing their hashes, and then add those hashes in turn to
 
474
        the inventory.  This should mean at least that there are no
 
475
        broken hash pointers.  There is no way we can get a snapshot
 
476
        of the whole directory at an instant.  This would also have to
 
477
        be robust against files disappearing, moving, etc.  So the
 
478
        whole thing is a bit hard.
 
479
 
 
480
        timestamp -- if not None, seconds-since-epoch for a
 
481
             postdated/predated commit.
 
482
        """
 
483
        self._need_writelock()
 
484
 
 
485
        ## TODO: Show branch names
 
486
 
 
487
        # TODO: Don't commit if there are no changes, unless forced?
 
488
 
 
489
        # First walk over the working inventory; and both update that
 
490
        # and also build a new revision inventory.  The revision
 
491
        # inventory needs to hold the text-id, sha1 and size of the
 
492
        # actual file versions committed in the revision.  (These are
 
493
        # not present in the working inventory.)  We also need to
 
494
        # detect missing/deleted files, and remove them from the
 
495
        # working inventory.
 
496
 
 
497
        work_inv = self.read_working_inventory()
 
498
        inv = Inventory()
 
499
        basis = self.basis_tree()
 
500
        basis_inv = basis.inventory
 
501
        missing_ids = []
 
502
        for path, entry in work_inv.iter_entries():
 
503
            ## TODO: Cope with files that have gone missing.
 
504
 
 
505
            ## TODO: Check that the file kind has not changed from the previous
 
506
            ## revision of this file (if any).
 
507
 
 
508
            entry = entry.copy()
 
509
 
 
510
            p = self.abspath(path)
 
511
            file_id = entry.file_id
 
512
            mutter('commit prep file %s, id %r ' % (p, file_id))
 
513
 
 
514
            if not os.path.exists(p):
 
515
                mutter("    file is missing, removing from inventory")
 
516
                if verbose:
 
517
                    show_status('D', entry.kind, quotefn(path))
 
518
                missing_ids.append(file_id)
 
519
                continue
 
520
 
 
521
            # TODO: Handle files that have been deleted
 
522
 
 
523
            # TODO: Maybe a special case for empty files?  Seems a
 
524
            # waste to store them many times.
 
525
 
 
526
            inv.add(entry)
 
527
 
 
528
            if basis_inv.has_id(file_id):
 
529
                old_kind = basis_inv[file_id].kind
 
530
                if old_kind != entry.kind:
 
531
                    bailout("entry %r changed kind from %r to %r"
 
532
                            % (file_id, old_kind, entry.kind))
 
533
 
 
534
            if entry.kind == 'directory':
 
535
                if not isdir(p):
 
536
                    bailout("%s is entered as directory but not a directory" % quotefn(p))
 
537
            elif entry.kind == 'file':
 
538
                if not isfile(p):
 
539
                    bailout("%s is entered as file but is not a file" % quotefn(p))
 
540
 
 
541
                content = file(p, 'rb').read()
 
542
 
 
543
                entry.text_sha1 = sha_string(content)
 
544
                entry.text_size = len(content)
 
545
 
 
546
                old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
 
547
                if (old_ie
 
548
                    and (old_ie.text_size == entry.text_size)
 
549
                    and (old_ie.text_sha1 == entry.text_sha1)):
 
550
                    ## assert content == basis.get_file(file_id).read()
 
551
                    entry.text_id = basis_inv[file_id].text_id
 
552
                    mutter('    unchanged from previous text_id {%s}' %
 
553
                           entry.text_id)
 
554
                    
 
555
                else:
 
556
                    entry.text_id = gen_file_id(entry.name)
 
557
                    self.text_store.add(content, entry.text_id)
 
558
                    mutter('    stored with text_id {%s}' % entry.text_id)
 
559
                    if verbose:
 
560
                        if not old_ie:
 
561
                            state = 'A'
 
562
                        elif (old_ie.name == entry.name
 
563
                              and old_ie.parent_id == entry.parent_id):
 
564
                            state = 'M'
 
565
                        else:
 
566
                            state = 'R'
 
567
 
 
568
                        show_status(state, entry.kind, quotefn(path))
 
569
 
 
570
        for file_id in missing_ids:
 
571
            # have to do this later so we don't mess up the iterator.
 
572
            # since parents may be removed before their children we
 
573
            # have to test.
 
574
 
 
575
            # FIXME: There's probably a better way to do this; perhaps
 
576
            # the workingtree should know how to filter itself.
 
577
            if work_inv.has_id(file_id):
 
578
                del work_inv[file_id]
 
579
 
 
580
 
 
581
        inv_id = rev_id = _gen_revision_id(time.time())
 
582
        
 
583
        inv_tmp = tempfile.TemporaryFile()
 
584
        inv.write_xml(inv_tmp)
 
585
        inv_tmp.seek(0)
 
586
        self.inventory_store.add(inv_tmp, inv_id)
 
587
        mutter('new inventory_id is {%s}' % inv_id)
 
588
 
 
589
        self._write_inventory(work_inv)
 
590
 
 
591
        if timestamp == None:
 
592
            timestamp = time.time()
 
593
 
 
594
        if committer == None:
 
595
            committer = username()
 
596
 
 
597
        if timezone == None:
 
598
            timezone = local_time_offset()
 
599
 
 
600
        mutter("building commit log message")
 
601
        rev = Revision(timestamp=timestamp,
 
602
                       timezone=timezone,
 
603
                       committer=committer,
 
604
                       precursor = self.last_patch(),
 
605
                       message = message,
 
606
                       inventory_id=inv_id,
 
607
                       revision_id=rev_id)
 
608
 
 
609
        rev_tmp = tempfile.TemporaryFile()
 
610
        rev.write_xml(rev_tmp)
 
611
        rev_tmp.seek(0)
 
612
        self.revision_store.add(rev_tmp, rev_id)
 
613
        mutter("new revision_id is {%s}" % rev_id)
 
614
        
 
615
        ## XXX: Everything up to here can simply be orphaned if we abort
 
616
        ## the commit; it will leave junk files behind but that doesn't
 
617
        ## matter.
 
618
 
 
619
        ## TODO: Read back the just-generated changeset, and make sure it
 
620
        ## applies and recreates the right state.
 
621
 
 
622
        ## TODO: Also calculate and store the inventory SHA1
 
623
        mutter("committing patch r%d" % (self.revno() + 1))
 
624
 
 
625
 
 
626
        self.append_revision(rev_id)
 
627
        
 
628
        if verbose:
 
629
            note("commited r%d" % self.revno())
 
630
 
 
631
 
514
632
    def append_revision(self, revision_id):
515
633
        mutter("add {%s} to revision-history" % revision_id)
516
634
        rev_history = self.revision_history()
532
650
 
533
651
    def get_revision(self, revision_id):
534
652
        """Return the Revision object for a named revision"""
 
653
        self._need_readlock()
535
654
        r = Revision.read_xml(self.revision_store[revision_id])
536
655
        assert r.revision_id == revision_id
537
656
        return r
543
662
        TODO: Perhaps for this and similar methods, take a revision
544
663
               parameter which can be either an integer revno or a
545
664
               string hash."""
 
665
        self._need_readlock()
546
666
        i = Inventory.read_xml(self.inventory_store[inventory_id])
547
667
        return i
548
668
 
549
669
 
550
670
    def get_revision_inventory(self, revision_id):
551
671
        """Return inventory of a past revision."""
 
672
        self._need_readlock()
552
673
        if revision_id == None:
553
674
            return Inventory()
554
675
        else:
561
682
        >>> ScratchBranch().revision_history()
562
683
        []
563
684
        """
564
 
        self.lock_read()
565
 
        try:
566
 
            return [l.rstrip('\r\n') for l in
567
 
                    self.controlfile('revision-history', 'r').readlines()]
568
 
        finally:
569
 
            self.unlock()
570
 
 
571
 
 
572
 
    def common_ancestor(self, other, self_revno=None, other_revno=None):
573
 
        """
574
 
        >>> import commit
575
 
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
576
 
        >>> sb.common_ancestor(sb) == (None, None)
577
 
        True
578
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
579
 
        >>> sb.common_ancestor(sb)[0]
580
 
        1
581
 
        >>> clone = sb.clone()
582
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
583
 
        >>> sb.common_ancestor(sb)[0]
584
 
        2
585
 
        >>> sb.common_ancestor(clone)[0]
586
 
        1
587
 
        >>> commit.commit(clone, "Committing divergent second revision", 
588
 
        ...               verbose=False)
589
 
        >>> sb.common_ancestor(clone)[0]
590
 
        1
591
 
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
592
 
        True
593
 
        >>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
594
 
        True
595
 
        >>> clone2 = sb.clone()
596
 
        >>> sb.common_ancestor(clone2)[0]
597
 
        2
598
 
        >>> sb.common_ancestor(clone2, self_revno=1)[0]
599
 
        1
600
 
        >>> sb.common_ancestor(clone2, other_revno=1)[0]
601
 
        1
602
 
        """
603
 
        my_history = self.revision_history()
604
 
        other_history = other.revision_history()
605
 
        if self_revno is None:
606
 
            self_revno = len(my_history)
607
 
        if other_revno is None:
608
 
            other_revno = len(other_history)
609
 
        indices = range(min((self_revno, other_revno)))
610
 
        indices.reverse()
611
 
        for r in indices:
612
 
            if my_history[r] == other_history[r]:
613
 
                return r+1, my_history[r]
614
 
        return None, None
615
 
 
616
 
    def enum_history(self, direction):
617
 
        """Return (revno, revision_id) for history of branch.
618
 
 
619
 
        direction
620
 
            'forward' is from earliest to latest
621
 
            'reverse' is from latest to earliest
622
 
        """
623
 
        rh = self.revision_history()
624
 
        if direction == 'forward':
625
 
            i = 1
626
 
            for rid in rh:
627
 
                yield i, rid
628
 
                i += 1
629
 
        elif direction == 'reverse':
630
 
            i = len(rh)
631
 
            while i > 0:
632
 
                yield i, rh[i-1]
633
 
                i -= 1
634
 
        else:
635
 
            raise ValueError('invalid history direction', direction)
 
685
        self._need_readlock()
 
686
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
636
687
 
637
688
 
638
689
    def revno(self):
640
691
 
641
692
        That is equivalent to the number of revisions committed to
642
693
        this branch.
 
694
 
 
695
        >>> b = ScratchBranch()
 
696
        >>> b.revno()
 
697
        0
 
698
        >>> b.commit('no foo')
 
699
        >>> b.revno()
 
700
        1
643
701
        """
644
702
        return len(self.revision_history())
645
703
 
646
704
 
647
705
    def last_patch(self):
648
706
        """Return last patch hash, or None if no history.
 
707
 
 
708
        >>> ScratchBranch().last_patch() == None
 
709
        True
649
710
        """
650
711
        ph = self.revision_history()
651
712
        if ph:
652
713
            return ph[-1]
653
714
        else:
654
715
            return None
655
 
 
656
 
 
657
 
    def missing_revisions(self, other):
658
 
        """
659
 
        If self and other have not diverged, return a list of the revisions
660
 
        present in other, but missing from self.
661
 
 
662
 
        >>> from bzrlib.commit import commit
663
 
        >>> bzrlib.trace.silent = True
664
 
        >>> br1 = ScratchBranch()
665
 
        >>> br2 = ScratchBranch()
666
 
        >>> br1.missing_revisions(br2)
667
 
        []
668
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
669
 
        >>> br1.missing_revisions(br2)
670
 
        [u'REVISION-ID-1']
671
 
        >>> br2.missing_revisions(br1)
672
 
        []
673
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
674
 
        >>> br1.missing_revisions(br2)
675
 
        []
676
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
677
 
        >>> br1.missing_revisions(br2)
678
 
        [u'REVISION-ID-2A']
679
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
680
 
        >>> br1.missing_revisions(br2)
681
 
        Traceback (most recent call last):
682
 
        DivergedBranches: These branches have diverged.
683
 
        """
684
 
        self_history = self.revision_history()
685
 
        self_len = len(self_history)
686
 
        other_history = other.revision_history()
687
 
        other_len = len(other_history)
688
 
        common_index = min(self_len, other_len) -1
689
 
        if common_index >= 0 and \
690
 
            self_history[common_index] != other_history[common_index]:
691
 
            raise DivergedBranches(self, other)
692
 
        if self_len < other_len:
693
 
            return other_history[self_len:]
694
 
        return []
695
 
 
696
 
 
697
 
    def update_revisions(self, other):
698
 
        """If self and other have not diverged, ensure self has all the
699
 
        revisions in other
700
 
 
701
 
        >>> from bzrlib.commit import commit
702
 
        >>> bzrlib.trace.silent = True
703
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
704
 
        >>> br1.add('foo')
705
 
        >>> br1.add('bar')
706
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
707
 
        >>> br2 = ScratchBranch()
708
 
        >>> br2.update_revisions(br1)
709
 
        Added 2 texts.
710
 
        Added 1 inventories.
711
 
        Added 1 revisions.
712
 
        >>> br2.revision_history()
713
 
        [u'REVISION-ID-1']
714
 
        >>> br2.update_revisions(br1)
715
 
        Added 0 texts.
716
 
        Added 0 inventories.
717
 
        Added 0 revisions.
718
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
719
 
        True
720
 
        """
721
 
        revision_ids = self.missing_revisions(other)
722
 
        revisions = [other.get_revision(f) for f in revision_ids]
723
 
        needed_texts = sets.Set()
724
 
        for rev in revisions:
725
 
            inv = other.get_inventory(str(rev.inventory_id))
726
 
            for key, entry in inv.iter_entries():
727
 
                if entry.text_id is None:
728
 
                    continue
729
 
                if entry.text_id not in self.text_store:
730
 
                    needed_texts.add(entry.text_id)
731
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
732
 
        print "Added %d texts." % count 
733
 
        inventory_ids = [ f.inventory_id for f in revisions ]
734
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
735
 
                                                inventory_ids)
736
 
        print "Added %d inventories." % count 
737
 
        revision_ids = [ f.revision_id for f in revisions]
738
 
        count = self.revision_store.copy_multi(other.revision_store, 
739
 
                                               revision_ids)
740
 
        for revision_id in revision_ids:
741
 
            self.append_revision(revision_id)
742
 
        print "Added %d revisions." % count
743
 
                    
744
 
        
745
 
    def commit(self, *args, **kw):
746
 
        """Deprecated"""
747
 
        from bzrlib.commit import commit
748
 
        commit(self, *args, **kw)
749
716
        
750
717
 
751
718
    def lookup_revision(self, revno):
765
732
 
766
733
        `revision_id` may be None for the null revision, in which case
767
734
        an `EmptyTree` is returned."""
768
 
        # TODO: refactor this to use an existing revision object
769
 
        # so we don't need to read it in twice.
 
735
        self._need_readlock()
770
736
        if revision_id == None:
771
737
            return EmptyTree()
772
738
        else:
776
742
 
777
743
    def working_tree(self):
778
744
        """Return a `Tree` for the working copy."""
779
 
        from workingtree import WorkingTree
780
745
        return WorkingTree(self.base, self.read_working_inventory())
781
746
 
782
747
 
784
749
        """Return `Tree` object for last revision.
785
750
 
786
751
        If there are no revisions yet, return an `EmptyTree`.
 
752
 
 
753
        >>> b = ScratchBranch(files=['foo'])
 
754
        >>> b.basis_tree().has_filename('foo')
 
755
        False
 
756
        >>> b.working_tree().has_filename('foo')
 
757
        True
 
758
        >>> b.add('foo')
 
759
        >>> b.commit('add foo')
 
760
        >>> b.basis_tree().has_filename('foo')
 
761
        True
787
762
        """
788
763
        r = self.last_patch()
789
764
        if r == None:
793
768
 
794
769
 
795
770
 
 
771
    def write_log(self, show_timezone='original', verbose=False):
 
772
        """Write out human-readable log of commits to this branch
 
773
 
 
774
        utc -- If true, show dates in universal time, not local time."""
 
775
        self._need_readlock()
 
776
        ## TODO: Option to choose either original, utc or local timezone
 
777
        revno = 1
 
778
        precursor = None
 
779
        for p in self.revision_history():
 
780
            print '-' * 40
 
781
            print 'revno:', revno
 
782
            ## TODO: Show hash if --id is given.
 
783
            ##print 'revision-hash:', p
 
784
            rev = self.get_revision(p)
 
785
            print 'committer:', rev.committer
 
786
            print 'timestamp: %s' % (format_date(rev.timestamp, rev.timezone or 0,
 
787
                                                 show_timezone))
 
788
 
 
789
            ## opportunistic consistency check, same as check_patch_chaining
 
790
            if rev.precursor != precursor:
 
791
                bailout("mismatched precursor!")
 
792
 
 
793
            print 'message:'
 
794
            if not rev.message:
 
795
                print '  (no message)'
 
796
            else:
 
797
                for l in rev.message.split('\n'):
 
798
                    print '  ' + l
 
799
 
 
800
            if verbose == True and precursor != None:
 
801
                print 'changed files:'
 
802
                tree = self.revision_tree(p)
 
803
                prevtree = self.revision_tree(precursor)
 
804
                
 
805
                for file_state, fid, old_name, new_name, kind in \
 
806
                                        diff_trees(prevtree, tree, ):
 
807
                    if file_state == 'A' or file_state == 'M':
 
808
                        show_status(file_state, kind, new_name)
 
809
                    elif file_state == 'D':
 
810
                        show_status(file_state, kind, old_name)
 
811
                    elif file_state == 'R':
 
812
                        show_status(file_state, kind,
 
813
                            old_name + ' => ' + new_name)
 
814
                
 
815
            revno += 1
 
816
            precursor = p
 
817
 
 
818
 
796
819
    def rename_one(self, from_rel, to_rel):
797
820
        """Rename one file.
798
821
 
799
822
        This can change the directory or the filename or both.
800
823
        """
801
 
        self.lock_write()
 
824
        self._need_writelock()
 
825
        tree = self.working_tree()
 
826
        inv = tree.inventory
 
827
        if not tree.has_filename(from_rel):
 
828
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
829
        if tree.has_filename(to_rel):
 
830
            bailout("can't rename: new working file %r already exists" % to_rel)
 
831
            
 
832
        file_id = inv.path2id(from_rel)
 
833
        if file_id == None:
 
834
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
835
 
 
836
        if inv.path2id(to_rel):
 
837
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
838
 
 
839
        to_dir, to_tail = os.path.split(to_rel)
 
840
        to_dir_id = inv.path2id(to_dir)
 
841
        if to_dir_id == None and to_dir != '':
 
842
            bailout("can't determine destination directory id for %r" % to_dir)
 
843
 
 
844
        mutter("rename_one:")
 
845
        mutter("  file_id    {%s}" % file_id)
 
846
        mutter("  from_rel   %r" % from_rel)
 
847
        mutter("  to_rel     %r" % to_rel)
 
848
        mutter("  to_dir     %r" % to_dir)
 
849
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
850
            
 
851
        inv.rename(file_id, to_dir_id, to_tail)
 
852
 
 
853
        print "%s => %s" % (from_rel, to_rel)
 
854
        
 
855
        from_abs = self.abspath(from_rel)
 
856
        to_abs = self.abspath(to_rel)
802
857
        try:
803
 
            tree = self.working_tree()
804
 
            inv = tree.inventory
805
 
            if not tree.has_filename(from_rel):
806
 
                raise BzrError("can't rename: old working file %r does not exist" % from_rel)
807
 
            if tree.has_filename(to_rel):
808
 
                raise BzrError("can't rename: new working file %r already exists" % to_rel)
809
 
 
810
 
            file_id = inv.path2id(from_rel)
811
 
            if file_id == None:
812
 
                raise BzrError("can't rename: old name %r is not versioned" % from_rel)
813
 
 
814
 
            if inv.path2id(to_rel):
815
 
                raise BzrError("can't rename: new name %r is already versioned" % to_rel)
816
 
 
817
 
            to_dir, to_tail = os.path.split(to_rel)
818
 
            to_dir_id = inv.path2id(to_dir)
819
 
            if to_dir_id == None and to_dir != '':
820
 
                raise BzrError("can't determine destination directory id for %r" % to_dir)
821
 
 
822
 
            mutter("rename_one:")
823
 
            mutter("  file_id    {%s}" % file_id)
824
 
            mutter("  from_rel   %r" % from_rel)
825
 
            mutter("  to_rel     %r" % to_rel)
826
 
            mutter("  to_dir     %r" % to_dir)
827
 
            mutter("  to_dir_id  {%s}" % to_dir_id)
828
 
 
829
 
            inv.rename(file_id, to_dir_id, to_tail)
830
 
 
831
 
            print "%s => %s" % (from_rel, to_rel)
832
 
 
833
 
            from_abs = self.abspath(from_rel)
834
 
            to_abs = self.abspath(to_rel)
835
 
            try:
836
 
                os.rename(from_abs, to_abs)
837
 
            except OSError, e:
838
 
                raise BzrError("failed to rename %r to %r: %s"
839
 
                        % (from_abs, to_abs, e[1]),
840
 
                        ["rename rolled back"])
841
 
 
842
 
            self._write_inventory(inv)
843
 
        finally:
844
 
            self.unlock()
 
858
            os.rename(from_abs, to_abs)
 
859
        except OSError, e:
 
860
            bailout("failed to rename %r to %r: %s"
 
861
                    % (from_abs, to_abs, e[1]),
 
862
                    ["rename rolled back"])
 
863
 
 
864
        self._write_inventory(inv)
 
865
            
845
866
 
846
867
 
847
868
    def move(self, from_paths, to_name):
855
876
        Note that to_name is only the last component of the new name;
856
877
        this doesn't change the directory.
857
878
        """
858
 
        self.lock_write()
859
 
        try:
860
 
            ## TODO: Option to move IDs only
861
 
            assert not isinstance(from_paths, basestring)
862
 
            tree = self.working_tree()
863
 
            inv = tree.inventory
864
 
            to_abs = self.abspath(to_name)
865
 
            if not isdir(to_abs):
866
 
                raise BzrError("destination %r is not a directory" % to_abs)
867
 
            if not tree.has_filename(to_name):
868
 
                raise BzrError("destination %r not in working directory" % to_abs)
869
 
            to_dir_id = inv.path2id(to_name)
870
 
            if to_dir_id == None and to_name != '':
871
 
                raise BzrError("destination %r is not a versioned directory" % to_name)
872
 
            to_dir_ie = inv[to_dir_id]
873
 
            if to_dir_ie.kind not in ('directory', 'root_directory'):
874
 
                raise BzrError("destination %r is not a directory" % to_abs)
875
 
 
876
 
            to_idpath = inv.get_idpath(to_dir_id)
877
 
 
878
 
            for f in from_paths:
879
 
                if not tree.has_filename(f):
880
 
                    raise BzrError("%r does not exist in working tree" % f)
881
 
                f_id = inv.path2id(f)
882
 
                if f_id == None:
883
 
                    raise BzrError("%r is not versioned" % f)
884
 
                name_tail = splitpath(f)[-1]
885
 
                dest_path = appendpath(to_name, name_tail)
886
 
                if tree.has_filename(dest_path):
887
 
                    raise BzrError("destination %r already exists" % dest_path)
888
 
                if f_id in to_idpath:
889
 
                    raise BzrError("can't move %r to a subdirectory of itself" % f)
890
 
 
891
 
            # OK, so there's a race here, it's possible that someone will
892
 
            # create a file in this interval and then the rename might be
893
 
            # left half-done.  But we should have caught most problems.
894
 
 
895
 
            for f in from_paths:
896
 
                name_tail = splitpath(f)[-1]
897
 
                dest_path = appendpath(to_name, name_tail)
898
 
                print "%s => %s" % (f, dest_path)
899
 
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
900
 
                try:
901
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
902
 
                except OSError, e:
903
 
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
904
 
                            ["rename rolled back"])
905
 
 
906
 
            self._write_inventory(inv)
907
 
        finally:
908
 
            self.unlock()
909
 
 
 
879
        self._need_writelock()
 
880
        ## TODO: Option to move IDs only
 
881
        assert not isinstance(from_paths, basestring)
 
882
        tree = self.working_tree()
 
883
        inv = tree.inventory
 
884
        to_abs = self.abspath(to_name)
 
885
        if not isdir(to_abs):
 
886
            bailout("destination %r is not a directory" % to_abs)
 
887
        if not tree.has_filename(to_name):
 
888
            bailout("destination %r not in working directory" % to_abs)
 
889
        to_dir_id = inv.path2id(to_name)
 
890
        if to_dir_id == None and to_name != '':
 
891
            bailout("destination %r is not a versioned directory" % to_name)
 
892
        to_dir_ie = inv[to_dir_id]
 
893
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
894
            bailout("destination %r is not a directory" % to_abs)
 
895
 
 
896
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
897
 
 
898
        for f in from_paths:
 
899
            if not tree.has_filename(f):
 
900
                bailout("%r does not exist in working tree" % f)
 
901
            f_id = inv.path2id(f)
 
902
            if f_id == None:
 
903
                bailout("%r is not versioned" % f)
 
904
            name_tail = splitpath(f)[-1]
 
905
            dest_path = appendpath(to_name, name_tail)
 
906
            if tree.has_filename(dest_path):
 
907
                bailout("destination %r already exists" % dest_path)
 
908
            if f_id in to_idpath:
 
909
                bailout("can't move %r to a subdirectory of itself" % f)
 
910
 
 
911
        # OK, so there's a race here, it's possible that someone will
 
912
        # create a file in this interval and then the rename might be
 
913
        # left half-done.  But we should have caught most problems.
 
914
 
 
915
        for f in from_paths:
 
916
            name_tail = splitpath(f)[-1]
 
917
            dest_path = appendpath(to_name, name_tail)
 
918
            print "%s => %s" % (f, dest_path)
 
919
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
920
            try:
 
921
                os.rename(self.abspath(f), self.abspath(dest_path))
 
922
            except OSError, e:
 
923
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
924
                        ["rename rolled back"])
 
925
 
 
926
        self._write_inventory(inv)
 
927
 
 
928
 
 
929
 
 
930
    def show_status(self, show_all=False):
 
931
        """Display single-line status for non-ignored working files.
 
932
 
 
933
        The list is show sorted in order by file name.
 
934
 
 
935
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
936
        >>> b.show_status()
 
937
        ?       foo
 
938
        >>> b.add('foo')
 
939
        >>> b.show_status()
 
940
        A       foo
 
941
        >>> b.commit("add foo")
 
942
        >>> b.show_status()
 
943
        >>> os.unlink(b.abspath('foo'))
 
944
        >>> b.show_status()
 
945
        D       foo
 
946
        
 
947
        TODO: Get state for single files.
 
948
        """
 
949
        self._need_readlock()
 
950
 
 
951
        # We have to build everything into a list first so that it can
 
952
        # sorted by name, incorporating all the different sources.
 
953
 
 
954
        # FIXME: Rather than getting things in random order and then sorting,
 
955
        # just step through in order.
 
956
 
 
957
        # Interesting case: the old ID for a file has been removed,
 
958
        # but a new file has been created under that name.
 
959
 
 
960
        old = self.basis_tree()
 
961
        new = self.working_tree()
 
962
 
 
963
        for fs, fid, oldname, newname, kind in diff_trees(old, new):
 
964
            if fs == 'R':
 
965
                show_status(fs, kind,
 
966
                            oldname + ' => ' + newname)
 
967
            elif fs == 'A' or fs == 'M':
 
968
                show_status(fs, kind, newname)
 
969
            elif fs == 'D':
 
970
                show_status(fs, kind, oldname)
 
971
            elif fs == '.':
 
972
                if show_all:
 
973
                    show_status(fs, kind, newname)
 
974
            elif fs == 'I':
 
975
                if show_all:
 
976
                    show_status(fs, kind, newname)
 
977
            elif fs == '?':
 
978
                show_status(fs, kind, newname)
 
979
            else:
 
980
                bailout("weird file state %r" % ((fs, fid),))
 
981
                
910
982
 
911
983
 
912
984
class ScratchBranch(Branch):
916
988
    >>> isdir(b.base)
917
989
    True
918
990
    >>> bd = b.base
919
 
    >>> b.destroy()
 
991
    >>> del b
920
992
    >>> isdir(bd)
921
993
    False
922
994
    """
923
 
    def __init__(self, files=[], dirs=[], base=None):
 
995
    def __init__(self, files=[], dirs=[]):
924
996
        """Make a test branch.
925
997
 
926
998
        This creates a temporary directory and runs init-tree in it.
927
999
 
928
1000
        If any files are listed, they are created in the working copy.
929
1001
        """
930
 
        init = False
931
 
        if base is None:
932
 
            base = tempfile.mkdtemp()
933
 
            init = True
934
 
        Branch.__init__(self, base, init=init)
 
1002
        Branch.__init__(self, tempfile.mkdtemp(), init=True)
935
1003
        for d in dirs:
936
1004
            os.mkdir(self.abspath(d))
937
1005
            
939
1007
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
940
1008
 
941
1009
 
942
 
    def clone(self):
943
 
        """
944
 
        >>> orig = ScratchBranch(files=["file1", "file2"])
945
 
        >>> clone = orig.clone()
946
 
        >>> os.path.samefile(orig.base, clone.base)
947
 
        False
948
 
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
949
 
        True
950
 
        """
951
 
        base = tempfile.mkdtemp()
952
 
        os.rmdir(base)
953
 
        shutil.copytree(self.base, base, symlinks=True)
954
 
        return ScratchBranch(base=base)
955
 
        
956
1010
    def __del__(self):
957
 
        self.destroy()
958
 
 
959
 
    def destroy(self):
960
1011
        """Destroy the test branch, removing the scratch directory."""
961
1012
        try:
962
 
            if self.base:
963
 
                mutter("delete ScratchBranch %s" % self.base)
964
 
                shutil.rmtree(self.base)
965
 
        except OSError, e:
 
1013
            shutil.rmtree(self.base)
 
1014
        except OSError:
966
1015
            # Work around for shutil.rmtree failing on Windows when
967
1016
            # readonly files are encountered
968
 
            mutter("hit exception in destroying ScratchBranch: %s" % e)
969
1017
            for root, dirs, files in os.walk(self.base, topdown=False):
970
1018
                for name in files:
971
1019
                    os.chmod(os.path.join(root, name), 0700)
972
1020
            shutil.rmtree(self.base)
973
 
        self.base = None
974
1021
 
975
1022
    
976
1023
 
993
1040
 
994
1041
 
995
1042
 
 
1043
def _gen_revision_id(when):
 
1044
    """Return new revision-id."""
 
1045
    s = '%s-%s-' % (user_email(), compact_date(when))
 
1046
    s += hexlify(rand_bytes(8))
 
1047
    return s
 
1048
 
 
1049
 
996
1050
def gen_file_id(name):
997
1051
    """Return new file id.
998
1052
 
999
1053
    This should probably generate proper UUIDs, but for the moment we
1000
1054
    cope with just randomness because running uuidgen every time is
1001
1055
    slow."""
1002
 
    import re
1003
 
 
1004
 
    # get last component
1005
1056
    idx = name.rfind('/')
1006
1057
    if idx != -1:
1007
1058
        name = name[idx+1 : ]
1009
1060
    if idx != -1:
1010
1061
        name = name[idx+1 : ]
1011
1062
 
1012
 
    # make it not a hidden file
1013
1063
    name = name.lstrip('.')
1014
1064
 
1015
 
    # remove any wierd characters; we don't escape them but rather
1016
 
    # just pull them out
1017
 
    name = re.sub(r'[^\w.]', '', name)
1018
 
 
1019
1065
    s = hexlify(rand_bytes(8))
1020
1066
    return '-'.join((name, compact_date(time.time()), s))