/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 compatibility with newer versions of dulwich.

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