Paths
rn_forge.commons.fs.paths
Filesystem helpers: atomic writes, backups, temp dirs and containment guards.
Includes atomic publish-by-rename, repository-root discovery, and
:meth:~PathUtils.assert_within containment checks.
PathUtils
Filesystem helpers with automatic parent-directory creation.
assert_within(root, target)
staticmethod
Resolve target and raise unless it stays inside root.
Covers both the lexical escape (a declared ../../.ssh/config) and
the symlink-escape case (a symlink that resolves outside root) —
:meth:~pathlib.Path.resolve collapses .. segments and follows
symlinks, so a single post-resolution containment check catches both.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
The directory target must stay within. |
required |
target
|
str | Path
|
The path to check, resolved before comparison. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved, absolute target path. |
Raises:
| Type | Description |
|---|---|
AppException
|
The resolved target is not root itself and is not inside it. |
atomic_replace(path, *, copy=True, mode=None)
staticmethod
Edit a temporary sibling of path and publish it over path atomically.
Yields a .<name>.<random>.tmp path in path's directory. When
copy is true it starts as a :func:shutil.copy2 copy of path; the
caller edits it with any tool, including one that replaces it by
rename. On a clean exit the temporary is fsync'd, given its
permissions, published over path with :func:os.replace, and the
parent directory is best-effort fsync'd.
Permissions: an explicit mode wins; otherwise an existing path's mode is kept; otherwise the temporary's default (restrictive) permissions are left as-is.
On any :class:BaseException, including :exc:KeyboardInterrupt,
the temporary is removed and path is left untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The file to replace. Its directory must exist. |
required |
copy
|
bool
|
Pre-fill the temporary with a copy of path. When false the temporary starts empty and path may not exist yet. |
True
|
mode
|
int | None
|
Optional explicit permission bits for the published file. |
None
|
Yields:
| Type | Description |
|---|---|
Generator[Path]
|
The temporary path to edit. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
copy is true and path does not exist. |
atomic_write(content, path, *, mode=None, encoding='utf-8')
staticmethod
Atomically write content to path, never leaving a partial file visible.
Writes to a .<name>.<random>.tmp temp file in path's directory,
fsyncs it, then publishes it over the target with
:func:os.replace — the rename is atomic, so a reader never observes
a partially-written file. The parent directory is then best-effort
fsync'd too: fsyncing only the file durably records its
contents, but the rename that makes those contents visible under
path lives in the parent directory's entry table, so a crash
between the two can still lose the new name on some filesystems.
Not every platform or filesystem permits opening a directory for this,
hence best-effort — failure here is silently swallowed.
Permissions: an explicit mode always wins; otherwise an existing file's mode is preserved across the replacement; otherwise (no existing file, no explicit mode) the temp file's default (restrictive) permissions are left as-is.
A :class:BaseException (not just :class:Exception) during the
write — including :exc:KeyboardInterrupt/:exc:SystemExit — still
cleans up the temp file before propagating, so an interrupted write
never leaves a stray temp file behind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str | bytes
|
Text or binary data to write. |
required |
path
|
str | Path
|
Destination file path. |
required |
mode
|
int | None
|
Optional explicit permission bits applied to the temp file before the atomic rename. Takes precedence over preserving an existing file's mode. |
None
|
encoding
|
str
|
Encoding used when content is |
'utf-8'
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved :class: |
backup(path, destination_root, *, relative_to=None)
staticmethod
Copy path under destination_root, preserving its relative layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The file to back up. A no-op (returns |
required |
destination_root
|
str | Path
|
Directory under which the backup is placed. |
required |
relative_to
|
Path | None
|
When given, path is stored under destination_root
at its path relative to this directory. When path is not
inside relative_to (or relative_to is omitted), it is
stored at its path with the filesystem root stripped, e.g.
|
None
|
Returns:
| Type | Description |
|---|---|
Path | None
|
The backup file's path, or |
delete(path, *, ignore_missing=True)
staticmethod
Delete a file or directory tree at path.
Files and symlinks are removed with :meth:~pathlib.Path.unlink;
directories are removed recursively with :func:shutil.rmtree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Target file or directory to delete. |
required |
ignore_missing
|
bool
|
When |
True
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If path does not exist and
|
find_root(start=None, *, markers=('.git',), fallback='start')
staticmethod
Walk up from start to the nearest ancestor containing any marker.
markers are checked in order — every ancestor is checked against
the first marker before the second marker is considered at all, so
marker precedence outranks proximity to start (e.g. a .git
several levels up beats a pyproject.toml one level up, if
markers=(".git", "pyproject.toml")).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str | Path | None
|
Directory (or file, whose parent is used) to search from. Defaults to the current working directory. |
None
|
markers
|
Sequence[str | Path]
|
Ordered marker paths (relative to a candidate ancestor)
whose existence identifies the root, e.g. |
('.git',)
|
fallback
|
Literal['start', 'raise']
|
|
'start'
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved root directory. |
Raises:
| Type | Description |
|---|---|
AppException
|
No marker matched and |
move_no_clobber(source, destination)
staticmethod
Move source to destination, never overwriting an existing file.
Creates destination's parent directories, then publishes with
:func:os.link and unlinks source. The link fails atomically when
destination exists, so a file that appears there during the call is
never replaced. Across filesystems, source is copied with
:func:shutil.copy2 to a temporary beside destination, fsync'd,
linked to destination and removed, then source is removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
The file to move. |
required |
destination
|
str | Path
|
The path to move it to. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
destination, as a :class: |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
destination exists. Both files are left as they were. |
FileNotFoundError
|
source does not exist. |
OSError
|
Any other failure, including a filesystem without hard links. Parent directories already created are kept. |
normalize_relative(raw)
staticmethod
Normalize raw to a POSIX relative path, rejecting escapes.
Rejects absolute paths and any ".." that would climb above the
(implicit) root. "." means the root itself. Purely lexical — does
not touch the filesystem or resolve symlinks; pair with
:meth:assert_within when the path will actually be used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
str
|
A path string, possibly using backslashes. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The normalized POSIX relative path, or |
Raises:
| Type | Description |
|---|---|
AppException
|
raw is empty/blank, absolute, or escapes the root. |
prune_empty_parents(start, stop)
staticmethod
Remove start and its empty ancestors, up to but excluding stop.
Both paths are resolved first. Starting at start, each directory is
removed with :meth:~pathlib.Path.rmdir and the walk moves to its
parent, ending at the first directory that is not empty. Only
directories strictly inside stop are touched: nothing happens when
the resolved start is stop or lies outside it. A directory that
no longer exists is skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str | Path
|
The directory to remove first. |
required |
stop
|
str | Path
|
The directory that bounds the walk; it is never removed. |
required |
Raises:
| Type | Description |
|---|---|
NotADirectoryError
|
start is a file. |
OSError
|
|
temp_dir()
staticmethod
Return the system's temporary directory as a :class:~pathlib.Path.
write_file(content, path, **kwargs)
staticmethod
Write content to path, creating parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str | bytes
|
Text or binary data to write. |
required |
path
|
str | Path
|
Destination file path. |
required |
**kwargs
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved :class: |