/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

UseĀ get_file_revision.

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 unversion(self, file_ids):
 
132
        for file_id in file_ids:
 
133
            path = self.id2path(file_id)
 
134
            del self.index[path.encode("utf-8")]
 
135
 
 
136
    def _add(self, files, ids, kinds):
 
137
        for (path, file_id, kind) in zip(files, ids, kinds):
 
138
            self._index_add_entry(path, file_id, kind)
 
139
 
 
140
    def move(self, from_paths, to_dir=None, after=False):
 
141
        rename_tuples = []
 
142
        to_abs = self.abspath(to_dir)
 
143
        if not os.path.isdir(to_abs):
 
144
            raise errors.BzrMoveFailedError('', to_dir,
 
145
                errors.NotADirectory(to_abs))
 
146
 
 
147
        for from_rel in from_paths:
 
148
            from_tail = os.path.split(from_rel)[-1]
 
149
            to_rel = os.path.join(to_dir, from_tail)
 
150
            self.rename_one(from_rel, to_rel, after=after)
 
151
            rename_tuples.append((from_rel, to_rel))
 
152
        return rename_tuples
 
153
 
 
154
    def rename_one(self, from_rel, to_rel, after=False):
 
155
        if not after:
 
156
            os.rename(self.abspath(from_rel), self.abspath(to_rel))
 
157
        self.index[to_rel] = self.index[from_rel]
 
158
        del self.index[from_rel]
 
159
 
 
160
    def get_root_id(self):
 
161
        return self.path2id("")
 
162
 
 
163
    @needs_read_lock
 
164
    def path2id(self, path):
 
165
        return self._fileid_map.lookup_file_id(path.encode("utf-8"))
 
166
 
 
167
    def extras(self):
 
168
        """Yield all unversioned files in this WorkingTree.
 
169
        """
 
170
        for (dirpath, dirnames, filenames) in os.walk(self.basedir):
 
171
            if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
 
172
                continue
 
173
            for filename in filenames:
 
174
                relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
 
175
                if not relpath in self.index:
 
176
                    yield relpath
 
177
 
 
178
    def unlock(self):
 
179
        # non-implementation specific cleanup
 
180
        self._cleanup()
 
181
 
 
182
        # reverse order of locking.
 
183
        try:
 
184
            return self._control_files.unlock()
 
185
        finally:
 
186
            self.branch.unlock()
 
187
 
 
188
    def flush(self):
 
189
        # TODO: Maybe this should only write on dirty ?
 
190
        if self._control_files._lock_mode != 'w':
 
191
            raise errors.NotWriteLocked(self)
 
192
        self.index.write()
 
193
 
 
194
    def __iter__(self):
 
195
        for path in self.index:
 
196
            yield self.path2id(path)
 
197
 
 
198
    def id2path(self, file_id):
 
199
        if type(file_id) != str:
 
200
            raise AssertionError
 
201
        path = self._fileid_map.lookup_path(file_id)
 
202
        if path in self.index:
 
203
            return path
 
204
        raise errors.NoSuchId(None, file_id)
 
205
 
 
206
    def get_ignore_list(self):
 
207
        ignoreset = getattr(self, '_ignoreset', None)
 
208
        if ignoreset is not None:
 
209
            return ignoreset
 
210
 
 
211
        ignore_globs = set()
 
212
        ignore_globs.update(ignores.get_runtime_ignores())
 
213
        ignore_globs.update(ignores.get_user_ignores())
 
214
        if self.has_filename(IGNORE_FILENAME):
 
215
            f = self.get_file_byname(IGNORE_FILENAME)
 
216
            try:
 
217
                ignore_globs.update(ignores.parse_ignore_file(f))
 
218
            finally:
 
219
                f.close()
 
220
        self._ignoreset = ignore_globs
 
221
        return ignore_globs
 
222
 
 
223
    def set_last_revision(self, revid):
 
224
        self._change_last_revision(revid)
 
225
 
 
226
    def _reset_data(self):
 
227
        try:
 
