~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-04-15 02:41:52 UTC
  • Revision ID: mbp@sourcefrog.net-20050415024152-caf2e2f1c3ec6129
- remove atexit() dependency for writing out execution times

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
from inventory import InventoryEntry, Inventory
29
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, chomp, \
30
30
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
 
     joinpath, sha_string, file_kind, local_time_offset
 
31
     joinpath, sha_string, file_kind, local_time_offset, appendpath
32
32
from store import ImmutableStore
33
33
from revision import Revision
34
 
from errors import bailout
 
34
from errors import bailout, BzrError
35
35
from textui import show_status
36
36
from diff import diff_trees
37
37
 
47
47
 
48
48
    Basically we keep looking up until we find the control directory or
49
49
    run into the root."""
50
 
    if f is None:
 
50
    if f == None:
51
51
        f = os.getcwd()
52
52
    elif hasattr(os.path, 'realpath'):
53
53
        f = os.path.realpath(f)
56
56
 
57
57
    orig_f = f
58
58
 
59
 
    last_f = f
60
59
    while True:
61
60
        if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
62
61
            return f
63
62
        head, tail = os.path.split(f)
64
63
        if head == f:
65
64
            # reached the root, whatever that may be
66
 
            bailout('%r is not in a branch' % orig_f)
 
65
            raise BzrError('%r is not in a branch' % orig_f)
67
66
        f = head
68
67
    
69
68
 
74
73
class Branch:
75
74
    """Branch holding a history of revisions.
76
75
 
77
 
    :todo: Perhaps use different stores for different classes of object,
 
76
    TODO: Perhaps use different stores for different classes of object,
78
77
           so that we can keep track of how much space each one uses,
79
78
           or garbage-collect them.
80
79
 
81
 
    :todo: Add a RemoteBranch subclass.  For the basic case of read-only
 
80
    TODO: Add a RemoteBranch subclass.  For the basic case of read-only
82
81
           HTTP access this should be very easy by, 
83
82
           just redirecting controlfile access into HTTP requests.
84
83
           We would need a RemoteStore working similarly.
85
84
 
86
 
    :todo: Keep the on-disk branch locked while the object exists.
 
85
    TODO: Keep the on-disk branch locked while the object exists.
87
86
 
88
 
    :todo: mkdir() method.
 
87
    TODO: mkdir() method.
89
88
    """
90
89
    def __init__(self, base, init=False, find_root=True):
91
90
        """Create new branch object at a particular location.
92
91
 
93
 
        :param base: Base directory for the branch.
 
92
        base -- Base directory for the branch.
94
93
        
95
 
        :param init: If True, create new control files in a previously
 
94
        init -- If True, create new control files in a previously
96
95
             unversioned directory.  If False, the branch must already
97
96
             be versioned.
98
97
 
99
 
        :param find_root: If true and init is false, find the root of the
 
98
        find_root -- If true and init is false, find the root of the
100
99
             existing branch containing base.
101
100
 
102
101
        In the test suite, creation of new trees is tested using the
153
152
 
154
153
 
155
154
    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)
 
155
        """Open a control file for this branch.
 
156
 
 
157
        There are two classes of file in the control directory: text
 
158
        and binary.  binary files are untranslated byte streams.  Text
 
159
        control files are stored with Unix newlines and in UTF-8, even
 
160
        if the platform or locale defaults are different.
 
161
        """
 
162
 
 
163
        fn = self.controlfilename(file_or_path)
 
164
 
 
165
        if mode == 'rb' or mode == 'wb':
 
166
            return file(fn, mode)
 
167
        elif mode == 'r' or mode == 'w':
 
168
            # open in binary mode anyhow so there's no newline translation;
 
169
            # codecs uses line buffering by default; don't want that.
 
170
            import codecs
 
171
            return codecs.open(fn, mode + 'b', 'utf-8',
 
172
                               buffering=60000)
 
173
        else:
 
174
            raise BzrError("invalid controlfile mode %r" % mode)
 
175
 
158
176
 
159
177
 
