~ubuntu-branches/debian/jessie/bzr-git/jessie

« back to all changes in this revision

Viewing changes to workingtree.py

  • Committer: Bazaar Package Importer
  • Author(s): Jelmer Vernooij
  • Date: 2011-05-01 03:27:52 UTC
  • mfrom: (1.1.16 upstream)
  • Revision ID: james.westby@ubuntu.com-20110501032752-tkhql577jb8wpgua
Tags: 0.6.0+bzr1213-1
* Add build dependency on python-bzrlib.tests for newer versions of
  bzr.
* New upstream snapshot.

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
25
26
from dulwich.index import (
26
27
    Index,
27
28
    )
 
29
from dulwich.object_store import (
 
30
    tree_lookup_path,
 
31
    )
28
32
from dulwich.objects import (
29
33
    Blob,
30
34
    ZERO_SHA,
31
35
    )
32
36
import os
 
37
import posix
 
38
import posixpath
33
39
import stat
34
40
 
35
41
from bzrlib import (
36
42
    errors,
37
43
    conflicts as _mod_conflicts,
38
44
    ignores,
 
45
    inventory,
39
46
    lockable_files,
40
47
    lockdir,
41
48
    osutils,
51
58
from bzrlib.plugins.git.dir import (
52
59
    LocalGitDir,
53
60
    )
54
 
from bzrlib.plugins.git.inventory import (
55
 
    GitIndexInventory,
56
 
    )
57
61
from bzrlib.plugins.git.tree import (
58
62
    changes_from_git_changes,
59
63
    tree_delta_from_git_changes,
60
64
    )
61
65
from bzrlib.plugins.git.mapping import (
62
66
    GitFileIdMap,
 
67
    mode_kind,
63
68
    )
64
69
 
65
70
IGNORE_FILENAME = ".gitignore"
72
77
        self.basedir = bzrdir.root_transport.local_abspath('.')
73
78
        self.bzrdir = bzrdir
74
79
        self.repository = repo
 
80
        self.store = self.repository._git.object_store
75
81
        self.mapping = self.repository.get_mapping()
76
82
        self._branch = branch
77
83
        self._transport = bzrdir.transport
91
97
        self.views = self._make_views()
92
98
        self._rules_searcher = None
93
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"))
94
191
 
95
192
    def extras(self):
96
193
        """Yield all unversioned files in this WorkingTree.
113
210
        finally:
114
211
            self.branch.unlock()
115
212
 
116
 
    def _rewrite_index(self):
117
 
        self.index.clear()
118
 
        for path, entry in self._inventory.iter_entries():
119
 
            if entry.kind == "directory":
120
 
                # Git indexes don't contain directories
121
 
                continue
122
 
            if entry.kind == "file":
123
 
                blob = Blob()
124
 
                try:
125
 
                    file, stat_val = self.get_file_with_stat(entry.file_id, path)
126
 
                except (errors.NoSuchFile, IOError):
127
 
                    # TODO: Rather than come up with something here, use the old index
128
 
                    file = StringIO()
129
 
                    from posix import stat_result
130
 
                    stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
131
 
                blob.set_raw_string(file.read())
132
 
            elif entry.kind == "symlink":
133
 
                blob = Blob()
134
 
                try:
135
 
                    stat_val = os.lstat(self.abspath(path))
136
 
                except (errors.NoSuchFile, OSError):
137
 
                    # TODO: Rather than come up with something here, use the 
138
 
                    # old index
139
 
                    from posix import stat_result
140
 
                    stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
141
 
                blob.set_raw_string(self.get_symlink_target(entry.file_id).encode("utf-8"))
142
 
            else:
143
 
                raise AssertionError("unknown kind '%s'" % entry.kind)
144
 
            # Add object to the repository if it didn't exist yet
145
 
            if not blob.id in self.repository._git.object_store:
146
 
                self.repository._git.object_store.add_object(blob)
147
 
            # Add an entry to the index or update the existing entry
148
 
            flags = 0 # FIXME
149
 
            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)
150
 
 
151
213
    def flush(self):
152
214
        # TODO: Maybe this should only write on dirty ?
153
215
        if self._control_files._lock_mode != 'w':
154
216
            raise errors.NotWriteLocked(self)
155
 
        self._rewrite_index()
156
217
        self.index.write()
157
 
        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
        # FIXME: What about directories?
 
260
        if path in self.index:
 
261
            return path
 
262
        raise errors.NoSuchId(None, file_id)
 
263
 
 
264
    def get_file_mtime(self, file_id, path=None):
 
265
        """See Tree.get_file_mtime."""
 
266
        if not path:
 
267
            path = self.id2path(file_id)
 
268
        return os.lstat(self.abspath(path)).st_mtime
158
269
 
159
270
    def get_ignore_list(self):
160
271
        ignoreset = getattr(self, '_ignoreset', None)
167
278
        if self.has_filename(IGNORE_FILENAME):
168
279
            f = self.get_file_byname(IGNORE_FILENAME)
169
280
            try:
 
281
                # FIXME: Parse git file format, rather than assuming it's
 
282
                # the same as for bzr's native formats.
170
283
                ignore_globs.update(ignores.parse_ignore_file(f))
171
284
            finally:
172
285
                f.close()
177
290
        self._change_last_revision(revid)
178
291
 
179
292
    def _reset_data(self):
180
 
        self._inventory_is_modified = False
181
293
        try:
182
294
            head = self.repository._git.head()
183
295
        except KeyError, name:
184
296
            raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
185
 
        basis_inv = self.repository.get_inventory(self.branch.lookup_foreign_revision_id(head))
186
 
        store = self.repository._git.object_store
187
297
        if head == ZERO_SHA:
188
 
            fileid_map = GitFileIdMap({}, self.mapping)
189
 
            basis_inv = None
 
298
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
190
299
        else:
191
 
            fileid_map = self.mapping.get_fileid_map(store.__getitem__,
192
 
                store[head].tree)
193
 
        result = GitIndexInventory(basis_inv, fileid_map, self.index, store)
194
 
        self._set_inventory(result, dirty=False)
 
300
            self._basis_fileid_map = self.mapping.get_fileid_map(self.store.__getitem__,
 
301
                self.store[head].tree)
195
302
 
196
303
    @needs_read_lock
197
304
    def get_file_sha1(self, file_id, path=None, stat_value=None):
198
305
        if not path:
199
 
            path = self._inventory.id2path(file_id)
 
306
            path = self.id2path(file_id)
200
307
        try:
201
308
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
202
309
        except OSError, (num, msg):
207
314
    def revision_tree(self, revid):
208
315
        return self.repository.revision_tree(revid)
209
316
 
 
317
    def _get_dir_ie(self, path, parent_id):
 
318
        file_id = self.path2id(path)
 
319
        return inventory.InventoryDirectory(file_id,
 
320
            posixpath.basename(path).strip("/"), parent_id)
 
321
 
 
322
    def _add_missing_parent_ids(self, path, dir_ids):
 
323
        if path in dir_ids:
 
324
            return []
 
325
        parent = posixpath.dirname(path).strip("/")
 
326
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
327
        parent_id = dir_ids[parent]
 
328
        ie = self._get_dir_ie(path, parent_id)
 
329
        dir_ids[path] = ie.file_id
 
330
        ret.append((path, ie))
 
331
        return ret
 
332
 
 
333
    def _get_file_ie(self, path, value, parent_id):
 
334
        assert isinstance(path, unicode)
 
335
        assert isinstance(value, tuple) and len(value) == 10
 
336
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
337
        file_id = self.path2id(path)
 
338
        if type(file_id) != str:
 
339
            raise AssertionError
 
340
        kind = mode_kind(mode)
 
341
        ie = inventory.entry_factory[kind](file_id,
 
342
            posixpath.basename(path), parent_id)
 
343
        if kind == 'symlink':
 
344
            ie.symlink_target = self.get_symlink_target(file_id)
 
345
        else:
 
346
            data = self.get_file_text(file_id, path)
 
347
            ie.text_sha1 = osutils.sha_string(data)
 
348
            ie.text_size = len(data)
 
349
            ie.executable = self.is_executable(file_id, path)
 
350
        ie.revision = None
 
351
        return ie
 
352
 
 
353
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
354
        mode = stat_result.st_mode
 
355
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
356
 
 
357
    def stored_kind(self, file_id, path=None):
 
358
        if path is None:
 
359
            path = self.id2path(file_id)
 
360
        head = self.repository._git.head()
 
361
        if head == ZERO_SHA:
 
362
            raise errors.NoSuchId(self, file_id)
 
363
        root_tree = self.store[head].tree
 
364
        (mode, hexsha) = tree_lookup_path(self.store.__getitem__, root_tree, path)
 
365
        return mode_kind(mode)
 
366
 
 
367
    if not osutils.supports_executable():
 
368
        def is_executable(self, file_id, path=None):
 
369
            basis_tree = self.basis_tree()
 
370
            if file_id in basis_tree:
 
371
                return basis_tree.is_executable(file_id)
 
372
            # Default to not executable
 
373
            return False
 
374
    else:
 
375
        def is_executable(self, file_id, path=None):
 
376
            if not path:
 
377
                path = self.id2path(file_id)
 
378
            mode = os.lstat(self.abspath(path)).st_mode
 
379
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
380
 
 
381
        _is_executable_from_path_and_stat = \
 
382
            _is_executable_from_path_and_stat_from_stat
 
383
 
 
384
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
385
        # FIXME: Yield non-versioned files
 
386
        # FIXME: support from_dir
 
387
        # FIXME: Support recursive
 
388
        dir_ids = {}
 
389
        root_ie = self._get_dir_ie(u"", None)
 
390
        if include_root and not from_dir:
 
391
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
392
        dir_ids[u""] = root_ie.file_id
 
393
        for path, value in self.index.iteritems():
 
394
            path = path.decode("utf-8")
 
395
            parent = posixpath.dirname(path).strip("/")
 
396
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
397
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
398
            ie = self._get_file_ie(path, value, dir_ids[parent])
 
399
            yield path, "V", ie.kind, ie.file_id, ie
 
400
 
 
401
    def all_file_ids(self):
 
402
        ids = {u"": self.path2id("")}
 
403
        for path in self.index:
 
404
            path = path.decode("utf-8")
 
405
            parent = posixpath.dirname(path).strip("/")
 
406
            for e in self._add_missing_parent_ids(parent, ids):
 
407
                pass
 
408
            ids[path] = self.path2id(path)
 
409
        return set(ids.values())
 
410
 
 
411
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
412
        # FIXME: Support specific_file_ids
 
413
        # FIXME: Is return order correct?
 
414
        if specific_file_ids is not None:
 
415
            raise NotImplementedError(self.iter_entries_by_dir)
 
416
        root_ie = self._get_dir_ie(u"", None)
 
417
        yield u"", root_ie
 
418
        dir_ids = {u"": root_ie.file_id}
 
419
        for path, value in self.index.iteritems():
 
420
            path = path.decode("utf-8")
 
421
            parent = posixpath.dirname(path).strip("/")
 
422
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
 
423
                    dir_ids):
 
424
                yield dir_path, dir_ie
 
425
            parent_id = self.path2id(parent)
 
426
            yield path, self._get_file_ie(path, value, parent_id)
 
427
 
210
428
    @needs_read_lock
211
429
    def conflicts(self):
212
430
        # FIXME:
213
431
        return _mod_conflicts.ConflictList()
214
432
 
 
433
    def update_basis_by_delta(self, new_revid, delta):
 
434
        # The index just contains content, which won't have changed.
 
435
        self._reset_data()
 
436
 
 
437
    def _walkdirs(self, prefix=""):
 
438
        if prefix != "":
 
439
            prefix += "/"
 
440
        per_dir = defaultdict(list)
 
441
        for path, value in self.index.iteritems():
 
442
            if not path.startswith(prefix):
 
443
                continue
 
444
            (dirname, child_name) = posixpath.split(path)
 
445
            dirname = dirname.decode("utf-8")
 
446
            dir_file_id = self.path2id(dirname)
 
447
            assert isinstance(value, tuple) and len(value) == 10
 
448
            (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
449
            stat_result = posix.stat_result((mode, ino,
 
450
                    dev, 1, uid, gid, size,
 
451
                    0, mtime, ctime))
 
452
            per_dir[(dirname, dir_file_id)].append(
 
453
                (path.decode("utf-8"), child_name.decode("utf-8"),
 
454
                mode_kind(mode), stat_result,
 
455
                self.path2id(path.decode("utf-8")),
 
456
                mode_kind(mode)))
 
457
        return per_dir.iteritems()
215
458
 
216
459
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
217
460
 
 
461
    _tree_class = GitWorkingTree
 
462
 
218
463
    @property
219
464
    def _matchingbzrdir(self):
220
465
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
251
496
                extra_trees=None, require_versioned=False, include_root=False,
252
497
                want_unversioned=False):
253
498
        changes = self._index.changes_from_tree(
254
 
            self.source._repository._git.object_store, self.source.tree, 
 
499
            self.source.store, self.source.tree, 
255
500
            want_unchanged=want_unchanged)
256
501
        source_fileid_map = self.source.mapping.get_fileid_map(
257
 
            self.source._repository._git.object_store.__getitem__,
 
502
            self.source.store.__getitem__,
258
503
            self.source.tree)
259
504
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
260
505
            file_id = self.target.path2id(
262
507
            if file_id is None:
263
508
                target_fileid_map = {}
264
509
            else:
265
 
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
 
510
                target_fileid_map = self.target.mapping.import_fileid_map(
 
511
                    Blob.from_string(self.target.get_file_text(file_id)))
266
512
        else:
267
513
            target_fileid_map = {}
268
 
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
 
514
        target_fileid_map = GitFileIdMap(target_fileid_map,
 
515
                self.target.mapping)
269
516
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
270
517
            (source_fileid_map, target_fileid_map),
271
518
            specific_file=specific_files, require_versioned=require_versioned)
272
519
        if want_unversioned:
273
520
            for e in self.target.extras():
274
 
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
521
                ret.unversioned.append((e, None,
 
522
                    osutils.file_kind(self.target.abspath(e))))
275
523
        return ret
276
524
 
277
525
    def iter_changes(self, include_unchanged=False, specific_files=None,
278
 
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
 
526
        pb=None, extra_trees=[], require_versioned=True,
 
527
        want_unversioned=False):
279
528
        changes = self._index.changes_from_tree(
280
 
            self.source._repository._git.object_store, self.source.tree,
 
529
            self.source.store, self.source.tree,
281
530
            want_unchanged=include_unchanged)
282
531
        # FIXME: Handle want_unversioned
283
532
        return changes_from_git_changes(changes, self.target.mapping,