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 (
25
from dulwich.index import (
28
from dulwich.objects import (
38
conflicts as _mod_conflicts,
48
from bzrlib.decorators import (
53
from bzrlib.plugins.git.dir import (
56
from bzrlib.plugins.git.tree import (
57
changes_from_git_changes,
58
tree_delta_from_git_changes,
60
from bzrlib.plugins.git.mapping import (
65
IGNORE_FILENAME = ".gitignore"
68
class GitWorkingTree(workingtree.WorkingTree):
69
"""A Git working tree."""
71
def __init__(self, bzrdir, repo, branch, index):
72
self.basedir = bzrdir.root_transport.local_abspath('.')
74
self.repository = repo
75
self.mapping = self.repository.get_mapping()
77
self._transport = bzrdir.transport
79
self.controldir = self.bzrdir.transport.local_abspath('bzr')
82
os.makedirs(self.controldir)
83
os.makedirs(os.path.join(self.controldir, 'lock'))
87
self._control_files = lockable_files.LockableFiles(
88
transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
89
self._format = GitWorkingTreeFormat()
91
self.views = self._make_views()
92
self._rules_searcher = None
93
self._detect_case_handling()
95
def _index_add_entry(self, path, file_id, kind):
96
if kind == "directory":
97
# Git indexes don't contain directories
102
file, stat_val = self.get_file_with_stat(file_id, path)
103
except (errors.NoSuchFile, IOError):
104
# TODO: Rather than come up with something here, use the old index
106
from posix import stat_result
107
stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
108
blob.set_raw_string(file.read())
109
elif kind == "symlink":
112
stat_val = os.lstat(self.abspath(path))
113
except (errors.NoSuchFile, OSError):
114
# TODO: Rather than come up with something here, use the
116
from posix import stat_result
117
stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
118
blob.set_raw_string(self.get_symlink_target(file_id).encode("utf-8"))
120
raise AssertionError("unknown kind '%s'" % kind)
121
# Add object to the repository if it didn't exist yet
122
if not blob.id in self.repository._git.object_store:
123
self.repository._git.object_store.add_object(blob)
124
# Add an entry to the index or update the existing entry
126
self.index[path.encode("utf-8")] = (stat_val.st_ctime,
127
stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
128
stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
129
stat_val.st_size, blob.id, flags)
131
def unversion(self, file_ids):
132
for file_id in file_ids:
133
path = self.id2path(file_id)
134
del self.index[path.encode("utf-8")]
136
def _add(self, files, ids, kinds):
137
for (path, file_id, kind) in zip(files, ids, kinds):
138
self._index_add_entry(path, file_id, kind)
140
def move(self, from_paths, to_dir=None, after=False):
142
to_abs = self.abspath(to_dir)
143
if not os.path.isdir(to_abs):
144
raise errors.BzrMoveFailedError('', to_dir,
145
errors.NotADirectory(to_abs))
147
for from_rel in from_paths:
148
from_tail = os.path.split(from_rel)[-1]
149
to_rel = os.path.join(to_dir, from_tail)
150
self.rename_one(from_rel, to_rel, after=after)
151
rename_tuples.append((from_rel, to_rel))
154
def rename_one(self, from_rel, to_rel, after=False):
156
os.rename(self.abspath(from_rel), self.abspath(to_rel))
157
self.index[to_rel] = self.index[from_rel]
158
del self.index[from_rel]
160
def get_root_id(self):
161
return self.path2id("")
164
def path2id(self, path):
165
return self._fileid_map.lookup_file_id(path.encode("utf-8"))
168
"""Yield all unversioned files in this WorkingTree.
170
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
171
if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
173
for filename in filenames:
174
relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
175
if not relpath in self.index:
179
# non-implementation specific cleanup
182
# reverse order of locking.
184
return self._control_files.unlock()
189
# TODO: Maybe this should only write on dirty ?
190
if self._control_files._lock_mode != 'w':
191
raise errors.NotWriteLocked(self)
195
for path in self.index:
196
yield self.path2id(path)
198
def id2path(self, file_id):
199
if type(file_id) != str:
201
path = self._fileid_map.lookup_path(file_id)
202
if path in self.index:
204
raise errors.NoSuchId(None, file_id)
206
def get_ignore_list(self):
207
ignoreset = getattr(self, '_ignoreset', None)
208
if ignoreset is not None:
212
ignore_globs.update(ignores.get_runtime_ignores())
213
ignore_globs.update(ignores.get_user_ignores())
214
if self.has_filename(IGNORE_FILENAME):
215
f = self.get_file_byname(IGNORE_FILENAME)
217
ignore_globs.update(ignores.parse_ignore_file(f))
220
self._ignoreset = ignore_globs
223
def set_last_revision(self, revid):
224
self._change_last_revision(revid)
226
def _reset_data(self):
228
head = self.repository._git.head()
229
except KeyError, name:
230
raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
231
store = self.repository._git.object_store
233
self._fileid_map = GitFileIdMap({}, self.mapping)
235
self._fileid_map = self.mapping.get_fileid_map(store.__getitem__,
239
def get_file_sha1(self, file_id, path=None, stat_value=None):
241
path = self.id2path(file_id)
243
return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
244
except OSError, (num, msg):
245
if num in (errno.EISDIR, errno.ENOENT):
249
def revision_tree(self, revid):
250
return self.repository.revision_tree(revid)
252
def _get_dir_ie(self, path, parent_id):
253
file_id = self.path2id(path)
254
return inventory.InventoryDirectory(file_id,
255
posixpath.basename(path).strip("/"), parent_id)
257
def _add_missing_parent_ids(self, path, dir_ids):
260
parent = posixpath.dirname(path).strip("/")
261
ret = self._add_missing_parent_ids(parent, dir_ids)
262
parent_id = dir_ids[parent]
263
ie = self._get_dir_ie(path, parent_id)
264
dir_ids[path] = ie.file_id
265
ret.append((path, ie))
268
def _get_file_ie(self, path, value, parent_id):
269
assert isinstance(path, unicode)
270
assert isinstance(value, tuple) and len(value) == 10
271
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
272
file_id = self.path2id(path)
273
if type(file_id) != str:
275
kind = mode_kind(mode)
276
ie = inventory.entry_factory[kind](file_id,
277
posixpath.basename(path), parent_id)
278
if kind == 'symlink':
279
ie.symlink_target = self.get_symlink_target(file_id)
281
data = self.get_file_text(file_id, path)
282
ie.text_sha1 = osutils.sha_string(data)
283
ie.text_size = len(data)
284
ie.executable = self.is_executable(file_id, path)
288
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
289
mode = stat_result.st_mode
290
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
292
if not osutils.supports_executable():
293
def is_executable(self, file_id, path=None):
294
basis_tree = self.basis_tree()
295
if file_id in basis_tree:
296
return basis_tree.is_executable(file_id)
297
# Default to not executable
300
def is_executable(self, file_id, path=None):
302
path = self.id2path(file_id)
303
mode = os.lstat(self.abspath(path)).st_mode
304
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
306
_is_executable_from_path_and_stat = \
307
_is_executable_from_path_and_stat_from_stat
309
def list_files(self, include_root=False, from_dir=None, recursive=True):
310
# FIXME: Yield non-versioned files
311
# FIXME: support from_dir
312
# FIXME: Support recursive
314
root_ie = self._get_dir_ie(u"", None)
315
if include_root and not from_dir:
316
yield "", "V", root_ie.kind, root_ie.file_id, root_ie
317
dir_ids[u""] = root_ie.file_id
318
for path, value in self.index.iteritems():
319
path = path.decode("utf-8")
320
parent = posixpath.dirname(path).strip("/")
321
for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
322
yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
323
ie = self._get_file_ie(path, value, dir_ids[parent])
324
yield path, "V", ie.kind, ie.file_id, ie
326
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
327
# FIXME: Support specific_file_ids
328
# FIXME: Is return order correct?
329
if specific_file_ids is not None:
330
raise NotImplementedError(self.iter_entries_by_dir)
331
root_ie = self._get_dir_ie(u"", None)
333
dir_ids = {u"": root_ie.file_id}
334
for path, value in self.index.iteritems():
335
path = path.decode("utf-8")
336
parent = posixpath.dirname(path).strip("/")
337
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent, dir_ids):
338
yield dir_path, dir_ie
339
parent_id = self.path2id(parent)
340
yield path, self._get_file_ie(path, value, parent_id)
345
return _mod_conflicts.ConflictList()
347
def update_basis_by_delta(self, new_revid, delta):
349
raise NotImplementedError(self.update_basis_by_delta)
352
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
355
def _matchingbzrdir(self):
356
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
357
return LocalGitControlDirFormat()
359
def get_format_description(self):
360
return "Git Working Tree"
362
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
363
accelerator_tree=None, hardlink=False):
364
"""See WorkingTreeFormat.initialize()."""
365
if not isinstance(a_bzrdir, LocalGitDir):
366
raise errors.IncompatibleFormat(self, a_bzrdir)
367
index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
369
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
370
a_bzrdir.open_branch(), index)
373
class InterIndexGitTree(tree.InterTree):
374
"""InterTree that works between a Git revision tree and an index."""
376
def __init__(self, source, target):
377
super(InterIndexGitTree, self).__init__(source, target)
378
self._index = target.index
381
def is_compatible(cls, source, target):
382
from bzrlib.plugins.git.repository import GitRevisionTree
383
return (isinstance(source, GitRevisionTree) and
384
isinstance(target, GitWorkingTree))
386
def compare(self, want_unchanged=False, specific_files=None,
387
extra_trees=None, require_versioned=False, include_root=False,
388
want_unversioned=False):
389
changes = self._index.changes_from_tree(
390
self.source._repository._git.object_store, self.source.tree,
391
want_unchanged=want_unchanged)
392
source_fileid_map = self.source.mapping.get_fileid_map(
393
self.source._repository._git.object_store.__getitem__,
395
if self.target.mapping.BZR_FILE_IDS_FILE is not None:
396
file_id = self.target.path2id(
397
self.target.mapping.BZR_FILE_IDS_FILE)
399
target_fileid_map = {}
401
target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
403
target_fileid_map = {}
404
target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
405
ret = tree_delta_from_git_changes(changes, self.target.mapping,
406
(source_fileid_map, target_fileid_map),
407
specific_file=specific_files, require_versioned=require_versioned)
409
for e in self.target.extras():
410
ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
413
def iter_changes(self, include_unchanged=False, specific_files=None,
414
pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
415
changes = self._index.changes_from_tree(
416
self.source._repository._git.object_store, self.source.tree,
417
want_unchanged=include_unchanged)
418
# FIXME: Handle want_unversioned
419
return changes_from_git_changes(changes, self.target.mapping,
420
specific_file=specific_files)
423
tree.InterTree.register_optimiser(InterIndexGitTree)