160
178
    def _make_control(self):
179
197
 
180
198
        In the future, we might need different in-memory Branch
181
199
        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()
 
200
        """
 
201
        # This ignores newlines so that we can open branches created
 
202
        # on Windows from Linux and so on.  I think it might be better
 
203
        # to always make all internal files in unix format.
 
204
        fmt = self.controlfile('branch-format', 'r').read()
 
205
        fmt.replace('\r\n', '')
185
206
        if fmt != BZR_BRANCH_FORMAT:
186
207
            bailout('sorry, branch format %r not supported' % fmt,
187
208
                    ['use a different bzr version',
191
212
    def read_working_inventory(self):
192
213
        """Read the working inventory."""
193
214
        before = time.time()
194
 
        inv = Inventory.read_xml(self.controlfile('inventory', 'r'))
 
215
        # ElementTree does its own conversion from UTF-8, so open in
 
216
        # binary.
 
217
        inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
195
218
        mutter("loaded inventory of %d items in %f"
196
219
               % (len(inv), time.time() - before))
197
220
        return inv
206
229
        ## TODO: factor out to atomicfile?  is rename safe on windows?
207
230
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
208
231
        tmpfname = self.controlfilename('inventory.tmp')
209
 
        tmpf = file(tmpfname, 'w')
 
232
        tmpf = file(tmpfname, 'wb')
210
233
        inv.write_xml(tmpf)
211
234
        tmpf.close()
212
 
        os.rename(tmpfname, self.controlfilename('inventory'))
 
235
        inv_fname = self.controlfilename('inventory')
 
236
        if sys.platform == 'win32':
 
237
            os.remove(inv_fname)
 
238
        os.rename(tmpfname, inv_fname)
213
239
        mutter('wrote working inventory')
214
240
 
215
241
 
220
246
    def add(self, files, verbose=False):
221
247
        """Make files versioned.
222
248
 
 
249
        Note that the command line normally calls smart_add instead.
 
250
 
223
251
        This puts the files in the Added state, so that they will be
224
252
        recorded by the next commit.
225
253
 
226
 
        :todo: Perhaps have an option to add the ids even if the files do
 
254
        TODO: Perhaps have an option to add the ids even if the files do
227
255
               not (yet) exist.
228
256
 
229
 
        :todo: Perhaps return the ids of the files?  But then again it
 
257
        TODO: Perhaps return the ids of the files?  But then again it
230
258
               is easy to retrieve them if they're needed.
231
259
 
232
 
        :todo: Option to specify file id.
 
260
        TODO: Option to specify file id.
233
261
 
234
 
        :todo: Adding a directory should optionally recurse down and
 
262
        TODO: Adding a directory should optionally recurse down and
235
263
               add all non-ignored children.  Perhaps do that in a
236
264
               higher-level method.
237
265
 
295
323
        self._write_inventory(inv)
296
324
 
297
325
 
 
326
    def print_file(self, file, revno):
 
327
        """Print `file` to stdout."""
 
328
        tree = self.revision_tree(self.lookup_revision(revno))
 
329
        # use inventory as it was in that revision
 
330
        file_id = tree.inventory.path2id(file)
 
331
        if not file_id:
 
332
            bailout("%r is not present in revision %d" % (file, revno))
 
333
        tree.print_file(file_id)
 
334
        
298
335
 
299
336
    def remove(self, files, verbose=False):
300
337
        """Mark nominated files for removal from the inventory.
301
338
 
302
339
        This does not remove their text.  This does not run on 
303
340
 
304
 
        :todo: Refuse to remove modified files unless --force is given?
 
341
        TODO: Refuse to remove modified files unless --force is given?
305
342
 
306
343
        >>> b = ScratchBranch(files=['foo'])
307
344
        >>> b.add('foo')
325
362
        >>> b.working_tree().has_filename('foo') 
326
363
        True
327
364
 
328
 
        :todo: Do something useful with directories.
 
365
        TODO: Do something useful with directories.
329
366
 
330
 
        :todo: Should this remove the text or not?  Tough call; not
 
367
        TODO: Should this remove the text or not?  Tough call; not
331
368
        removing may be useful and the user can just use use rm, and
332
369
        is the opposite of add.  Removing it is consistent with most
333
370
        other tools.  Maybe an option.
397
434
        be robust against files disappearing, moving, etc.  So the
398
435
        whole thing is a bit hard.
399
436
 
400
 
        :param timestamp: if not None, seconds-since-epoch for a
 
437
        timestamp -- if not None, seconds-since-epoch for a
401
438
             postdated/predated commit.
402
439
        """
