/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

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2008 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
25
24
import errno
26
 
from dulwich.index import (
27
 
    Index,
28
 
    )
29
 
from dulwich.object_store import (
30
 
    tree_lookup_path,
31
 
    )
32
25
from dulwich.objects import (
33
26
    Blob,
 
27
    )
 
28
from dulwich.protocol import (
34
29
    ZERO_SHA,
35
30
    )
36
31
import os
37
 
import posix
38
 
import posixpath
39
32
import stat
40
 
import sys
41
33
 
42
34
from bzrlib import (
43
35
    errors,
44
 
    conflicts as _mod_conflicts,
45
36
    ignores,
46
 
    inventory,
47
37
    lockable_files,
48
38
    lockdir,
49
39
    osutils,
50
 
    trace,
51
40
    transport,
52
41
    tree,
53
42
    workingtree,
57
46
    )
58
47
 
59
48
 
60
 
from bzrlib.plugins.git.dir import (
61
 
    LocalGitDir,
 
49
from bzrlib.plugins.git.inventory import (
 
50
    GitIndexInventory,
62
51
    )
63
52
from bzrlib.plugins.git.tree import (
64
53
    changes_from_git_changes,
66
55
    )
67
56
from bzrlib.plugins.git.mapping import (
68
57
    GitFileIdMap,
69
 
    mode_kind,
70
58
    )
71
59
 
72
60
IGNORE_FILENAME = ".gitignore"
79
67
        self.basedir = bzrdir.root_transport.local_abspath('.')
80
68
        self.bzrdir = bzrdir
81
69
        self.repository = repo
82
 
        self.store = self.repository._git.object_store
83
70
        self.mapping = self.repository.get_mapping()
84
71
        self._branch = branch
85
72
        self._transport = bzrdir.transport
96
83
            transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
97
84
        self._format = GitWorkingTreeFormat()
98
85
        self.index = index
99
 
        self._versioned_dirs = None
100
86
        self.views = self._make_views()
101
 
        self._rules_searcher = None
102
87
        self._detect_case_handling()
103
 
        self._reset_data()
104
 
        self._fileid_map = self._basis_fileid_map.copy()
105
 
 
106
 
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
107
 
        self.set_parent_ids([p for p, t in parents_list])
108
 
 
109
 
    def _index_add_entry(self, path, file_id, kind):
110
 
        assert isinstance(path, basestring)
111
 
        assert type(file_id) == str
112
 
        if kind == "directory":
113
 
            # Git indexes don't contain directories
114
 
            return
115
 
        if kind == "file":
116
 
            blob = Blob()
117
 
            try:
118
 
                file, stat_val = self.get_file_with_stat(file_id, path)
119
 
            except (errors.NoSuchFile, IOError):
120
 
                # TODO: Rather than come up with something here, use the old index
121
 
                file = StringIO()
122
 
                from posix import stat_result
123
 
                stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
124
 
            blob.set_raw_string(file.read())
125
 
        elif kind == "symlink":
126
 
            blob = Blob()
127
 
            try:
128
 
                stat_val = os.lstat(self.abspath(path))
129
 
            except (errors.NoSuchFile, OSError):
130
 
                # TODO: Rather than come up with something here, use the 
131
 
                # old index
132
 
                from posix import stat_result
133
 
                stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
134
 
            blob.set_raw_string(self.get_symlink_target(file_id).encode("utf-8"))
135
 
        else:
136
 
            raise AssertionError("unknown kind '%s'" % kind)
137
 
        # Add object to the repository if it didn't exist yet
138
 
        if not blob.id in self.store:
139
 
            self.store.add_object(blob)
140
 
        # Add an entry to the index or update the existing entry
141
 
        flags = 0 # FIXME
142
 
        encoded_path = path.encode("utf-8")
143
 
        self.index[encoded_path] = (stat_val.st_ctime,
144
 
                stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
145
 
                stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
146
 
                stat_val.st_size, blob.id, flags)
147
 
        if self._versioned_dirs is not None:
148
 
            self._ensure_versioned_dir(encoded_path)
149
 
 
150
 
    def _ensure_versioned_dir(self, dirname):
151
 
        if dirname in self._versioned_dirs:
152
 
            return
153
 
        if dirname != "":
154
 
            self._ensure_versioned_dir(posixpath.dirname(dirname))
155
 
        self._versioned_dirs.add(dirname)
156
 
 
157
 
    def _load_dirs(self):
158
 
        self._versioned_dirs = set()
159
 
        for p in self.index:
160
 
            self._ensure_versioned_dir(posixpath.dirname(p))
161
 
 
162
 
    def _unversion_path(self, path):
163
 
        encoded_path = path.encode("utf-8")
164
 
        try:
165
 
            del self.index[encoded_path]
166
 
        except KeyError:
167
 
            # A directory, perhaps?
168
 
            for p in list(self.index):
169
 
                if p.startswith(encoded_path+"/"):
170
 
                    del self.index[p]
171
 
        # FIXME: remove empty directories
172
 
 
173
 
    def unversion(self, file_ids):
174
 
        for file_id in file_ids:
175
 
            path = self.id2path(file_id)
176
 
            self._unversion_path(path)
177
 
 
178
 
    def check_state(self):
179
 
        """Check that the working state is/isn't valid."""
180
 
        pass
181
 
 
182
 
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
183
 
        force=False):
