/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to workingtree.py

Implement CommitBuilder.revision_tree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2011 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
 
 
17
 
 
18
"""An adapter between a Git index and a Bazaar Working Tree"""
 
19
 
 
20
 
 
21
from cStringIO import (
 
22
    StringIO,
 
23
    )
 
24
import errno
 
25
from dulwich.index import (
 
26
    Index,
 
27
    )
 
28
from dulwich.objects import (
 
29
    Blob,
 
30
    ZERO_SHA,
 
31
    )
 
32
import os
 
33
import posixpath
 
34
import stat
 
35
 
 
36
from bzrlib import (
 
37
    errors,
 
38
    conflicts as _mod_conflicts,
 
39
    ignores,
 
40
    inventory,
 
41
    lockable_files,
 
42
    lockdir,
 
43
    osutils,
 
44
    transport,
 
45
    tree,
 
46
    workingtree,
 
47
    )
 
48
from bzrlib.decorators import (
 
49
    needs_read_lock,
 
50
    )
 
51
 
 
52
 
 
53
from bzrlib.plugins.git.dir import (
 
54
    LocalGitDir,
 
55
    )
 
56
from bzrlib.plugins.git.tree import (
 
57
    changes_from_git_changes,
 
58
    tree_delta_from_git_changes,
 
59
    )
 
60
from bzrlib.plugins.git.mapping import (
 
61
    GitFileIdMap,
 
62
    mode_kind,
 
63
    )
 
64
 
 
65
IGNORE_FILENAME = ".gitignore"
 
66
 
 
67
 
 
68
class GitWorkingTree(workingtree.WorkingTree):
 
69
    """A Git working tree."""
 
70
 
 
71
    def __init__(self, bzrdir, repo, branch, index):
 
72
        self.basedir = bzrdir.root_transport.local_abspath('.')
 
73
        self.bzrdir = bzrdir
 
74
        self.repository = repo
 
75
        self.mapping = self.repository.get_mapping()
 
76
        self._branch = branch
 
77
        self._transport = bzrdir.transport
 
78
 
 
79
        self.controldir = self.bzrdir.transport.local_abspath('bzr')
 
80
 
 
81
        try:
 
82
            os.makedirs(self.controldir)
 
83
            os.makedirs(os.path.join(self.controldir, 'lock'))
 
84
        except OSError:
 
85
            pass
 