228
            head = self.repository._git.head()
 
229
        except KeyError, name:
 
230
            raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
 
231
        store = self.repository._git.object_store
 
232
        if head == ZERO_SHA:
 
233
            self._fileid_map = GitFileIdMap({}, self.mapping)
 
234
        else:
 
235
            self._fileid_map = self.mapping.get_fileid_map(store.__getitem__,
 
236
                store[head].tree)
 
237
 
 
238
    @needs_read_lock
 
239
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
240
        if not path:
 
241
            path = self.id2path(file_id)
 
242
        try:
 
243
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
 
244
        except OSError, (num, msg):
 
245
            if num in (errno.EISDIR, errno.ENOENT):
 
246
                return None
 
247
            raise
 
248
 
 
249
    def revision_tree(self, revid):
 
250
        return self.repository.revision_tree(revid)
 
251
 
 
252
    def _get_dir_ie(self, path, parent_id):
 
253
        file_id = self.path2id(path)
 
254
        return inventory.InventoryDirectory(file_id,
 
255
            posixpath.basename(path).strip("/"), parent_id)
 
256
 
 
257
    def _add_missing_parent_ids(self, path, dir_ids):
 
258
        if path in dir_ids:
 
259
            return []
 
260
        parent = posixpath.dirname(path).strip("/")
 
261
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
262
        parent_id = dir_ids[parent]
 
263
        ie = self._get_dir_ie(path, parent_id)
 
264
        dir_ids[path] = ie.file_id
 
265
        ret.append((path, ie))
 
266
        return ret
 
267
 
 
268
    def _get_file_ie(self, path, value, parent_id):
 
269
        assert isinstance(path, unicode)
 
270
        assert isinstance(value, tuple) and len(value) == 10
 
271
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
272
        file_id = self.path2id(path)
 
273
        if type(file_id) != str:
 
274
            raise AssertionError
 
275
        kind = mode_kind(mode)
 
276
        ie = inventory.entry_factory[kind](file_id,
 
277
            posixpath.basename(path), parent_id)
 
278
        if kind == 'symlink':
 
279
            ie.symlink_target = self.get_symlink_target(file_id)
 
280
        else:
 
281
            data = self.get_file_text(file_id, path)
 
282
            ie.text_sha1 = osutils.sha_string(data)
 
283
            ie.text_size = len(data)
 
284
            ie.executable = self.is_executable(file_id, path)
 
285
        ie.revision = None
 
286
        return ie
 
287
 
 
288
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
289
        mode = stat_result.st_mode
 
290
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
291
 
 
292
    if not osutils.supports_executable():
 
293
        def is_executable(self, file_id, path=None):
 
294
            basis_tree = self.basis_tree()
 
295
            if file_id in basis_tree:
 
296
                return basis_tree.is_executable(file_id)
 
297
            # Default to not executable
 
298
            return False
 
299
    else:
 
300
        def is_executable(self, file_id, path=None):
 
301
            if not path:
 
302
                path = self.id2path(file_id)
 
303
            mode = os.lstat(self.abspath(path)).st_mode
 
304
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
305
 
 
306
        _is_executable_from_path_and_stat = \
 
307
            _is_executable_from_path_and_stat_from_stat
 
308
 
 
309
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
310
        # FIXME: Yield non-versioned files
 
311
        # FIXME: support from_dir
 
312
        # FIXME: Support recursive
 
313
        dir_ids = {}
 
314
        root_ie = self._get_dir_ie(u"", None)
 
315
        if include_root and not from_dir:
 
316
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
317
        dir_ids[u""] = root_ie.file_id
 
318
        for path, value in self.index.iteritems():
 
319
            path = path.decode("utf-8")
 
320
            parent = posixpath.dirname(path).strip("/")
 
321
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
322
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
323
            ie = self._get_file_ie(path, value, dir_ids[parent])
 
324
            yield path, "V", ie.kind, ie.file_id, ie
 
325
 
 
326
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
327
        # FIXME: Support specific_file_ids
 