403
440
 
480
517
                            state = 'A'
481
518
                        elif (old_ie.name == entry.name
482
519
                              and old_ie.parent_id == entry.parent_id):
 
520
                            state = 'M'
 
521
                        else:
483
522
                            state = 'R'
484
 
                        else:
485
 
                            state = 'M'
486
523
 
487
524
                        show_status(state, entry.kind, quotefn(path))
488
525
 
541
578
        ## TODO: Also calculate and store the inventory SHA1
542
579
        mutter("committing patch r%d" % (self.revno() + 1))
543
580
 
544
 
        mutter("append to revision-history")
545
 
        self.controlfile('revision-history', 'at').write(rev_id + '\n')
546
 
 
547
 
        mutter("done!")
 
581
 
 
582
        self.append_revision(rev_id)
 
583
        
 
584
        if verbose:
 
585
            note("commited r%d" % self.revno())
 
586
 
 
587
 
 
588
    def append_revision(self, revision_id):
 
589
        mutter("add {%s} to revision-history" % revision_id)
 
590
        rev_history = self.revision_history()
 
591
 
 
592
        tmprhname = self.controlfilename('revision-history.tmp')
 
593
        rhname = self.controlfilename('revision-history')
 
594
        
 
595
        f = file(tmprhname, 'wt')
 
596
        rev_history.append(revision_id)
 
597
        f.write('\n'.join(rev_history))
 
598
        f.write('\n')
 
599
        f.close()
 
600
 
 
601
        if sys.platform == 'win32':
 
602
            os.remove(rhname)
 
603
        os.rename(tmprhname, rhname)
 
604
        
548
605
 
549
606
 
550
607
    def get_revision(self, revision_id):
557
614
    def get_inventory(self, inventory_id):
558
615
        """Get Inventory object by hash.
559
616
 
560
 
        :todo: Perhaps for this and similar methods, take a revision
 
617
        TODO: Perhaps for this and similar methods, take a revision
561
618
               parameter which can be either an integer revno or a
562
619
               string hash."""
563
620
        i = Inventory.read_xml(self.inventory_store[inventory_id])
578
635
        >>> ScratchBranch().revision_history()
579
636
        []
580
637
        """
581
 
        return [chomp(l) for l in self.controlfile('revision-history').readlines()]
 
638
        return [chomp(l) for l in self.controlfile('revision-history', 'r').readlines()]
582
639
 
583
640
 
584
641
    def revno(self):
606
663
        ph = self.revision_history()
607
664
        if ph:
608
665
            return ph[-1]
609
 
 
 
666
        else:
 
667
            return None
 
668
        
610
669
 
611
670
    def lookup_revision(self, revno):
612
671
        """Return revision hash for revision number."""
617
676
            # list is 0-based; revisions are 1-based
618
677
            return self.revision_history()[revno-1]
619
678
        except IndexError:
620
 
            bailout("no such revision %s" % revno)
 
679
            raise BzrError("no such revision %s" % revno)
621
680
 
622
681
 
623
682
    def revision_tree(self, revision_id):
661
720
 
662
721
 
663
722
 
664
 
    def write_log(self, show_timezone='original'):
 
723
    def write_log(self, show_timezone='original', verbose=False):
665
724
        """Write out human-readable log of commits to this branch
666
725
 
667
 
        :param utc: If true, show dates in universal time, not local time."""
 
726
        utc -- If true, show dates in universal time, not local time."""
668
727
        ## TODO: Option to choose either original, utc or local timezone
