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
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
351
if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
353
for filename in filenames:
354
relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
355
if not self._is_versioned(relpath):
359
# non-implementation specific cleanup
362
# reverse order of locking.
364
return self._control_files.unlock()
369
# TODO: Maybe this should only write on dirty ?
370
if self._control_files._lock_mode != 'w':
371
raise errors.NotWriteLocked(self)
375
for path in self.index:
376
yield self.path2id(path)
378
for path in self._versioned_dirs:
379
yield self.path2id(path)
381
def has_or_had_id(self, file_id):
382
if self.has_id(file_id):
384
if self.had_id(file_id):
388
def had_id(self, file_id):
389
path = self._basis_fileid_map.lookup_file_id(file_id)
391
head = self.repository._git.head()
393
# Assume no if basis is not accessible
397
root_tree = self.store[head].tree
399
tree_lookup_path(self.store.__getitem__, root_tree, path)
405
def has_id(self, file_id):
407
self.id2path(file_id)
408
except errors.NoSuchId:
413
def id2path(self, file_id):
414
if type(file_id) != str:
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)
422
def get_file_mtime(self, file_id, path=None):
423
"""See Tree.get_file_mtime."""
425
path = self.id2path(file_id)
426
return os.lstat(self.abspath(path)).st_mtime
428
def get_ignore_list(self):
429
ignoreset = getattr(self, '_ignoreset', None)
430
if ignoreset is not None:
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)
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))
444
self._ignoreset = ignore_globs
447
def set_last_revision(self, revid):
448
self._change_last_revision(revid)
450
def _reset_data(self):
452
head = self.repository._git.head()
453
except KeyError, name:
454
raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
456
self._basis_fileid_map = GitFileIdMap({}, self.mapping)
458
self._basis_fileid_map = self.mapping.get_fileid_map(self.store.__getitem__,
459
self.store[head].tree)
462
def get_file_sha1(self, file_id, path=None, stat_value=None):
464
path = self.id2path(file_id)
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):
472
def revision_tree(self, revid):
473
return self.repository.revision_tree(revid)
475
def _is_versioned(self, path):
476
return (path in self.index or self._has_dir(path))
478
def filter_unversioned_files(self, files):
479
return set([p for p in files if self._is_versioned(p.encode("utf-8"))])
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)
486
def _add_missing_parent_ids(self, path, dir_ids):
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))
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:
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)
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)
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)
521
def stored_kind(self, file_id, path=None):
523
path = self.id2path(file_id)
524
head = self.repository._git.head()
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)
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
539
def is_executable(self, file_id, path=None):
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)
545
_is_executable_from_path_and_stat = \
546
_is_executable_from_path_and_stat_from_stat
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
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
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):
572
ids[path] = self.path2id(path)
573
return set(ids.values())
575
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
576
# FIXME: Is return order correct?
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
584
specific_paths = set(specific_paths)
586
specific_paths = None
587
root_ie = self._get_dir_ie(u"", None)
588
if specific_paths is None:
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:
596
file_ie = self._get_file_ie(path, value, None)
599
parent = posixpath.dirname(path).strip("/")
600
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
602
yield dir_path, dir_ie
603
file_ie.parent_id = self.path2id(parent)
609
return _mod_conflicts.ConflictList()
611
def update_basis_by_delta(self, new_revid, delta):
612
# The index just contains content, which won't have changed.
615
def _walkdirs(self, prefix=""):
618
per_dir = defaultdict(list)
619
for path, value in self.index.iteritems():
620
if not path.startswith(prefix):
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,
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")),
635
return per_dir.iteritems()
637
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
639
_tree_class = GitWorkingTree
641
supports_versioned_directories = False
644
def _matchingbzrdir(self):
645
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
646
return LocalGitControlDirFormat()
648
def get_format_description(self):
649
return "Git Working Tree"
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"))
658
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
659
a_bzrdir.open_branch(), index)
662
class InterIndexGitTree(tree.InterTree):
663
"""InterTree that works between a Git revision tree and an index."""
665
def __init__(self, source, target):
666
super(InterIndexGitTree, self).__init__(source, target)
667
self._index = target.index
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))
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__,
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)
688
target_fileid_map = {}
690
target_fileid_map = self.target.mapping.import_fileid_map(
691
Blob.from_string(self.target.get_file_text(file_id)))
693
target_fileid_map = {}
694
target_fileid_map = GitFileIdMap(target_fileid_map,
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)
700
for e in self.target.extras():
701
ret.unversioned.append((e, None,
702
osutils.file_kind(self.target.abspath(e))))
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)
716
tree.InterTree.register_optimiser(InterIndexGitTree)