/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

Support read locking object stores.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
from cStringIO import (
22
22
    StringIO,
23
23
    )
 
24
from collections import defaultdict
24
25
import errno
 
26
from dulwich.index import (
 
27
    Index,
 
28
    )
 
29
from dulwich.object_store import (
 
30
    tree_lookup_path,
 
31
    )
25
32
from dulwich.objects import (
26
33
    Blob,
27
 
    )
28
 
from dulwich.protocol import (
29
34
    ZERO_SHA,
30
35
    )
31
36
import os
 
37
import posix
 
38
import posixpath
32
39
import stat
33
40
 
34
41
from bzrlib import (
35
42
    errors,
 
43
    conflicts as _mod_conflicts,
36
44
    ignores,
 
45
    inventory,
37
46
    lockable_files,
38
47
    lockdir,
39
48
    osutils,
46
55
    )
47
56
 
48
57
 
49
 
from bzrlib.plugins.git.inventory import (
50
 
    GitIndexInventory,
 
58
from bzrlib.plugins.git.dir import (
 
59
    LocalGitDir,
51
60
    )
52
61
from bzrlib.plugins.git.tree import (
53
62
    changes_from_git_changes,
55
64
    )
56
65
from bzrlib.plugins.git.mapping import (
57
66
    GitFileIdMap,
 
67
    mode_kind,
58
68
    )
59
69
 
60
70
IGNORE_FILENAME = ".gitignore"
67
77
        self.basedir = bzrdir.root_transport.local_abspath('.')
68
78
        self.bzrdir = bzrdir
69
79
        self.repository = repo
 
80
        self.store = self.repository._git.object_store
70
81
        self.mapping = self.repository.get_mapping()
71
82
        self._branch = branch
72
83
        self._transport = bzrdir.transport
84
95
        self._format = GitWorkingTreeFormat()
85
96
        self.index = index
86
97
        self.views = self._make_views()
 
98
        self._rules_searcher = None
87
99
        self._detect_case_handling()
 
100
        self._reset_data()
 
101
        self._fileid_map = self._basis_fileid_map.copy()
 
102
 
 
103
    def _index_add_entry(self, path, file_id, kind):
 
104
        assert isinstance(path, basestring)
 
105
        assert type(file_id) == str
 
106
        if kind == "directory":
 
107
            # Git indexes don't contain directories
 
108
            return
 
109
        if kind == "file":
 
110
            blob = Blob()
 
111
            try:
 
112
                file, stat_val = self.get_file_with_stat(file_id, path)
 
113
            except (errors.NoSuchFile, IOError):
 
114
                # TODO: Rather than come up with something here, use the old index
 
115
                file = StringIO()
 
116
                from posix import stat_result
 
117
                stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
118
            blob.set_raw_string(file.read())
 
119
        elif kind == "symlink":
 
120
            blob = Blob()
 
121
            try:
 
122
                stat_val = os.lstat(self.abspath(path))
 
123
            except (errors.NoSuchFile, OSError):
 
124
                # TODO: Rather than come up with something here, use the 
 
125
                # old index
 
126
                from posix import stat_result
 
127
                stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
128
            blob.set_raw_string(self.get_symlink_target(file_id).encode("utf-8"))
 
129
        else:
 
130
            raise AssertionError("unknown kind '%s'" % kind)
 
131
        # Add object to the repository if it didn't exist yet
 
132
        if not blob.id in self.store:
 
133
            self.store.add_object(blob)
 
134
        # Add an entry to the index or update the existing entry
 
135
        flags = 0 # FIXME
 
136
        self.index[path.encode("utf-8")] = (stat_val.st_ctime,
 
137
                stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
 
138
                stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
 
139
                stat_val.st_size, blob.id, flags)
 
140
 
 
141
    def unversion(self, file_ids):
 
142
        for file_id in file_ids:
 
143
            path = self.id2path(file_id)
 
144
            del self.index[path.encode("utf-8")]
 
145
 
 
146
    def _add(self, files, ids, kinds):
 
147
        for (path, file_id, kind) in zip(files, ids, kinds):
 
148
            if file_id is not None:
 
149
                self._fileid_map.set_file_id(path.encode("utf-8"), file_id)
 
150
            else:
 
151
                file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
 
152
            self._index_add_entry(path, file_id, kind)
 
153
 
 
154
    def _set_root_id(self, file_id):
 
155
        self._fileid_map.set_file_id("", file_id)
 
156
 
 
157
    def move(self, from_paths, to_dir=None, after=False):
 
158
        rename_tuples = []
 
159
        to_abs = self.abspath(to_dir)
 
160
        if not os.path.isdir(to_abs):
 
161
            raise errors.BzrMoveFailedError('', to_dir,
 
162
                errors.NotADirectory(to_abs))
 
163
 
 
164
        for from_rel in from_paths:
 
165
            from_tail = os.path.split(from_rel)[-1]
 
166
            to_rel = os.path.join(to_dir, from_tail)
 
167
            self.rename_one(from_rel, to_rel, after=after)
 
168
            rename_tuples.append((from_rel, to_rel))
 
169
        return rename_tuples
 
170
 
 
171
    def rename_one(self, from_rel, to_rel, after=False):
 
172
        if not after:
 
173
            os.rename(self.abspath(from_rel), self.abspath(to_rel))
 
174
        from_path = from_rel.encode("utf-8")
 
175
        to_path = to_rel.encode("utf-8")
 
176
        if not self.has_filename(to_rel):
 
177
            raise errors.BzrMoveFailedError(from_rel, to_rel,
 
178
                errors.NoSuchFile(to_rel))
 
179
        if not from_path in self.index:
 
180
            raise errors.BzrMoveFailedError(from_rel, to_rel,
 
181
                errors.NotVersionedError(path=from_rel))
 
182
        self.index[to_path] = self.index[from_path]
 
183
        del self.index[from_path]
 
184
 
 
185
    def get_root_id(self):
 
186
        return self.path2id("")
 
187
 
 
188
    @needs_read_lock
 
189
    def path2id(self, path):
 
190
        return self._fileid_map.lookup_file_id(path.encode("utf-8"))
88
191
 
89
192
    def extras(self):
90
193
        """Yield all unversioned files in this WorkingTree.
97
200
                if not relpath in self.index:
98
201
                    yield relpath
99
202
 
100
 
 
101
203
    def unlock(self):
102
204
        # non-implementation specific cleanup
103
205
        self._cleanup()
108
210
        finally:
109
211
            self.branch.unlock()
110
212
 
111
 
    def is_control_filename(self, path):
112
 
        return os.path.basename(path) == ".git"
113
 
 
114
 
    def _rewrite_index(self):
115
 
        self.index.clear()
116
 
        for path, entry in self._inventory.iter_entries():
117
 
            if entry.kind == "directory":
118
 
                # Git indexes don't contain directories
119
 
                continue
120
 
            if entry.kind == "file":
121
 
                blob = Blob()
122
 
                try:
123
 
                    file, stat_val = self.get_file_with_stat(entry.file_id, path)
124
 
                except (errors.NoSuchFile, IOError):
125
 
                    # TODO: Rather than come up with something here, use the old index
126
 
                    file = StringIO()
127
 
                    from posix import stat_result
128
 
                    stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
129
 
                blob.set_raw_string(file.read())
130
 
            elif entry.kind == "symlink":
131
 
                blob = Blob()
132
 
                try:
133
 
                    stat_val = os.lstat(self.abspath(path))
134
 
                except (errors.NoSuchFile, OSError):
135
 
                    # TODO: Rather than come up with something here, use the 
136
 
                    # old index
137
 
                    from posix import stat_result
138
 
                    stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
139
 
                blob.set_raw_string(entry.symlink_target)
140
 
            else:
141
 
                raise AssertionError("unknown kind '%s'" % entry.kind)
142
 
            # Add object to the repository if it didn't exist yet
143
 
            if not blob.id in self.repository._git.object_store:
144
 
                self.repository._git.object_store.add_object(blob)
145
 
            # Add an entry to the index or update the existing entry
146
 
            flags = 0 # FIXME
147
 
            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)
148
 
 
149
213
    def flush(self):
150
214
        # TODO: Maybe this should only write on dirty ?
151
215
        if self._control_files._lock_mode != 'w':
152
216
            raise errors.NotWriteLocked(self)
153
 
        self._rewrite_index()
154
217
        self.index.write()
155
 
        self._inventory_is_modified = False
 
218
 
 
219
    def __iter__(self):
 
220
        for path in self.index:
 
221
            yield self.path2id(path)
 
222
 
 
223
    def has_or_had_id(self, file_id):
 
224
        if self.has_id(file_id):
 
225
            return True
 
226
        if self.had_id(file_id):
 
227
            return True
 
228
        return False
 
229
 
 
230
    def had_id(self, file_id):
 
231
        path = self._basis_fileid_map.lookup_file_id(file_id)
 
232
        try:
 
233
            head = self.repository._git.head()
 
234
        except KeyError:
 
235
            # Assume no if basis is not accessible
 
236
            return False
 
237
        if head == ZERO_SHA:
 
238
            return False
 
239
        root_tree = self.store[head].tree
 
240
        try:
 
241
            tree_lookup_path(self.store.__getitem__, root_tree, path)
 
242
        except KeyError:
 
243
            return False
 
244
        else:
 
245
            return True
 
246
 
 
247
    def has_id(self, file_id):
 
248
        try:
 
249
            self.id2path(file_id)
 
250
        except errors.NoSuchId:
 
251
            return False
 
252
        else:
 
253
            return True
 
254
 
 
255
    def id2path(self, file_id):
 
256
        if type(file_id) != str:
 
257
            raise AssertionError
 
258
        path = self._fileid_map.lookup_path(file_id)
 
259
        if path in self.index:
 
260
            return path
 
261
        raise errors.NoSuchId(None, file_id)
 
262
 
 
263
    def get_file_mtime(self, file_id, path=None):
 
264
        """See Tree.get_file_mtime."""
 
265
        if not path:
 
266
            path = self.id2path(file_id)
 
267
        return os.lstat(self.abspath(path)).st_mtime
156
268
 
157
269
    def get_ignore_list(self):
158
270
        ignoreset = getattr(self, '_ignoreset', None)
165
277
        if self.has_filename(IGNORE_FILENAME):
166
278
            f = self.get_file_byname(IGNORE_FILENAME)
167
279
            try:
 
280
                # FIXME: Parse git file format, rather than assuming it's
 
281
                # the same as for bzr's native formats.
168
282
                ignore_globs.update(ignores.parse_ignore_file(f))
169
283
            finally:
170
284
                f.close()
175
289
        self._change_last_revision(revid)
176
290
 
177
291
    def _reset_data(self):
178
 
        self._inventory_is_modified = False
179
292
        try:
180
293
            head = self.repository._git.head()
181
294
        except KeyError, name:
182
295
            raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
183
 
        basis_inv = self.repository.get_inventory(self.branch.lookup_foreign_revision_id(head))
184
 
        store = self.repository._git.object_store
185
296
        if head == ZERO_SHA:
186
 
            fileid_map = GitFileIdMap({}, self.mapping)
187
 
            basis_inv = None
 
297
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
188
298
        else:
189
 
            fileid_map = self.mapping.get_fileid_map(store.__getitem__,
190
 
                store[head].tree)
191
 
        result = GitIndexInventory(basis_inv, fileid_map, self.index, store)
192
 
        self._set_inventory(result, dirty=False)
 
299
            self._basis_fileid_map = self.mapping.get_fileid_map(self.store.__getitem__,
 
300
                self.store[head].tree)
193
301
 
194
302
    @needs_read_lock
195
303
    def get_file_sha1(self, file_id, path=None, stat_value=None):
196
304
        if not path:
197
 
            path = self._inventory.id2path(file_id)
 
305
            path = self.id2path(file_id)
198
306
        try:
199
307
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
200
308
        except OSError, (num, msg):
205
313
    def revision_tree(self, revid):
206
314
        return self.repository.revision_tree(revid)
207
315
 
 
316
    def _get_dir_ie(self, path, parent_id):
 
317
        file_id = self.path2id(path)
 
318
        return inventory.InventoryDirectory(file_id,
 
319
            posixpath.basename(path).strip("/"), parent_id)
 
320
 
 
321
    def _add_missing_parent_ids(self, path, dir_ids):
 
322
        if path in dir_ids:
 
323
            return []
 
324
        parent = posixpath.dirname(path).strip("/")
 
325
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
326
        parent_id = dir_ids[parent]
 
327
        ie = self._get_dir_ie(path, parent_id)
 
328
        dir_ids[path] = ie.file_id
 
329
        ret.append((path, ie))
 
330
        return ret
 
331
 
 
332
    def _get_file_ie(self, path, value, parent_id):
 
333
        assert isinstance(path, unicode)
 
334
        assert isinstance(value, tuple) and len(value) == 10
 
335
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
336
        file_id = self.path2id(path)
 
337
        if type(file_id) != str:
 
338
            raise AssertionError
 
339
        kind = mode_kind(mode)
 
340
        ie = inventory.entry_factory[kind](file_id,
 
341
            posixpath.basename(path), parent_id)
 
342
        if kind == 'symlink':
 
343
            ie.symlink_target = self.get_symlink_target(file_id)
 
344
        else:
 
345
            data = self.get_file_text(file_id, path)
 
346
            ie.text_sha1 = osutils.sha_string(data)
 
347
            ie.text_size = len(data)
 
348
            ie.executable = self.is_executable(file_id, path)
 
349
        ie.revision = None
 
350
        return ie
 
351
 
 
352
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
353
        mode = stat_result.st_mode
 
354
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
355
 
 
356
    def stored_kind(self, file_id, path=None):
 
357
        if path is None:
 
358
            path = self.id2path(file_id)
 
359
        head = self.repository._git.head()
 
360
        if head == ZERO_SHA:
 
361
            raise errors.NoSuchId(self, file_id)
 
362
        root_tree = self.store[head].tree
 
363
        (mode, hexsha) = tree_lookup_path(self.store.__getitem__, root_tree, path)
 
364
        return mode_kind(mode)
 
365
 
 
366
    if not osutils.supports_executable():
 
367
        def is_executable(self, file_id, path=None):
 
368
            basis_tree = self.basis_tree()
 
369
            if file_id in basis_tree:
 
370
                return basis_tree.is_executable(file_id)
 
371
            # Default to not executable
 
372
            return False
 
373
    else:
 
374
        def is_executable(self, file_id, path=None):
 
375
            if not path:
 
376
                path = self.id2path(file_id)
 
377
            mode = os.lstat(self.abspath(path)).st_mode
 
378
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
379
 
 
380
        _is_executable_from_path_and_stat = \
 
381
            _is_executable_from_path_and_stat_from_stat
 
382
 
 
383
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
384
        # FIXME: Yield non-versioned files
 
385
        # FIXME: support from_dir
 
386
        # FIXME: Support recursive
 
387
        dir_ids = {}
 
388
        root_ie = self._get_dir_ie(u"", None)
 
389
        if include_root and not from_dir:
 
390
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
391
        dir_ids[u""] = root_ie.file_id
 
392
        for path, value in self.index.iteritems():
 
393
            path = path.decode("utf-8")
 
394
            parent = posixpath.dirname(path).strip("/")
 
395
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
396
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
397
            ie = self._get_file_ie(path, value, dir_ids[parent])
 
398
            yield path, "V", ie.kind, ie.file_id, ie
 
399
 
 
400
    def all_file_ids(self):
 
401
        ids = {u"": self.path2id("")}
 
402
        for path in self.index:
 
403
            path = path.decode("utf-8")
 
404
            parent = posixpath.dirname(path).strip("/")
 
405
            for e in self._add_missing_parent_ids(parent, ids):
 
406
                pass
 
407
            ids[path] = self.path2id(path)
 
408
        return set(ids.values())
 
409
 
 
410
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
411
        # FIXME: Support specific_file_ids
 
412
        # FIXME: Is return order correct?
 
413
        if specific_file_ids is not None:
 
414
            raise NotImplementedError(self.iter_entries_by_dir)
 
415
        root_ie = self._get_dir_ie(u"", None)
 
416
        yield u"", root_ie
 
417
        dir_ids = {u"": root_ie.file_id}
 
418
        for path, value in self.index.iteritems():
 
419
            path = path.decode("utf-8")
 
420
            parent = posixpath.dirname(path).strip("/")
 
421
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
 
422
                    dir_ids):
 
423
                yield dir_path, dir_ie
 
424
            parent_id = self.path2id(parent)
 
425
            yield path, self._get_file_ie(path, value, parent_id)
 
426
 
208
427
    @needs_read_lock
209
428
    def conflicts(self):
210
429
        # FIXME:
211
 
        return []
212
 
 
 
430
        return _mod_conflicts.ConflictList()
 
431
 
 
432
    def update_basis_by_delta(self, new_revid, delta):
 
433
        # The index just contains content, which won't have changed.
 
434
        self._reset_data()
 
435
 
 
436
    def _walkdirs(self, prefix=""):
 
437
        if prefix != "":
 
438
            prefix += "/"
 
439
        per_dir = defaultdict(list)
 
440
        for path, value in self.index.iteritems():
 
441
            if not path.startswith(prefix):
 
442
                continue
 
443
            (dirname, child_name) = posixpath.split(path)
 
444
            dirname = dirname.decode("utf-8")
 
445
            dir_file_id = self.path2id(dirname)
 
446
            assert isinstance(value, tuple) and len(value) == 10
 
447
            (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
448
            stat_result = posix.stat_result((mode, ino,
 
449
                    dev, 1, uid, gid, size,
 
450
                    0, mtime, ctime))
 
451
            per_dir[(dirname, dir_file_id)].append(
 
452
                (path.decode("utf-8"), child_name.decode("utf-8"),
 
453
                mode_kind(mode), stat_result,
 
454
                self.path2id(path.decode("utf-8")),
 
455
                mode_kind(mode)))
 
456
        return per_dir.iteritems()
213
457
 
214
458
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
215
459
 
 
460
    _tree_class = GitWorkingTree
 
461
 
216
462
    @property
217
463
    def _matchingbzrdir(self):
218
 
        from bzrlib.plugins.git import LocalGitControlDirFormat
 
464
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
219
465
        return LocalGitControlDirFormat()
220
466
 
221
467
    def get_format_description(self):
222
468
        return "Git Working Tree"
223
469
 
 
470
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
471
                   accelerator_tree=None, hardlink=False):
 
472
        """See WorkingTreeFormat.initialize()."""
 
473
        if not isinstance(a_bzrdir, LocalGitDir):
 
474
            raise errors.IncompatibleFormat(self, a_bzrdir)
 
475
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
 
476
        index.write()
 
477
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
 
478
            a_bzrdir.open_branch(), index)
 
479
 
224
480
 
225
481
class InterIndexGitTree(tree.InterTree):
226
482
    """InterTree that works between a Git revision tree and an index."""
239
495
                extra_trees=None, require_versioned=False, include_root=False,
240
496
                want_unversioned=False):
241
497
        changes = self._index.changes_from_tree(
242
 
            self.source._repository._git.object_store, self.source.tree, 
 
498
            self.source.store, self.source.tree, 
243
499
            want_unchanged=want_unchanged)
244
500
        source_fileid_map = self.source.mapping.get_fileid_map(
245
 
            self.source._repository._git.object_store.__getitem__,
 
501
            self.source.store.__getitem__,
246
502
            self.source.tree)
247
503
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
248
504
            file_id = self.target.path2id(
250
506
            if file_id is None:
251
507
                target_fileid_map = {}
252
508
            else:
253
 
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
 
509
                target_fileid_map = self.target.mapping.import_fileid_map(
 
510
                    Blob.from_string(self.target.get_file_text(file_id)))
254
511
        else:
255
512
            target_fileid_map = {}
256
 
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
 
513
        target_fileid_map = GitFileIdMap(target_fileid_map,
 
514
                self.target.mapping)
257
515
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
258
516
            (source_fileid_map, target_fileid_map),
259
517
            specific_file=specific_files, require_versioned=require_versioned)
260
518
        if want_unversioned:
261
519
            for e in self.target.extras():
262
 
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
520
                ret.unversioned.append((e, None,
 
521
                    osutils.file_kind(self.target.abspath(e))))
263
522
        return ret
264
523
 
265
524
    def iter_changes(self, include_unchanged=False, specific_files=None,
266
 
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
 
525
        pb=None, extra_trees=[], require_versioned=True,
 
526
        want_unversioned=False):
267
527
        changes = self._index.changes_from_tree(
268
 
            self.source._repository._git.object_store, self.source.tree, 
 
528
            self.source.store, self.source.tree,
269
529
            want_unchanged=include_unchanged)
270
530
        # FIXME: Handle want_unversioned
271
 
        return changes_from_git_changes(changes, self.target.mapping, 
 
531
        return changes_from_git_changes(changes, self.target.mapping,
272
532
            specific_file=specific_files)
273
533
 
 
534
 
274
535
tree.InterTree.register_optimiser(InterIndexGitTree)