Skip to content
Merged
1 change: 1 addition & 0 deletions src/polystore/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"StreamingDataType": ".streaming_constants",
"SourcePixelRef": ".virtual_workspace",
"GitBackend": ".git",
"GitStreamBackend": ".git_stream",
"GitCommit": ".git",
"DiskBackend": ".disk",
"DiskStorageBackend": ".disk",
Expand Down
1 change: 1 addition & 0 deletions src/polystore/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Backend(Enum):
MEMORY = "memory"
ZARR = "zarr"
GIT = "git"
GIT_STREAM = "git_stream"
OME_ZARR = "ome_zarr"
STREAMING = "streaming"
NAPARI_STREAM = "napari_stream"
Expand Down
98 changes: 67 additions & 31 deletions src/polystore/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,45 @@ def __init__(self, repository: str | Path, ref: str = "refs/heads/main") -> None
self._run("init", "--bare", "--quiet", str(self.repository), bound=False)
# A checkpoint that returned is on disk: objects and the ref are fsynced.
self._run(f"--git-dir={self.repository}", "config", "core.fsync", "all", bound=False)
self._open_staging()
# The checkpoint this instance's staged tree is based on: the only head its own
# checkpoint may replace.
self._base = self.head()
self._stage_tree_at(self._base.id if self._base else None)

# -- where the staged tree is kept ---------------------------------------

def _open_staging(self) -> None:
"""Somewhere of this instance's own to stage in: a git index file."""
staging = self.repository / "polystore-index"
staging.mkdir(exist_ok=True)
handle, index = tempfile.mkstemp(dir=staging, suffix=".index")
os.close(handle)
os.unlink(index) # git creates it; a zero-byte file is not a valid index
self._index = index
self._finalizer = weakref.finalize(self, _discard, index)
# The checkpoint this instance's staged tree is based on: the only head its own
# checkpoint may replace.
self._base = self.head()
self._git("read-tree", self._base.id if self._base else "--empty")

def _staging_environment(self) -> dict[str, str]:
"""What a git started for this instance is told about where it stages."""
return {"GIT_INDEX_FILE": self._index}

def _stage_tree_at(self, ref: str | None) -> None:
"""Make the staged tree the one recorded at ``ref``; the empty tree for ``None``."""
self._git("read-tree", ref or "--empty")

def _stage_blobs(self, staged: dict[str, str]) -> None:
"""Stage blobs git already holds, each at its path."""
self._run(
"update-index", "--add", "-z", "--index-info",
input="".join(f"{_FILE_MODE} {blob}\t{path}\0" for path, blob in staged.items()).encode(),
)

# -- git plumbing -------------------------------------------------------

def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes:
environment = {
def _environment(self, bound: bool = True) -> dict[str, str]:
"""What a git started here runs under: this user's and this machine's configuration
play no part, and a git bound to the repository stages where this instance does."""
return {
"PATH": os.environ.get("PATH", os.defpath),
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_CONFIG_GLOBAL": os.devnull,
Expand All @@ -82,13 +105,14 @@ def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True)
"GIT_AUTHOR_EMAIL": "polystore@localhost",
"GIT_COMMITTER_NAME": "polystore",
"GIT_COMMITTER_EMAIL": "polystore@localhost",
**(self._staging_environment() if bound else {}),
}
command = ["git"]
if bound:
command.append(f"--git-dir={self.repository}")
environment["GIT_INDEX_FILE"] = self._index

