~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-06-30 01:38:26 UTC
  • Revision ID: mbp@sourcefrog.net-20050630013826-518cd32a20a13199
- Cope if locale.getpreferredencoding() returns None
  Reported by Uros Trebec

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