/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Ā limitĀ argument.

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
        assert type(file_id) is str, "file id not a string: %r" % file_id
 
486
        file_id = osutils.safe_utf8(file_id)
 
487
        path = self._fileid_map.lookup_path(file_id)
 
488
        # FIXME: What about directories?
 
489
        if self._is_versioned(path):
 
490
            return path.decode("utf-8")
 
491
        raise errors.NoSuchId(self, file_id)
 
492
 
 
493
    def get_file_mtime(self, file_id, path=None):
 
494
        """See Tree.get_file_mtime."""
 
495
        if not path:
 
496
            path = self.id2path(file_id)
 
497
        return os.lstat(self.abspath(path)).st_mtime
156
498
 
157
499
    def get_ignore_list(self):
158
500
        ignoreset = getattr(self, '_ignoreset', None)
165
507
        if self.has_filename(IGNORE_FILENAME):
166
508
            f = self.get_file_byname(IGNORE_FILENAME)
167
509
            try:
 
510
                # FIXME: Parse git file format, rather than assuming it's
 
511
                # the same as for bzr's native formats.
168
512
                ignore_globs.update(ignores.parse_ignore_file(f))
169
513
            finally:
170
514
                f.close()
175
519
        self._change_last_revision(revid)
176
520
 
177
521
    def _reset_data(self):
178
 
        self._inventory_is_modified = False
179
522
        try:
180
523
            head = self.repository._git.head()
181
524
        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
 
525
            raise errors.NotBranchError("branch %s at %s" % (name,
 
526
                self.repository.base))
185
527
        if head == ZERO_SHA:
186
 
            fileid_map = GitFileIdMap({}, self.mapping)
187
 
            basis_inv = None
 
528
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
188
529
        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)
 
530
            self._basis_fileid_map = self.mapping.get_fileid_map(
 
531
                self.store.__getitem__, self.store[head].tree)
 
532
 
 
533
    @needs_read_lock
 
534
    def get_file_verifier(self, file_id, path=None, stat_value=None):
 
535
        if path is None:
 
536
            path = self.id2path(file_id)
 
537
        return ("GIT", self.index[path][-2])
193
538
 
194
539
    @needs_read_lock
195
540
    def get_file_sha1(self, file_id, path=None, stat_value=None):
196
541
        if not path:
197
 
            path = self._inventory.id2path(file_id)
 
542
            path = self.id2path(file_id)
 
543
        abspath = self.abspath(path).encode(osutils._fs_enc)
198
544
        try:
199
 
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
 
545
            return osutils.sha_file_by_name(abspath)
200
546
        except OSError, (num, msg):
201
547
            if num in (errno.EISDIR, errno.ENOENT):
202
548
                return None
205
551
    def revision_tree(self, revid):
206
552
        return self.repository.revision_tree(revid)
207
553
 
 
554
    def _is_versioned(self, path):
 
555
        assert self._lock_mode is not None
 
556
        return (path in self.index or self._has_dir(path))
 
557
 
 
558
    def filter_unversioned_files(self, files):
 
559
        return set([p for p in files if not self._is_versioned(p.encode("utf-8"))])
 
560
 
 
561
    def _get_dir_ie(self, path, parent_id):
 
562
        file_id = self.path2id(path)
 
563
        return inventory.InventoryDirectory(file_id,
 
564
            posixpath.basename(path).strip("/"), parent_id)
 
565
 
 
566
    def _add_missing_parent_ids(self, path, dir_ids):
 
567
        if path in dir_ids:
 
568
            return []
 
569
        parent = posixpath.dirname(path).strip("/")
 
570
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
571
        parent_id = dir_ids[parent]
 
572
        ie = self._get_dir_ie(path, parent_id)
 
573
        dir_ids[path] = ie.file_id
 
574
        ret.append((path, ie))
 
575
        return ret
 
576
 
 
577
    def _get_file_ie(self, name, path, value, parent_id):
 
578
        assert isinstance(name, unicode)
 
579
        assert isinstance(path, unicode)
 