def _run(self, *arguments: str, input: bytes | None = None, bound: bool = True) -> bytes:
command = ["git", *([f"--git-dir={self.repository}"] if bound else [])]
completed = subprocess.run(
[*command, *arguments], input=input, env=environment, capture_output=True, check=False,
[*command, *arguments], input=input, env=self._environment(bound),
capture_output=True, check=False,
)
if completed.returncode != 0:
raise StorageResolutionError(
Expand All @@ -110,15 +134,18 @@ def _path(identifier: str | Path, *, directory: bool = False) -> str:
raise StorageResolutionError("A git file path cannot be the repository root")
return text

def _rows(self, ref: str | None = None) -> list[tuple[str, str, str]]:
"""Every file's mode, blob id and path: of the staged tree, or of the tree at ``ref``."""
listing = self._run(*(("ls-files", "--stage", "-z") if ref is None
else ("ls-tree", "-r", "-z", ref))).decode()
rows = (row.split("\t", 1) for row in listing.split("\0") if row)
# "mode blob stage" for the index, "mode type blob" for a tree.
return [(meta.split()[0], meta.split()[1 if ref is None else 2], path)
for meta, path in rows]

def _entries(self, ref: str | None = None) -> dict[str, str]:
"""Every file path and its blob id: the staged tree, or the tree at ``ref``."""
if ref is None:
listing = self._run("ls-files", "--stage", "-z").decode()
rows = (row.split("\t", 1) for row in listing.split("\0") if row)
return {path: meta.split()[1] for meta, path in rows}
listing = self._run("ls-tree", "-r", "-z", ref).decode()
rows = (row.split("\t", 1) for row in listing.split("\0") if row)
return {path: meta.split()[2] for meta, path in rows}
return {path: blob for _mode, blob, path in self._rows(ref)}

@staticmethod
def _under(entries: dict[str, str], directory: str) -> dict[str, str]:
Expand All @@ -134,20 +161,30 @@ def accepts_payload(self, data: Any, identifier: str | Path) -> bool:
def save(self, data: Any, identifier: str | Path, **kwargs) -> None:
"""Stage ``data`` (bytes, or text as UTF-8) at ``identifier``, replacing what was there;
the previous content stays in every checkpoint that recorded it."""
del kwargs
if isinstance(data, str):
data = data.encode("utf-8")
if not isinstance(data, bytes):
raise TypeError(f"GitBackend stores bytes or text, not {type(data).__name__}")
path = self._path(identifier)
blob = self._git("hash-object", "-w", "--stdin", input=data)
self._git("update-index", "--add", "--cacheinfo", f"{_FILE_MODE},{blob},{path}")
self.save_batch([data], [identifier], **kwargs)

def save_batch(self, data_list: list[Any], identifiers: list[str | Path], **kwargs) -> None:
"""Stage each of ``data_list`` at its identifier. Git is started twice whatever the
number of files: once to store every blob, once to stage every path."""
del kwargs
if len(data_list) != len(identifiers):
raise ValueError("data_list and identifiers must have the same length")
for data, identifier in zip(data_list, identifiers, strict=True):
self.save(data, identifier, **kwargs)
payloads = [data.encode("utf-8") if isinstance(data, str) else data for data in data_list]
for payload in payloads:
if not isinstance(payload, bytes):
raise TypeError(f"GitBackend stores bytes or text, not {type(payload).__name__}")
paths = [self._path(identifier) for identifier in identifiers]
if not paths:
return
with tempfile.TemporaryDirectory(dir=Path(self._index).parent) as folder:
files = [Path(folder) / str(number) for number in range(len(payloads))]
for file, payload in zip(files, payloads, strict=True):
file.write_bytes(payload)
blobs = self._git(
"hash-object", "-w", "--stdin-paths",
input="".join(f"{file}\n" for file in files).encode(),
).split()
self._stage_blobs(dict(zip(paths, blobs, strict=True)))

# -- DataSource ---------------------------------------------------------

Expand Down Expand Up @@ -256,8 +293,7 @@ def copy(self, src: str | Path, dst: str | Path) -> None:
)
if not moved:
raise FileNotFoundError(f"No such git path: {source}")
for path, blob in moved.items():
self._git("update-index", "--add", "--cacheinfo", f"{_FILE_MODE},{blob},{path}")
self._stage_blobs(moved)

def move(self, src: str | Path, dst: str | Path) -> None:
self.copy(src, dst)
Expand Down Expand Up @@ -316,7 +352,7 @@ def history(
def restore(self, ref: str) -> None:
"""Stage the tree recorded at ``ref``. The next checkpoint records the return as a
new commit; history is never rewritten."""
self._git("read-tree", ref)
self._stage_tree_at(ref)

def fork(self, ref: str) -> GitBackend:
"""A new branch starting at this branch's head; staged changes are not carried."""
Expand Down
Loading
Loading