/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

Fix revision_history test when no DeprecationWarning is printed and bzr 2.5
is used.

Older prereleases of bzr 2.5 didn't deprecate Branch.revision_history.

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