/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to workingtree.py

More fixes for compatibility with bzr.dev testsuite.

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