184
 
        """Remove nominated files from the working tree metadata.
185
 
 
186
 
        :param files: File paths relative to the basedir.
187
 
        :param keep_files: If true, the files will also be kept.
188
 
        :param force: Delete files and directories, even if they are changed
189
 
            and even if the directories are not empty.
190
 
        """
191
 
        all_files = set() # specified and nested files 
192
 
 
193
 
        if isinstance(files, basestring):
194
 
            files = [files]
195
 
 
196
 
        if to_file is None:
197
 
            to_file = sys.stdout
198
 
 
199
 
        files = list(all_files)
200
 
 
201
 
        if len(files) == 0:
202
 
            return # nothing to do
203
 
 
204
 
        # Sort needed to first handle directory content before the directory
205
 
        files.sort(reverse=True)
206
 
 
207
 
        def backup(file_to_backup):
208
 
            abs_path = self.abspath(file_to_backup)
209
 
            backup_name = self.bzrdir._available_backup_name(file_to_backup)
210
 
            osutils.rename(abs_path, self.abspath(backup_name))
211
 
            return "removed %s (but kept a copy: %s)" % (
212
 
                file_to_backup, backup_name)
213
 
 
214
 
        for f in files:
215
 
            fid = self.path2id(f)
216
 
            if not fid:
217
 
                message = "%s is not versioned." % (f,)
218
 
            else:
219
 
                abs_path = self.abspath(f)
220
 
                if verbose:
221
 
                    # having removed it, it must be either ignored or unknown
222
 
                    if self.is_ignored(f):
223
 
                        new_status = 'I'
224
 
                    else:
225
 
                        new_status = '?'
226
 
                    # XXX: Really should be a more abstract reporter interface
227
 
                    kind_ch = osutils.kind_marker(self.kind(fid))
228
 
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
229
 
                # Unversion file
230
 
                # FIXME: _unversion_path() is O(size-of-index) for directories
231
 
                self._unversion_path(f)
232
 
                message = "removed %s" % (f,)
233
 
                if osutils.lexists(abs_path):
234
 
                    if (osutils.isdir(abs_path) and
235
 
                        len(os.listdir(abs_path)) > 0):
236
 
                        if force:
237
 
                            osutils.rmtree(abs_path)
238
 
                            message = "deleted %s" % (f,)
239
 
                        else:
240
 
                            message = backup(f)
241
 
                    else:
242
 
                        if not keep_files:
