/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 colocated branch support.

Show diffs side-by-side

added added

removed removed

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