/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1
# Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
17
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
18
"""An adapter between a Git index and a Bazaar Working Tree"""
19
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
20
0.200.385 by Jelmer Vernooij
Cope with removed files.
21
from cStringIO import (
22
    StringIO,
23
    )
0.239.4 by Jelmer Vernooij
Cope with nonexistent files and directories in get_file_sha1.
24
import errno
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
25
from dulwich.index import (
26
    Index,
27
    )
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
28
from dulwich.objects import (
29
    Blob,
30
    )
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
31
from dulwich.protocol import (
32
    ZERO_SHA,
33
    )
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
34
import os
0.200.384 by Jelmer Vernooij
Fix reading of inventory from index.
35
import stat
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
36
37
from bzrlib import (
0.200.382 by Jelmer Vernooij
Support flushing index.
38
    errors,
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
39
    ignores,
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
40
    lockable_files,
41
    lockdir,
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
42
    osutils,
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
43
    transport,
0.200.519 by Jelmer Vernooij
Move imports down, might not be available in older bzr-git versions.
44
    tree,
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
45
    workingtree,
46
    )
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
47
from bzrlib.decorators import (
48
    needs_read_lock,
49
    )
50
51
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
52
from bzrlib.plugins.git.dir import (
53
    LocalGitDir,
54
    )
0.200.401 by Jelmer Vernooij
Move working tree inventory code to inventory.
55
from bzrlib.plugins.git.inventory import (
56
    GitIndexInventory,
57
    )
0.200.617 by Jelmer Vernooij
Add custom InterTree for use between git revision trees.
58
from bzrlib.plugins.git.tree import (
0.200.622 by Jelmer Vernooij
Implement InterTree.iter_changes() as well.
59
    changes_from_git_changes,
0.200.617 by Jelmer Vernooij
Add custom InterTree for use between git revision trees.
60
    tree_delta_from_git_changes,
61
    )
0.200.971 by Chadrik
Fix 'bzr status' after 'bzr add' in native git working trees.
62
from bzrlib.plugins.git.mapping import (
63
    GitFileIdMap,
64
    )
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
65
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
66
IGNORE_FILENAME = ".gitignore"
67
68
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
69
class GitWorkingTree(workingtree.WorkingTree):
70
    """A Git working tree."""
71
0.200.803 by Jelmer Vernooij
Default to non-bare repositories when initializing a control directory.
72
    def __init__(self, bzrdir, repo, branch, index):
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
73
        self.basedir = bzrdir.root_transport.local_abspath('.')
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
74
        self.bzrdir = bzrdir
75
        self.repository = repo
0.200.384 by Jelmer Vernooij
Fix reading of inventory from index.
76
        self.mapping = self.repository.get_mapping()
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
77
        self._branch = branch
78
        self._transport = bzrdir.transport
79
0.246.3 by Jelmer Vernooij
Simplify call to abspath, without involving private variables.
80
        self.controldir = self.bzrdir.transport.local_abspath('bzr')
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
81
82
        try:
83
            os.makedirs(self.controldir)
84
            os.makedirs(os.path.join(self.controldir, 'lock'))
85
        except OSError:
86
            pass