580
        assert isinstance(value, tuple) and len(value) == 10
 
581
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
582
        file_id = self.path2id(path)
 
583
        if type(file_id) != str:
 
584
            raise AssertionError
 
585
        kind = mode_kind(mode)
 
586
        ie = inventory.entry_factory[kind](file_id, name, parent_id)
 
587
        if kind == 'symlink':
 
588
            ie.symlink_target = self.get_symlink_target(file_id)
 
589
        else:
 
590
            data = self.get_file_text(file_id, path)
 
591
            ie.text_sha1 = osutils.sha_string(data)
 
592
            ie.text_size = len(data)
 
593
            ie.executable = self.is_executable(file_id, path)
 
594
        ie.revision = None
 
595
        return ie
 
596
 
 
597
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
598
        mode = stat_result.st_mode
 
599
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
600
 
 
601
    @needs_read_lock
 
602
    def stored_kind(self, file_id, path=None):
 
603
        if path is None:
 
604
            path = self.id2path(file_id)
 
605
        try:
 
606
            return mode_kind(self.index[path.encode("utf-8")][4])
 
607
        except KeyError:
 
608
            # Maybe it's a directory?
 
609
            if self._has_dir(path):
 
610
                return "directory"
 
611
            raise errors.NoSuchId(self, file_id)
 
612
 
 
613
    if not osutils.supports_executable():
 
614
        def is_executable(self, file_id, path=None):
 
615
            basis_tree = self.basis_tree()
 
616
            if file_id in basis_tree:
 
617
                return basis_tree.is_executable(file_id)
 
618
            # Default to not executable
 
619
            return False
 
620
    else:
 
621
        def is_executable(self, file_id, path=None):
 
622
            if not path:
 
623
                path = self.id2path(file_id)
 
624
            mode = os.lstat(self.abspath(path)).st_mode
 
625
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
626
 
 
627
        _is_executable_from_path_and_stat = \
 
628
            _is_executable_from_path_and_stat_from_stat
 
629
 
 
630
    @needs_read_lock
 
631
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
632
        # FIXME: Yield non-versioned files
 
633
        if from_dir is None:
 
634
            from_dir = ""
 
635
        dir_ids = {}
 
636
        fk_entries = {'directory': workingtree.TreeDirectory,
 
637
                      'file': workingtree.TreeFile,
 
638
                      'symlink': workingtree.TreeLink}
 
639
        root_ie = self._get_dir_ie(u"", None)
 
640
        if include_root and not from_dir:
 
641
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
 
642
        dir_ids[u""] = root_ie.file_id
 
643
        if recursive:
 
644
            path_iterator = self._iter_files_recursive(from_dir)
 
645
        else:
 
646
            if from_dir is None:
 
647
                start = self.basedir
 
648
            else:
 
649
                start = os.path.join(self.basedir, from_dir)
 
650
            path_iterator = sorted([os.path.join(from_dir, name) for name in
 
651
                os.listdir(start) if not self.bzrdir.is_control_filename(name)
 
652
                and not self.mapping.is_special_file(name)])
 
653
        for path in path_iterator:
 
654
            try:
 
655
                value = self.index[path]
 
656
            except KeyError:
 
657
                value = None
 
658
            path = path.decode("utf-8")
 
659
            parent, name = posixpath.split(path)
 
660
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
 
661
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
 
662
            if value is not None:
 
663
                ie = self._get_file_ie(name, path, value, dir_ids[parent])
 
664
                yield path, "V", ie.kind, ie.file_id, ie
 
665
            else:
 
666
                kind = osutils.file_kind(self.abspath(path))
 
667
                ie = fk_entries[kind]()
 
668
                yield path, "?", kind, None, ie
 
669
 
 
670
    @needs_read_lock
 
671
    def all_file_ids(self):
 
672
        ids = {u"": self.path2id("")}
 
673
        for path in self.index:
 
674
            if self.mapping.is_special_file(path):
 
675
                continue
 
676
            path = path.decode("utf-8")
 
