ReMe/reme/steps/file_io/save.py
jinliyl 54fa3381d7
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
refactor(core): reorganize the ReMe runtime and shared helpers (#769)
* refactor(core): reorganize the ReMe runtime and shared helpers

* test(status): import the base component from its canonical module

* test: remove redundant unit checks

* refactor(core): use canonical runtime imports and shared CLI discovery

Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service.

* fix(cli): honor caller config when service replay is incomplete

Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
2026-11-20 22:06:46 +08:00

73 lines
3.1 KiB
Python

"""Save a text file verbatim with optional optimistic-concurrency protection."""
from datetime import datetime
from ._base import _FileIOStep
from ._file_io import detect_file_encoding, write_file_safe
from ...utils.files.path_lock import get_path_lock
from ._path import check_path_permission, resolve_path
from ...core.registry import R
@R.register("save_step")
class SaveStep(_FileIOStep):
"""Persist editor content without interpreting or rebuilding frontmatter.
``expected_mtime`` is the ISO timestamp returned by ``stat``. When supplied,
saving fails if the file changed after it was opened. This keeps the
filesystem authoritative when ReMe and another editor are used together.
"""
async def execute(self):
assert self.context is not None
raw_path = str(self.context.get("path") or "")
content = str(self.context.get("content") or "")
expected_mtime = self.context.get("expected_mtime")
target, error = resolve_path(self.workspace_path, raw_path)
if error or target is None:
self._fail(error or "invalid path", path=raw_path)
return self.context.response
if not check_path_permission(self.workspace_path, target, self.context.get("_allowed_paths")):
self._fail("no permission to write this file", path=raw_path)
return self.context.response
if target.exists() and not target.is_file():
self._fail("target is not a file", path=raw_path)
return self.context.response
lock = await get_path_lock(target)
async with lock:
current_mtime = datetime.fromtimestamp(target.stat().st_mtime).isoformat() if target.exists() else None
if expected_mtime and current_mtime != str(expected_mtime):
self._fail(
"file changed outside ReMe; reload it before saving",
code="file_conflict",
path=raw_path,
expected_mtime=str(expected_mtime),
current_mtime=current_mtime,
)
return self.context.response
encoding = await detect_file_encoding(target) if target.exists() else "utf-8"
try:
await write_file_safe(target, content, encoding=encoding)
except Exception as exc: # pylint: disable=broad-except
self._fail(f"save failed: {exc}", path=raw_path)
return self.context.response
stat = target.stat()
saved_mtime = datetime.fromtimestamp(stat.st_mtime).isoformat()
self.context.response.success = True
self.context.response.answer = f"Saved {raw_path} ({stat.st_size} bytes)"
self.context.response.metadata.update(
{
"path": raw_path,
"exists": True,
"type": "file",
"size": stat.st_size,
"mtime": saved_mtime,
},
)
self.logger.info(f"[{self.name}] saved path={target} bytes={stat.st_size} encoding={encoding}")
return self.context.response