87
88
        self._control_files = lockable_files.LockableFiles(
89
            transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
90
        self._format = GitWorkingTreeFormat()
0.200.803 by Jelmer Vernooij
Default to non-bare repositories when initializing a control directory.
91
        self.index = index
0.200.239 by Jelmer Vernooij
Provide views.
92
        self.views = self._make_views()
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
93
        self._detect_case_handling()
0.200.173 by Jelmer Vernooij
Merge changes, open index.
94
0.200.605 by Jelmer Vernooij
Ignore directories in WorkingTree.extras().
95
    def extras(self):
96
        """Yield all unversioned files in this WorkingTree.
97
        """
0.200.615 by Jelmer Vernooij
Optimize WorkingTree.extras().
98
        for (dirpath, dirnames, filenames) in os.walk(self.basedir):
99
            if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
0.200.605 by Jelmer Vernooij
Ignore directories in WorkingTree.extras().
100
                continue
0.200.615 by Jelmer Vernooij
Optimize WorkingTree.extras().
101
            for filename in filenames:
102
                relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
103
                if not relpath in self.index:
0.200.605 by Jelmer Vernooij
Ignore directories in WorkingTree.extras().
104
                    yield relpath
105
106
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
107
    def unlock(self):
0.200.224 by Jelmer Vernooij
Fix working tree locking.
108
        # non-implementation specific cleanup
109
        self._cleanup()
110
111
        # reverse order of locking.
112
        try:
113
            return self._control_files.unlock()
114
        finally:
115
            self.branch.unlock()
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
116
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
117
    def _rewrite_index(self):
118
        self.index.clear()
119
        for path, entry in self._inventory.iter_entries():
120
            if entry.kind == "directory":
121
                # Git indexes don't contain directories
122
                continue
123
            if entry.kind == "file":
124
                blob = Blob()
0.200.385 by Jelmer Vernooij
Cope with removed files.
125
                try:
126
                    file, stat_val = self.get_file_with_stat(entry.file_id, path)
127
                except (errors.NoSuchFile, IOError):
128
                    # TODO: Rather than come up with something here, use the old index
129
                    file = StringIO()
0.239.4 by Jelmer Vernooij
Cope with nonexistent files and directories in get_file_sha1.
130
                    from posix import stat_result
131
                    stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
0.200.502 by Jelmer Vernooij
Fill in sha1s in inventory.
132
                blob.set_raw_string(file.read())
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
133
            elif entry.kind == "symlink":
134
                blob = Blob()
0.200.502 by Jelmer Vernooij
Fill in sha1s in inventory.
135
                try:
136
                    stat_val = os.lstat(self.abspath(path))
137
                except (errors.NoSuchFile, OSError):
138
                    # TODO: Rather than come up with something here, use the 
139
                    # old index
0.239.4 by Jelmer Vernooij
Cope with nonexistent files and directories in get_file_sha1.
140
                    from posix import stat_result
141
                    stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
0.200.1124 by Jelmer Vernooij
Cope inventory entries in working trees not having a symlink target.
142
                blob.set_raw_string(self.get_symlink_target(entry.file_id).encode("utf-8"))
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
143
            else:
144
                raise AssertionError("unknown kind '%s'" % entry.kind)
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
145
            # Add object to the repository if it didn't exist yet
146
            if not blob.id in self.repository._git.object_store:
147
                self.repository._git.object_store.add_object(blob)
148
            # Add an entry to the index or update the existing entry
0.200.522 by Jelmer Vernooij
Simplify index handling a bit more.
149
            flags = 0 # FIXME
150
            self.index[path.encode("utf-8")] = (stat_val.st_ctime, stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino, stat_val.st_mode, stat_val.st_uid, stat_val.st_gid, stat_val.st_size, blob.id, flags)
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
151
0.200.382 by Jelmer Vernooij
Support flushing index.
152
    def flush(self):
153
        # TODO: Maybe this should only write on dirty ?
154
        if self._control_files._lock_mode != 'w':
155
            raise errors.NotWriteLocked(self)
0.200.983 by Jelmer Vernooij
Use support opening index of first revision.
156
        self._rewrite_index()
0.200.385 by Jelmer Vernooij
Cope with removed files.
157
        self.index.write()
0.200.382 by Jelmer Vernooij
Support flushing index.
158
        self._inventory_is_modified = False
159
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
160
    def get_ignore_list(self):
161
        ignoreset = getattr(self, '_ignoreset', None)
162
        if ignoreset is not None:
163
            return ignoreset
164
165
        ignore_globs = set()
166
        ignore_globs.update(ignores.get_runtime_ignores())
167
        ignore_globs.update(ignores.get_user_ignores())
168
        if self.has_filename(IGNORE_FILENAME):
169
            f = self.get_file_byname(IGNORE_FILENAME)
170
            try:
171
                ignore_globs.update(ignores.parse_ignore_file(f))
172
            finally:
173
                f.close()
174
        self._ignoreset = ignore_globs
175
        return ignore_globs
176
0.200.508 by Jelmer Vernooij
Skip inventory caching bits.
177
    def set_last_revision(self, revid):
178
        self._change_last_revision(revid)
179
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
180
    def _reset_data(self):
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
181
        self._inventory_is_modified = False
0.248.3 by Jelmer Vernooij
Handle working trees without valid HEAD branch.
182
        try:
183
            head = self.repository._git.head()
184
        except KeyError, name:
185
            raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
186
        basis_inv = self.repository.get_inventory(self.branch.lookup_foreign_revision_id(head))
0.252.33 by Jelmer Vernooij
Fix file id map lookups.
187
        store = self.repository._git.object_store
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
188
        if head == ZERO_SHA:
0.200.983 by Jelmer Vernooij
Use support opening index of first revision.
189
            fileid_map = GitFileIdMap({}, self.mapping)
190
            basis_inv = None
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
191
        else:
192
            fileid_map = self.mapping.get_fileid_map(store.__getitem__,
193
                store[head].tree)
0.200.983 by Jelmer Vernooij
Use support opening index of first revision.
194
        result = GitIndexInventory(basis_inv, fileid_map, self.index, store)
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
195
        self._set_inventory(result, dirty=False)
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
196
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
197
    @needs_read_lock
198
    def get_file_sha1(self, file_id, path=None, stat_value=None):
199
        if not path:
200
            path = self._inventory.id2path(file_id)
0.239.4 by Jelmer Vernooij
Cope with nonexistent files and directories in get_file_sha1.
201
        try:
202
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
203
        except OSError, (num, msg):
204
            if num in (errno.EISDIR, errno.ENOENT):
205
                return None
206
            raise
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
207
0.200.610 by Jelmer Vernooij
Support retrieving basis tree properly.
208
    def revision_tree(self, revid):
209
        return self.repository.revision_tree(revid)
210
0.200.619 by Jelmer Vernooij
Provide dummy WorkingTree.conflicts() implementation rather than spending a lot of time not finding any conflicts.
211
    @needs_read_lock
212
    def conflicts(self):
213
        # FIXME:
214
        return []
215
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
216
217
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
218
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
219
    @property
220
    def _matchingbzrdir(self):
0.200.1140 by Jelmer Vernooij
Update now that the control dir formats are no longer in __init__.
221
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
0.200.1013 by Jelmer Vernooij
More renames.
222
        return LocalGitControlDirFormat()
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
223
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
224
    def get_format_description(self):
225
        return "Git Working Tree"
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
226
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
227
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
228
                   accelerator_tree=None, hardlink=False):