669
728
        revno = 1
670
729
        precursor = None
689
748
                for l in rev.message.split('\n'):
690
749
                    print '  ' + l
691
750
 
 
751
            if verbose == True and precursor != None:
 
752
                print 'changed files:'
 
753
                tree = self.revision_tree(p)
 
754
                prevtree = self.revision_tree(precursor)
 
755
                
 
756
                for file_state, fid, old_name, new_name, kind in \
 
757
                                        diff_trees(prevtree, tree, ):
 
758
                    if file_state == 'A' or file_state == 'M':
 
759
                        show_status(file_state, kind, new_name)
 
760
                    elif file_state == 'D':
 
761
                        show_status(file_state, kind, old_name)
 
762
                    elif file_state == 'R':
 
763
                        show_status(file_state, kind,
 
764
                            old_name + ' => ' + new_name)
 
765
                
692
766
            revno += 1
693
767
            precursor = p
694
768
 
695
769
 
696
 
 
697
 
    def show_status(branch, show_all=False):
 
770
    def rename_one(self, from_rel, to_rel):
 
771
        tree = self.working_tree()
 
772
        inv = tree.inventory
 
773
        if not tree.has_filename(from_rel):
 
774
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
775
        if tree.has_filename(to_rel):
 
776
            bailout("can't rename: new working file %r already exists" % to_rel)
 
777
            
 
778
        file_id = inv.path2id(from_rel)
 
779
        if file_id == None:
 
780
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
781
 
 
782
        if inv.path2id(to_rel):
 
783
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
784
 
 
785
        to_dir, to_tail = os.path.split(to_rel)
 
786
        to_dir_id = inv.path2id(to_dir)
 
787
        if to_dir_id == None and to_dir != '':
 
788
            bailout("can't determine destination directory id for %r" % to_dir)
 
789
 
 
790
        mutter("rename_one:")
 
791
        mutter("  file_id    {%s}" % file_id)
 
792
        mutter("  from_rel   %r" % from_rel)
 
793
        mutter("  to_rel     %r" % to_rel)
 
794
        mutter("  to_dir     %r" % to_dir)
 
795
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
796
            
 
797
        inv.rename(file_id, to_dir_id, to_tail)
 
798
 
 
799
        print "%s => %s" % (from_rel, to_rel)
 
800
        
 
801
        from_abs = self.abspath(from_rel)
 
802
        to_abs = self.abspath(to_rel)
 
803
        try:
 
804
            os.rename(from_abs, to_abs)
 
805
        except OSError, e:
 
806
            bailout("failed to rename %r to %r: %s"
 
807
                    % (from_abs, to_abs, e[1]),
 
808
                    ["rename rolled back"])
 
809
 
 
810
        self._write_inventory(inv)
 
811
            
 
812
 
 
813
 
 
814
    def move(self, from_paths, to_name):
 
815
        """Rename files.
 
816
 
 
817
        to_name must exist as a versioned directory.
 
818
 
 
819
        If to_name exists and is a directory, the files are moved into
 
820
        it, keeping their old names.  If it is a directory, 
 
821
 
 
822
        Note that to_name is only the last component of the new name;
 
823
        this doesn't change the directory.
 
824
        """
 
825
        ## TODO: Option to move IDs only
 
826
        assert not isinstance(from_paths, basestring)
 
827
        tree = self.working_tree()
 
828
        inv = tree.inventory
 
829
        to_abs = self.abspath(to_name)
 
830
        if not isdir(to_abs):
 
831
            bailout("destination %r is not a directory" % to_abs)
 
832
        if not tree.has_filename(to_name):
 
833
            bailout("destination %r not in working directory" % to_abs)
 
834
        to_dir_id = inv.path2id(to_name)
 
835
        if to_dir_id == None and to_name != '':
 
836
            bailout("destination %r is not a versioned directory" % to_name)
 
837
        to_dir_ie = inv[to_dir_id]
 
838
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
839
            bailout("destination %r is not a directory" % to_abs)
 
