1
# Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
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.
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.
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
18
"""An adapter between a Git index and a Bazaar Working Tree"""
21
from cStringIO import (
24
from collections import defaultdict
26
from dulwich.index import (
29
from dulwich.object_store import (
32
from dulwich.objects import (
44
conflicts as _mod_conflicts,
55
from bzrlib.decorators import (
60
from bzrlib.plugins.git.dir import (
63
from bzrlib.plugins.git.tree import (
64
changes_from_git_changes,
65
tree_delta_from_git_changes,
67
from bzrlib.plugins.git.mapping import (
72
IGNORE_FILENAME = ".gitignore"
75
class GitWorkingTree(workingtree.WorkingTree):
76
"""A Git working tree."""
78
def __init__(self, bzrdir, repo, branch, index):
79
self.basedir = bzrdir.root_transport.local_abspath('.')
81
self.repository = repo
82
self.store = self.repository._git.object_store
83
self.mapping = self.repository.get_mapping()
85
self._transport = bzrdir.transport
87
self.controldir = self.bzrdir.transport.local_abspath('bzr')
90
os.makedirs(self.controldir)
91
os.makedirs(os.path.join(self.controldir, 'lock'))
95
self._control_files = lockable_files.LockableFiles(
96
transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
97
self._format = GitWorkingTreeFormat()
99
self._versioned_dirs = None
100
self.views = self._make_views()
101
self._rules_searcher = None
102
self._detect_case_handling()
104
self._fileid_map = self._basis_fileid_map.copy()
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])
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
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
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":
128
stat_val = os.lstat(self.abspath(path))
129
except (errors.NoSuchFile, OSError):
130
# TODO: Rather than come up with something here, use the
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"))
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
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)
150
def _ensure_versioned_dir(self, dirname):
151
if dirname in self._versioned_dirs:
154
self._ensure_versioned_dir(posixpath.dirname(dirname))
155
self._versioned_dirs.add(dirname)
157
def _load_dirs(self):
158
self._versioned_dirs = set()
160
self._ensure_versioned_dir(posixpath.dirname(p))
162
def _unversion_path(self, path):
163
encoded_path = path.encode("utf-8")
165
del self.index[encoded_path]
167
# A directory, perhaps?
168
for p in list(self.index):
169
if p.startswith(encoded_path+"/"):
171
# FIXME: remove empty directories
173
def unversion(self, file_ids):
174
for file_id in file_ids:
175
path = self.id2path(file_id)
176
self._unversion_path(path)
178
def check_state(self):
179
"""Check that the working state is/isn't valid."""
182
def remove(self, files, verbose=False, to_file=None, keep_files=True,
184
"""Remove nominated files from the working tree metadata.
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.
191
all_files = set() # specified and nested files
193
if isinstance(files, basestring):
199
files = list(all_files)
202
return # nothing to do
204
# Sort needed to first handle directory content before the directory
205
files.sort(reverse=True)
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)
215
fid = self.path2id(f)
217
message = "%s is not versioned." % (f,)
219
abs_path = self.abspath(f)
221
# having removed it, it must be either ignored or unknown
222
if self.is_ignored(f):
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')
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):
237
osutils.rmtree(abs_path)
238
message = "deleted %s" % (f,)
243
osutils.delete_any(abs_path)
244
message = "deleted %s" % (f,)
246
# print only one message (if any) per file.
247
if message is not None:
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)
255
file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
256
self._index_add_entry(path, file_id, kind)
258
def smart_add(self, file_list, recurse=True, action=None, save=True):
262
for filepath in osutils.canonical_relpaths(self.basedir, file_list):
263
if action is not None:
267
abspath = self.abspath(filepath)
268
kind = osutils.file_kind(abspath)
269
if kind in ("file", "symlink"):
271
self._index_add_entry(filepath, file_id, kind)
272
added.append(filepath)
273
elif kind == "directory":
275
user_dirs.append(filepath)
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):
284
ignore_glob = self.is_ignored(subp)
285
if ignore_glob is not None:
286
ignored.setdefault(ignore_glob, []).append(subp)
288
abspath = self.abspath(subp)
289
kind = osutils.file_kind(abspath)
290
if kind == "directory":
291
user_dirs.append(subp)
293
if action is not None:
298
self._index_add_entry(subp, file_id, kind)
299
return added, ignored
301
def _set_root_id(self, file_id):
302
self._fileid_map.set_file_id("", file_id)
304
def move(self, from_paths, to_dir=None, after=False):
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))
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))
318
def rename_one(self, from_rel, to_rel, after=False):
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]
332
def get_root_id(self):
333
return self.path2id("")
335
def _has_dir(self, path):
336
if self._versioned_dirs is None:
338
return path in self._versioned_dirs
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)
348
"""Yield all unversioned files in this WorkingTree.
350
present_files = set()
351
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
352
dir_relpath = dirpath[len(self.basedir):].strip("/")
353
if self.bzrdir.is_control_filename(dir_relpath):
355
for filename in filenames:
356
relpath = os.path.join(dir_relpath, filename)
357
present_files.add(relpath)
358
return present_files - set(self.index)
361
# non-implementation specific cleanup
364
# reverse order of locking.
366
return self._control_files.unlock()
371
# TODO: Maybe this should only write on dirty ?
372
if self._control_files._lock_mode != 'w':
373
raise errors.NotWriteLocked(self)
377
for path in self.index:
378
yield self.path2id(path)
380
for path in self._versioned_dirs:
381
yield self.path2id(path)
383
def has_or_had_id(self, file_id):
384
if self.has_id(file_id):
386
if self.had_id(file_id):
390
def had_id(self, file_id):
391
path = self._basis_fileid_map.lookup_file_id(file_id)
393
head = self.repository._git.head()
395
# Assume no if basis is not accessible
399
root_tree = self.store[head].tree
401
tree_lookup_path(self.store.__getitem__, root_tree, path)
407
def has_id(self, file_id):
409
self.id2path(file_id)
410
except errors.NoSuchId:
415
def id2path(self, file_id):
416
if type(file_id) != str:
418
path = self._fileid_map.lookup_path(file_id)
419
# FIXME: What about directories?
420
if self._is_versioned(path):
421
return path.decode("utf-8")
422
raise errors.NoSuchId(self, file_id)
424
def get_file_mtime(self, file_id, path=None):
425
"""See Tree.get_file_mtime."""
427
path = self.id2path(file_id)
428
return os.lstat(self.abspath(path)).st_mtime
430
def get_ignore_list(self):
431
ignoreset = getattr(self, '_ignoreset', None)
432
if ignoreset is not None:
436
ignore_globs.update(ignores.get_runtime_ignores())
437
ignore_globs.update(ignores.get_user_ignores())
438
if self.has_filename(IGNORE_FILENAME):
439
f = self.get_file_byname(IGNORE_FILENAME)
441
# FIXME: Parse git file format, rather than assuming it's
442
# the same as for bzr's native formats.
443
ignore_globs.update(ignores.parse_ignore_file(f))
446
self._ignoreset = ignore_globs
449
def set_last_revision(self, revid):
450
self._change_last_revision(revid)
452
def _reset_data(self):
454
head = self.repository._git.head()
455
except KeyError, name:
456
raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
458
self._basis_fileid_map = GitFileIdMap({}, self.mapping)
460
self._basis_fileid_map = self.mapping.get_fileid_map(self.store.__getitem__,
461
self.store[head].tree)
464
def get_file_verifier(self, file_id, path=None, stat_value=None):
466
path = self.id2path(file_id)
467
return ("GIT", self.index[path][-2])
470
def get_file_sha1(self, file_id, path=None, stat_value=None):
472
path = self.id2path(file_id)
473
abspath = self.abspath(path).encode(osutils._fs_enc)
475
return osutils.sha_file_by_name(abspath)
476
except OSError, (num, msg):
477
if num in (errno.EISDIR, errno.ENOENT):
481
def revision_tree(self, revid):
482
return self.repository.revision_tree(revid)
484
def _is_versioned(self, path):
485
return (path in self.index or self._has_dir(path))
487
def filter_unversioned_files(self, files):
488
return set([p for p in files if self._is_versioned(p.encode("utf-8"))])
490
def _get_dir_ie(self, path, parent_id):
491
file_id = self.path2id(path)
492
return inventory.InventoryDirectory(file_id,
493
posixpath.basename(path).strip("/"), parent_id)
495
def _add_missing_parent_ids(self, path, dir_ids):
498
parent = posixpath.dirname(path).strip("/")
499
ret = self._add_missing_parent_ids(parent, dir_ids)
500
parent_id = dir_ids[parent]
501
ie = self._get_dir_ie(path, parent_id)
502
dir_ids[path] = ie.file_id
503
ret.append((path, ie))
506
def _get_file_ie(self, path, value, parent_id):
507
assert isinstance(path, unicode)
508
assert isinstance(value, tuple) and len(value) == 10
509
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
510
file_id = self.path2id(path)
511
if type(file_id) != str:
513
kind = mode_kind(mode)
514
ie = inventory.entry_factory[kind](file_id,
515
posixpath.basename(path), parent_id)
516
if kind == 'symlink':
517
ie.symlink_target = self.get_symlink_target(file_id)
519
data = self.get_file_text(file_id, path)
520
ie.text_sha1 = osutils.sha_string(data)
521
ie.text_size = len(data)
522
ie.executable = self.is_executable(file_id, path)
526
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
527
mode = stat_result.st_mode
528
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
530
def stored_kind(self, file_id, path=None):
532
path = self.id2path(file_id)
533
head = self.repository._git.head()
535
raise errors.NoSuchId(self, file_id)
536
root_tree = self.store[head].tree
537
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, root_tree, path)
538
return mode_kind(mode)
540
if not osutils.supports_executable():
541
def is_executable(self, file_id, path=None):
542
basis_tree = self.basis_tree()
543
if file_id in basis_tree:
544
return basis_tree.is_executable(file_id)
545
# Default to not executable
548
def is_executable(self, file_id, path=None):
550
path = self.id2path(file_id)
551
mode = os.lstat(self.abspath(path)).st_mode
552
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
554
_is_executable_from_path_and_stat = \
555
_is_executable_from_path_and_stat_from_stat
557
def list_files(self, include_root=False, from_dir=None, recursive=True):
558
# FIXME: Yield non-versioned files
559
# FIXME: support from_dir
560
# FIXME: Support recursive
562
root_ie = self._get_dir_ie(u"", None)
563
if include_root and not from_dir:
564
yield "", "V", root_ie.kind, root_ie.file_id, root_ie
565
dir_ids[u""] = root_ie.file_id
566
for path, value in self.index.iteritems():
567
path = path.decode("utf-8")
568
parent = posixpath.dirname(path).strip("/")
569
for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
570
yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
571
ie = self._get_file_ie(path, value, dir_ids[parent])
572
yield path, "V", ie.kind, ie.file_id, ie
574
def all_file_ids(self):
575
ids = {u"": self.path2id("")}
576
for path in self.index:
577
path = path.decode("utf-8")
578
parent = posixpath.dirname(path).strip("/")
579
for e in self._add_missing_parent_ids(parent, ids):
581
ids[path] = self.path2id(path)
582
return set(ids.values())
584
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
585
# FIXME: Is return order correct?
587
raise NotImplementedError(self.iter_entries_by_dir)
588
if specific_file_ids is not None:
589
specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
590
if specific_paths in ([u""], []):
591
specific_paths = None
593
specific_paths = set(specific_paths)
595
specific_paths = None
596
root_ie = self._get_dir_ie(u"", None)
597
if specific_paths is None:
599
dir_ids = {u"": root_ie.file_id}
600
for path, value in self.index.iteritems():
601
path = path.decode("utf-8")
602
if specific_paths is not None and not path in specific_paths:
605
file_ie = self._get_file_ie(path, value, None)
608
parent = posixpath.dirname(path).strip("/")
609
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
611
yield dir_path, dir_ie
612
file_ie.parent_id = self.path2id(parent)
618
return _mod_conflicts.ConflictList()
620
def update_basis_by_delta(self, new_revid, delta):
621
# The index just contains content, which won't have changed.
624
def _walkdirs(self, prefix=""):
627
per_dir = defaultdict(list)
628
for path, value in self.index.iteritems():
629
if not path.startswith(prefix):
631
(dirname, child_name) = posixpath.split(path)
632
dirname = dirname.decode("utf-8")
633
dir_file_id = self.path2id(dirname)
634
assert isinstance(value, tuple) and len(value) == 10
635
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
636
stat_result = posix.stat_result((mode, ino,
637
dev, 1, uid, gid, size,
639
per_dir[(dirname, dir_file_id)].append(
640
(path.decode("utf-8"), child_name.decode("utf-8"),
641
mode_kind(mode), stat_result,
642
self.path2id(path.decode("utf-8")),
644
return per_dir.iteritems()
646
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
648
_tree_class = GitWorkingTree
650
supports_versioned_directories = False
653
def _matchingbzrdir(self):
654
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
655
return LocalGitControlDirFormat()
657
def get_format_description(self):
658
return "Git Working Tree"
660
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
661
accelerator_tree=None, hardlink=False):
662
"""See WorkingTreeFormat.initialize()."""
663
if not isinstance(a_bzrdir, LocalGitDir):
664
raise errors.IncompatibleFormat(self, a_bzrdir)
665
index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
667
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
668
a_bzrdir.open_branch(), index)
671
class InterIndexGitTree(tree.InterTree):
672
"""InterTree that works between a Git revision tree and an index."""
674
def __init__(self, source, target):
675
super(InterIndexGitTree, self).__init__(source, target)
676
self._index = target.index
679
def is_compatible(cls, source, target):
680
from bzrlib.plugins.git.repository import GitRevisionTree
681
return (isinstance(source, GitRevisionTree) and
682
isinstance(target, GitWorkingTree))
684
def compare(self, want_unchanged=False, specific_files=None,
685
extra_trees=None, require_versioned=False, include_root=False,
686
want_unversioned=False):
687
changes = self._index.changes_from_tree(
688
self.source.store, self.source.tree,
689
want_unchanged=want_unchanged)
690
source_fileid_map = self.source.mapping.get_fileid_map(
691
self.source.store.__getitem__,
693
if self.target.mapping.BZR_FILE_IDS_FILE is not None:
694
file_id = self.target.path2id(
695
self.target.mapping.BZR_FILE_IDS_FILE)
697
target_fileid_map = {}
699
target_fileid_map = self.target.mapping.import_fileid_map(
700
Blob.from_string(self.target.get_file_text(file_id)))
702
target_fileid_map = {}
703
target_fileid_map = GitFileIdMap(target_fileid_map,
705
ret = tree_delta_from_git_changes(changes, self.target.mapping,
706
(source_fileid_map, target_fileid_map),
707
specific_file=specific_files, require_versioned=require_versioned)
709
for e in self.target.extras():
710
ret.unversioned.append((e, None,
711
osutils.file_kind(self.target.abspath(e))))
714
def iter_changes(self, include_unchanged=False, specific_files=None,
715
pb=None, extra_trees=[], require_versioned=True,
716
want_unversioned=False):
717
changes = self._index.changes_from_tree(
718
self.source.store, self.source.tree,
719
want_unchanged=include_unchanged)
720
# FIXME: Handle want_unversioned
721
return changes_from_git_changes(changes, self.target.mapping,
722
specific_file=specific_files)
725
tree.InterTree.register_optimiser(InterIndexGitTree)