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 (
58
from bzrlib.mutabletree import needs_tree_write_lock
61
from bzrlib.plugins.git.dir import (
64
from bzrlib.plugins.git.tree import (
65
changes_from_git_changes,
66
tree_delta_from_git_changes,
68
from bzrlib.plugins.git.mapping import (
73
IGNORE_FILENAME = ".gitignore"
76
class GitWorkingTree(workingtree.WorkingTree):
77
"""A Git working tree."""
79
def __init__(self, bzrdir, repo, branch, index):
80
self.basedir = bzrdir.root_transport.local_abspath('.')
82
self.repository = repo
83
self.store = self.repository._git.object_store
84
self.mapping = self.repository.get_mapping()
86
self._transport = bzrdir.transport
88
self.controldir = self.bzrdir.transport.local_abspath('bzr')
91
os.makedirs(self.controldir)
92
os.makedirs(os.path.join(self.controldir, 'lock'))
96
self._control_files = lockable_files.LockableFiles(
97
transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
98
self._format = GitWorkingTreeFormat()
100
self._versioned_dirs = None
101
self.views = self._make_views()
102
self._rules_searcher = None
103
self._detect_case_handling()
105
self._fileid_map = self._basis_fileid_map.copy()
107
def merge_modified(self):
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])
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
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
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":
132
stat_val = os.lstat(self.abspath(path))
133
except (errors.NoSuchFile, OSError):
134
# TODO: Rather than come up with something here, use the
136
from posix import stat_result
137
stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
139
self.get_symlink_target(file_id, path).encode("utf-8"))
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
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)
155
def _ensure_versioned_dir(self, dirname):
156
if dirname in self._versioned_dirs:
159
self._ensure_versioned_dir(posixpath.dirname(dirname))
160
self._versioned_dirs.add(dirname)
162
def _load_dirs(self):
163
self._versioned_dirs = set()
165
self._ensure_versioned_dir(posixpath.dirname(p))
167
def _unversion_path(self, path):
168
encoded_path = path.encode("utf-8")
170
del self.index[encoded_path]
172
# A directory, perhaps?
173
for p in list(self.index):
174
if p.startswith(encoded_path+"/"):
176
# FIXME: remove empty directories
178
def unversion(self, file_ids):
179
for file_id in file_ids:
180
path = self.id2path(file_id)
181
self._unversion_path(path)
183
def check_state(self):
184
"""Check that the working state is/isn't valid."""
187
def remove(self, files, verbose=False, to_file=None, keep_files=True,
189
"""Remove nominated files from the working tree metadata.
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.
196
all_files = set() # specified and nested files
198
if isinstance(files, basestring):
204
files = list(all_files)
207
return # nothing to do
209
# Sort needed to first handle directory content before the directory
210
files.sort(reverse=True)
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)
220
fid = self.path2id(f)
222
message = "%s is not versioned." % (f,)
224
abs_path = self.abspath(f)
226
# having removed it, it must be either ignored or unknown
227
if self.is_ignored(f):
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')
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):
242
osutils.rmtree(abs_path)
243
message = "deleted %s" % (f,)
248
osutils.delete_any(abs_path)
249
message = "deleted %s" % (f,)
251
# print only one message (if any) per file.
252
if message is not None:
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)
260
file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
261
self._index_add_entry(path, file_id, kind)
263
@needs_tree_write_lock
264
def smart_add(self, file_list, recurse=True, action=None, save=True):
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)
275
if kind in ("file", "symlink"):
277
self._index_add_entry(filepath, file_id, kind)
278
added.append(filepath)
279
elif kind == "directory":
281
user_dirs.append(filepath)
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):
290
ignore_glob = self.is_ignored(subp)
291
if ignore_glob is not None:
292
ignored.setdefault(ignore_glob, []).append(subp)
294
abspath = self.abspath(subp)
295
kind = osutils.file_kind(abspath)
296
if kind == "directory":
297
user_dirs.append(subp)
299
if action is not None:
304
self._index_add_entry(subp, file_id, kind)
307
return added, ignored
309
def _set_root_id(self, file_id):
310
self._fileid_map.set_file_id("", file_id)
312
@needs_tree_write_lock
313
def move(self, from_paths, to_dir=None, after=False):
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))
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))
327
@needs_tree_write_lock
328
def rename_one(self, from_rel, to_rel, after=False):
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]
342
def get_root_id(self):
343
return self.path2id("")
345
def _has_dir(self, path):
346
if self._versioned_dirs is None:
348
return path in self._versioned_dirs
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)
358
"""Yield all unversioned files in this WorkingTree.
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):
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)
371
# non-implementation specific cleanup
374
# reverse order of locking.
376
return self._control_files.unlock()
381
# TODO: Maybe this should only write on dirty ?
382
if self._control_files._lock_mode != 'w':
383
raise errors.NotWriteLocked(self)
387
for path in self.index:
388
yield self.path2id(path)
390
for path in self._versioned_dirs:
391
yield self.path2id(path)
393
def has_or_had_id(self, file_id):
394
if self.has_id(file_id):
396
if self.had_id(file_id):
400
def had_id(self, file_id):
401
path = self._basis_fileid_map.lookup_file_id(file_id)
403
head = self.repository._git.head()
405
# Assume no if basis is not accessible
409
root_tree = self.store[head].tree
411
tree_lookup_path(self.store.__getitem__, root_tree, path)
417
def has_id(self, file_id):
419
self.id2path(file_id)
420
except errors.NoSuchId:
425
def id2path(self, file_id):
426
if type(file_id) != str:
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)
434
def get_file_mtime(self, file_id, path=None):
435
"""See Tree.get_file_mtime."""
437
path = self.id2path(file_id)
438
return os.lstat(self.abspath(path)).st_mtime
440
def get_ignore_list(self):
441
ignoreset = getattr(self, '_ignoreset', None)
442
if ignoreset is not None:
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)
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))
456
self._ignoreset = ignore_globs
459
def set_last_revision(self, revid):
460
self._change_last_revision(revid)
462
def _reset_data(self):
464
head = self.repository._git.head()
465
except KeyError, name:
466
raise errors.NotBranchError("branch %s at %s" % (name,
467
self.repository.base))
469
self._basis_fileid_map = GitFileIdMap({}, self.mapping)
471
self._basis_fileid_map = self.mapping.get_fileid_map(
472
self.store.__getitem__, self.store[head].tree)
475
def get_file_verifier(self, file_id, path=None, stat_value=None):
477
path = self.id2path(file_id)
478
return ("GIT", self.index[path][-2])
481
def get_file_sha1(self, file_id, path=None, stat_value=None):
483
path = self.id2path(file_id)
484
abspath = self.abspath(path).encode(osutils._fs_enc)
486
return osutils.sha_file_by_name(abspath)
487
except OSError, (num, msg):
488
if num in (errno.EISDIR, errno.ENOENT):
492
def revision_tree(self, revid):
493
return self.repository.revision_tree(revid)
495
def _is_versioned(self, path):
496
return (path in self.index or self._has_dir(path))
498
def filter_unversioned_files(self, files):
499
return set([p for p in files if not self._is_versioned(p.encode("utf-8"))])
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)
506
def _add_missing_parent_ids(self, path, dir_ids):
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))
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:
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)
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)
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)
541
def stored_kind(self, file_id, path=None):
543
path = self.id2path(file_id)
544
head = self.repository._git.head()
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)
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
559
def is_executable(self, file_id, path=None):
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)
565
_is_executable_from_path_and_stat = \
566
_is_executable_from_path_and_stat_from_stat
568
def list_files(self, include_root=False, from_dir=None, recursive=True):
569
# FIXME: Yield non-versioned files
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)):
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
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):
596
ids[path] = self.path2id(path)
597
return set(ids.values())
599
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
600
# FIXME: Is return order correct?
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
608
specific_paths = set(specific_paths)
610
specific_paths = None
611
root_ie = self._get_dir_ie(u"", None)
612
if specific_paths is None:
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:
619
(parent, name) = posixpath.split(path)
621
file_ie = self._get_file_ie(name, path, value, None)
624
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
626
yield dir_path, dir_ie
627
file_ie.parent_id = self.path2id(parent)
633
return _mod_conflicts.ConflictList()
635
def update_basis_by_delta(self, new_revid, delta):
636
# The index just contains content, which won't have changed.
639
def _walkdirs(self, prefix=""):
642
per_dir = defaultdict(list)
643
for path, value in self.index.iteritems():
644
if not path.startswith(prefix):
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,
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")),
659
return per_dir.iteritems()
662
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
664
_tree_class = GitWorkingTree
666
supports_versioned_directories = False
669
def _matchingbzrdir(self):
670
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
671
return LocalGitControlDirFormat()
673
def get_format_description(self):
674
return "Git Working Tree"
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"))
683
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
684
a_bzrdir.open_branch(), index)
687
class InterIndexGitTree(tree.InterTree):
688
"""InterTree that works between a Git revision tree and an index."""
690
def __init__(self, source, target):
691
super(InterIndexGitTree, self).__init__(source, target)
692
self._index = target.index
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))
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__,
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)
713
target_fileid_map = {}
715
target_fileid_map = self.target.mapping.import_fileid_map(
716
Blob.from_string(self.target.get_file_text(file_id)))
718
target_fileid_map = {}
719
target_fileid_map = GitFileIdMap(target_fileid_map,
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)
725
for e in self.target.extras():
726
ret.unversioned.append((e, None,
727
osutils.file_kind(self.target.abspath(e))))
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)
741
tree.InterTree.register_optimiser(InterIndexGitTree)