840
 
 
841
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
842
 
 
843
        for f in from_paths:
 
844
            if not tree.has_filename(f):
 
845
                bailout("%r does not exist in working tree" % f)
 
846
            f_id = inv.path2id(f)
 
847
            if f_id == None:
 
848
                bailout("%r is not versioned" % f)
 
849
            name_tail = splitpath(f)[-1]
 
850
            dest_path = appendpath(to_name, name_tail)
 
851
            if tree.has_filename(dest_path):
 
852
                bailout("destination %r already exists" % dest_path)
 
853
            if f_id in to_idpath:
 
854
                bailout("can't move %r to a subdirectory of itself" % f)
 
855
 
 
856
        # OK, so there's a race here, it's possible that someone will
 
857
        # create a file in this interval and then the rename might be
 
858
        # left half-done.  But we should have caught most problems.
 
859
 
 
860
        for f in from_paths:
 
861
            name_tail = splitpath(f)[-1]
 
862
            dest_path = appendpath(to_name, name_tail)
 
863
            print "%s => %s" % (f, dest_path)
 
864
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
865
            try:
 
866
                os.rename(self.abspath(f), self.abspath(dest_path))
 
867
            except OSError, e:
 
868
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
869
                        ["rename rolled back"])
 
870
 
 
871
        self._write_inventory(inv)
 
872
 
 
873
 
 
874
 
 
875
    def show_status(self, show_all=False):
698
876
        """Display single-line status for non-ignored working files.
699
877
 
700
878
        The list is show sorted in order by file name.
712
890
        D       foo
713
891
        
714
892
 
715
 
        :todo: Get state for single files.
 
893
        TODO: Get state for single files.
716
894
 
717
 
        :todo: Perhaps show a slash at the end of directory names.        
 
895
        TODO: Perhaps show a slash at the end of directory names.        
718
896
 
719
897
        """
720
898
 
727
905
        # Interesting case: the old ID for a file has been removed,
728
906
        # but a new file has been created under that name.
729
907
 
730
 
        old = branch.basis_tree()
731
 
        old_inv = old.inventory
732
 
        new = branch.working_tree()
733
 
        new_inv = new.inventory
 
908
        old = self.basis_tree()
 
909
        new = self.working_tree()
734
910
 
735
911
        for fs, fid, oldname, newname, kind in diff_trees(old, new):
736
912
            if fs == 'R':
749
925
            elif fs == '?':
750
926
                show_status(fs, kind, newname)
751
927
            else:
752
 
                bailout("wierd file state %r" % ((fs, fid),))
 
928
                bailout("weird file state %r" % ((fs, fid),))
753
929
                
754
930
 
755
931
 
764
940
    >>> isdir(bd)
765
941
    False
766
942
    """
767
 
    def __init__(self, files = []):
 
943
    def __init__(self, files=[], dirs=[]):
768
944
        """Make a test branch.
769
945
 
770
946
        This creates a temporary directory and runs init-tree in it.
772
948
        If any files are listed, they are created in the working copy.
773
949
        """
774
950
        Branch.__init__(self, tempfile.mkdtemp(), init=True)
 
951
        for d in dirs:
 
952
            os.mkdir(self.abspath(d))
 
953
            
775
954
        for f in files:
776
955
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
777
956
 
778
957
 
779
958
    def __del__(self):
780
959
        """Destroy the test branch, removing the scratch directory."""
781
 
        shutil.rmtree(self.base)
 
960
        try:
 
961
            shutil.rmtree(self.base)
 
962
        except OSError:
 
963
            # Work around for shutil.rmtree failing on Windows when
 
964
            # readonly files are encountered
 
965
            for root, dirs, files in os.walk(self.base, topdown=False):
 
966
                for name in files:
 
967
                    os.chmod(os.path.join(root, name), 0700)
 
968
            shutil.rmtree(self.base)
782
969
 
783
970
    
784
971
 
822
1009
 
823
1010
    s = hexlify(rand_bytes(8))
824
1011
    return '-'.join((name, compact_date(time.time()), s))
825
 
 
826