229
        """See WorkingTreeFormat.initialize()."""
230
        if not isinstance(a_bzrdir, LocalGitDir):
231
            raise errors.IncompatibleFormat(self, a_bzrdir)
232
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
233
        index.write()
234
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
235
            a_bzrdir.open_branch(), index)
236
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
237
238
class InterIndexGitTree(tree.InterTree):
239
    """InterTree that works between a Git revision tree and an index."""
240
241
    def __init__(self, source, target):
242
        super(InterIndexGitTree, self).__init__(source, target)
243
        self._index = target.index
244
245
    @classmethod
246
    def is_compatible(cls, source, target):
247
        from bzrlib.plugins.git.repository import GitRevisionTree
248
        return (isinstance(source, GitRevisionTree) and 
249
                isinstance(target, GitWorkingTree))
250
251
    def compare(self, want_unchanged=False, specific_files=None,
252
                extra_trees=None, require_versioned=False, include_root=False,
253
                want_unversioned=False):
254
        changes = self._index.changes_from_tree(
255
            self.source._repository._git.object_store, self.source.tree, 
256
            want_unchanged=want_unchanged)
0.200.920 by Jelmer Vernooij
Fix some more tests.
257
        source_fileid_map = self.source.mapping.get_fileid_map(
0.252.43 by Jelmer Vernooij
Some refactoring, support proper file ids in revision deltas.
258
            self.source._repository._git.object_store.__getitem__,
259
            self.source.tree)
0.200.922 by Jelmer Vernooij
Fix remaining test.
260
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
261
            file_id = self.target.path2id(
262
                self.target.mapping.BZR_FILE_IDS_FILE)
263
            if file_id is None:
0.200.922 by Jelmer Vernooij
Fix remaining test.
264
                target_fileid_map = {}
265
            else:
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
266
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
0.200.922 by Jelmer Vernooij
Fix remaining test.
267
        else:
268
            target_fileid_map = {}
0.200.971 by Chadrik
Fix 'bzr status' after 'bzr add' in native git working trees.
269
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
270
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
0.252.43 by Jelmer Vernooij
Some refactoring, support proper file ids in revision deltas.
271
            (source_fileid_map, target_fileid_map),
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
272
            specific_file=specific_files, require_versioned=require_versioned)
273
        if want_unversioned:
274
            for e in self.target.extras():
275
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
276
        return ret
277
0.200.622 by Jelmer Vernooij
Implement InterTree.iter_changes() as well.
278
    def iter_changes(self, include_unchanged=False, specific_files=None,
279
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
280
        changes = self._index.changes_from_tree(
281
            self.source._repository._git.object_store, self.source.tree, 
282
            want_unchanged=include_unchanged)
283
        # FIXME: Handle want_unversioned
284
        return changes_from_git_changes(changes, self.target.mapping, 
285
            specific_file=specific_files)
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
286
287
tree.InterTree.register_optimiser(InterIndexGitTree)