~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: mbp at sourcefrog
  • Date: 2005-04-06 05:02:09 UTC
  • Revision ID: mbp@sourcefrog.net-20050406050209-fa9f0c791a1bedd023281fd0
bzr 0.0.3 release!

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
 
# -*- coding: UTF-8 -*-
 
1
# Copyright (C) 2005 Canonical Ltd
3
2
 
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
29
28
from inventory import InventoryEntry, Inventory
30
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, chomp, \
31
30
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
32
 
     joinpath, sha_string, file_kind, local_time_offset
 
31
     joinpath, sha_string, file_kind, local_time_offset, appendpath
33
32
from store import ImmutableStore
34
33
from revision import Revision
35
34
from errors import bailout
41
40
 
42
41
 
43
42
 
 
43
def find_branch_root(f=None):
 
44
    """Find the branch root enclosing f, or pwd.
 
45
 
 
46
    It is not necessary that f exists.
 
47
 
 
48
    Basically we keep looking up until we find the control directory or
 
49
    run into the root."""
 
50
    if f is None:
 
51
        f = os.getcwd()
 
52
    elif hasattr(os.path, 'realpath'):
 
53
        f = os.path.realpath(f)
 
54
    else:
 
55
        f = os.path.abspath(f)
 
56
 
 
57
    orig_f = f
 
58
 
 
59
    last_f = f
 
60
    while True:
 
61
        if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
 
62
            return f
 
63
        head, tail = os.path.split(f)
 
64
        if head == f:
 
65
            # reached the root, whatever that may be
 
66
            bailout('%r is not in a branch' % orig_f)
 
67
        f = head
 
68
    
44
69
 
45
70
 
46
71
######################################################################
62
87
 
63
88
    :todo: mkdir() method.
64
89
    """
65
 
    def __init__(self, base, init=False):
 
90
    def __init__(self, base, init=False, find_root=True):
66
91
        """Create new branch object at a particular location.
67
92
 
68
93
        :param base: Base directory for the branch.
69
 
 
 
94
        
70
95
        :param init: If True, create new control files in a previously
71
96
             unversioned directory.  If False, the branch must already
72
97
             be versioned.
73
98
 
 
99
        :param find_root: If true and init is false, find the root of the
 
100
             existing branch containing base.
 
101
 
74
102
        In the test suite, creation of new trees is tested using the
75
103
        `ScratchBranch` class.
76
104
        """
77
 
        self.base = os.path.realpath(base)
78
105
        if init:
 
106
            self.base = os.path.realpath(base)
79
107
            self._make_control()
 
108
        elif find_root:
 
109
            self.base = find_branch_root(base)
80
110
        else:
 
111
            self.base = os.path.realpath(base)
81
112
            if not isdir(self.controlfilename('.')):
82
113
                bailout("not a bzr branch: %s" % quotefn(base),
83
114
                        ['use "bzr init" to initialize a new working tree',
84
115
                         'current bzr can only operate from top-of-tree'])
85
 
            self._check_format()
 
116
        self._check_format()
86
117
 
87
118
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
88
119
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
96
127
    __repr__ = __str__
97
128
 
98
129
 
99
 
    def _rel(self, name):
100
 
        """Return filename relative to branch top"""
 
130
    def abspath(self, name):
 
131
        """Return absolute filename for something in the branch"""
101
132
        return os.path.join(self.base, name)
102
 
        
 
133
 
 
134
 
 
135
    def relpath(self, path):
 
136
        """Return path relative to this branch of something inside it.
 
137
 
 
138
        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
 
146
 
103
147
 
104
148
    def controlfilename(self, file_or_path):
105
149
        """Return location relative to branch."""
118
162
        self.controlfile('README', 'w').write(
119
163
            "This is a Bazaar-NG control directory.\n"
120
164
            "Do not change any files in this directory.")
121
 
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
 
165
        self.controlfile('branch-format', 'wb').write(BZR_BRANCH_FORMAT)
122
166
        for d in ('text-store', 'inventory-store', 'revision-store'):
123
167
            os.mkdir(self.controlfilename(d))