677
            parent = posixpath.dirname(path).strip("/")
 
678
            for e in self._add_missing_parent_ids(parent, ids):
 
679
                pass
 
680
            ids[path] = self.path2id(path)
 
681
        return set(ids.values())
 
682
 
 
683
    def _directory_is_tree_reference(self, path):
 
684
        # FIXME: Check .gitsubmodules for path
 
685
        return False
 
686
 
 
687
    @needs_read_lock
 
688
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
689
        # FIXME: Is return order correct?
 
690
        if yield_parents:
 
691
            raise NotImplementedError(self.iter_entries_by_dir)
 
692
        if specific_file_ids is not None:
 
693
            specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
 
694
            if specific_paths in ([u""], []):
 
695
                specific_paths = None
 
696
            else:
 
697
                specific_paths = set(specific_paths)
 
698
        else:
 
699
            specific_paths = None
 
700
        root_ie = self._get_dir_ie(u"", None)
 
701
        if specific_paths is None:
 
702
            yield u"", root_ie
 
703
        dir_ids = {u"": root_ie.file_id}
 
704
        for path, value in self.index.iteritems():
 
705
            if self.mapping.is_special_file(path):
 
706
                continue
 
707
            path = path.decode("utf-8")
 
708
            if specific_paths is not None and not path in specific_paths:
 
709
                continue
 
710
            (parent, name) = posixpath.split(path)
 
711
            try:
 
712
                file_ie = self._get_file_ie(name, path, value, None)
 
713
            except IOError:
 
714
                continue
 
715
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
 
716
                    dir_ids):
 
717
                yield dir_path, dir_ie
 
718
            file_ie.parent_id = self.path2id(parent)
 
719
            yield path, file_ie
 
720
 
208
721
    @needs_read_lock
209
722
    def conflicts(self):
210
723
        # FIXME:
211
 
        return []
 
724
        return _mod_conflicts.ConflictList()
 
725
 
 
726
    def update_basis_by_delta(self, new_revid, delta):
 
727
        # The index just contains content, which won't have changed.
 
728
        self._reset_data()
 
729
 
 
730
    @needs_read_lock
 
731
    def get_canonical_inventory_path(self, path):
 
732
        for p in self.index:
 
733
            if p.lower() == path.lower():
 
734
                return p
 
735
        else:
 
736
            return path
 
737
 
 
738
    @needs_read_lock
 
739
    def _walkdirs(self, prefix=""):
 
740
        if prefix != "":
 
741
            prefix += "/"
 
742
        per_dir = defaultdict(list)
 
743
        for path, value in self.index.iteritems():
 
744
            if self.mapping.is_special_file(path):
 
745
                continue
 
746
            if not path.startswith(prefix):
 
747
                continue
 
748
            (dirname, child_name) = posixpath.split(path)
 
749
            dirname = dirname.decode("utf-8")
 
750
            dir_file_id = self.path2id(dirname)
 
751
            assert isinstance(value, tuple) and len(value) == 10
 
752
            (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
753
            stat_result = os.stat_result((mode, ino,
 
754
                    dev, 1, uid, gid, size,
 
755
                    0, mtime, ctime))
 
756
            per_dir[(dirname, dir_file_id)].append(
 
757
                (path.decode("utf-8"), child_name.decode("utf-8"),
 
758
                mode_kind(mode), stat_result,
 
759
                self.path2id(path.decode("utf-8")),
 
760
                mode_kind(mode)))
 
761
        return per_dir.iteritems()
212
762
 
213
763
 
214
764
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
215
765
 
 
766
    _tree_class = GitWorkingTree
 
767
 
 
768
    supports_versioned_directories = False
 
769
 
216
770
    @property
217
771
    def _matchingbzrdir(self):
218
 
        from bzrlib.plugins.git import LocalGitControlDirFormat
 
772
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
219
773
        return LocalGitControlDirFormat()
220
774
 
221
775
    def get_format_description(self):
222
776
        return "Git Working Tree"
223
777
 
 
778
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
779
                   accelerator_tree=None, hardlink=False):
 
