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 _detect_case_handling(self):
109
self._transport.stat(".git/cOnFiG")
110
except errors.NoSuchFile:
111
self.case_sensitive = True
113
self.case_sensitive = False
115
def merge_modified(self):
118
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
119
self.set_parent_ids([p for p, t in parents_list])
121
def _index_add_entry(self, path, file_id, kind):
122
assert isinstance(path, basestring)
123
assert type(file_id) == str or file_id is None
124
if kind == "directory":
125
# Git indexes don't contain directories
130
file, stat_val = self.get_file_with_stat(file_id, path)
131
except (errors.NoSuchFile, IOError):
132
# TODO: Rather than come up with something here, use the old index
134
from posix import stat_result
135
stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
136
blob.set_raw_string(file.read())
137
elif kind == "symlink":
140
stat_val = os.lstat(self.abspath(path))
141
except (errors.NoSuchFile, OSError):
142
# TODO: Rather than come up with something here, use the
144
from posix import stat_result
145
stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
147
self.get_symlink_target(file_id, path).encode("utf-8"))
149
raise AssertionError("unknown kind '%s'" % kind)
150
# Add object to the repository if it didn't exist yet
151
if not blob.id in self.store:
152
self.store.add_object(blob)
153
# Add an entry to the index or update the existing entry
155
encoded_path = path.encode("utf-8")
156
self.index[encoded_path] = (stat_val.st_ctime,
157
stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
158
stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
159
stat_val.st_size, blob.id, flags)
160
if self._versioned_dirs is not None:
161
self._ensure_versioned_dir(encoded_path)
163
def _ensure_versioned_dir(self, dirname):
164
if dirname in self._versioned_dirs:
167
self._ensure_versioned_dir(posixpath.dirname(dirname))
168
self._versioned_dirs.add(dirname)
170
def _load_dirs(self):
171
self._versioned_dirs = set()
173
self._ensure_versioned_dir(posixpath.dirname(p))
175
def _unversion_path(self, path):
176
encoded_path = path.encode("utf-8")
178
del self.index[encoded_path]
180
# A directory, perhaps?
181
for p in list(self.index):
182
if p.startswith(encoded_path+"/"):
184
# FIXME: remove empty directories
186
def unversion(self, file_ids):
187
for file_id in file_ids:
188
path = self.id2path(file_id)
189
self._unversion_path(path)
191
def check_state(self):
192
"""Check that the working state is/isn't valid."""
195
def remove(self, files, verbose=False, to_file=None, keep_files=True,
197
"""Remove nominated files from the working tree metadata.
199
:param files: File paths relative to the basedir.
200
:param keep_files: If true, the files will also be kept.
201
:param force: Delete files and directories, even if they are changed
202
and even if the directories are not empty.
204
all_files = set() # specified and nested files
206
if isinstance(files, basestring):
212
files = list(all_files)
215
return # nothing to do
217
# Sort needed to first handle directory content before the directory
218
files.sort(reverse=True)
220
def backup(file_to_backup):
221
abs_path = self.abspath(file_to_backup)
222
backup_name = self.bzrdir._available_backup_name(file_to_backup)
223
osutils.rename(abs_path, self.abspath(backup_name))
224
return "removed %s (but kept a copy: %s)" % (
225
file_to_backup, backup_name)
228
fid = self.path2id(f)
230
message = "%s is not versioned." % (f,)
232
abs_path = self.abspath(f)
234
# having removed it, it must be either ignored or unknown
235
if self.is_ignored(f):
239
# XXX: Really should be a more abstract reporter interface
240
kind_ch = osutils.kind_marker(self.kind(fid))
241
to_file.write(new_status + ' ' + f + kind_ch + '\n')
243
# FIXME: _unversion_path() is O(size-of-index) for directories
244
self._unversion_path(f)
245
message = "removed %s" % (f,)
246
if osutils.lexists(abs_path):
247
if (osutils.isdir(abs_path) and
248
len(os.listdir(abs_path)) > 0):
250
osutils.rmtree(abs_path)
251
message = "deleted %s" % (f,)
256
osutils.delete_any(abs_path)
257
message = "deleted %s" % (f,)
259
# print only one message (if any) per file.
260
if message is not None:
263
def _add(self, files, ids, kinds):
264
for (path, file_id, kind) in zip(files, ids, kinds):
265
if file_id is not None:
266
self._fileid_map.set_file_id(path.encode("utf-8"), file_id)
268
file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
269
self._index_add_entry(path, file_id, kind)
271
@needs_tree_write_lock
272
def smart_add(self, file_list, recurse=True, action=None, save=True):
276
for filepath in osutils.canonical_relpaths(self.basedir, file_list):
277
abspath = self.abspath(filepath)
278
kind = osutils.file_kind(abspath)
279
if action is not None:
280
file_id = action(self, None, filepath, kind)
283
if kind in ("file", "symlink"):
285
self._index_add_entry(filepath, file_id, kind)
286
added.append(filepath)
287
elif kind == "directory":
289
user_dirs.append(filepath)
291
raise errors.BadFileKindError(filename=abspath, kind=kind)
292
for user_dir in user_dirs:
293
abs_user_dir = self.abspath(user_dir)
294
for name in os.listdir(abs_user_dir):
295
subp = os.path.join(user_dir, name)
296
if self.is_control_filename(subp):
298
ignore_glob = self.is_ignored(subp)
299
if ignore_glob is not None:
300
ignored.setdefault(ignore_glob, []).append(subp)
302
abspath = self.abspath(subp)
303
kind = osutils.file_kind(abspath)
304
if kind == "directory":
305
user_dirs.append(subp)
307
if action is not None:
312
self._index_add_entry(subp, file_id, kind)
315
return added, ignored
317
def _set_root_id(self, file_id):
318
self._fileid_map.set_file_id("", file_id)
320
@needs_tree_write_lock
321
def move(self, from_paths, to_dir=None, after=False):
323
to_abs = self.abspath(to_dir)
324
if not os.path.isdir(to_abs):
325
raise errors.BzrMoveFailedError('', to_dir,
326
errors.NotADirectory(to_abs))
328
for from_rel in from_paths:
329
from_tail = os.path.split(from_rel)[-1]
330
to_rel = os.path.join(to_dir, from_tail)
331
self.rename_one(from_rel, to_rel, after=after)
332
rename_tuples.append((from_rel, to_rel))
335
@needs_tree_write_lock
336
def rename_one(self, from_rel, to_rel, after=False):
338
os.rename(self.abspath(from_rel), self.abspath(to_rel))
339
from_path = from_rel.encode("utf-8")
340
to_path = to_rel.encode("utf-8")
341
if not self.has_filename(to_rel):
342
raise errors.BzrMoveFailedError(from_rel, to_rel,
343
errors.NoSuchFile(to_rel))
344
if not from_path in self.index:
345
raise errors.BzrMoveFailedError(from_rel, to_rel,
346
errors.NotVersionedError(path=from_rel))
347
self.index[to_path] = self.index[from_path]
348
del self.index[from_path]
350
def get_root_id(self):
351
return self.path2id("")
353
def _has_dir(self, path):
354
if self._versioned_dirs is None:
356
return path in self._versioned_dirs
359
def path2id(self, path):
360
encoded_path = path.encode("utf-8")
361
if self._is_versioned(encoded_path):
362
return self._fileid_map.lookup_file_id(encoded_path)
366
"""Yield all unversioned files in this WorkingTree.
368
present_files = set()
369
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
370
dir_relpath = dirpath[len(self.basedir):].strip("/")
371
if self.bzrdir.is_control_filename(dir_relpath):
373
for filename in filenames:
374
relpath = os.path.join(dir_relpath, filename)
375
present_files.add(relpath)
376
return present_files - set(self.index)
379
# non-implementation specific cleanup
382
# reverse order of locking.
384
return self._control_files.unlock()
389
# TODO: Maybe this should only write on dirty ?
390
if self._control_files._lock_mode != 'w':
391
raise errors.NotWriteLocked(self)
395
for path in self.index:
396
yield self.path2id(path)
398
for path in self._versioned_dirs:
399
yield self.path2id(path)
401
def has_or_had_id(self, file_id):
402
if self.has_id(file_id):
404
if self.had_id(file_id):
408
def had_id(self, file_id):
409
path = self._basis_fileid_map.lookup_file_id(file_id)
411
head = self.repository._git.head()
413
# Assume no if basis is not accessible
417
root_tree = self.store[head].tree
419
tree_lookup_path(self.store.__getitem__, root_tree, path)
425
def has_id(self, file_id):
427
self.id2path(file_id)
428
except errors.NoSuchId:
433
def id2path(self, file_id):
434
if type(file_id) != str:
436
path = self._fileid_map.lookup_path(file_id)
437
# FIXME: What about directories?
438
if self._is_versioned(path):
439
return path.decode("utf-8")
440
raise errors.NoSuchId(self, file_id)
442
def get_file_mtime(self, file_id, path=None):
443
"""See Tree.get_file_mtime."""
445
path = self.id2path(file_id)
446
return os.lstat(self.abspath(path)).st_mtime
448
def get_ignore_list(self):
449
ignoreset = getattr(self, '_ignoreset', None)
450
if ignoreset is not None:
454
ignore_globs.update(ignores.get_runtime_ignores())
455
ignore_globs.update(ignores.get_user_ignores())
456
if self.has_filename(IGNORE_FILENAME):
457
f = self.get_file_byname(IGNORE_FILENAME)
459
# FIXME: Parse git file format, rather than assuming it's
460
# the same as for bzr's native formats.
461
ignore_globs.update(ignores.parse_ignore_file(f))
464
self._ignoreset = ignore_globs
467
def set_last_revision(self, revid):
468
self._change_last_revision(revid)
470
def _reset_data(self):
472
head = self.repository._git.head()
473
except KeyError, name:
474
raise errors.NotBranchError("branch %s at %s" % (name,
475
self.repository.base))
477
self._basis_fileid_map = GitFileIdMap({}, self.mapping)
479
self._basis_fileid_map = self.mapping.get_fileid_map(
480
self.store.__getitem__, self.store[head].tree)
483
def get_file_verifier(self, file_id, path=None, stat_value=None):
485
path = self.id2path(file_id)
486
return ("GIT", self.index[path][-2])
489
def get_file_sha1(self, file_id, path=None, stat_value=None):
491
path = self.id2path(file_id)
492
abspath = self.abspath(path).encode(osutils._fs_enc)
494
return osutils.sha_file_by_name(abspath)
495
except OSError, (num, msg):
496
if num in (errno.EISDIR, errno.ENOENT):
500
def revision_tree(self, revid):
501
return self.repository.revision_tree(revid)
503
def _is_versioned(self, path):
504
return (path in self.index or self._has_dir(path))
506
def filter_unversioned_files(self, files):
507
return set([p for p in files if not self._is_versioned(p.encode("utf-8"))])
509
def _get_dir_ie(self, path, parent_id):
510
file_id = self.path2id(path)
511
return inventory.InventoryDirectory(file_id,
512
posixpath.basename(path).strip("/"), parent_id)
514
def _add_missing_parent_ids(self, path, dir_ids):
517
parent = posixpath.dirname(path).strip("/")
518
ret = self._add_missing_parent_ids(parent, dir_ids)
519
parent_id = dir_ids[parent]
520
ie = self._get_dir_ie(path, parent_id)
521
dir_ids[path] = ie.file_id
522
ret.append((path, ie))
525
def _get_file_ie(self, name, path, value, parent_id):
526
assert isinstance(name, unicode)
527
assert isinstance(path, unicode)
528
assert isinstance(value, tuple) and len(value) == 10
529
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
530
file_id = self.path2id(path)
531
if type(file_id) != str:
533
kind = mode_kind(mode)
534
ie = inventory.entry_factory[kind](file_id, name, parent_id)
535
if kind == 'symlink':
536
ie.symlink_target = self.get_symlink_target(file_id)
538
data = self.get_file_text(file_id, path)
539
ie.text_sha1 = osutils.sha_string(data)
540
ie.text_size = len(data)
541
ie.executable = self.is_executable(file_id, path)
545
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
546
mode = stat_result.st_mode
547
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
549
def stored_kind(self, file_id, path=None):
551
path = self.id2path(file_id)
552
head = self.repository._git.head()
554
raise errors.NoSuchId(self, file_id)
555
root_tree = self.store[head].tree
556
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, root_tree, path)
557
return mode_kind(mode)
559
if not osutils.supports_executable():
560
def is_executable(self, file_id, path=None):
561
basis_tree = self.basis_tree()
562
if file_id in basis_tree:
563
return basis_tree.is_executable(file_id)
564
# Default to not executable
567
def is_executable(self, file_id, path=None):
569
path = self.id2path(file_id)
570
mode = os.lstat(self.abspath(path)).st_mode
571
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
573
_is_executable_from_path_and_stat = \
574
_is_executable_from_path_and_stat_from_stat
576
def list_files(self, include_root=False, from_dir=None, recursive=True):
577
# FIXME: Yield non-versioned files
581
root_ie = self._get_dir_ie(u"", None)
582
if include_root and not from_dir:
583
yield "", "V", root_ie.kind, root_ie.file_id, root_ie
584
dir_ids[u""] = root_ie.file_id
585
for path, value in self.index.iteritems():
586
path = path.decode("utf-8")
587
parent, name = posixpath.split(path)
588
if (from_dir is not None and
589
(recursive and not osutils.is_inside(from_dir, path)) or
590
(not recursive and from_dir != parent)):
592
for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
593
yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
594
ie = self._get_file_ie(name, path, value, dir_ids[parent])
595
yield path, "V", ie.kind, ie.file_id, ie
597
def all_file_ids(self):
598
ids = {u"": self.path2id("")}
599
for path in self.index:
600
path = path.decode("utf-8")
601
parent = posixpath.dirname(path).strip("/")
602
for e in self._add_missing_parent_ids(parent, ids):
604
ids[path] = self.path2id(path)
605
return set(ids.values())
607
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
608
# FIXME: Is return order correct?
610
raise NotImplementedError(self.iter_entries_by_dir)
611
if specific_file_ids is not None:
612
specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
613
if specific_paths in ([u""], []):
614
specific_paths = None
616
specific_paths = set(specific_paths)
618
specific_paths = None
619
root_ie = self._get_dir_ie(u"", None)
620
if specific_paths is None:
622
dir_ids = {u"": root_ie.file_id}
623
for path, value in self.index.iteritems():
624
path = path.decode("utf-8")
625
if specific_paths is not None and not path in specific_paths:
627
(parent, name) = posixpath.split(path)
629
file_ie = self._get_file_ie(name, path, value, None)
632
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
634
yield dir_path, dir_ie
635
file_ie.parent_id = self.path2id(parent)
641
return _mod_conflicts.ConflictList()
643
def update_basis_by_delta(self, new_revid, delta):
644
# The index just contains content, which won't have changed.
647
def _walkdirs(self, prefix=""):
650
per_dir = defaultdict(list)
651
for path, value in self.index.iteritems():
652
if not path.startswith(prefix):
654
(dirname, child_name) = posixpath.split(path)
655
dirname = dirname.decode("utf-8")
656
dir_file_id = self.path2id(dirname)
657
assert isinstance(value, tuple) and len(value) == 10
658
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
659
stat_result = posix.stat_result((mode, ino,
660
dev, 1, uid, gid, size,
662
per_dir[(dirname, dir_file_id)].append(
663
(path.decode("utf-8"), child_name.decode("utf-8"),
664
mode_kind(mode), stat_result,
665
self.path2id(path.decode("utf-8")),
667
return per_dir.iteritems()
670
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
672
_tree_class = GitWorkingTree
674
supports_versioned_directories = False
677
def _matchingbzrdir(self):
678
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
679
return LocalGitControlDirFormat()
681
def get_format_description(self):
682
return "Git Working Tree"
684
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
685
accelerator_tree=None, hardlink=False):
686
"""See WorkingTreeFormat.initialize()."""
687
if not isinstance(a_bzrdir, LocalGitDir):
688
raise errors.IncompatibleFormat(self, a_bzrdir)
689
index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
691
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
692
a_bzrdir.open_branch(), index)
695
class InterIndexGitTree(tree.InterTree):
696
"""InterTree that works between a Git revision tree and an index."""
698
def __init__(self, source, target):
699
super(InterIndexGitTree, self).__init__(source, target)
700
self._index = target.index
703
def is_compatible(cls, source, target):
704
from bzrlib.plugins.git.repository import GitRevisionTree
705
return (isinstance(source, GitRevisionTree) and
706
isinstance(target, GitWorkingTree))
708
def compare(self, want_unchanged=False, specific_files=None,
709
extra_trees=None, require_versioned=False, include_root=False,
710
want_unversioned=False):
711
changes = self._index.changes_from_tree(
712
self.source.store, self.source.tree,
713
want_unchanged=want_unchanged)
714
source_fileid_map = self.source.mapping.get_fileid_map(
715
self.source.store.__getitem__,
717
if self.target.mapping.BZR_FILE_IDS_FILE is not None:
718
file_id = self.target.path2id(
719
self.target.mapping.BZR_FILE_IDS_FILE)
721
target_fileid_map = {}
723
target_fileid_map = self.target.mapping.import_fileid_map(
724
Blob.from_string(self.target.get_file_text(file_id)))
726
target_fileid_map = {}
727
target_fileid_map = GitFileIdMap(target_fileid_map,
729
ret = tree_delta_from_git_changes(changes, self.target.mapping,
730
(source_fileid_map, target_fileid_map),
731
specific_file=specific_files, require_versioned=require_versioned)
733
for e in self.target.extras():
734
ret.unversioned.append((e, None,
735
osutils.file_kind(self.target.abspath(e))))
738
def iter_changes(self, include_unchanged=False, specific_files=None,
739
pb=None, extra_trees=[], require_versioned=True,
740
want_unversioned=False):
741
changes = self._index.changes_from_tree(
742
self.source.store, self.source.tree,
743
want_unchanged=include_unchanged)
744
# FIXME: Handle want_unversioned
745
return changes_from_git_changes(changes, self.target.mapping,
746
specific_file=specific_files)
749
tree.InterTree.register_optimiser(InterIndexGitTree)