/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

Don't trust index contents - verify against file timestamps.

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
    changes_from_tree,
 
29
    cleanup_mode,
 
30
    index_entry_from_stat,
 
31
    )
 
32
from dulwich.object_store import (
 
33
    tree_lookup_path,
 
34
    )
25
35
from dulwich.objects import (
26
36
    Blob,
27
 
    )
28
 
from dulwich.protocol import (
29
37
    ZERO_SHA,
30
38
    )
31
39
import os
 
40
import posixpath
32
41
import stat
 
42
import sys
33
43
 
34
44
from bzrlib import (
35
45
    errors,
 
46
    conflicts as _mod_conflicts,
36
47
    ignores,
37
 
    lockable_files,
38
 
    lockdir,
 
48
    inventory,
 
49
    lock,
39
50
    osutils,
40
 
    transport,
 
51
    trace,
41
52
    tree,
42
53
    workingtree,
43
54
    )
44
55
from bzrlib.decorators import (
45
56
    needs_read_lock,
46
57
    )
47
 
 
48
 
 
49
 
from bzrlib.plugins.git.inventory import (
50
 
    GitIndexInventory,
 
58
from bzrlib.mutabletree import needs_tree_write_lock
 
59
 
 
60
 
 
61
from bzrlib.plugins.git.dir import (
 
62
    LocalGitDir,
51
63
    )
52
64
from bzrlib.plugins.git.tree import (
53
65
    changes_from_git_changes,
55
67
    )
56
68
from bzrlib.plugins.git.mapping import (
57
69
    GitFileIdMap,
 
70
    mode_kind,
58
71
    )
59
72
 
60
73
IGNORE_FILENAME = ".gitignore"
67
80
        self.basedir = bzrdir.root_transport.local_abspath('.')
68
81
        self.bzrdir = bzrdir
69
82
        self.repository = repo
 
83
        self.store = self.repository._git.object_store
70
84
        self.mapping = self.repository.get_mapping()
71
85
        self._branch = branch
72
86
        self._transport = bzrdir.transport
73
 
 
74
 
        self.controldir = self.bzrdir.transport.local_abspath('bzr')
75
 
 
76
 
        try:
77
 
            os.makedirs(self.controldir)
78
 
            os.makedirs(os.path.join(self.controldir, 'lock'))
79
 
        except OSError:
80
 
            pass
81
 
 
82
 
        self._control_files = lockable_files.LockableFiles(
83
 
            transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
84
87
        self._format = GitWorkingTreeFormat()
85
88
        self.index = index
 
89
        self._versioned_dirs = None
86
90
        self.views = self._make_views()
 
91
        self._rules_searcher = None
87
92
        self._detect_case_handling()
88
 
 
 
93
        self._reset_data()
 
94
        self._fileid_map = self._basis_fileid_map.copy()
 
95
        self._lock_mode = None
 
96
        self._lock_count = 0
 
97
 
 
98
    def lock_read(self):
 
99
        """Lock the repository for read operations.
 
100
 
 
101
        :return: A bzrlib.lock.LogicalLockResult.
 
102
        """
 
103
        if not self._lock_mode:
 
104
            self._lock_mode = 'r'
 
105
            self._lock_count = 1
 
106
            self.index.read()
 
107
        else:
 
108
            self._lock_count += 1
 
109
        self.branch.lock_read()
 
110
        return lock.LogicalLockResult(self.unlock)
 
111
 
 
112
    def lock_tree_write(self):
 
113
        if not self._lock_mode:
 
114
            self._lock_mode = 'w'
 
115
            self._lock_count = 1
 
116
            self.index.read()
 
117
        elif self._lock_mode == 'r':
 
118
            raise errors.ReadOnlyError(self)
 
119
        else:
 
120
            self._lock_count +=1
 
121
        self.branch.lock_read()
 
122
        return lock.LogicalLockResult(self.unlock)
 
123
 
 
124
    def lock_write(self, token=None):
 
125
        if not self._lock_mode:
 
126
            self._lock_mode = 'w'
 
127
            self._lock_count = 1
 
128
            self.index.read()
 
129
        elif self._lock_mode == 'r':
 
130
            raise errors.ReadOnlyError(self)
 
131
        else:
 
132
            self._lock_count +=1
 
133
        self.branch.lock_write()
 
134
        return lock.LogicalLockResult(self.unlock)
 
135
 
 
136
    def is_locked(self):
 
137
        return self._lock_count >= 1
 
138
 
 
139
    def get_physical_lock_status(self):
 
140
        return False
 
141
 
 
142
    def unlock(self):
 
143
        if not self._lock_count:
 
144
            return lock.cant_unlock_not_held(self)
 
145
        self.branch.unlock()
 
146
        self._cleanup()
 
147
        self._lock_count -= 1
 
148
        if self._lock_count > 0:
 
149
            return
 
150
        self._lock_mode = None
 
151
 
 
152
    def _detect_case_handling(self):
 
153
        try:
 
154
            self._transport.stat(".git/cOnFiG")
 
155
        except errors.NoSuchFile:
 
156
            self.case_sensitive = True
 
157
        else:
 
158
            self.case_sensitive = False
 
159
 
 
160
    def merge_modified(self):
 
161
        return {}
 
162
 
 
163
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
 
164
        self.set_parent_ids([p for p, t in parents_list])
 
165
 
 
166
    def _index_add_entry(self, path, file_id, kind):
 
167
        assert self._lock_mode is not None
 
168
        assert isinstance(path, basestring)
 
169
        assert type(file_id) == str or file_id is None
 
170
        if kind == "directory":
 
171
            # Git indexes don't contain directories
 
172
            return
 
173
        if kind == "file":
 
174
            blob = Blob()
 
175
            try:
 
176
                file, stat_val = self.get_file_with_stat(file_id, path)
 
177
            except (errors.NoSuchFile, IOError):
 
178
                # TODO: Rather than come up with something here, use the old index
 
179
                file = StringIO()
 
180
                stat_val = os.stat_result(
 
181
                    (stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
182
            blob.set_raw_string(file.read())
 
183
        elif kind == "symlink":
 
184
            blob = Blob()
 
185
            try:
 
186
                stat_val = os.lstat(self.abspath(path))
 
187
            except (errors.NoSuchFile, OSError):
 
188
                # TODO: Rather than come up with something here, use the 
 
189
                # old index
 
190
                stat_val = os.stat_result(
 
191
                    (stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
192
            blob.set_raw_string(
 
193
                self.get_symlink_target(file_id, path).encode("utf-8"))
 
194
        else:
 
195
            raise AssertionError("unknown kind '%s'" % kind)
 
196
        # Add object to the repository if it didn't exist yet
 
197
        if not blob.id in self.store:
 
198
            self.store.add_object(blob)
 
199
        # Add an entry to the index or update the existing entry
 
200
        flags = 0 # FIXME
 
201
        encoded_path = path.encode("utf-8")
 
202
        self.index[encoded_path] = index_entry_from_stat(
 
203
            stat_val, blob.id, flags)
 
204
        if self._versioned_dirs is not None:
 
205
            self._ensure_versioned_dir(encoded_path)
 
206
 
 
207
    def _ensure_versioned_dir(self, dirname):
 
208
        if dirname in self._versioned_dirs:
 
209
            return
 
210
        if dirname != "":
 
211
            self._ensure_versioned_dir(posixpath.dirname(dirname))
 
212
        self._versioned_dirs.add(dirname)
 
213
 
 
214
    def _load_dirs(self):
 
215
        assert self._lock_mode is not None
 
216
        self._versioned_dirs = set()
 
217
        for p in self.index:
 
218
            self._ensure_versioned_dir(posixpath.dirname(p))
 
219
 
 
220
    def _unversion_path(self, path):
 
221
        assert self._lock_mode is not None
 
222
        encoded_path = path.encode("utf-8")
 
223
        try:
 
224
            del self.index[encoded_path]
 
225
        except KeyError:
 
226
            # A directory, perhaps?
 
227
            for p in list(self.index):
 
228
                if p.startswith(encoded_path+"/"):
 
229
                    del self.index[p]
 
230
        # FIXME: remove empty directories
 
231
 
 
232
    @needs_tree_write_lock
 
233
    def unversion(self, file_ids):
 
234
        for file_id in file_ids:
 
235
            path = self.id2path(file_id)
 
236
            self._unversion_path(path)
 
237
        self.flush()
 
238
 
 
239
    def check_state(self):
 
240
        """Check that the working state is/isn't valid."""
 
241
        pass
 
242
 
 
243
    @needs_tree_write_lock
 
244
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
 
245
        force=False):
 
246
        """Remove nominated files from the working tree metadata.
 
247
 
 
248
        :param files: File paths relative to the basedir.
 
249
        :param keep_files: If true, the files will also be kept.
 
250
        :param force: Delete files and directories, even if they are changed
 
251
            and even if the directories are not empty.
 
252
        """
 
253
        all_files = set() # specified and nested files 
 
254
 
 
255
        if isinstance(files, basestring):
 
256
            files = [files]
 
257
 
 
258
        if to_file is None:
 
259
            to_file = sys.stdout
 
260
 
 
261
        files = list(all_files)
 
262
 
 
263
        if len(files) == 0:
 
264
            return # nothing to do
 
265
 
 
266
        # Sort needed to first handle directory content before the directory
 
267
        files.sort(reverse=True)
 
268
 
 
269
        def backup(file_to_backup):
 
270
            abs_path = self.abspath(file_to_backup)
 
271
            backup_name = self.bzrdir._available_backup_name(file_to_backup)
 
272
            osutils.rename(abs_path, self.abspath(backup_name))
 
273
            return "removed %s (but kept a copy: %s)" % (
 
274
                file_to_backup, backup_name)
 
275
 
 
276
        for f in files:
 
277
            fid = self.path2id(f)
 
278
            if not fid:
 
279
                message = "%s is not versioned." % (f,)
 
280
            else:
 
281
                abs_path = self.abspath(f)
 
282
                if verbose:
 
283
                    # having removed it, it must be either ignored or unknown
 
284
                    if self.is_ignored(f):
 
285
                        new_status = 'I'
 
286
                    else:
 
287
                        new_status = '?'
 
288
                    # XXX: Really should be a more abstract reporter interface
 
289
                    kind_ch = osutils.kind_marker(self.kind(fid))
 
290
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
 
291
                # Unversion file
 
292
                # FIXME: _unversion_path() is O(size-of-index) for directories
 
293
                self._unversion_path(f)
 
294
                message = "removed %s" % (f,)
 
295
                if osutils.lexists(abs_path):
 
296
                    if (osutils.isdir(abs_path) and
 
297
                        len(os.listdir(abs_path)) > 0):
 
298
                        if force:
 
299
                            osutils.rmtree(abs_path)
 
300
                            message = "deleted %s" % (f,)
 
301
                        else:
 
302
                            message = backup(f)
 
303
                    else:
 
304
                        if not keep_files:
 
305
                            osutils.delete_any(abs_path)
 
306
                            message = "deleted %s" % (f,)
 
307
 
 
308
            # print only one message (if any) per file.
 
309
            if message is not None:
 
310
                trace.note(message)
 
311
        self.flush()
 
312
 
 
313
    def _add(self, files, ids, kinds):
 
314
        for (path, file_id, kind) in zip(files, ids, kinds):
 
315
            if file_id is not None:
 
316
                self._fileid_map.set_file_id(path.encode("utf-8"), file_id)
 
317
            else:
 
318
                file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
 
319
            self._index_add_entry(path, file_id, kind)
 
320
 
 
321
    @needs_tree_write_lock
 
322
    def smart_add(self, file_list, recurse=True, action=None, save=True):
 
323
        added = []
 
324
        ignored = {}
 
325
        user_dirs = []
 
326
        for filepath in osutils.canonical_relpaths(self.basedir, file_list):
 
327
            abspath = self.abspath(filepath)
 
328
            kind = osutils.file_kind(abspath)
 
329
            if action is not None:
 
330
                file_id = action(self, None, filepath, kind)
 
331
            else:
 
332
                file_id = None
 
333
            if kind in ("file", "symlink"):
 
334
                if save:
 
335
                    self._index_add_entry(filepath, file_id, kind)
 
336
                added.append(filepath)
 
337
            elif kind == "directory":
 
338
                if recurse:
 
339
                    user_dirs.append(filepath)
 
340
            else:
 
341
                raise errors.BadFileKindError(filename=abspath, kind=kind)
 
342
        for user_dir in user_dirs:
 
343
            abs_user_dir = self.abspath(user_dir)
 
344
            for name in os.listdir(abs_user_dir):
 
345
                subp = os.path.join(user_dir, name)
 
346
                if self.is_control_filename(subp) or self.mapping.is_special_file(subp):
 
347
                    continue
 
348
                ignore_glob = self.is_ignored(subp)
 
349
                if ignore_glob is not None:
 
350
                    ignored.setdefault(ignore_glob, []).append(subp)
 
351
                    continue
 
352
                abspath = self.abspath(subp)
 
353
                kind = osutils.file_kind(abspath)
 
354
                if kind == "directory":
 
355
                    user_dirs.append(subp)
 
356
                else:
 
357
                    if action is not None:
 
358
                        file_id = action(self, None, filepath, kind)
 
359
                    else:
 
360
                        file_id = None
 
361
                    if save:
 
362
                        self._index_add_entry(subp, file_id, kind)
 
363
        if added and save:
 
364
            self.flush()
 
365
        return added, ignored
 
366
 
 
367
    def _set_root_id(self, file_id):
 
368
        self._fileid_map.set_file_id("", file_id)
 
369
 
 
370
    @needs_tree_write_lock
 
371
    def move(self, from_paths, to_dir=None, after=False):
 
372
        rename_tuples = []
 
373
        to_abs = self.abspath(to_dir)
 
374
        if not os.path.isdir(to_abs):
 
375
            raise errors.BzrMoveFailedError('', to_dir,
 
376
                errors.NotADirectory(to_abs))
 
377
 
 
378
        for from_rel in from_paths:
 
379
            from_tail = os.path.split(from_rel)[-1]
 
380
            to_rel = os.path.join(to_dir, from_tail)
 
381
            self.rename_one(from_rel, to_rel, after=after)
 
382
            rename_tuples.append((from_rel, to_rel))
 
383
        self.flush()
 
384
        return rename_tuples
 
385
 
 
386
    @needs_tree_write_lock
 
387
    def rename_one(self, from_rel, to_rel, after=False):
 
388
        from_path = from_rel.encode("utf-8")
 
389
        to_path = to_rel.encode("utf-8")
 
390
        if not self.has_filename(to_rel):
 
391
            raise errors.BzrMoveFailedError(from_rel, to_rel,
 
392
                errors.NoSuchFile(to_rel))
 
393
        if not from_path in self.index:
 
394
            raise errors.BzrMoveFailedError(from_rel, to_rel,
 
395
                errors.NotVersionedError(path=from_rel))
 
396
        if not after:
 
397
            os.rename(self.abspath(from_rel), self.abspath(to_rel))
 
398
        self.index[to_path] = self.index[from_path]
 
399
        del self.index[from_path]
 
400
        self.flush()
 
401
 
 
402
    def get_root_id(self):
 
403
        return self.path2id("")
 
404
 
 
405
    def _has_dir(self, path):
 
406
        if path == "":
 
407
            return True
 
408
        if self._versioned_dirs is None:
 
409
            self._load_dirs()
 
410
        return path in self._versioned_dirs
 
411
 
 
412
    @needs_read_lock
 
413
    def path2id(self, path):
 
414
        encoded_path = path.encode("utf-8")
 
415
        if self._is_versioned(encoded_path):
 
416
            return self._fileid_map.lookup_file_id(encoded_path)
 
417
        return None
 
418
 
 
419
    def _iter_files_recursive(self, from_dir=None):
 
420
        if from_dir is None:
 
421
            from_dir = ""
 
422
        for (dirpath, dirnames, filenames) in os.walk(self.abspath(from_dir)):
 
423
            dir_relpath = dirpath[len(self.basedir):].strip("/")
 
424
            if self.bzrdir.is_control_filename(dir_relpath):
 
425
                continue
 
426
            for filename in filenames:
 
427
                if not self.mapping.is_special_file(filename):
 
428
                    yield os.path.join(dir_relpath, filename)
 
429
 
 
430
    @needs_read_lock
89
431
    def extras(self):
90
432
        """Yield all unversioned files in this WorkingTree.
91
433
        """
92
 
        for (dirpath, dirnames, filenames) in os.walk(self.basedir):
93
 
            if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
94
 
                continue
95
 
            for filename in filenames:
96
 
                relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
97
 
                if not relpath in self.index:
98
 
                    yield relpath
99
 
 
100
 
 
101
 
    def unlock(self):
102
 
        # non-implementation specific cleanup
103
 
        self._cleanup()
104
 
 
105
 
        # reverse order of locking.
106
 
        try:
107
 
            return self._control_files.unlock()
108
 
        finally:
109
 
            self.branch.unlock()
110
 
 
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
 
 
 
434
        return set(self._iter_files_recursive()) - set(self.index)
 
435
 
 
436
    @needs_tree_write_lock
149
437
    def flush(self):
150
438
        # TODO: Maybe this should only write on dirty ?
151
 
        if self._control_files._lock_mode != 'w':
 
439
        if self._lock_mode != 'w':
152
440
            raise errors.NotWriteLocked(self)
153
 
        self._rewrite_index()
154
441
        self.index.write()
155
 
        self._inventory_is_modified = False
 
442
 
 
443
    @needs_read_lock
 
444
    def __iter__(self):
 
445
        for path in self.index:
 
446
            yield self.path2id(path)
 
447
        self._load_dirs()
 
448
        for path in self._versioned_dirs:
 
449
            yield self.path2id(path)
 
450
 
 
451
    def has_or_had_id(self, file_id):
 
452
        if self.has_id(file_id):
 
453
            return True
 
454
        if self.had_id(file_id):
 
455
            return True
 
456
        return False
 
457
 
 
458
    def had_id(self, file_id):
 
459
        path = self._basis_fileid_map.lookup_file_id(file_id)
 
460
        try:
 
461
            head = self.repository._git.head()
 
462
        except KeyError:
 
463
            # Assume no if basis is not accessible
 
464
            return False
 
465
        if head == ZERO_SHA:
 
466
            return False
 
467
        root_tree = self.store[head].tree
 
468
        try:
 
469
            tree_lookup_path(self.store.__getitem__, root_tree, path)
 
470
        except KeyError:
 
471
            return False
 
472
        else:
 
473
            return True
 
474
 
 
475
    def has_id(self, file_id):
 
476
        try:
 
477
            self.id2path(file_id)
 
478
        except errors.NoSuchId:
 
479
            return False
 
480
        else:
 
481
            return True
 
482
 
 
483
    @needs_read_lock
 
484
    def id2path(self, file_id):
 
485
        file_id = osutils.safe_utf8(file_id)
 
486
        path = self._fileid_map.lookup_path(file_id)
 
487
        # FIXME: What about directories?
 
488
        if self._is_versioned(path):
 
489
            return path.decode("utf-8")
 
490
        raise errors.NoSuchId(self, file_id)
 
491
 
 
492
    def get_file_mtime(self, file_id, path=None):
 
493
        """See Tree.get_file_mtime."""
 
494
        if not path:
 
495
            path = self.id2path(file_id)
 
496
        return os.lstat(self.abspath(path)).st_mtime
156
497
 
157
498
    def get_ignore_list(self):
158
499
        ignoreset = getattr(self, '_ignoreset', None)
165
506
        if self.has_filename(IGNORE_FILENAME):
166
507
            f = self.get_file_byname(IGNORE_FILENAME)
167
508
            try:
 
509
                # FIXME: Parse git file format, rather than assuming it's
 
510
                # the same as for bzr's native formats.
168
511
                ignore_globs.update(ignores.parse_ignore_file(f))
169
512
            finally:
170
513
                f.close()
175
518
        self._change_last_revision(revid)
176
519
 
177
520
    def _reset_data(self):
178
 
        self._inventory_is_modified = False
179
521
        try:
180
522
            head = self.repository._git.head()
181
523
        except KeyError, name:
182
 
            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
 
524
            raise errors.NotBranchError("branch %s at %s" % (name,
 
525
                self.repository.base))
185
526
        if head == ZERO_SHA:
186
 
            fileid_map = GitFileIdMap({}, self.mapping)
187
 
            basis_inv = None
 
527
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
188
528
        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)
 
529
            self._basis_fileid_map = self.mapping.get_fileid_map(
 
530
                self.store.__getitem__, self.store[head].tree)
 
531
 
 
532
    @needs_read_lock
 
533
    def get_file_verifier(self, file_id, path=None, stat_value=None):
 
534
        if path is None:
 
535
            path = self.id2path(file_id)
 
536
        return ("GIT", self.index[path][-2])
193
537
 
194
538
    @needs_read_lock
195
539
    def get_file_sha1(self, file_id, path=None, stat_value=None):
196
540
        if not path:
197
 
            path = self._inventory.id2path(file_id)
 
541
            path = self.id2path(file_id)
 
542
        abspath = self.abspath(path).encode(osutils._fs_enc)
198
543
        try:
199
 
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
 
544
            return osutils.sha_file_by_name(abspath)
200
545
        except OSError, (num, msg):
201
546
            if num in (errno.EISDIR, errno.ENOENT):
202
547
                return None
205
550
    def revision_tree(self, revid):
206
551
        return self.repository.revision_tree(revid)
207
552
 
 
553
    def _is_versioned(self, path):
 
554
        assert self._lock_mode is not None
 
555
        return (path in self.index or self._has_dir(path))
 
556
 
 
557
    def filter_unversioned_files(self, files):
 
558
        return set([p for p in files if not self._is_versioned(p.encode("utf-8"))])
 
559
 
 
560
    def _get_dir_ie(self, path, parent_id):
 
561
        file_id = self.path2id(path)
 
562
        return inventory.InventoryDirectory(file_id,
 
563
            posixpath.basename(path).strip("/"), parent_id)
 
564
 
 
565
    def _add_missing_parent_ids(self, path, dir_ids):
 
566
        if path in dir_ids:
 
567
            return []
 
568
        parent = posixpath.dirname(path).strip("/")
 
569
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
570
        parent_id = dir_ids[parent]
 
571
        ie = self._get_dir_ie(path, parent_id)
 
572
        dir_ids[path] = ie.file_id
 
573
        ret.append((path, ie))
 
574
        return ret
 
575
 
 
576
    def _get_file_ie(self, name, path, value, parent_id):
 
577
        assert isinstance(name, unicode)
 
578
        assert isinstance(path, unicode)
 
579
        assert isinstance(value, tuple) and len(value) == 10
 
580
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
581
        file_id = self.path2id(path)
 
582
        if type(file_id) != str:
 
583
            raise AssertionError
 
584
        kind = mode_kind(mode)
 
585
        ie = inventory.entry_factory[kind](file_id, name, parent_id)
 
586
        if kind == 'symlink':
 
587
            ie.symlink_target = self.get_symlink_target(file_id)
 
588
        else:
 
589
            data = self.get_file_text(file_id, path)
 
590
            ie.text_sha1 = osutils.sha_string(data)
 
591
            ie.text_size = len(data)
 
592
            ie.executable = self.is_executable(file_id, path)
 
593
        ie.revision = None
 
594
        return ie
 
595
 
 
596
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
597
        mode = stat_result.st_mode
 
598
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
599
 
 
600
    @needs_read_lock
 
601
    def stored_kind(self, file_id, path=None):
 
602
        if path is None:
 
603
            path = self.id2path(file_id)
 
604
        try:
 
605
            return mode_kind(self.index[path.encode("utf-8")][4])
 
606
        except KeyError:
 
607
            # Maybe it's a directory?
 
608
            if self._has_dir(path):
 
609
                return "directory"
 
610
            raise errors.NoSuchId(self, file_id)
 
611
 
 
612
    if not osutils.supports_executable():
 
613
        def is_executable(self, file_id, path=None):
 
614
            basis_tree = self.basis_tree()
 
615
            if file_id in basis_tree:
 
616
                return basis_tree.is_executable(file_id)
 
617
            # Default to not executable
 
618
            return False
 
619
    else:
 
620
        def is_executable(self, file_id, path=None):
 
621
            if not path:
 
622
                path = self.id2path(file_id)
 
623
            mode = os.lstat(self.abspath(path)).st_mode
 
624
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
625
 
 
626
        _is_executable_from_path_and_stat = \
 
627
            _is_executable_from_path_and_stat_from_stat
 
628
 
 
629
    @needs_read_lock
 
630
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
631
        # FIXME: Yield non-versioned files
 
632
        if from_dir is None:
 
633
            from_dir = ""
 
634
        dir_ids = {}
 
635
        fk_entries = {'directory': workingtree.TreeDirectory,
 
636
                      'file': workingtree.TreeFile,
 
637
                      'symlink': workingtree.TreeLink}
 
638
        root_ie = self._get_dir_ie(u"", None)
 
639
        if include_root and not from_dir:
 
640
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
641
        dir_ids[u""] = root_ie.file_id
 
642
        if recursive:
 
643
            path_iterator = self._iter_files_recursive(from_dir)
 
644
        else:
 
645
            if from_dir is None:
 
646
                start = self.basedir
 
647
            else:
 
648
                start = os.path.join(self.basedir, from_dir)
 
649
            path_iterator = sorted([os.path.join(from_dir, name) for name in
 
650
                os.listdir(start) if not self.bzrdir.is_control_filename(name)
 
651
                and not self.mapping.is_special_file(name)])
 
652
        for path in path_iterator:
 
653
            try:
 
654
                value = self.index[path]
 
655
            except KeyError:
 
656
                value = None
 
657
            path = path.decode("utf-8")
 
658
            parent, name = posixpath.split(path)
 
659
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
660
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
661
            if value is not None:
 
662
                ie = self._get_file_ie(name, path, value, dir_ids[parent])
 
663
                yield path, "V", ie.kind, ie.file_id, ie
 
664
            else:
 
665
                kind = osutils.file_kind(self.abspath(path))
 
666
                ie = fk_entries[kind]()
 
667
                yield path, "?", kind, None, ie
 
668
 
 
669
    @needs_read_lock
 
670
    def all_file_ids(self):
 
671
        ids = {u"": self.path2id("")}
 
672
        for path in self.index:
 
673
            if self.mapping.is_special_file(path):
 
674
                continue
 
675
            path = path.decode("utf-8")
 
676
            parent = posixpath.dirname(path).strip("/")
 
677
            for e in self._add_missing_parent_ids(parent, ids):
 
678
                pass
 
679
            ids[path] = self.path2id(path)
 
680
        return set(ids.values())
 
681
 
 
682
    def _directory_is_tree_reference(self, path):
 
683
        # FIXME: Check .gitsubmodules for path
 
684
        return False
 
685
 
 
686
    @needs_read_lock
 
687
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
688
        # FIXME: Is return order correct?
 
689
        if yield_parents:
 
690
            raise NotImplementedError(self.iter_entries_by_dir)
 
691
        if specific_file_ids is not None:
 
692
            specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
 
693
            if specific_paths in ([u""], []):
 
694
                specific_paths = None
 
695
            else:
 
696
                specific_paths = set(specific_paths)
 
697
        else:
 
698
            specific_paths = None
 
699
        root_ie = self._get_dir_ie(u"", None)
 
700
        if specific_paths is None:
 
701
            yield u"", root_ie
 
702
        dir_ids = {u"": root_ie.file_id}
 
703
        for path, value in self.index.iteritems():
 
704
            if self.mapping.is_special_file(path):
 
705
                continue
 
706
            path = path.decode("utf-8")
 
707
            if specific_paths is not None and not path in specific_paths:
 
708
                continue
 
709
            (parent, name) = posixpath.split(path)
 
710
            try:
 
711
                file_ie = self._get_file_ie(name, path, value, None)
 
712
            except IOError:
 
713
                continue
 
714
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
 
715
                    dir_ids):
 
716
                yield dir_path, dir_ie
 
717
            file_ie.parent_id = self.path2id(parent)
 
718
            yield path, file_ie
 
719
 
208
720
    @needs_read_lock
209
721
    def conflicts(self):
210
722
        # FIXME:
211
 
        return []
 
723
        return _mod_conflicts.ConflictList()
 
724
 
 
725
    def update_basis_by_delta(self, new_revid, delta):
 
726
        # The index just contains content, which won't have changed.
 
727
        self._reset_data()
 
728
 
 
729
    @needs_read_lock
 
730
    def get_canonical_inventory_path(self, path):
 
731
        for p in self.index:
 
732
            if p.lower() == path.lower():
 
733
                return p
 
734
        else:
 
735
            return path
 
736
 
 
737
    @needs_read_lock
 
738
    def _walkdirs(self, prefix=""):
 
739
        if prefix != "":
 
740
            prefix += "/"
 
741
        per_dir = defaultdict(list)
 
742
        for path, value in self.index.iteritems():
 
743
            if self.mapping.is_special_file(path):
 
744
                continue
 
745
            if not path.startswith(prefix):
 
746
                continue
 
747
            (dirname, child_name) = posixpath.split(path)
 
748
            dirname = dirname.decode("utf-8")
 
749
            dir_file_id = self.path2id(dirname)
 
750
            assert isinstance(value, tuple) and len(value) == 10
 
751
            (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
752
            stat_result = os.stat_result((mode, ino,
 
753
                    dev, 1, uid, gid, size,
 
754
                    0, mtime, ctime))
 
755
            per_dir[(dirname, dir_file_id)].append(
 
756
                (path.decode("utf-8"), child_name.decode("utf-8"),
 
757
                mode_kind(mode), stat_result,
 
758
                self.path2id(path.decode("utf-8")),
 
759
                mode_kind(mode)))
 
760
        return per_dir.iteritems()
212
761
 
213
762
 
214
763
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
215
764
 
 
765
    _tree_class = GitWorkingTree
 
766
 
 
767
    supports_versioned_directories = False
 
768
 
216
769
    @property
217
770
    def _matchingbzrdir(self):
218
 
        from bzrlib.plugins.git import LocalGitControlDirFormat
 
771
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
219
772
        return LocalGitControlDirFormat()
220
773
 
221
774
    def get_format_description(self):
222
775
        return "Git Working Tree"
223
776
 
 
777
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
778
                   accelerator_tree=None, hardlink=False):
 
779
        """See WorkingTreeFormat.initialize()."""
 
780
        if not isinstance(a_bzrdir, LocalGitDir):
 
781
            raise errors.IncompatibleFormat(self, a_bzrdir)
 
782
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
 
783
        index.write()
 
784
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
 
785
            a_bzrdir.open_branch(), index)
 
786
 
224
787
 
225
788
class InterIndexGitTree(tree.InterTree):
226
789
    """InterTree that works between a Git revision tree and an index."""
227
790
 
228
791
    def __init__(self, source, target):
229
792
        super(InterIndexGitTree, self).__init__(source, target)
 
793
        assert target.is_locked()
230
794
        self._index = target.index
231
795
 
232
796
    @classmethod
238
802
    def compare(self, want_unchanged=False, specific_files=None,
239
803
                extra_trees=None, require_versioned=False, include_root=False,
240
804
                want_unversioned=False):
241
 
        changes = self._index.changes_from_tree(
242
 
            self.source._repository._git.object_store, self.source.tree, 
243
 
            want_unchanged=want_unchanged)
244
 
        source_fileid_map = self.source.mapping.get_fileid_map(
245
 
            self.source._repository._git.object_store.__getitem__,
246
 
            self.source.tree)
247
 
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
248
 
            file_id = self.target.path2id(
249
 
                self.target.mapping.BZR_FILE_IDS_FILE)
250
 
            if file_id is None:
251
 
                target_fileid_map = {}
252
 
            else:
253
 
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
254
 
        else:
255
 
            target_fileid_map = {}
256
 
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
 
805
        # FIXME: Handle include_root
 
806
        changes = changes_between_git_tree_and_index(
 
807
            self.source.store, self.source.tree, 
 
808
            self.target.basedir, self.target.index,
 
809
            want_unchanged=want_unchanged,
 
810
            want_unversioned=want_unversioned)
 
811
        source_fileid_map = self.source._fileid_map
 
812
        target_fileid_map = self.target._fileid_map
257
813
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
258
814
            (source_fileid_map, target_fileid_map),
259
815
            specific_file=specific_files, require_versioned=require_versioned)
260
816
        if want_unversioned:
261
817
            for e in self.target.extras():
262
 
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
818
                ret.unversioned.append((e, None,
 
819
                    osutils.file_kind(self.target.abspath(e))))
263
820
        return ret
264
821
 
265
822
    def iter_changes(self, include_unchanged=False, specific_files=None,
266
 
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
267
 
        changes = self._index.changes_from_tree(
268
 
            self.source._repository._git.object_store, self.source.tree, 
269
 
            want_unchanged=include_unchanged)
270
 
        # FIXME: Handle want_unversioned
271
 
        return changes_from_git_changes(changes, self.target.mapping, 
 
823
        pb=None, extra_trees=[], require_versioned=True,
 
824
        want_unversioned=False):
 
825
        changes = changes_between_git_tree_and_index(
 
826
            self.source.store, self.source.tree,
 
827
            self.target.basedir, self.target.index,
 
828
            want_unchanged=include_unchanged,
 
829
            want_unversioned=want_unversioned)
 
830
        return changes_from_git_changes(changes, self.target.mapping,
272
831
            specific_file=specific_files)
273
832
 
 
833
 
274
834
tree.InterTree.register_optimiser(InterIndexGitTree)
 
835
 
 
836
 
 
837
def changes_between_git_tree_and_index(object_store, tree, base_path, index,
 
838
        want_unchanged=False, want_unversioned=False, update_index=False):
 
839
    """Determine the changes between a git tree and a working tree with index.
 
840
 
 
841
    """
 
842
    names = index._byname.keys()
 
843
    def lookup_entry(path):
 
844
        entry = index[path]
 
845
        index_mode = entry[-6]
 
846
        index_sha = entry[-2]
 
847
        disk_path = os.path.join(base_path, path)
 
848
        disk_stat = os.lstat(disk_path)
 
849
        mtime = disk_stat.st_mtime
 
850
        mtime_delta = (entry[1][0] - mtime)
 
851
        disk_mode = cleanup_mode(disk_stat.st_mode)
 
852
        if (mtime_delta > 0 or
 
853
            disk_mode != index_mode):
 
854
            with open(disk_path, 'r') as f:
 
855
                blob = Blob.from_string(f.read())
 
856
            if update_index:
 
857
                flags = 0 # FIXME
 
858
                index[path] = index_entry_from_stat(disk_stat, blob.id, flags)
 
859
            return (blob.id, disk_mode)
 
860
        return (index_sha, index_mode)
 
861
    for (name, mode, sha) in changes_from_tree(names, lookup_entry,
 
862
            object_store, tree, want_unchanged=want_unchanged):
 
863
        yield (name, mode, sha)