780
        """See WorkingTreeFormat.initialize()."""
 
781
        if not isinstance(a_bzrdir, LocalGitDir):
 
782
            raise errors.IncompatibleFormat(self, a_bzrdir)
 
783
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
 
784
        index.write()
 
785
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
 
786
            a_bzrdir.open_branch(), index)
 
787
 
224
788
 
225
789
class InterIndexGitTree(tree.InterTree):
226
790
    """InterTree that works between a Git revision tree and an index."""
227
791
 
228
792
    def __init__(self, source, target):
229
793
        super(InterIndexGitTree, self).__init__(source, target)
 
794
        assert target.is_locked()
230
795
        self._index = target.index
231
796
 
232
797
    @classmethod
238
803
    def compare(self, want_unchanged=False, specific_files=None,
239
804
                extra_trees=None, require_versioned=False, include_root=False,
240
805
                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)
 
806
        # FIXME: Handle include_root
 
807
        changes = changes_between_git_tree_and_index(
 
808
            self.source.store, self.source.tree, 
 
809
            self.target.basedir, self.target.index,
 
810
            want_unchanged=want_unchanged,
 
811
            want_unversioned=want_unversioned)
 
812
        source_fileid_map = self.source._fileid_map
 
813
        target_fileid_map = self.target._fileid_map
257
814
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
258
815
            (source_fileid_map, target_fileid_map),
259
816
            specific_file=specific_files, require_versioned=require_versioned)
260
817
        if want_unversioned:
261
818
            for e in self.target.extras():
262
 
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
 
819
                ret.unversioned.append((e, None,
 
820
                    osutils.file_kind(self.target.abspath(e))))
263
821
        return ret
264
822
 
265
823
    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, 
 
824
        pb=None, extra_trees=[], require_versioned=True,
 
825
        want_unversioned=False):
 
826
        changes = changes_between_git_tree_and_index(
 
827
            self.source.store, self.source.tree,
 
828
            self.target.basedir, self.target.index,
 
829
            want_unchanged=include_unchanged,
 
830
            want_unversioned=want_unversioned)
 
831
        return changes_from_git_changes(changes, self.target.mapping,
272
832
            specific_file=specific_files)
273
833
 
 
834
 
274
835
tree.InterTree.register_optimiser(InterIndexGitTree)
 
836
 
 
837
 
 
838
def changes_between_git_tree_and_index(object_store, tree, base_path, index,
 
839
        want_unchanged=False, want_unversioned=False, update_index=False):
 
840
    """Determine the changes between a git tree and a working tree with index.
 
841
 
 
842
    """
 
843
    names = index._byname.keys()
 
844
    def lookup_entry(path):
 
845
        entry = index[path]
 
846
        index_mode = entry[-6]
 
847
        index_sha = entry[-2]
 
848
        disk_path = os.path.join(base_path, path)
 
849
        disk_stat = os.lstat(disk_path)
 
850
        disk_mtime = disk_stat.st_mtime
 
851
        if isinstance(entry[1], tuple):
 
852
            index_mtime = entry[1][0]
 
853
        else:
 
854
            index_mtime = int(entry[1])
 
855
        mtime_delta = (index_mtime - disk_mtime)
 
856
        disk_mode = cleanup_mode(disk_stat.st_mode)
 
857
        if (mtime_delta > 0 or
 
858
            disk_mode != index_mode):
 
859
            with open(disk_path, 'r') as f:
 
860
                blob = Blob.from_string(f.read())
 
861
            if update_index:
 
862
                flags = 0 # FIXME
 
863
                index[path] = index_entry_from_stat(disk_stat, blob.id, flags)
 
864
            return (blob.id, disk_mode)
 
865
        return (index_sha, index_mode)
 
866
    for (name, mode, sha) in changes_from_tree(names, lookup_entry,
 
867
            object_store, tree, want_unchanged=want_unchanged):
 
868
        yield (name, mode, sha)