~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-04 10:35:13 UTC
  • Revision ID: mbp@sourcefrog.net-20050404103513-d938ee5693d52989
merge win32 portability fixes

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
 
388
432
 
389
433
            entry = entry.copy()
390
434
 
391
 
            p = self._rel(path)
 
435
            p = self.abspath(path)
392
436
            file_id = entry.file_id
393
437
            mutter('commit prep file %s, id %r ' % (p, file_id))
394
438
 
434
478
                           entry.text_id)
435
479
                    
436
480
                else:
437
 
                    entry.text_id = _gen_file_id(entry.name)
 
481
                    entry.text_id = gen_file_id(entry.name)
438
482
                    self.text_store.add(content, entry.text_id)
439
483
                    mutter('    stored with text_id {%s}' % entry.text_id)
440
484
                    if verbose:
442
486
                            state = 'A'
443
487
                        elif (old_ie.name == entry.name
444
488
                              and old_ie.parent_id == entry.parent_id):
 
489
                            state = 'M'
 
490
                        else:
445
491
                            state = 'R'
446
 
                        else:
447
 
                            state = 'M'
448
492
 
449
493
                        show_status(state, entry.kind, quotefn(path))
450
494
 
504
548
        mutter("committing patch r%d" % (self.revno() + 1))
505
549
 
506
550
        mutter("append to revision-history")
507
 
        self.controlfile('revision-history', 'at').write(rev_id + '\n')
 
551
        f = self.controlfile('revision-history', 'at')
 
552
        f.write(rev_id + '\n')
 
553
        f.close()
508
554
 
509
 
        mutter("done!")
 
555
        if verbose:
 
556
            note("commited r%d" % self.revno())
510
557
 
511
558
 
512
559
    def get_revision(self, revision_id):
656
703
 
657
704
 
658
705
 
 
706
    def rename(self, from_paths, to_name):
 
707
        """Rename files.
 
708
 
 
709
        If to_name exists and is a directory, the files are moved into
 
710
        it, keeping their old names.  If it is a directory, 
 
711
 
 
712
        Note that to_name is only the last component of the new name;
 
713
        this doesn't change the directory.
 
714
        """
 
715
        ## TODO: Option to move IDs only
 
716
        assert not isinstance(from_paths, basestring)
 
717
        tree = self.working_tree()
 
718
        inv = tree.inventory
 
719
        dest_dir = isdir(self.abspath(to_name))
 
720
        if dest_dir:
 
721
            # TODO: Wind back properly if some can't be moved?
 
722
            dest_dir_id = inv.path2id(to_name)
 
723
            if not dest_dir_id and to_name != '':
 
724
                bailout("destination %r is not a versioned directory" % to_name)
 
725
            for f in from_paths:
 
726
                name_tail = splitpath(f)[-1]
 
727
                dest_path = appendpath(to_name, name_tail)
 
728
                print "%s => %s" % (f, dest_path)
 
729
                inv.rename(inv.path2id(f), dest_dir_id, name_tail)
 
730
                os.rename(self.abspath(f), self.abspath(dest_path))
 
731
            self._write_inventory(inv)
 
732
        else:
 
733
            if len(from_paths) != 1:
 
734
                bailout("when moving multiple files, destination must be a directory")
 
735
            bailout("rename to non-directory %r not implemented sorry" % to_name)
 
736
 
 
737
 
 
738
 
659
739
    def show_status(branch, show_all=False):
660
740
        """Display single-line status for non-ignored working files.
661
741
 
669
749
        A       foo
670
750
        >>> b.commit("add foo")
671
751
        >>> b.show_status()
672
 
        >>> os.unlink(b._rel('foo'))
 
752
        >>> os.unlink(b.abspath('foo'))
673
753
        >>> b.show_status()
674
754
        D       foo
675
755
        
726
806
    >>> isdir(bd)
727
807
    False
728
808
    """
729
 
    def __init__(self, files = []):
 
809
    def __init__(self, files=[], dirs=[]):
730
810
        """Make a test branch.
731
811
 
732
812
        This creates a temporary directory and runs init-tree in it.
734
814
        If any files are listed, they are created in the working copy.
735
815
        """
736
816
        Branch.__init__(self, tempfile.mkdtemp(), init=True)
 
817
        for d in dirs:
 
818
            os.mkdir(self.abspath(d))
 
819
            
737
820
        for f in files:
738
821
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
739
822
 
740
823
 
741
824
    def __del__(self):
742
825
        """Destroy the test branch, removing the scratch directory."""
743
 
        shutil.rmtree(self.base)
 
826
        try:
 
827
            shutil.rmtree(self.base)
 
828
        except OSError:
 
829
            # Work around for shutil.rmtree failing on Windows when
 
830
            # readonly files are encountered
 
831
            for root, dirs, files in os.walk(self.base, topdown=False):
 
832
                for name in files:
 
833
                    os.chmod(os.path.join(root, name), 0700)
 
834
            shutil.rmtree(self.base)
744
835
 
745
836
    
746
837
 
756
847
        ## mutter('check %r for control file' % ((head, tail), ))
757
848
        if tail == bzrlib.BZRDIR:
758
849
            return True
 
850
        if filename == head:
 
851
            break
759
852
        filename = head
760
853
    return False
761
854
 
768
861
    return s
769
862
 
770
863
 
771
 
def _gen_file_id(name):
 
864
def gen_file_id(name):
772
865
    """Return new file id.
773
866
 
774
867
    This should probably generate proper UUIDs, but for the moment we
775
868
    cope with just randomness because running uuidgen every time is
776
869
    slow."""
777
 
    assert '/' not in name
778
 
    while name[0] == '.':
779
 
        name = name[1:]
 
870
    idx = name.rfind('/')
 
871
    if idx != -1:
 
872
        name = name[idx+1 : ]
 
873
 
 
874
    name = name.lstrip('.')
 
875
 
780
876
    s = hexlify(rand_bytes(8))
781
877
    return '-'.join((name, compact_date(time.time()), s))
782
878