/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

UseĀ peeling.

Show diffs side-by-side

added added

removed removed

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