86
 
 
87
        self._control_files = lockable_files.LockableFiles(
 
88
            transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
 
89
        self._format = GitWorkingTreeFormat()
 
90
        self.index = index
 
91
        self.views = self._make_views()
 
92
        self._rules_searcher = None
 
93
        self._detect_case_handling()
 
94
 
 
95
    def _index_add_entry(self, path, file_id, kind):
 
96
        if kind == "directory":
 
97
            # Git indexes don't contain directories
 
98
            return
 
99
        if kind == "file":
 
100
            blob = Blob()
 
101
            try:
 
102
                file, stat_val = self.get_file_with_stat(file_id, path)
 
103
            except (errors.NoSuchFile, IOError):
 
104
                # TODO: Rather than come up with something here, use the old index
 
105
                file = StringIO()
 
106
                from posix import stat_result
 
107
                stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
108
            blob.set_raw_string(file.read())
 
109
        elif kind == "symlink":
 
110
            blob = Blob()
 
111
            try:
 
112
                stat_val = os.lstat(self.abspath(path))
 
113
            except (errors.NoSuchFile, OSError):
 
114
                # TODO: Rather than come up with something here, use the 
 
115
                # old index
 
116
                from posix import stat_result
 
117
                stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
118
            blob.set_raw_string(self.get_symlink_target(file_id).encode("utf-8"))
 
119
        else:
 
120
            raise AssertionError("unknown kind '%s'" % kind)
 
121
        # Add object to the repository if it didn't exist yet
 
122
        if not blob.id in self.repository._git.object_store:
 
123
            self.repository._git.object_store.add_object(blob)
 
124
        # Add an entry to the index or update the existing entry
 
125
        flags = 0 # FIXME
 
126
        self.index[path.encode("utf-8")] = (stat_val.st_ctime,
 
127
                stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
 
128
                stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
 
129
                stat_val.st_size, blob.id, flags)
 
130
 
 
131
    def _add(self, files, ids, kinds):
 
132
        for (path, file_id, kind) in zip(files, ids, kinds):
 
133
            self._index_add_entry(path, file_id, kind)
 
134
 
 
135
    def get_root_id(self):
 
136
        return self.mapping.generate_file_id("")
 
137
 
 
138
    def extras(self):
 
139
        """Yield all unversioned files in this WorkingTree.
 
140
        """
 
141
        for (dirpath, dirnames, filenames) in os.walk(self.basedir):
 
142
            if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
 
143
                continue
 
144
            for filename in filenames:
 
145
                relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
 
146
                if not relpath in self.index:
 
147
                    yield relpath
 
148
 
 
149
    def unlock(self):
 
150
        # non-implementation specific cleanup
 
151
        self._cleanup()
 
152
 
 
153
        # reverse order of locking.
 
154
        try:
 
155
            return self._control_files.unlock()
 
156
        finally:
 
157
            self.branch.unlock()
 
158
 
 
159
    def _rewrite_index(self):
 
160
        self.index.clear()
 
161
        for path, entry in self._inventory.iter_entries():
 
162
            self._index_add_entry(path, entry.file_id, entry.kind)
 
163
 
 
164
    def flush(self):
 
165
        # TODO: Maybe this should only write on dirty ?
 
166
        if self._control_files._lock_mode != 'w':
 
167
            raise errors.NotWriteLocked(self)
 
168
        self._rewrite_index()
 
169
        self.index.write()
 
170
 
 
171
    def __iter__(self):
 
172
        for path in self.index:
 
173
            yield self._fileid_map.lookup_file_id(path)
 
174
 
 
175
    def id2path(self, file_id):
 
176
        if type(file_id) != str:
 
177
            raise AssertionError
 
178
        path = self._fileid_map.lookup_path(file_id)
 
179
        if path in self.index:
 
180
            return path
 
181
        raise errors.NoSuchId(None, file_id)
 
182
 
 
183
    def get_ignore_list(self):
 
184
        ignoreset = getattr(self, '_ignoreset', None)
 
185
        if ignoreset is not None:
 
186
            return ignoreset
 
187
 
 
188
        ignore_globs = set()
 
189
        ignore_globs.update(ignores.get_runtime_ignores())
 
190
        ignore_globs.update(ignores.get_user_ignores())
 
191
        if self.has_filename(IGNORE_FILENAME):
 
192
            f = self.get_file_byname(IGNORE_FILENAME)
 
193
            try:
 
194
                ignore_globs.update(ignores.parse_ignore_file(f))
 
195
            finally:
 
196
                f.close()
 
197
        self._ignoreset = ignore_globs
 
198
        return ignore_globs
 
199
 
 
200
    def set_last_revision(self, revid):
 
201
        self._change_last_revision(revid)
 
202
 
 
203
    def _reset_data(self):
 
204
        try:
 
205
            head = self.repository._git.head()
 
206
        except KeyError, name:
 
207
            raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
 
208
        store = self.repository._git.object_store
 
209
        if head == ZERO_SHA:
 
210
            self._fileid_map = GitFileIdMap({}, self.mapping)
 
211
        else:
 
212
            self._fileid_map = self.mapping.get_fileid_map(store.__getitem__,
 
213
                store[head].tree)
 
214
 
 
215
    @needs_read_lock
 
216
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
217
        if not path:
 
218
            path = self.id2path(file_id)
 
219
        try:
 
220
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
 
221
        except OSError, (num, msg):
 
222
            if num in (errno.EISDIR, errno.ENOENT):
 
223
                return None
 
224
            raise
 
225
 
 
226
    def revision_tree(self, revid):
 
227
        return self.repository.revision_tree(revid)
 
228
 
 
229
    def _get_dir_ie(self, path, parent_id):
 
230
        file_id = self._fileid_map.lookup_file_id(path)
 
231
        return inventory.InventoryDirectory(file_id,
 
232
            posixpath.basename(path).strip("/"), parent_id)
 
233
 
 
234
    def _add_missing_parent_ids(self, path, dir_ids):
 
235
        if path in dir_ids:
 
236
            return []
 
237
        parent = posixpath.dirname(path).strip("/")
 
238
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
239
        parent_id = dir_ids[parent]
 
240
        ie = self._get_dir_ie(path, parent_id)
 
241
        dir_ids[path] = ie.file_id
 
242
        ret.append((path, ie))
 
243
        return ret
 
244
 
 
245
    def _get_file_ie(self, path, value, parent_id):
 
246
        assert isinstance(path, str)
 
247
        assert isinstance(value, tuple) and len(value) == 10
 
248
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
249
        file_id = self._fileid_map.lookup_file_id(path)
 
250
        if type(file_id) != str:
 
251
            raise AssertionError
 
252
        kind = mode_kind(mode)
 
253
        ie = inventory.entry_factory[kind](file_id,
 
254
            posixpath.basename(path.decode("utf-8")), parent_id)
 
255
        if kind == 'symlink':
 
256
            ie.symlink_target = self.get_symlink_target(file_id)
 
257
        else:
 
258
            data = self.get_file_text(file_id, path)
 
259
            ie.text_sha1 = osutils.sha_string(data)
 
260
            ie.text_size = len(data)
 
261
            ie.executable = self.is_executable(file_id, path)
 
262
        ie.revision = None
 
263
        return ie
 
264
 
 
265
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
266
        mode = stat_result.st_mode
 
267
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
268
 
 
269
    if not osutils.supports_executable():
 
270
        def is_executable(self, file_id, path=None):
 
271
            basis_tree = self.basis_tree()
 
272
            if file_id in basis_tree:
 
273
                return basis_tree.is_executable(file_id)
 
274
            # Default to not executable
 
275
            return False
 
276
    else:
 
277
        def is_executable(self, file_id, path=None):
 
278
            if not path:
 
279
                path = self.id2path(file_id)
 
280
            mode = os.lstat(self.abspath(path)).st_mode
 
281
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
282
 
 
283
        _is_executable_from_path_and_stat = \
 
284
            _is_executable_from_path_and_stat_from_stat
 
285
 
 
286
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
287
        # FIXME: Yield non-versioned files
 
288
        # FIXME: support from_dir
 
289
        # FIXME: Support recursive
 
290
        dir_ids = {}
 
291
        root_ie = self._get_dir_ie("", None)
 
292
        if include_root and not from_dir:
 
293
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
294
        dir_ids[""] = root_ie.file_id
 
295
        for path, value in self.index.iteritems():
 
296
            parent = posixpath.dirname(path).strip("/")
 
297
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
298
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
299
            ie = self._get_file_ie(path, value, dir_ids[parent])
 
300
            yield path, "V", ie.kind, ie.file_id, ie
 
301
 
 
302
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
303
        # FIXME: Support specific_file_ids
 
304
        # FIXME: Is return order correct?
 
305
        if specific_file_ids is not None:
 
306
            raise NotImplementedError(self.iter_entries_by_dir)
 
307
        root_ie = self._get_dir_ie("", None)
 
308
        yield "", root_ie
 
309
        dir_ids = {"": root_ie.file_id}
 
310
        for path, value in self.index.iteritems():
 
311
            parent = posixpath.dirname(path).strip("/")
 
312
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent, dir_ids):
 