328
        # FIXME: Is return order correct?
 
329
        if specific_file_ids is not None:
 
330
            raise NotImplementedError(self.iter_entries_by_dir)
 
331
        root_ie = self._get_dir_ie(u"", None)
 
332
        yield u"", root_ie
 
333
        dir_ids = {u"": root_ie.file_id}
 
334
        for path, value in self.index.iteritems():
 
335
            path = path.decode("utf-8")
 
336
            parent = posixpath.dirname(path).strip("/")
 
337
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent, dir_ids):
 
338
                yield dir_path, dir_ie
 
339
            parent_id = self.path2id(parent)
 
340
            yield path, self._get_file_ie(path, value, parent_id)
 
341
 
 
342
    @needs_read_lock
 
343
    def conflicts(self):
 
344
        # FIXME:
 
345
        return _mod_conflicts.ConflictList()
 
346
 
 
347
    def update_basis_by_delta(self, new_revid, delta):
 
348
        # FIXME
 
349
        raise NotImplementedError(self.update_basis_by_delta)
 
350
 
 
351
 
 
352
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
 
353
 
 
354
    @property
 
355
    def _matchingbzrdir(self):
 
356
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
357
        return LocalGitControlDirFormat()
 
358
 
 
359
    def get_format_description(self):
 
360
        return "Git Working Tree"
 
361
 
 
362
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
363
                   accelerator_tree=None, hardlink=False):
 
364
        """See WorkingTreeFormat.initialize()."""
 
365
        if not isinstance(a_bzrdir, LocalGitDir):
 
366
            raise errors.IncompatibleFormat(self, a_bzrdir)
 
367
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
 
368
        index.write()
 
369
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
 
370
            a_bzrdir.open_branch(), index)
 
371
 
 
372
 
 
373
class InterIndexGitTree(tree.InterTree):
 
374
    """InterTree that works between a Git revision tree and an index."""
 
375
 
 
376
    def __init__(self, source, target):
 
377
        super(InterIndexGitTree, self).__init__(source, target)
 
378
        self._index = target.index
 
379
 
 
380
    @classmethod
 
381
    def is_compatible(cls, source, target):
 
382
        from bzrlib.plugins.git.repository import GitRevisionTree
 
383
        return (isinstance(source, GitRevisionTree) and 
 
384
                isinstance(target, GitWorkingTree))
 
385
 
 
386
    def compare(self, want_unchanged=False, specific_files=None,
 
387
                extra_trees=None, require_versioned=False, include_root=False,
 
388
                want_unversioned=False):
 
389
        changes = self._index.changes_from_tree(
 
390
            self.source._repository._git.object_store, self.source.tree, 
 
391
            want_unchanged=want_unchanged)
 
392
        source_fileid_map = self.source.mapping.get_fileid_map(
 
393
            self.source._repository._git.object_store.__getitem__,
 
394
            self.source.tree)
 
395
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
 
396
            file_id = self.target.path2id(
 
397
                self.target.mapping.BZR_FILE_IDS_FILE)
 
398
            if file_id is None:
 
399
                target_fileid_map = {}
 
400
            else:
 
401
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
 
402
        else:
 
403
            target_fileid_map = {}
 
404
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
 
405
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
 
406
            (source_fileid_map, target_fileid_map),
 
407
            specific_file=specific_files, require_versioned=require_versioned)
 
408
        if want_unversioned:
 
409
            for e in self.target.extras():
 
410
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
411
        return ret
 
412
 
 
413
    def iter_changes(self, include_unchanged=False, specific_files=None,
 
414
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
 
415
        changes = self._index.changes_from_tree(
 
416
            self.source._repository._git.object_store, self.source.tree,
 
417
            want_unchanged=include_unchanged)
 
418
        # FIXME: Handle want_unversioned
 
419
        return changes_from_git_changes(changes, self.target.mapping,
 
420
            specific_file=specific_files)
 
421
 
 
422
 
 
423
tree.InterTree.register_optimiser(InterIndexGitTree)