~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-19 01:41:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050319014144-5298a74caebaf378
fix local-time-offset calculation

Show diffs side-by-side

added added

removed removed

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