124
168
        for f in ('revision-history', 'merged-patches',
135
179
 
136
180
        In the future, we might need different in-memory Branch
137
181
        classes to support downlevel branches.  But not yet.
138
 
        """        
139
 
        # read in binary mode to detect newline wierdness.
 
182
        """
 
183
        # This ignores newlines so that we can open branches created
 
184
        # on Windows from Linux and so on.  I think it might be better
 
185
        # to always make all internal files in unix format.
140
186
        fmt = self.controlfile('branch-format', 'rb').read()
 
187
        fmt.replace('\r\n', '')
141
188
        if fmt != BZR_BRANCH_FORMAT:
142
189
            bailout('sorry, branch format %r not supported' % fmt,
143
190
                    ['use a different bzr version',
160
207
        will be committed to the next revision.
161
208
        """
162
209
        ## TODO: factor out to atomicfile?  is rename safe on windows?
 
210
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
163
211
        tmpfname = self.controlfilename('inventory.tmp')
164
212
        tmpf = file(tmpfname, 'w')
165
213
        inv.write_xml(tmpf)
166
214
        tmpf.close()
167
 
        os.rename(tmpfname, self.controlfilename('inventory'))
 
215
        inv_fname = self.controlfilename('inventory')
 
216
        if sys.platform == 'win32':
 
217
            os.remove(inv_fname)
 
218
        os.rename(tmpfname, inv_fname)
168
219
        mutter('wrote working inventory')
169
220
 
170
221
 
228
279
            if len(fp) == 0:
229
280
                bailout("cannot add top-level %r" % f)
230
281
                
231
 
            fullpath = os.path.normpath(self._rel(f))
232
 
 
233
 
            if isfile(fullpath):
234
 
                kind = 'file'
235
 
            elif isdir(fullpath):
236
 
                kind = 'directory'
237
 
            else:
238
 
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
239
 
 
240
 
            if len(fp) > 1:
241
 
                parent_name = joinpath(fp[:-1])
242
 
                mutter("lookup parent %r" % parent_name)
243
 
                parent_id = inv.path2id(parent_name)
244
 
                if parent_id == None:
245
 
                    bailout("cannot add: parent %r is not versioned"
246
 
                            % joinpath(fp[:-1]))
247
 
            else:
248
 
                parent_id = None
249
 
 
250
 
            file_id = _gen_file_id(fp[-1])
251
 
            inv.add(InventoryEntry(file_id, fp[-1], kind=kind, parent_id=parent_id))
 
282
            fullpath = os.path.normpath(self.abspath(f))
 
283
 
 
284
            try:
 
285
                kind = file_kind(fullpath)
 
286
            except OSError:
 
287
                # maybe something better?
 
288
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
289
            
 
290
            if kind != 'file' and kind != 'directory':
 
291
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
292
 
 
293
            file_id = gen_file_id(f)
 
294
            inv.add_path(f, kind=kind, file_id=file_id)
 
295
 
252
296
            if verbose:
253
297
                show_status('A', kind, quotefn(f))
254
298
                
255
 
            mutter("add file %s file_id:{%s} kind=%r parent_id={%s}"
256
 
                   % (f, file_id, kind, parent_id))
 
299
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
300
            
257
301
        self._write_inventory(inv)
258
302
 
259
303
 
 
304
    def print_file(self, file, revno):
 
305
        """Print `file` to stdout."""
 
306
        tree = self.revision_tree(self.lookup_revision(revno))
 
307
        # use inventory as it was in that revision
 
308
        file_id = tree.inventory.path2id(file)
 
309
        if not file_id:
 
310
            bailout("%r is not present in revision %d" % (file, revno))
 
311
        tree.print_file(file_id)
 
312
        
260
313
 
261
314
    def remove(self, files, verbose=False):
262
315
        """Mark nominated files for removal from the inventory.
388
441
 
389
442
            entry = entry.copy()
390
443
 
391
 
            p = self._rel(path)
 
444
            p = self.abspath(path)
392
445
            file_id = entry.file_id
393
446
            mutter('commit prep file %s, id %r ' % (p, file_id))
394
447
 
434
487
                           entry.text_id)
435
488
                    
436
489
                else:
437
 
                    entry.text_id = _gen_file_id(entry.name)
 
490
                    entry.text_id = gen_file_id(entry.name)
438
491
                    self.text_store.add(content, entry.text_id)
439
492
                    mutter('    stored with text_id {%s}' % entry.text_id)
440
493
                    if verbose:
442
495
                            state = 'A'
443
496
                        elif (old_ie.name == entry.name
444
497
                              and old_ie.parent_id == entry.parent_id):
 
498
                            state = 'M'
 
499
                        else:
445
500
                            state = 'R'
446
 
                        else:
447
 
                            state = 'M'
448
501
 
449
502
                        show_status(state, entry.kind, quotefn(path))
450
503
 
504
557
        mutter("committing patch r%d" % (self.revno() + 1))
505
558
 
506
559
        mutter("append to revision-history")
507
 
        self.controlfile('revision-history', 'at').write(rev_id + '\n')
 
560
        f = self.controlfile('revision-history', 'at')
 
561
        f.write(rev_id + '\n')
 
562
        f.close()
508
563
 
509
 
        mutter("done!")
 
564
        if verbose:
 
565
            note("commited r%d" % self.revno())
510
566
 
511
567
 
512
568
    def get_revision(self, revision_id):
655
711
            precursor = p
656
712
 
657
713
 
 
714
    def rename_one(self, from_rel, to_rel):
 
715
        tree = self.working_tree()
 
716
        inv = tree.inventory
 
717
        if not tree.has_filename(from_rel):
 
718
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
719
        if tree.has_filename(to_rel):
 
720
            bailout("can't rename: new working file %r already exists" % to_rel)
 
721
            
 
722
        file_id = inv.path2id(from_rel)
 
723
        if file_id == None:
 
724
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
725
 
 
726
        if inv.path2id(to_rel):
 
727
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
728
 
 
729
        to_dir, to_tail = os.path.split(to_rel)
 
730
        to_dir_id = inv.path2id(to_dir)
 
731
        if to_dir_id == None and to_dir != '':
 
732
            bailout("can't determine destination directory id for %r" % to_dir)
 
733
 
 
734
        mutter("rename_one:")
 
735
        mutter("  file_id    {%s}" % file_id)
 
736
        mutter("  from_rel   %r" % from_rel)
 
737
        mutter("  to_rel     %r" % to_rel)
 
738
        mutter("  to_dir     %r" % to_dir)
 
739
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
740
            
 
741
        inv.rename(file_id, to_dir_id, to_tail)
 
742
 
 
743
        print "%s => %s" % (from_rel, to_rel)
 
744
        
 
745
        from_abs = self.abspath(from_rel)
 
746
        to_abs = self.abspath(to_rel)
 
747
        try:
 
748
            os.rename(from_abs, to_abs)
 
749
        except OSError, e:
 
750
            bailout("failed to rename %r to %r: %s"
 
751
                    % (from_abs, to_abs, e[1]),
 
752
                    ["rename rolled back"])
 
753
 
 
754
        self._write_inventory(inv)
 
755
            
 
756
 
 
757
 
 
758
    def move(self, from_paths, to_name):
 
759
        """Rename files.
 
760
 
 
761
        to_name must exist as a versioned directory.
 
762
 
 
763
        If to_name exists and is a directory, the files are moved into
 
764
        it, keeping their old names.  If it is a directory, 
 
765
 
 
766
        Note that to_name is only the last component of the new name;
 
767
        this doesn't change the directory.
 
768
        """
 
769
        ## TODO: Option to move IDs only
 
770
        assert not isinstance(from_paths, basestring)
 
771
        tree = self.working_tree()
 
772
        inv = tree.inventory
 
773
        to_abs = self.abspath(to_name)
 
774
        if not isdir(to_abs):
 
775
            bailout("destination %r is not a directory" % to_abs)
 
776
        if not tree.has_filename(to_name):
 
777
            bailout("destination %r not in working directory" % to_abs)
 
778
        to_dir_id = inv.path2id(to_name)
 
779
        if to_dir_id == None and to_name != '':
 
780
            bailout("destination %r is not a versioned directory" % to_name)
 
781
        to_dir_ie = inv[to_dir_id]
 
782
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
783
            bailout("destination %r is not a directory" % to_abs)
 
784
 
 
785
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
786
 
 
787
        for f in from_paths:
 
788
            if not tree.has_filename(f):
 
789
                bailout("%r does not exist in working tree" % f)
 
790
            f_id = inv.path2id(f)
 
791
            if f_id == None:
 
792
                bailout("%r is not versioned" % f)
 
793
            name_tail = splitpath(f)[-1]
 
794
            dest_path = appendpath(to_name, name_tail)
 
795
            if tree.has_filename(dest_path):
 
796
                bailout("destination %r already exists" % dest_path)
 
797
            if f_id in to_idpath:
 
798
                bailout("can't move %r to a subdirectory of itself" % f)
 
799
 
 
800
        # OK, so there's a race here, it's possible that someone will
 
801
        # create a file in this interval and then the rename might be
 
802
        # left half-done.  But we should have caught most problems.
 
803
 
 
804
        for f in from_paths:
 
805
            name_tail = splitpath(f)[-1]
 
806
            dest_path = appendpath(to_name, name_tail)
 
807
            print "%s => %s" % (f, dest_path)
 
808
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
809
            try:
 
810
                os.rename(self.abspath(f), self.abspath(dest_path))
 
811
            except OSError, e:
 
812
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
813
                        ["rename rolled back"])
 
814
 
 
815
        self._write_inventory(inv)
 
816
 
 
817
 
658
818
 
659
819
    def show_status(branch, show_all=False):
660
820
        """Display single-line status for non-ignored working files.
669
829
        A       foo
670
830
        >>> b.commit("add foo")
671
831
        >>> b.show_status()
672
 
        >>> os.unlink(b._rel('foo'))
 
832
        >>> os.unlink(b.abspath('foo'))
673
833
        >>> b.show_status()
674
834
        D       foo
675
835
        
726
886
    >>> isdir(bd)
727
887
    False
728
888
    """
729
 
    def __init__(self, files = []):
 
889
    def __init__(self, files=[], dirs=[]):
730
890
        """Make a test branch.
731
891
 
732
892
        This creates a temporary directory and runs init-tree in it.
734
894
        If any files are listed, they are created in the working copy.
735
895
        """
736
896
        Branch.__init__(self, tempfile.mkdtemp(), init=True)
 
897
        for d in dirs:
 
898
            os.mkdir(self.abspath(d))
 
899
            
737
900
        for f in files:
738
901
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
739
902
 
740
903
 
741
904
    def __del__(self):
742
905
        """Destroy the test branch, removing the scratch directory."""
743
 
        shutil.rmtree(self.base)
 
906
        try:
 
907
            shutil.rmtree(self.base)
 
908
        except OSError:
 
909
            # Work around for shutil.rmtree failing on Windows when
 
910
            # readonly files are encountered
 
911
            for root, dirs, files in os.walk(self.base, topdown=False):
 
912
                for name in files:
 
913
                    os.chmod(os.path.join(root, name), 0700)
 
914
            shutil.rmtree(self.base)
744
915
 
745
916
    
746
917
 
756
927
        ## mutter('check %r for control file' % ((head, tail), ))
757
928
        if tail == bzrlib.BZRDIR:
758
929
            return True
 
930
        if filename == head:
 
931
            break
759
932
        filename = head
760
933
    return False
761
934
 
764
937
def _gen_revision_id(when):
765
938
    """Return new revision-id."""
766
939
    s = '%s-%s-' % (user_email(), compact_date(when))
767
 
    s += hexlify(rand_bytes(8))
 
940
    s += hexlify(rand_bytes(12))
768
941
    return s
769
942
 
770
943
 
771
 
def _gen_file_id(name):
 
944
def gen_file_id(name):
772
945
    """Return new file id.
773
946
 
774
947
    This should probably generate proper UUIDs, but for the moment we
775
948
    cope with just randomness because running uuidgen every time is
776
949
    slow."""
777
 
    assert '/' not in name
778
 
    while name[0] == '.':
779
 
        name = name[1:]
780
 
    s = hexlify(rand_bytes(8))
 
950
    idx = name.rfind('/')
 
951
    if idx != -1:
 
952
        name = name[idx+1 : ]
 
953
 
 
954
    name = name.lstrip('.')
 
955
 
 
956
    s = hexlify(rand_bytes(12))
781
957
    return '-'.join((name, compact_date(time.time()), s))
782
958
 
783
959