313
                yield dir_path, dir_ie
 
314
            parent_id = self.fileid_map.lookup_file_id(parent)
 
315
            yield path, self._get_file_ie(path, value, parent_id)
 
316
 
 
317
    @needs_read_lock
 
318
    def conflicts(self):
 
319
        # FIXME:
 
320
        return _mod_conflicts.ConflictList()
 
321
 
 
322
 
 
323
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
 
324
 
 
325
    @property
 
326
    def _matchingbzrdir(self):
 
327
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
328
        return LocalGitControlDirFormat()
 
329
 
 
330
    def get_format_description(self):
 
331
        return "Git Working Tree"
 
332
 
 
333
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
334
                   accelerator_tree=None, hardlink=False):
 
335
        """See WorkingTreeFormat.initialize()."""
 
336
        if not isinstance(a_bzrdir, LocalGitDir):
 
337
            raise errors.IncompatibleFormat(self, a_bzrdir)
 
338
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
 
339
        index.write()
 
340
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
 
341
            a_bzrdir.open_branch(), index)
 
342
 
 
343
 
 
344
class InterIndexGitTree(tree.InterTree):
 
345
    """InterTree that works between a Git revision tree and an index."""
 
346
 
 
347
    def __init__(self, source, target):
 
348
        super(InterIndexGitTree, self).__init__(source, target)
 
349
        self._index = target.index
 
350
 
 
351
    @classmethod
 
352
    def is_compatible(cls, source, target):
 
353
        from bzrlib.plugins.git.repository import GitRevisionTree
 
354
        return (isinstance(source, GitRevisionTree) and 
 
355
                isinstance(target, GitWorkingTree))
 
356
 
 
357
    def compare(self, want_unchanged=False, specific_files=None,
 
358
                extra_trees=None, require_versioned=False, include_root=False,
 
359
                want_unversioned=False):
 
360
        changes = self._index.changes_from_tree(
 
361
            self.source._repository._git.object_store, self.source.tree, 
 
362
            want_unchanged=want_unchanged)
 
363
        source_fileid_map = self.source.mapping.get_fileid_map(
 
364
            self.source._repository._git.object_store.__getitem__,
 
365
            self.source.tree)
 
366
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
 
367
            file_id = self.target.path2id(
 
368
                self.target.mapping.BZR_FILE_IDS_FILE)
 
369
            if file_id is None:
 
370
                target_fileid_map = {}
 
371
            else:
 
372
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
 
373
        else:
 
374
            target_fileid_map = {}
 
375
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
 
376
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
 
377
            (source_fileid_map, target_fileid_map),
 
378
            specific_file=specific_files, require_versioned=require_versioned)
 
379
        if want_unversioned:
 
380
            for e in self.target.extras():
 
381
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
382
        return ret
 
383
 
 
384
    def iter_changes(self, include_unchanged=False, specific_files=None,
 
385
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
 
386
        changes = self._index.changes_from_tree(
 
387
            self.source._repository._git.object_store, self.source.tree,
 
388
            want_unchanged=include_unchanged)
 
389
        # FIXME: Handle want_unversioned
 
390
        return changes_from_git_changes(changes, self.target.mapping,
 
391
            specific_file=specific_files)
 
392
 
 
393
 
 
394
tree.InterTree.register_optimiser(InterIndexGitTree)