/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

Simplify push handling.

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