243
 
                            osutils.delete_any(abs_path)
244
 
                            message = "deleted %s" % (f,)
245
 
 
246
 
            # print only one message (if any) per file.
247
 
            if message is not None:
248
 
                trace.note(message)
249
 
 
250
 
    def _add(self, files, ids, kinds):
251
 
        for (path, file_id, kind) in zip(files, ids, kinds):
252
 
            if file_id is not None:
253
 
                self._fileid_map.set_file_id(path.encode("utf-8"), file_id)
254
 
            else:
255
 
                file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
256
 
            self._index_add_entry(path, file_id, kind)
257
 
 
258
 
    def smart_add(self, file_list, recurse=True, action=None, save=True):
259
 
        added = []
260
 
        ignored = {}
261
 
        user_dirs = []
262
 
        for filepath in osutils.canonical_relpaths(self.basedir, file_list):
263
 
            if action is not None:
264
 
                file_id = action()
265
 
            else:
266
 
                file_id = None
267
 
            abspath = self.abspath(filepath)
268
 
            kind = osutils.file_kind(abspath)
269
 
            if kind in ("file", "symlink"):
270
 
                if not save:
271
 
                    self._index_add_entry(filepath, file_id, kind)
272
 
                added.append(filepath)
273
 
            elif kind == "directory":
274
 
                if recurse:
275
 
                    user_dirs.append(filepath)
276
 
            else:
277
 
                raise errors.BadFileKindError(filename=abspath, kind=kind)
278
 
        for user_dir in user_dirs:
279
 
            abs_user_dir = self.abspath(user_dir)
280
 
            for name in os.listdir(abs_user_dir):
281
 
                subp = os.path.join(user_dir, name)
282
 
                if self.is_control_filename(subp):
283
 
                    trace.mutter("skip control directory %r", subp)
284
 
                ignore_glob = self.is_ignored(subp)
285
 
                if ignore_glob is not None:
286
 
                    ignored.setdefault(ignore_glob, []).append(subp)
287
 
                    continue
288
 
                abspath = self.abspath(subp)
289
 
                kind = osutils.file_kind(abspath)
290
 
                if kind == "directory":
291
 
                    user_dirs.append(subp)
292
 
                else:
293
 
                    if action is not None:
294
 
                        file_id = action()
295
 
                    else:
296
 
                        file_id = None
297
 
                    if not save:
298
 
                        self._index_add_entry(subp, file_id, kind)
299
 
        return added, ignored
300
 
 
301
 
    def _set_root_id(self, file_id):
302
 
        self._fileid_map.set_file_id("", file_id)
303
 
 
304
 
    def move(self, from_paths, to_dir=None, after=False):
305
 
        rename_tuples = []
306
 
        to_abs = self.abspath(to_dir)
307
 
        if not os.path.isdir(to_abs):
308
 
            raise errors.BzrMoveFailedError('', to_dir,
309
 
                errors.NotADirectory(to_abs))
310
 
 
311
 
        for from_rel in from_paths:
312
 
            from_tail = os.path.split(from_rel)[-1]
313
 
            to_rel = os.path.join(to_dir, from_tail)
314
 
            self.rename_one(from_rel, to_rel, after=after)
315
 
            rename_tuples.append((from_rel, to_rel))
316
 
        return rename_tuples
317
 
 
318
 
    def rename_one(self, from_rel, to_rel, after=False):
319
 
        if not after:
320
 
            os.rename(self.abspath(from_rel), self.abspath(to_rel))
321
 
        from_path = from_rel.encode("utf-8")
322
 
        to_path = to_rel.encode("utf-8")
323
 
        if not self.has_filename(to_rel):
324
 
            raise errors.BzrMoveFailedError(from_rel, to_rel,
325
 
                errors.NoSuchFile(to_rel))
326
 
        if not from_path in self.index:
327
 
            raise errors.BzrMoveFailedError(from_rel, to_rel,
328
 
                errors.NotVersionedError(path=from_rel))
329
 
        self.index[to_path] = self.index[from_path]
330
 
        del self.index[from_path]
331
 
 
332
 
    def get_root_id(self):
333
 
        return self.path2id("")
334
 
 
335
 
    def _has_dir(self, path):
336
 
        if self._versioned_dirs is None:
337
 
            self._load_dirs()
338
 
        return path in self._versioned_dirs
339
 
 
340
 
    @needs_read_lock
341
 
    def path2id(self, path):
342
 
        encoded_path = path.encode("utf-8")
343
 
        if self._is_versioned(encoded_path):
344
 
            return self._fileid_map.lookup_file_id(encoded_path)
345
 
        return None
346
88
 
347
89
    def extras(self):
348
90
        """Yield all unversioned files in this WorkingTree.
352
94
                continue
353
95
            for filename in filenames:
354
96
                relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
355
 
                if not self._is_versioned(relpath):
 
97
                if not relpath in self.index:
356
98
                    yield relpath
357
99
 
 
100
 
358
101
    def unlock(self):
359
102
        # non-implementation specific cleanup
360
103
        self._cleanup()
365
108
        finally:
366
109
            self.branch.unlock()
367
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
 
368
149
    def flush(self):
369
150
        # TODO: Maybe this should only write on dirty ?
370
151
        if self._control_files._lock_mode != 'w':
371
152
            raise errors.NotWriteLocked(self)
 
153
        self._rewrite_index()
372
154
        self.index.write()
373
 
 
374
 
    def __iter__(self):
375
 
        for path in self.index:
376
 
            yield self.path2id(path)
377
 
        self._load_dirs()
378
 
        for path in self._versioned_dirs:
379
 
            yield self.path2id(path)
380
 
 
381
 
    def has_or_had_id(self, file_id):
382
 
        if self.has_id(file_id):
383
 
            return True
384
 
        if self.had_id(file_id):
385
 
            return True
386
 
        return False
387
 
 
388
 
    def had_id(self, file_id):
389
 
        path = self._basis_fileid_map.lookup_file_id(file_id)
390
 
        try:
391
 
            head = self.repository._git.head()
392
 
        except KeyError:
393
 
            # Assume no if basis is not accessible
394
 
            return False
395
 
        if head == ZERO_SHA:
396
 
            return False
397
 
        root_tree = self.store[head].tree
398
 
        try:
399
 
            tree_lookup_path(self.store.__getitem__, root_tree, path)
400
 
        except KeyError:
401
 
            return False
402
 
        else:
403
 
            return True
404
 
 
405
 
    def has_id(self, file_id):
406
 
        try:
407
 
            self.id2path(file_id)
408
 
        except errors.NoSuchId:
409
 
            return False
410
 
        else:
411
 
            return True
412
 
 
413
 
    def id2path(self, file_id):
414
 
        if type(file_id) != str:
415
 
            raise AssertionError
416
 
        path = self._fileid_map.lookup_path(file_id)
417
 
        # FIXME: What about directories?
418
 
        if self._is_versioned(path):
419
 
            return path.decode("utf-8")
420
 
        raise errors.NoSuchId(self, file_id)
421
 
 
422
 
    def get_file_mtime(self, file_id, path=None):
423
 
        """See Tree.get_file_mtime."""
424
 
        if not path:
425
 
            path = self.id2path(file_id)
426
 
        return os.lstat(self.abspath(path)).st_mtime
 
155
        self._inventory_is_modified = False
427
156
 
428
157
    def get_ignore_list(self):
429
158
        ignoreset = getattr(self, '_ignoreset', None)
436
165
        if self.has_filename(IGNORE_FILENAME):
437
166
            f = self.get_file_byname(IGNORE_FILENAME)
438
167
            try:
439
 
                # FIXME: Parse git file format, rather than assuming it's
440
 
                # the same as for bzr's native formats.
441
168
                ignore_globs.update(ignores.parse_ignore_file(f))
442
169
            finally:
443
170
                f.close()
448
175
        self._change_last_revision(revid)
449
176
 
450
177
    def _reset_data(self):
 
178
        self._inventory_is_modified = False
451
179
        try:
452
180
            head = self.repository._git.head()
453
181
        except KeyError, name:
454
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
455
185
        if head == ZERO_SHA:
456
 
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
 
186
            fileid_map = GitFileIdMap({}, self.mapping)
 
187
            basis_inv = None
457
188
        else:
458
 
            self._basis_fileid_map = self.mapping.get_fileid_map(self.store.__getitem__,
459
 
                self.store[head].tree)
 
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)
460
193
 
461
194
    @needs_read_lock
462
195
    def get_file_sha1(self, file_id, path=None, stat_value=None):
463
196
        if not path:
464
 
            path = self.id2path(file_id)
 
197
            path = self._inventory.id2path(file_id)
465
198
        try:
466
199
            return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
467
200
        except OSError, (num, msg):
472
205
    def revision_tree(self, revid):
473
206
        return self.repository.revision_tree(revid)
474
207
 
475
 
    def _is_versioned(self, path):
476
 
        return (path in self.index or self._has_dir(path))
477
 
 
478
 
    def filter_unversioned_files(self, files):
479
 
        return set([p for p in files if self._is_versioned(p.encode("utf-8"))])
480
 
 
481
 
    def _get_dir_ie(self, path, parent_id):
482
 
        file_id = self.path2id(path)
483
 
        return inventory.InventoryDirectory(file_id,
484
 
            posixpath.basename(path).strip("/"), parent_id)
485
 
 
486
 
    def _add_missing_parent_ids(self, path, dir_ids):
487
 
        if path in dir_ids:
488
 
            return []
489
 
        parent = posixpath.dirname(path).strip("/")
490
 
        ret = self._add_missing_parent_ids(parent, dir_ids)
491
 
        parent_id = dir_ids[parent]
492
 
        ie = self._get_dir_ie(path, parent_id)
493
 
        dir_ids[path] = ie.file_id
494
 
        ret.append((path, ie))
495
 
        return ret
496
 
 
497
 
    def _get_file_ie(self, path, value, parent_id):
498
 
        assert isinstance(path, unicode)
499
 
        assert isinstance(value, tuple) and len(value) == 10
500
 
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
501
 
        file_id = self.path2id(path)
502
 
        if type(file_id) != str:
503
 
            raise AssertionError
504
 
        kind = mode_kind(mode)
505
 
        ie = inventory.entry_factory[kind](file_id,
506
 
            posixpath.basename(path), parent_id)
507
 
        if kind == 'symlink':
508
 
            ie.symlink_target = self.get_symlink_target(file_id)
509
 
        else:
510
 
            data = self.get_file_text(file_id, path)
511
 
            ie.text_sha1 = osutils.sha_string(data)
512
 
            ie.text_size = len(data)
513
 
            ie.executable = self.is_executable(file_id, path)
514
 
        ie.revision = None
515
 
        return ie
516
 
 
517
 
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
518
 
        mode = stat_result.st_mode
519
 
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
520
 
 
521
 
    def stored_kind(self, file_id, path=None):
522
 
        if path is None:
523
 
            path = self.id2path(file_id)
524
 
        head = self.repository._git.head()
525
 
        if head == ZERO_SHA:
526
 
            raise errors.NoSuchId(self, file_id)
527
 
        root_tree = self.store[head].tree
528
 
        (mode, hexsha) = tree_lookup_path(self.store.__getitem__, root_tree, path)
529
 
        return mode_kind(mode)
530
 
 
531
 
    if not osutils.supports_executable():
532
 
        def is_executable(self, file_id, path=None):
533
 
            basis_tree = self.basis_tree()
534
 
            if file_id in basis_tree:
535
 
                return basis_tree.is_executable(file_id)
536
 
            # Default to not executable
537
 
            return False
538
 
    else:
539
 
        def is_executable(self, file_id, path=None):
540
 
            if not path:
541
 
                path = self.id2path(file_id)
542
 
            mode = os.lstat(self.abspath(path)).st_mode
543
 
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
544
 
 
545
 
        _is_executable_from_path_and_stat = \
546
 
            _is_executable_from_path_and_stat_from_stat
547
 
 
548
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
549
 
        # FIXME: Yield non-versioned files
550
 
        # FIXME: support from_dir
551
 
        # FIXME: Support recursive
552
 
        dir_ids = {}
553
 
        root_ie = self._get_dir_ie(u"", None)
554
 
        if include_root and not from_dir:
555
 
            yield "", "V", root_ie.kind, root_ie.file_id, root_ie
556
 
        dir_ids[u""] = root_ie.file_id
557
 
        for path, value in self.index.iteritems():
558
 
            path = path.decode("utf-8")
559
 
            parent = posixpath.dirname(path).strip("/")
560
 
            for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
561
 
                yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
562
 
            ie = self._get_file_ie(path, value, dir_ids[parent])
563
 
            yield path, "V", ie.kind, ie.file_id, ie
564
 
 
565
 
    def all_file_ids(self):
566
 
        ids = {u"": self.path2id("")}
567
 
        for path in self.index:
568
 
            path = path.decode("utf-8")
569
 
            parent = posixpath.dirname(path).strip("/")
570
 
            for e in self._add_missing_parent_ids(parent, ids):
571
 
                pass
572
 
            ids[path] = self.path2id(path)
573
 
        return set(ids.values())
574
 
 
575
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
576
 
        # FIXME: Is return order correct?
577
 
        if yield_parents:
578
 
            raise NotImplementedError(self.iter_entries_by_dir)
579
 
        if specific_file_ids is not None:
580
 
            specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
581
 
            if specific_paths in ([u""], []):
582
 
                specific_paths = None
583
 
            else:
584
 
                specific_paths = set(specific_paths)
585
 
        else:
586
 
            specific_paths = None
587
 
        root_ie = self._get_dir_ie(u"", None)
588
 
        if specific_paths is None:
589
 
            yield u"", root_ie
590
 
        dir_ids = {u"": root_ie.file_id}
591
 
        for path, value in self.index.iteritems():
592
 
            path = path.decode("utf-8")
593
 
            if specific_paths is not None and not path in specific_paths:
594
 
                continue
595
 
            try:
596
 
                file_ie = self._get_file_ie(path, value, None)
597
 
            except IOError:
598
 
                continue
599
 
            parent = posixpath.dirname(path).strip("/")
600
 
            for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
601
 
                    dir_ids):
602
 
                yield dir_path, dir_ie
603
 
            file_ie.parent_id = self.path2id(parent)
604
 
            yield path, file_ie
605
 
 
606
208
    @needs_read_lock
607
209
    def conflicts(self):
608
210
        # FIXME:
609
 
        return _mod_conflicts.ConflictList()
610
 
 
611
 
    def update_basis_by_delta(self, new_revid, delta):
612
 
        # The index just contains content, which won't have changed.
613
 
        self._reset_data()
614
 
 
615
 
    def _walkdirs(self, prefix=""):
616
 
        if prefix != "":
617
 
            prefix += "/"
618
 
        per_dir = defaultdict(list)
619
 
        for path, value in self.index.iteritems():
620
 
            if not path.startswith(prefix):
621
 
                continue
622
 
            (dirname, child_name) = posixpath.split(path)
623
 
            dirname = dirname.decode("utf-8")
624
 
            dir_file_id = self.path2id(dirname)
625
 
            assert isinstance(value, tuple) and len(value) == 10
626
 
            (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
627
 
            stat_result = posix.stat_result((mode, ino,
628
 
                    dev, 1, uid, gid, size,
629
 
                    0, mtime, ctime))
630
 
            per_dir[(dirname, dir_file_id)].append(
631
 
                (path.decode("utf-8"), child_name.decode("utf-8"),
632
 
                mode_kind(mode), stat_result,
633
 
                self.path2id(path.decode("utf-8")),
634
 
                mode_kind(mode)))
635
 
        return per_dir.iteritems()
 
211
        return []
 
212
 
636
213
 
637
214
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
638
215
 
639
 
    _tree_class = GitWorkingTree
640
 
 
641
216
    @property
642
217
    def _matchingbzrdir(self):
643
 
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
218
        from bzrlib.plugins.git import LocalGitControlDirFormat
644
219
        return LocalGitControlDirFormat()
645
220
 
646
221
    def get_format_description(self):
647
222
        return "Git Working Tree"
648
223
 
649
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
650
 
                   accelerator_tree=None, hardlink=False):
651
 
        """See WorkingTreeFormat.initialize()."""
652
 
        if not isinstance(a_bzrdir, LocalGitDir):
653
 
            raise errors.IncompatibleFormat(self, a_bzrdir)
654
 
        index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
655
 
        index.write()
656
 
        return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
657
 
            a_bzrdir.open_branch(), index)
658
 
 
659
224
 
660
225
class InterIndexGitTree(tree.InterTree):
661
226
    """InterTree that works between a Git revision tree and an index."""
674
239
                extra_trees=None, require_versioned=False, include_root=False,
675
240
                want_unversioned=False):
676
241
        changes = self._index.changes_from_tree(
677
 
            self.source.store, self.source.tree, 
 
242
            self.source._repository._git.object_store, self.source.tree, 
678
243
            want_unchanged=want_unchanged)
679
244
        source_fileid_map = self.source.mapping.get_fileid_map(
680
 
            self.source.store.__getitem__,
 
245
            self.source._repository._git.object_store.__getitem__,
681
246
            self.source.tree)
682
247
        if self.target.mapping.BZR_FILE_IDS_FILE is not None:
683
248
            file_id = self.target.path2id(
685
250
            if file_id is None:
686
251
                target_fileid_map = {}
687
252
            else:
688
 
                target_fileid_map = self.target.mapping.import_fileid_map(
689
 
                    Blob.from_string(self.target.get_file_text(file_id)))
 
253
                target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
690
254
        else:
691
255
            target_fileid_map = {}
692
 
        target_fileid_map = GitFileIdMap(target_fileid_map,
693
 
                self.target.mapping)
 
256
        target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
694
257
        ret = tree_delta_from_git_changes(changes, self.target.mapping,
695
258
            (source_fileid_map, target_fileid_map),
696
259
            specific_file=specific_files, require_versioned=require_versioned)
697
260
        if want_unversioned:
698
261
            for e in self.target.extras():
699
 
                ret.unversioned.append((e, None,
700
 
                    osutils.file_kind(self.target.abspath(e))))
 
262
                ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
701
263
        return ret
702
264
 
703
265
    def iter_changes(self, include_unchanged=False, specific_files=None,
704
 
        pb=None, extra_trees=[], require_versioned=True,
705
 
        want_unversioned=False):
 
266
        pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
706
267
        changes = self._index.changes_from_tree(
707
 
            self.source.store, self.source.tree,
 
268
            self.source._repository._git.object_store, self.source.tree, 
708
269
            want_unchanged=include_unchanged)
709
270
        # FIXME: Handle want_unversioned
710
 
        return changes_from_git_changes(changes, self.target.mapping,
 
271
        return changes_from_git_changes(changes, self.target.mapping, 
711
272
            specific_file=specific_files)
712
273
 
713
 
 
714
274
tree.InterTree.register_optimiser(InterIndexGitTree)