67
78
self.basedir = bzrdir.root_transport.local_abspath('.')
68
79
self.bzrdir = bzrdir
69
80
self.repository = repo
81
self.store = self.repository._git.object_store
70
82
self.mapping = self.repository.get_mapping()
71
83
self._branch = branch
72
84
self._transport = bzrdir.transport
74
self.controldir = self.bzrdir.transport.local_abspath('bzr')
77
os.makedirs(self.controldir)
78
os.makedirs(os.path.join(self.controldir, 'lock'))
82
self._control_files = lockable_files.LockableFiles(
83
transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
84
85
self._format = GitWorkingTreeFormat()
87
self._versioned_dirs = None
86
88
self.views = self._make_views()
89
self._rules_searcher = None
87
90
self._detect_case_handling()
92
self._fileid_map = self._basis_fileid_map.copy()
93
self._lock_mode = None
97
"""Lock the repository for read operations.
99
:return: A bzrlib.lock.LogicalLockResult.
101
if not self._lock_mode:
102
self._lock_mode = 'r'
105
self._lock_count += 1
106
self.branch.lock_read()
107
return lock.LogicalLockResult(self.unlock)
109
def lock_tree_write(self):
110
if not self._lock_mode:
111
self._lock_mode = 'w'
113
elif self._lock_mode == 'r':
114
raise errors.ReadOnlyError(self)
117
self.branch.lock_read()
118
return lock.LogicalLockResult(self.unlock)
120
def lock_write(self, token=None):
121
if not self._lock_mode:
122
self._lock_mode = 'w'
124
elif self._lock_mode == 'r':
125
raise errors.ReadOnlyError(self)
128
self.branch.lock_write()
129
return lock.LogicalLockResult(self.unlock)
132
return self._lock_count >= 1
134
def get_physical_lock_status(self):
138
if not self._lock_count:
139
return lock.cant_unlock_not_held(self)
141
self._lock_count -= 1
142
if self._lock_count > 0:
144
self._lock_mode = None
147
def _detect_case_handling(self):
149
self._transport.stat(".git/cOnFiG")
150
except errors.NoSuchFile:
151
self.case_sensitive = True
153
self.case_sensitive = False
155
def merge_modified(self):
158
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
159
self.set_parent_ids([p for p, t in parents_list])
161
def _index_add_entry(self, path, file_id, kind):
162
assert isinstance(path, basestring)
163
assert type(file_id) == str or file_id is None
164
if kind == "directory":
165
# Git indexes don't contain directories
170
file, stat_val = self.get_file_with_stat(file_id, path)
171
except (errors.NoSuchFile, IOError):
172
# TODO: Rather than come up with something here, use the old index
174
stat_val = os.stat_result(
175
(stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
176
blob.set_raw_string(file.read())
177
elif kind == "symlink":
180
stat_val = os.lstat(self.abspath(path))
181
except (errors.NoSuchFile, OSError):
182
# TODO: Rather than come up with something here, use the
184
stat_val = os.stat_result(
185
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
187
self.get_symlink_target(file_id, path).encode("utf-8"))
189
raise AssertionError("unknown kind '%s'" % kind)
190
# Add object to the repository if it didn't exist yet
191
if not blob.id in self.store:
192
self.store.add_object(blob)
193
# Add an entry to the index or update the existing entry
195
encoded_path = path.encode("utf-8")
196
self.index[encoded_path] = (stat_val.st_ctime,
197
stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino,
198
stat_val.st_mode, stat_val.st_uid, stat_val.st_gid,
199
stat_val.st_size, blob.id, flags)
200
if self._versioned_dirs is not None:
201
self._ensure_versioned_dir(encoded_path)
203
def _ensure_versioned_dir(self, dirname):
204
if dirname in self._versioned_dirs:
207
self._ensure_versioned_dir(posixpath.dirname(dirname))
208
self._versioned_dirs.add(dirname)
210
def _load_dirs(self):
211
self._versioned_dirs = set()
213
self._ensure_versioned_dir(posixpath.dirname(p))
215
def _unversion_path(self, path):
216
encoded_path = path.encode("utf-8")
218
del self.index[encoded_path]
220
# A directory, perhaps?
221
for p in list(self.index):
222
if p.startswith(encoded_path+"/"):
224
# FIXME: remove empty directories
226
@needs_tree_write_lock
227
def unversion(self, file_ids):
228
for file_id in file_ids:
229
path = self.id2path(file_id)
230
self._unversion_path(path)
233
def check_state(self):
234
"""Check that the working state is/isn't valid."""
237
@needs_tree_write_lock
238
def remove(self, files, verbose=False, to_file=None, keep_files=True,
240
"""Remove nominated files from the working tree metadata.
242
:param files: File paths relative to the basedir.
243
:param keep_files: If true, the files will also be kept.
244
:param force: Delete files and directories, even if they are changed
245
and even if the directories are not empty.
247
all_files = set() # specified and nested files
249
if isinstance(files, basestring):
255
files = list(all_files)
258
return # nothing to do
260
# Sort needed to first handle directory content before the directory
261
files.sort(reverse=True)
263
def backup(file_to_backup):
264
abs_path = self.abspath(file_to_backup)
265
backup_name = self.bzrdir._available_backup_name(file_to_backup)
266
osutils.rename(abs_path, self.abspath(backup_name))
267
return "removed %s (but kept a copy: %s)" % (
268
file_to_backup, backup_name)
271
fid = self.path2id(f)
273
message = "%s is not versioned." % (f,)
275
abs_path = self.abspath(f)
277
# having removed it, it must be either ignored or unknown
278
if self.is_ignored(f):
282
# XXX: Really should be a more abstract reporter interface
283
kind_ch = osutils.kind_marker(self.kind(fid))
284
to_file.write(new_status + ' ' + f + kind_ch + '\n')
286
# FIXME: _unversion_path() is O(size-of-index) for directories
287
self._unversion_path(f)
288
message = "removed %s" % (f,)
289
if osutils.lexists(abs_path):
290
if (osutils.isdir(abs_path) and
291
len(os.listdir(abs_path)) > 0):
293
osutils.rmtree(abs_path)
294
message = "deleted %s" % (f,)
299
osutils.delete_any(abs_path)
300
message = "deleted %s" % (f,)
302
# print only one message (if any) per file.
303
if message is not None:
307
def _add(self, files, ids, kinds):
308
for (path, file_id, kind) in zip(files, ids, kinds):
309
if file_id is not None:
310
self._fileid_map.set_file_id(path.encode("utf-8"), file_id)
312
file_id = self._fileid_map.lookup_file_id(path.encode("utf-8"))
313
self._index_add_entry(path, file_id, kind)
315
@needs_tree_write_lock
316
def smart_add(self, file_list, recurse=True, action=None, save=True):
320
for filepath in osutils.canonical_relpaths(self.basedir, file_list):
321
abspath = self.abspath(filepath)
322
kind = osutils.file_kind(abspath)
323
if action is not None:
324
file_id = action(self, None, filepath, kind)
327
if kind in ("file", "symlink"):
329
self._index_add_entry(filepath, file_id, kind)
330
added.append(filepath)
331
elif kind == "directory":
333
user_dirs.append(filepath)
335
raise errors.BadFileKindError(filename=abspath, kind=kind)
336
for user_dir in user_dirs:
337
abs_user_dir = self.abspath(user_dir)
338
for name in os.listdir(abs_user_dir):
339
subp = os.path.join(user_dir, name)
340
if self.is_control_filename(subp) or self.mapping.is_special_file(subp):
342
ignore_glob = self.is_ignored(subp)
343
if ignore_glob is not None:
344
ignored.setdefault(ignore_glob, []).append(subp)
346
abspath = self.abspath(subp)
347
kind = osutils.file_kind(abspath)
348
if kind == "directory":
349
user_dirs.append(subp)
351
if action is not None:
356
self._index_add_entry(subp, file_id, kind)
359
return added, ignored
361
def _set_root_id(self, file_id):
362
self._fileid_map.set_file_id("", file_id)
364
@needs_tree_write_lock
365
def move(self, from_paths, to_dir=None, after=False):
367
to_abs = self.abspath(to_dir)
368
if not os.path.isdir(to_abs):
369
raise errors.BzrMoveFailedError('', to_dir,
370
errors.NotADirectory(to_abs))
372
for from_rel in from_paths:
373
from_tail = os.path.split(from_rel)[-1]
374
to_rel = os.path.join(to_dir, from_tail)
375
self.rename_one(from_rel, to_rel, after=after)
376
rename_tuples.append((from_rel, to_rel))
380
@needs_tree_write_lock
381
def rename_one(self, from_rel, to_rel, after=False):
382
from_path = from_rel.encode("utf-8")
383
to_path = to_rel.encode("utf-8")
384
if not self.has_filename(to_rel):
385
raise errors.BzrMoveFailedError(from_rel, to_rel,
386
errors.NoSuchFile(to_rel))
387
if not from_path in self.index:
388
raise errors.BzrMoveFailedError(from_rel, to_rel,
389
errors.NotVersionedError(path=from_rel))
391
os.rename(self.abspath(from_rel), self.abspath(to_rel))
392
self.index[to_path] = self.index[from_path]
393
del self.index[from_path]
396
def get_root_id(self):
397
return self.path2id("")
399
def _has_dir(self, path):
402
if self._versioned_dirs is None:
404
return path in self._versioned_dirs
407
def path2id(self, path):
408
encoded_path = path.encode("utf-8")
409
if self._is_versioned(encoded_path):
410
return self._fileid_map.lookup_file_id(encoded_path)
413
def _iter_files_recursive(self, from_dir=None):
416
for (dirpath, dirnames, filenames) in os.walk(self.abspath(from_dir)):
417
dir_relpath = dirpath[len(self.basedir):].strip("/")
418
if self.bzrdir.is_control_filename(dir_relpath):
420
for filename in filenames:
421
if not self.mapping.is_special_file(filename):
422
yield os.path.join(dir_relpath, filename)
90
425
"""Yield all unversioned files in this WorkingTree.
92
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
93
if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
95
for filename in filenames:
96
relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
97
if not relpath in self.index:
102
# non-implementation specific cleanup
105
# reverse order of locking.
107
return self._control_files.unlock()
111
def is_control_filename(self, path):
112
return os.path.basename(path) == ".git"
114
def _rewrite_index(self):
116
for path, entry in self._inventory.iter_entries():
117
if entry.kind == "directory":
118
# Git indexes don't contain directories
120
if entry.kind == "file":
123
file, stat_val = self.get_file_with_stat(entry.file_id, path)
124
except (errors.NoSuchFile, IOError):
125
# TODO: Rather than come up with something here, use the old index
127
from posix import stat_result
128
stat_val = stat_result((stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
129
blob.set_raw_string(file.read())
130
elif entry.kind == "symlink":
133
stat_val = os.lstat(self.abspath(path))
134
except (errors.NoSuchFile, OSError):
135
# TODO: Rather than come up with something here, use the
137
from posix import stat_result
138
stat_val = stat_result((stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
139
blob.set_raw_string(entry.symlink_target)
141
raise AssertionError("unknown kind '%s'" % entry.kind)
142
# Add object to the repository if it didn't exist yet
143
if not blob.id in self.repository._git.object_store:
144
self.repository._git.object_store.add_object(blob)
145
# Add an entry to the index or update the existing entry
147
self.index[path.encode("utf-8")] = (stat_val.st_ctime, stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino, stat_val.st_mode, stat_val.st_uid, stat_val.st_gid, stat_val.st_size, blob.id, flags)
427
return set(self._iter_files_recursive()) - set(self.index)
150
430
# TODO: Maybe this should only write on dirty ?
151
if self._control_files._lock_mode != 'w':
431
if self._lock_mode != 'w':
152
432
raise errors.NotWriteLocked(self)
153
self._rewrite_index()
154
433
self.index.write()
155
self._inventory_is_modified = False
436
for path in self.index:
437
yield self.path2id(path)
439
for path in self._versioned_dirs:
440
yield self.path2id(path)
442
def has_or_had_id(self, file_id):
443
if self.has_id(file_id):
445
if self.had_id(file_id):
449
def had_id(self, file_id):
450
path = self._basis_fileid_map.lookup_file_id(file_id)
452
head = self.repository._git.head()
454
# Assume no if basis is not accessible
458
root_tree = self.store[head].tree
460
tree_lookup_path(self.store.__getitem__, root_tree, path)
466
def has_id(self, file_id):
468
self.id2path(file_id)
469
except errors.NoSuchId:
474
def id2path(self, file_id):
475
file_id = osutils.safe_utf8(file_id)
476
path = self._fileid_map.lookup_path(file_id)
477
# FIXME: What about directories?
478
if self._is_versioned(path):
479
return path.decode("utf-8")
480
raise errors.NoSuchId(self, file_id)
482
def get_file_mtime(self, file_id, path=None):
483
"""See Tree.get_file_mtime."""
485
path = self.id2path(file_id)
486
return os.lstat(self.abspath(path)).st_mtime
157
488
def get_ignore_list(self):
158
489
ignoreset = getattr(self, '_ignoreset', None)
205
540
def revision_tree(self, revid):
206
541
return self.repository.revision_tree(revid)
543
def _is_versioned(self, path):
544
return (path in self.index or self._has_dir(path))
546
def filter_unversioned_files(self, files):
547
return set([p for p in files if not self._is_versioned(p.encode("utf-8"))])
549
def _get_dir_ie(self, path, parent_id):
550
file_id = self.path2id(path)
551
return inventory.InventoryDirectory(file_id,
552
posixpath.basename(path).strip("/"), parent_id)
554
def _add_missing_parent_ids(self, path, dir_ids):
557
parent = posixpath.dirname(path).strip("/")
558
ret = self._add_missing_parent_ids(parent, dir_ids)
559
parent_id = dir_ids[parent]
560
ie = self._get_dir_ie(path, parent_id)
561
dir_ids[path] = ie.file_id
562
ret.append((path, ie))
565
def _get_file_ie(self, name, path, value, parent_id):
566
assert isinstance(name, unicode)
567
assert isinstance(path, unicode)
568
assert isinstance(value, tuple) and len(value) == 10
569
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
570
file_id = self.path2id(path)
571
if type(file_id) != str:
573
kind = mode_kind(mode)
574
ie = inventory.entry_factory[kind](file_id, name, parent_id)
575
if kind == 'symlink':
576
ie.symlink_target = self.get_symlink_target(file_id)
578
data = self.get_file_text(file_id, path)
579
ie.text_sha1 = osutils.sha_string(data)
580
ie.text_size = len(data)
581
ie.executable = self.is_executable(file_id, path)
585
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
586
mode = stat_result.st_mode
587
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
589
def stored_kind(self, file_id, path=None):
591
path = self.id2path(file_id)
593
return mode_kind(self.index[path.encode("utf-8")][4])
595
# Maybe it's a directory?
596
if self._has_dir(path):
598
raise errors.NoSuchId(self, file_id)
600
if not osutils.supports_executable():
601
def is_executable(self, file_id, path=None):
602
basis_tree = self.basis_tree()
603
if file_id in basis_tree:
604
return basis_tree.is_executable(file_id)
605
# Default to not executable
608
def is_executable(self, file_id, path=None):
610
path = self.id2path(file_id)
611
mode = os.lstat(self.abspath(path)).st_mode
612
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
614
_is_executable_from_path_and_stat = \
615
_is_executable_from_path_and_stat_from_stat
617
def list_files(self, include_root=False, from_dir=None, recursive=True):
618
# FIXME: Yield non-versioned files
622
fk_entries = {'directory': workingtree.TreeDirectory,
623
'file': workingtree.TreeFile,
624
'symlink': workingtree.TreeLink}
625
root_ie = self._get_dir_ie(u"", None)
626
if include_root and not from_dir:
627
yield "", "V", root_ie.kind, root_ie.file_id, root_ie
628
dir_ids[u""] = root_ie.file_id
630
path_iterator = self._iter_files_recursive(from_dir)
635
start = os.path.join(self.basedir, from_dir)
636
path_iterator = sorted([os.path.join(from_dir, name) for name in
637
os.listdir(start) if not self.bzrdir.is_control_filename(name)
638
and not self.mapping.is_special_file(name)])
639
for path in path_iterator:
641
value = self.index[path]
644
path = path.decode("utf-8")
645
parent, name = posixpath.split(path)
646
for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
647
yield dir_path, "V", dir_ie.kind, dir_ie.file_id, dir_ie
648
if value is not None:
649
ie = self._get_file_ie(name, path, value, dir_ids[parent])
650
yield path, "V", ie.kind, ie.file_id, ie
652
kind = osutils.file_kind(self.abspath(path))
653
ie = fk_entries[kind]()
654
yield path, "?", kind, None, ie
656
def all_file_ids(self):
657
ids = {u"": self.path2id("")}
658
for path in self.index:
659
if self.mapping.is_special_file(path):
661
path = path.decode("utf-8")
662
parent = posixpath.dirname(path).strip("/")
663
for e in self._add_missing_parent_ids(parent, ids):
665
ids[path] = self.path2id(path)
666
return set(ids.values())
668
def _directory_is_tree_reference(self, path):
669
# FIXME: Check .gitsubmodules for path
672
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
673
# FIXME: Is return order correct?
675
raise NotImplementedError(self.iter_entries_by_dir)
676
if specific_file_ids is not None:
677
specific_paths = [self.id2path(file_id) for file_id in specific_file_ids]
678
if specific_paths in ([u""], []):
679
specific_paths = None
681
specific_paths = set(specific_paths)
683
specific_paths = None
684
root_ie = self._get_dir_ie(u"", None)
685
if specific_paths is None:
687
dir_ids = {u"": root_ie.file_id}
688
for path, value in self.index.iteritems():
689
if self.mapping.is_special_file(path):
691
path = path.decode("utf-8")
692
if specific_paths is not None and not path in specific_paths:
694
(parent, name) = posixpath.split(path)
696
file_ie = self._get_file_ie(name, path, value, None)
699
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
701
yield dir_path, dir_ie
702
file_ie.parent_id = self.path2id(parent)
209
706
def conflicts(self):
708
return _mod_conflicts.ConflictList()
710
def update_basis_by_delta(self, new_revid, delta):
711
# The index just contains content, which won't have changed.
714
def get_canonical_inventory_path(self, path):
716
if p.lower() == path.lower():
721
def _walkdirs(self, prefix=""):
724
per_dir = defaultdict(list)
725
for path, value in self.index.iteritems():
726
if self.mapping.is_special_file(path):
728
if not path.startswith(prefix):
730
(dirname, child_name) = posixpath.split(path)
731
dirname = dirname.decode("utf-8")
732
dir_file_id = self.path2id(dirname)
733
assert isinstance(value, tuple) and len(value) == 10
734
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
735
stat_result = os.stat_result((mode, ino,
736
dev, 1, uid, gid, size,
738
per_dir[(dirname, dir_file_id)].append(
739
(path.decode("utf-8"), child_name.decode("utf-8"),
740
mode_kind(mode), stat_result,
741
self.path2id(path.decode("utf-8")),
743
return per_dir.iteritems()
214
746
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
748
_tree_class = GitWorkingTree
750
supports_versioned_directories = False
217
753
def _matchingbzrdir(self):
218
from bzrlib.plugins.git import LocalGitControlDirFormat
754
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
219
755
return LocalGitControlDirFormat()
221
757
def get_format_description(self):
222
758
return "Git Working Tree"
760
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
761
accelerator_tree=None, hardlink=False):
762
"""See WorkingTreeFormat.initialize()."""
763
if not isinstance(a_bzrdir, LocalGitDir):
764
raise errors.IncompatibleFormat(self, a_bzrdir)
765
index = Index(a_bzrdir.root_transport.local_abspath(".git/index"))
767
return GitWorkingTree(a_bzrdir, a_bzrdir.open_repository(),
768
a_bzrdir.open_branch(), index)
225
771
class InterIndexGitTree(tree.InterTree):
226
772
"""InterTree that works between a Git revision tree and an index."""