| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import typing |
| 4 |
|
| 5 |
from typing import ( |
| 6 |
Any, |
| 7 |
Collection, |
| 8 |
Iterable, |
| 9 |
Iterator, |
| 10 |
) |
| 11 |
|
| 12 |
from mercurial.node import sha1nodeconstants |
| 13 |
from mercurial.interfaces.types import MatcherT |
| 14 |
|
| 15 |
from mercurial import ( |
| 16 |
match as matchmod, |
| 17 |
pathutil, |
| 18 |
pycompat, |
| 19 |
util, |
| 20 |
) |
| 21 |
from mercurial.interfaces import ( |
| 22 |
repository, |
| 23 |
) |
| 24 |
|
| 25 |
from . import gitutil |
| 26 |
|
| 27 |
if typing.TYPE_CHECKING: |
| 28 |
# We need to fully qualify the set primitive when typing the imanifestdict |
| 29 |
# class, so its set() method doesn't hide the primitive. |
| 30 |
import builtins |
| 31 |
|
| 32 |
from collections.abc import ( |
| 33 |
ByteString, # TODO: change to Buffer for 3.14 |
| 34 |
) |
| 35 |
|
| 36 |
pygit2 = gitutil.get_pygit2() |
| 37 |
|
| 38 |
|
| 39 |
class gittreemanifest(repository.imanifestdict): |
| 40 |
"""Expose git trees (and optionally a builder's overlay) as a manifestdict. |
| 41 |
|
| 42 |
Very similar to mercurial.manifest.treemanifest. |
| 43 |
""" |
| 44 |
|
| 45 |
def __init__(self, git_repo, root_tree, pending_changes): |
| 46 |
"""Initializer. |
| 47 |
|
| 48 |
Args: |
| 49 |
git_repo: The git_repo we're walking (required to look up child |
| 50 |
trees). |
| 51 |
root_tree: The root Git tree object for this manifest. |
| 52 |
pending_changes: A dict in which pending changes will be |
| 53 |
tracked. The enclosing memgittreemanifestctx will use this to |
| 54 |
construct any required Tree objects in Git during it's |
| 55 |
`write()` method. |
| 56 |
""" |
| 57 |
self._git_repo = git_repo |
| 58 |
self._tree = root_tree |
| 59 |
if pending_changes is None: |
| 60 |
pending_changes = {} |
| 61 |
# dict of path: Optional[Tuple(node, flags)] |
| 62 |
self._pending_changes = pending_changes |
| 63 |
|
| 64 |
def _resolve_entry(self, path) -> tuple[bytes, bytes]: |
| 65 |
"""Given a path, load its node and flags, or raise KeyError if missing. |
| 66 |
|
| 67 |
This takes into account any pending writes in the builder. |
| 68 |
""" |
| 69 |
upath = pycompat.fsdecode(path) |
| 70 |
ent = None |
| 71 |
if path in self._pending_changes: |
| 72 |
val = self._pending_changes[path] |
| 73 |
if val is None: |
| 74 |
raise KeyError |
| 75 |
return val |
| 76 |
t = self._tree |
| 77 |
comps = upath.split('/') |
| 78 |
te = self._tree |
| 79 |
for comp in comps[:-1]: |
| 80 |
te = te[comp] |
| 81 |
t = self._git_repo[te.id] |
| 82 |
ent = t[comps[-1]] |
| 83 |
if ent.filemode == pygit2.GIT_FILEMODE_BLOB: |
| 84 |
flags = b'' |
| 85 |
elif ent.filemode == pygit2.GIT_FILEMODE_BLOB_EXECUTABLE: |
| 86 |
flags = b'x' |
| 87 |
elif ent.filemode == pygit2.GIT_FILEMODE_LINK: |
| 88 |
flags = b'l' |
| 89 |
else: |
| 90 |
raise ValueError('unsupported mode %s' % oct(ent.filemode)) |
| 91 |
return ent.id.raw, flags |
| 92 |
|
| 93 |
def __getitem__(self, path: bytes) -> bytes: |
| 94 |
return self._resolve_entry(path)[0] |
| 95 |
|
| 96 |
def find(self, path: bytes) -> tuple[bytes, bytes]: |
| 97 |
return self._resolve_entry(path) |
| 98 |
|
| 99 |
def __len__(self) -> int: |
| 100 |
return len(list(self.walk(matchmod.always()))) |
| 101 |
|
| 102 |
def __nonzero__(self) -> bool: |
| 103 |
try: |
| 104 |
next(iter(self)) |
| 105 |
return True |
| 106 |
except StopIteration: |
| 107 |
return False |
| 108 |
|
| 109 |
__bool__ = __nonzero__ |
| 110 |
|
| 111 |
def __contains__(self, path: bytes) -> bool: |
| 112 |
try: |
| 113 |
self._resolve_entry(path) |
| 114 |
return True |
| 115 |
except KeyError: |
| 116 |
return False |
| 117 |
|
| 118 |
def iterkeys(self) -> Iterator[bytes]: |
| 119 |
return self.walk(matchmod.always()) |
| 120 |
|
| 121 |
def keys(self) -> list[bytes]: |
| 122 |
return list(self.iterkeys()) |
| 123 |
|
| 124 |
def __iter__(self) -> Iterator[bytes]: |
| 125 |
return self.iterkeys() |
| 126 |
|
| 127 |
def set(self, path: bytes, node: bytes, flags: bytes) -> None: |
| 128 |
raise NotImplementedError # TODO: implement this |
| 129 |
|
| 130 |
def __setitem__(self, path: bytes, node: bytes) -> None: |
| 131 |
self._pending_changes[path] = node, self.flags(path) |
| 132 |
|
| 133 |
def __delitem__(self, path: bytes) -> None: |
| 134 |
# TODO: should probably KeyError for already-deleted files? |
| 135 |
self._pending_changes[path] = None |
| 136 |
|
| 137 |
def filesnotin(self, other, match=None) -> builtins.set[bytes]: |
| 138 |
if match is not None: |
| 139 |
match = matchmod.badmatch(match, lambda path, msg: None) |
| 140 |
sm2 = set(other.walk(match)) |
| 141 |
return {f for f in self.walk(match) if f not in sm2} |
| 142 |
return {f for f in self if f not in other} |
| 143 |
|
| 144 |
@util.propertycache |
| 145 |
def _dirs(self): |
| 146 |
return pathutil.dirs(self) |
| 147 |
|
| 148 |
def dirs(self) -> pathutil.dirs: |
| 149 |
return self._dirs # TODO: why is there a prpoertycache? |
| 150 |
|
| 151 |
def hasdir(self, dir: bytes) -> bool: |
| 152 |
return dir in self._dirs |
| 153 |
|
| 154 |
def diff( |
| 155 |
self, |
| 156 |
other: Any, # TODO: 'manifestdict' or (better) equivalent interface |
| 157 |
match: Any = lambda x: True, # TODO: Optional[matchmod.basematcher] = None, |
| 158 |
clean: bool = False, |
| 159 |
) -> dict[ |
| 160 |
bytes, |
| 161 |
tuple[tuple[bytes | None, bytes], tuple[bytes | None, bytes]] | None, |
| 162 |
]: |
| 163 |
"""Finds changes between the current manifest and m2. |
| 164 |
|
| 165 |
The result is returned as a dict with filename as key and |
| 166 |
values of the form ((n1,fl1),(n2,fl2)), where n1/n2 is the |
| 167 |
nodeid in the current/other manifest and fl1/fl2 is the flag |
| 168 |
in the current/other manifest. Where the file does not exist, |
| 169 |
the nodeid will be None and the flags will be the empty |
| 170 |
string. |
| 171 |
""" |
| 172 |
result = {} |
| 173 |
|
| 174 |
def _iterativediff(t1, t2, subdir): |
| 175 |
"""compares two trees and appends new tree nodes to examine to |
| 176 |
the stack""" |
| 177 |
if t1 == t2: |
| 178 |
# If the trees are the same (git) object, then there are no |
| 179 |
# differences in this tree or any of its children. |
| 180 |
return |
| 181 |
|
| 182 |
if t1 is None: |
| 183 |
t1 = {} |
| 184 |
if t2 is None: |
| 185 |
t2 = {} |
| 186 |
|
| 187 |
for e1 in t1: |
| 188 |
realname = subdir + pycompat.fsencode(e1.name) |
| 189 |
|
| 190 |
if e1.type == pygit2.GIT_OBJ_TREE: |
| 191 |
try: |
| 192 |
e2 = t2[e1.name] |
| 193 |
if e2.type != pygit2.GIT_OBJ_TREE: |
| 194 |
e2 = None |
| 195 |
except KeyError: |
| 196 |
e2 = None |
| 197 |
|
| 198 |
stack.append((realname + b'/', e1, e2)) |
| 199 |
else: |
| 200 |
n1, fl1 = self.find(realname) |
| 201 |
|
| 202 |
try: |
| 203 |
e2 = t2[e1.name] |
| 204 |
n2, fl2 = other.find(realname) |
| 205 |
except KeyError: |
| 206 |
e2 = None |
| 207 |
n2, fl2 = (None, b'') |
| 208 |
|
| 209 |
if e2 is not None and e2.type == pygit2.GIT_OBJ_TREE: |
| 210 |
stack.append((realname + b'/', None, e2)) |
| 211 |
|
| 212 |
if not match(realname): |
| 213 |
continue |
| 214 |
|
| 215 |
if n1 != n2 or fl1 != fl2: |
| 216 |
result[realname] = ((n1, fl1), (n2, fl2)) |
| 217 |
elif clean: |
| 218 |
result[realname] = None |
| 219 |
|
| 220 |
for e2 in t2: |
| 221 |
if e2.name in t1: |
| 222 |
continue |
| 223 |
|
| 224 |
realname = subdir + pycompat.fsencode(e2.name) |
| 225 |
|
| 226 |
if e2.type == pygit2.GIT_OBJ_TREE: |
| 227 |
stack.append((realname + b'/', None, e2)) |
| 228 |
elif match(realname): |
| 229 |
n2, fl2 = other.find(realname) |
| 230 |
result[realname] = ((None, b''), (n2, fl2)) |
| 231 |
|
| 232 |
stack = [] |
| 233 |
_iterativediff(self._tree, other._tree, b'') |
| 234 |
while stack: |
| 235 |
subdir, t1, t2 = stack.pop() |
| 236 |
# stack is populated in the function call |
| 237 |
_iterativediff(t1, t2, subdir) |
| 238 |
|
| 239 |
return result |
| 240 |
|
| 241 |
def setflag(self, path: bytes, flag: bytes) -> None: |
| 242 |
node, unused_flag = self._resolve_entry(path) |
| 243 |
self._pending_changes[path] = node, flag |
| 244 |
|
| 245 |
def get(self, path: bytes, default=None) -> bytes | None: |
| 246 |
try: |
| 247 |
return self._resolve_entry(path)[0] |
| 248 |
except KeyError: |
| 249 |
return default |
| 250 |
|
| 251 |
def flags(self, path: bytes) -> bytes: |
| 252 |
try: |
| 253 |
return self._resolve_entry(path)[1] |
| 254 |
except KeyError: |
| 255 |
return b'' |
| 256 |
|
| 257 |
def copy(self) -> gittreemanifest: |
| 258 |
return gittreemanifest( |
| 259 |
self._git_repo, self._tree, dict(self._pending_changes) |
| 260 |
) |
| 261 |
|
| 262 |
def items(self) -> Iterator[tuple[bytes, bytes]]: |
| 263 |
for f in self: |
| 264 |
# TODO: build a proper iterator version of this |
| 265 |
yield f, self[f] |
| 266 |
|
| 267 |
def iteritems(self) -> Iterator[tuple[bytes, bytes]]: |
| 268 |
return self.items() |
| 269 |
|
| 270 |
def iterentries(self) -> Iterator[tuple[bytes, bytes, bytes]]: |
| 271 |
for f in self: |
| 272 |
# TODO: build a proper iterator version of this |
| 273 |
yield f, *self._resolve_entry(f) |
| 274 |
|
| 275 |
def text(self) -> ByteString: |
| 276 |
# TODO can this method move out of the manifest iface? |
| 277 |
raise NotImplementedError |
| 278 |
|
| 279 |
def fastdelta( |
| 280 |
self, base: ByteString, changes: Iterable[tuple[bytes, bool]] |
| 281 |
) -> tuple[ByteString, ByteString]: |
| 282 |
raise NotImplementedError # TODO: implement this |
| 283 |
|
| 284 |
def _walkonetree(self, tree, match, subdir) -> Iterator[bytes]: |
| 285 |
for te in tree: |
| 286 |
# TODO: can we prune dir walks with the matcher? |
| 287 |
realname = subdir + pycompat.fsencode(te.name) |
| 288 |
if te.type == pygit2.GIT_OBJ_TREE: |
| 289 |
yield from self._walkonetree( |
| 290 |
self._git_repo[te.id], match, realname + b'/' |
| 291 |
) |
| 292 |
elif match(realname): |
| 293 |
yield pycompat.fsencode(realname) |
| 294 |
|
| 295 |
def walk(self, match: MatcherT) -> Iterator[bytes]: |
| 296 |
# TODO: this is a very lazy way to merge in the pending |
| 297 |
# changes. There is absolutely room for optimization here by |
| 298 |
# being clever about walking over the sets... |
| 299 |
baseline = set(self._walkonetree(self._tree, match, b'')) |
| 300 |
deleted = {p for p, v in self._pending_changes.items() if v is None} |
| 301 |
pend = {p for p in self._pending_changes if match(p)} |
| 302 |
return iter(sorted((baseline | pend) - deleted)) |
| 303 |
|
| 304 |
|
| 305 |
class gittreemanifestctx(repository.imanifestrevisionstored): |
| 306 |
def __init__(self, repo, gittree): |
| 307 |
self._repo = repo |
| 308 |
self._tree = gittree |
| 309 |
|
| 310 |
def read(self): |
| 311 |
return gittreemanifest(self._repo, self._tree, None) |
| 312 |
|
| 313 |
def copy(self): |
| 314 |
# NB: it's important that we return a memgittreemanifestctx |
| 315 |
# because the caller expects a mutable manifest. |
| 316 |
return memgittreemanifestctx(self._repo, self._tree) |
| 317 |
|
| 318 |
def find(self, path: bytes) -> tuple[bytes, bytes]: |
| 319 |
return self.read().find(path) |
| 320 |
|
| 321 |
def node(self) -> bytes: |
| 322 |
raise NotImplementedError |
| 323 |
|
| 324 |
def read_any_fast_delta( |
| 325 |
self, |
| 326 |
valid_bases: Collection[int] | None = None, |
| 327 |
*, |
| 328 |
shallow: bool = False, |
| 329 |
): |
| 330 |
raise NotImplementedError |
| 331 |
|
| 332 |
def read_delta_parents(self, *, shallow: bool = False, exact: bool = True): |
| 333 |
raise NotImplementedError |
| 334 |
|
| 335 |
def read_delta_new_entries(self, *, shallow: bool = False): |
| 336 |
raise NotImplementedError |
| 337 |
|
| 338 |
@property |
| 339 |
def parents(self): |
| 340 |
# FIXME: the 2 parent nodes |
| 341 |
return sha1nodeconstants.nullid, sha1nodeconstants.nullid |
| 342 |
|
| 343 |
|
| 344 |
class memgittreemanifestctx(repository.imanifestrevisionwritable): |
| 345 |
def __init__(self, repo, tree): |
| 346 |
self._repo = repo |
| 347 |
self._tree = tree |
| 348 |
# dict of path: Optional[Tuple(node, flags)] |
| 349 |
self._pending_changes = {} |
| 350 |
|
| 351 |
def read(self): |
| 352 |
return gittreemanifest(self._repo, self._tree, self._pending_changes) |
| 353 |
|
| 354 |
def copy(self): |
| 355 |
# TODO: if we have a builder in play, what should happen here? |
| 356 |
# Maybe we can shuffle copy() into the immutable interface. |
| 357 |
return memgittreemanifestctx(self._repo, self._tree) |
| 358 |
|
| 359 |
def write(self, transaction, link, p1, p2, added, removed, match=None): |
| 360 |
# We're not (for now, anyway) going to audit filenames, so we |
| 361 |
# can ignore added and removed. |
| 362 |
|
| 363 |
# TODO what does this match argument get used for? hopefully |
| 364 |
# just narrow? |
| 365 |
assert not match or isinstance(match, matchmod.alwaysmatcher) |
| 366 |
|
| 367 |
touched_dirs = pathutil.dirs(list(self._pending_changes)) |
| 368 |
trees = { |
| 369 |
b'': self._tree, |
| 370 |
} |
| 371 |
# path: treebuilder |
| 372 |
builders = { |
| 373 |
b'': self._repo.TreeBuilder(self._tree), |
| 374 |
} |
| 375 |
# get a TreeBuilder for every tree in the touched_dirs set |
| 376 |
for d in sorted(touched_dirs, key=lambda x: (len(x), x)): |
| 377 |
if d == b'': |
| 378 |
# loaded root tree above |
| 379 |
continue |
| 380 |
comps = d.split(b'/') |
| 381 |
full = b'' |
| 382 |
for part in comps: |
| 383 |
parent = trees[full] |
| 384 |
try: |
| 385 |
parent_tree_id = parent[pycompat.fsdecode(part)].id |
| 386 |
new = self._repo[parent_tree_id] |
| 387 |
except KeyError: |
| 388 |
# new directory |
| 389 |
new = None |
| 390 |
full += b'/' + part |
| 391 |
if new is not None: |
| 392 |
# existing directory |
| 393 |
trees[full] = new |
| 394 |
builders[full] = self._repo.TreeBuilder(new) |
| 395 |
else: |
| 396 |
# new directory, use an empty dict to easily |
| 397 |
# generate KeyError as any nested new dirs get |
| 398 |
# created. |
| 399 |
trees[full] = {} |
| 400 |
builders[full] = self._repo.TreeBuilder() |
| 401 |
for f, info in self._pending_changes.items(): |
| 402 |
if b'/' not in f: |
| 403 |
dirname = b'' |
| 404 |
basename = f |
| 405 |
else: |
| 406 |
dirname, basename = f.rsplit(b'/', 1) |
| 407 |
dirname = b'/' + dirname |
| 408 |
if info is None: |
| 409 |
builders[dirname].remove(pycompat.fsdecode(basename)) |
| 410 |
else: |
| 411 |
n, fl = info |
| 412 |
mode = { |
| 413 |
b'': pygit2.GIT_FILEMODE_BLOB, |
| 414 |
b'x': pygit2.GIT_FILEMODE_BLOB_EXECUTABLE, |
| 415 |
b'l': pygit2.GIT_FILEMODE_LINK, |
| 416 |
}[fl] |
| 417 |
builders[dirname].insert( |
| 418 |
pycompat.fsdecode(basename), gitutil.togitnode(n), mode |
| 419 |
) |
| 420 |
# This visits the buffered TreeBuilders in deepest-first |
| 421 |
# order, bubbling up the edits. |
| 422 |
for b in sorted(builders, key=len, reverse=True): |
| 423 |
if b == b'': |
| 424 |
break |
| 425 |
cb = builders[b] |
| 426 |
dn, bn = b.rsplit(b'/', 1) |
| 427 |
builders[dn].insert( |
| 428 |
pycompat.fsdecode(bn), cb.write(), pygit2.GIT_FILEMODE_TREE |
| 429 |
) |
| 430 |
return builders[b''].write().raw |