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 _add(self, files, ids, kinds):
132
for (path, file_id, kind) in zip(files, ids, kinds):
133
self._index_add_entry(path, file_id, kind)
135
def get_root_id(self):
136
return self.mapping.generate_file_id("")
139
"""Yield all unversioned files in this WorkingTree.
141
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
142
if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
144
for filename in filenames:
145
relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
146
if not relpath in self.index:
150
# non-implementation specific cleanup
153
# reverse order of locking.
155
return self._control_files.unlock()
159
def _rewrite_index(self):
161
for path, entry in self._inventory.iter_entries():
162
self._index_add_entry(path, entry.file_id, entry.kind)
165
# TODO: Maybe this should only write on dirty ?
166
if self._control_files._lock_mode != 'w':
167
raise errors.NotWriteLocked(self)
168
self._rewrite_index()
172
for path in self.index:
173
yield self._fileid_map.lookup_file_id(path)
175
def id2path(self, file_id):
176
if type(file_id) != str:
178
path = self._fileid_map.lookup_path(file_id)
179
if path in self.index:
181
raise errors.NoSuchId(None, file_id)
183
def get_ignore_list(self):
184
ignoreset = getattr(self, '_ignoreset', None)
185
if ignoreset is not None:
189
ignore_globs.update(ignores.get_runtime_ignores())
190
ignore_globs.update(ignores.get_user_ignores())
191
if self.has_filename(IGNORE_FILENAME):
192
f = self.get_file_byname(IGNORE_FILENAME)
194
ignore_globs.update(ignores.parse_ignore_file(f))
197
self._ignoreset = ignore_globs
200
def set_last_revision(self, revid):
201
self._change_last_revision(revid)
203
def _reset_data(self):
205
head = self.repository._git.head()
206
except KeyError, name:
207
raise errors.NotBranchError("branch %s at %s" % (name, self.repository.base))
208
store = self.repository._git.object_store
210
self._fileid_map = GitFileIdMap({}, self.mapping)
212
self._fileid_map = self.mapping.get_fileid_map(store.__getitem__,
216
def get_file_sha1(self, file_id, path=None, stat_value=None):
218
path = self.id2path(file_id)
220
return osutils.sha_file_by_name(self.abspath(path).encode(osutils._fs_enc))
221
except OSError, (num, msg):
222
if num in (errno.EISDIR, errno.ENOENT):
226
def revision_tree(self, revid):
227
return self.repository.revision_tree(revid)
229
def _get_dir_ie(self, path, parent_id):
230
file_id = self._fileid_map.lookup_file_id(path)
231
return inventory.InventoryDirectory(file_id,
232
posixpath.basename(path).strip("/"), parent_id)
234
def _add_missing_parent_ids(self, path, dir_ids):
237
parent = posixpath.dirname(path).strip("/")
238
ret = self._add_missing_parent_ids(parent, dir_ids)
239
parent_id = dir_ids[parent]
240
ie = self._get_dir_ie(path, parent_id)
241
dir_ids[path] = ie.file_id
242
ret.append((path, ie))
245
def _get_file_ie(self, path, value, parent_id):
246
assert isinstance(path, str)
247
assert isinstance(value, tuple) and len(value) == 10
248
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
249
file_id = self._fileid_map.lookup_file_id(path)
250
if type(file_id) != str:
252
kind = mode_kind(mode)
253
ie = inventory.entry_factory[kind](file_id,
254
posixpath.basename(path.decode("utf-8")), parent_id)
255
if kind == 'symlink':
256
ie.symlink_target = self.get_symlink_target(file_id)
258
data = self.get_file_text(file_id, path)
259
ie.text_sha1 = osutils.sha_string(data)
260
ie.text_size = len(data)
261
ie.executable = self.is_executable(file_id, path)
265
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
266
mode = stat_result.st_mode
267
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
269
if not osutils.supports_executable():
270
def is_executable(self, file_id, path=None):
271
basis_tree = self.basis_tree()
272
if file_id in basis_tree:
273
return basis_tree.is_executable(file_id)
274
# Default to not executable
277
def is_executable(self, file_id, path=None):
279
path = self.id2path(file_id)
280
mode = os.lstat(self.abspath(path)).st_mode
281
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
283
_is_executable_from_path_and_stat = \
284
_is_executable_from_path_and_stat_from_stat
286
def list_files(self, include_root=False, from_dir=None, recursive=True):
287
# FIXME: Yield non-versioned files
288
# FIXME: support from_dir
289
# FIXME: Support recursive
291
root_ie = self._get_dir_ie("", None)
292
if include_root and not from_dir:
293
yield "", "V", root_ie.kind, root_ie.file_id, root_ie
294
dir_ids[""] = root_ie.file_id
295
for path, value in self.index.iteritems():
296
parent = posixpath.dirname(path).strip("/")
297
for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
298
yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
299
ie = self._get_file_ie(path, value, dir_ids[parent])
300
yield path, "V", ie.kind, ie.file_id, ie
302
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
303
# FIXME: Support specific_file_ids
304
# FIXME: Is return order correct?
305
if specific_file_ids is not None:
306
raise NotImplementedError(self.iter_entries_by_dir)
307
root_ie = self._get_dir_ie("", None)
309
dir_ids = {"": root_ie.file_id}
310
for path, value in self.index.iteritems():
311
parent = posixpath.dirname(path).strip("/")
312
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent, dir_ids):
313
yield dir_path, dir_ie
314
parent_id = self.fileid_map.lookup_file_id(parent)
315
yield path, self._get_file_ie(path, value, parent_id)
320
return _mod_conflicts.ConflictList()
323
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
326
def _matchingbzrdir(self):
327
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
328
return LocalGitControlDirFormat()
330
def get_format_description(self):
331
return "Git Working Tree"
333
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
334
accelerator_tree=None, hardlink=False):
335
"""See WorkingTreeFormat.initialize()."""
336
if not isinstance(a_bzrdir, LocalGitDir):
337
raise errors.IncompatibleFormat(self, a_bzrdir)
338
index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
340
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
341
a_bzrdir.open_branch(), index)
344
class InterIndexGitTree(tree.InterTree):
345
"""InterTree that works between a Git revision tree and an index."""
347
def __init__(self, source, target):
348
super(InterIndexGitTree, self).__init__(source, target)
349
self._index = target.index
352
def is_compatible(cls, source, target):
353
from bzrlib.plugins.git.repository import GitRevisionTree
354
return (isinstance(source, GitRevisionTree) and
355
isinstance(target, GitWorkingTree))
357
def compare(self, want_unchanged=False, specific_files=None,
358
extra_trees=None, require_versioned=False, include_root=False,
359
want_unversioned=False):
360
changes = self._index.changes_from_tree(
361
self.source._repository._git.object_store, self.source.tree,
362
want_unchanged=want_unchanged)
363
source_fileid_map = self.source.mapping.get_fileid_map(
364
self.source._repository._git.object_store.__getitem__,
366
if self.target.mapping.BZR_FILE_IDS_FILE is not None:
367
file_id = self.target.path2id(
368
self.target.mapping.BZR_FILE_IDS_FILE)
370
target_fileid_map = {}
372
target_fileid_map = self.target.mapping.import_fileid_map(Blob.from_string(self.target.get_file_text(file_id)))
374
target_fileid_map = {}
375
target_fileid_map = GitFileIdMap(target_fileid_map, self.target.mapping)
376
ret = tree_delta_from_git_changes(changes, self.target.mapping,
377
(source_fileid_map, target_fileid_map),
378
specific_file=specific_files, require_versioned=require_versioned)
380
for e in self.target.extras():
381
ret.unversioned.append((e, None, osutils.file_kind(self.target.abspath(e))))
384
def iter_changes(self, include_unchanged=False, specific_files=None,
385
pb=None, extra_trees=[], require_versioned=True, want_unversioned=False):
386
changes = self._index.changes_from_tree(
387
self.source._repository._git.object_store, self.source.tree,
388
want_unchanged=include_unchanged)
389
# FIXME: Handle want_unversioned
390
return changes_from_git_changes(changes, self.target.mapping,
391
specific_file=specific_files)
394
tree.InterTree.register_optimiser(InterIndexGitTree)