83
97
transport.get_transport(self.controldir), 'lock', lockdir.LockDir)
84
98
self._format = GitWorkingTreeFormat()
100
self._versioned_dirs = None
86
101
self.views = self._make_views()
102
self._rules_searcher = None
87
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)
90
366
"""Yield all unversioned files in this WorkingTree.
368
present_files = set()
92
369
for (dirpath, dirnames, filenames) in os.walk(self.basedir):
93
if self.bzrdir.is_control_filename(dirpath[len(self.basedir):].strip("/")):
370
dir_relpath = dirpath[len(self.basedir):].strip("/")
371
if self.bzrdir.is_control_filename(dir_relpath):
95
373
for filename in filenames:
96
relpath = os.path.join(dirpath[len(self.basedir):].strip("/"), filename)
97
if not relpath in self.index:
374
relpath = os.path.join(dir_relpath, filename)
375
present_files.add(relpath)
376
return present_files - set(self.index)
101
378
def unlock(self):
102
379
# non-implementation specific cleanup
109
386
self.branch.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)
150
389
# TODO: Maybe this should only write on dirty ?
151
390
if self._control_files._lock_mode != 'w':
152
391
raise errors.NotWriteLocked(self)
153
self._rewrite_index()
154
392
self.index.write()
155
self._inventory_is_modified = False
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
157
448
def get_ignore_list(self):
158
449
ignoreset = getattr(self, '_ignoreset', None)
205
500
def revision_tree(self, revid):
206
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)
209
639
def conflicts(self):
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()
214
670
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
672
_tree_class = GitWorkingTree
674
supports_versioned_directories = False
217
677
def _matchingbzrdir(self):
218
from bzrlib.plugins.git import LocalGitControlDirFormat
678
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
219
679
return LocalGitControlDirFormat()
221
681
def get_format_description(self):
222
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)
225
695
class InterIndexGitTree(tree.InterTree):
226
696
"""InterTree that works between a Git revision tree and an index."""