oaknut.file

The shared metadata layer every other oaknut-* package builds on. It knows nothing of disc images or catalogues; it deals only in the side-channel metadata an Acorn file carries — load and execution addresses, the access byte, RISC OS filetypes — and the several host-side representations that metadata can travel in: INF sidecars, extended attributes, encoded filenames, and the acorn text codec.

Every name documented here is importable directly from oaknut.file.

Core types

The central metadata types and the host round-trip helpers are introduced, with worked examples, in the API patterns rather than repeated here:

Errors

The filesystem exception hierarchy. Each inherits from DataError; the broader error model and the handled_errors boundary are covered in Error handling.

exception oaknut.file.FSError(*args, exit_code=None)

Base exception for every oaknut filesystem error.

Format-specific subclasses live inside each filesystem package (e.g. oaknut.dfs.exceptions.DFSError, oaknut.adfs.exceptions.ADFSError, oaknut.afs.exceptions.AFSError). The default ExitCode is ExitCode.DATA_ERR inherited from DataError; specific subclasses override _exit_code to a more precise code.

Parameters:
  • args (object)

  • exit_code (Optional[ExitCode])

Return type:

None

exception oaknut.file.FilesystemClosedError(*args, exit_code=None)

An I/O operation was attempted on a closed filesystem handle.

Raised when a path object outlives the with block that opened its filesystem and a method is called that would have needed to touch the underlying disc image. Pure path manipulation (slash-join, parent, name, parts, path, equality) does not raise this.

Parameters:
  • args (object)

  • exit_code (Optional[ExitCode])

Return type:

None

exception oaknut.file.TitleNotSupportedError(*args, exit_code=None)

The target entity cannot carry a title.

A title is a human-readable label distinct from a name. Only some Acorn entities have a slot for one: the disc (every filesystem) and — on ADFS only — every directory. DFS and AFS directories have no title field, and files never do. Attempting to read or set a title on such an entity raises this.

Parameters:
  • args (object)

  • exit_code (Optional[ExitCode])

Return type:

None

exception oaknut.file.InvalidAddressError(*args, exit_code=None)

A load or execution address could not be parsed.

Addresses are written as integer literals whose base comes from the prefix — 0x hex, 0o octal, 0b binary, or none for decimal. Input that is not a valid literal (non-numeric text, or the Acorn & hex sigil) raises this. As an FSError it carries the data-error exit code and is rendered by the CLI boundary without a traceback.

Parameters:
  • args (object)

  • exit_code (Optional[ExitCode])

Return type:

None

Load and execution addresses

oaknut.file.parse_address(text)

Parse a load/exec address literal, honouring its base prefix.

0x1900 is hex, 0o14400 octal, 0b1 binary, and a bare 6400 decimal. Raises InvalidAddressError if text is not a valid integer literal.

Parameters:

text (str)

Return type:

int

Access flags

The Access enum (see File metadata) is the in-memory form; these helpers convert to and from the textual and hexadecimal representations used in INF sidecars and CLI output.

oaknut.file.parse_access(text)

Parse an access string back to an Access value.

Accepts three forms:

  • Symbolic: "LWR/R", "WR/WR", "R/" — letters before the slash are owner flags (P, L, W, R, E), letters after are public flags (W, R, E, L). P before the slash and L after it are the same bit 7, which format_access_text() writes as P (BeebWiki FNf_access). Case-insensitive. A missing slash treats the entire string as owner flags.

  • Hex with prefix: "0x0B", "0x33" — parsed as an integer.

  • Bare hex: "0B", "33" — two hex digits without prefix.

Raises InvalidAccessError on unrecognised input (a subclass of ValueError, so existing except ValueError handlers keep working, while the CLI boundary renders it cleanly without a traceback).

Parameters:

text (str)

Return type:

Access

oaknut.file.parse_access_spec(spec)

Compile an access spec into a transform on a file’s current access.

An absolute spec — "LWR/R", "WR/WR", "0x0B", "33" — is parsed by parse_access() and replaces the access wholesale, ignoring the current value.

An incremental spec begins with + or - and edits the current value: a sequence of +letters / -letters clauses applied left to right. Each clause uses the same owner/public slash convention as the absolute form, so +L locks, -W removes owner write, +R/R adds owner and public read, -/R removes public read, and +L-W combines them. Incremental edits are idempotent (adding a set flag or removing a clear one is a no-op).

The spec is validated now, so a malformed one raises InvalidAccessError immediately — even when the resulting transform is later applied to no files.

Parameters:

spec (str)

Return type:

Callable[[Access], Access]

oaknut.file.format_access_text(attr)

Format attributes as a human-readable access string.

Returns "owner/public" form, e.g. "LWR/R", after BeebWiki’s FNf_access. The owner E is shown only when the owner has neither R nor W — a run-only file reads E/ — since most filing systems treat a readable file as executable anyway; the public E likewise. Bit 7 leads the owner part as P. Bits 8–10 are attributes, not access, and are not shown.

Parameters:

attr (int | None)

Return type:

str

oaknut.file.format_access_hex(attr)

Format the access byte of attr as a two-digit uppercase hex string.

Bits 8–10 (the DOS attributes) are not part of the access byte. Returns empty string for None.

Parameters:

attr (int | None)

Return type:

str

Access conventions

Each filing system maps its own access representation to and from the Access word through an access convention, so every command that reads, copies or shows a file applies the same rules. A copy asks translate_access() what the destination will hold.

class oaknut.file.AccessConvention

A named mapping between one native access form and the canonical word.

A subclass states facts about its filing system: which canonical bits it can hold (representable), and how its native value reads as and is written from an Access. It makes no policy choices; those belong to translate_access().

abstractmethod to_canonical(native, context=AccessContext(is_directory=False, filetype=None))

Read a native access value as the canonical word.

Parameters:
Return type:

Access

abstractmethod from_canonical(access, context=AccessContext(is_directory=False, filetype=None), current=None)

Write the canonical word as a native value.

Bits the canonical word cannot express (for example the ADFS private bit) are taken from current, the object’s existing native value, when one is given.

Parameters:
Return type:

Native

settle(access, context=AccessContext(is_directory=False, filetype=None))

The canonical access this convention would hold if given access.

Parameters:
Return type:

Access

class oaknut.file.AccessContext(is_directory=False, filetype=None)

What a convention may need to know about an object besides its access.

Some rules depend on the kind of object: directories on most Acorn filing systems carry only the locked bit, and the UnixFS rules derive execute permission from a file’s filetype.

Parameters:
oaknut.file.FILE_CONTEXT = AccessContext(is_directory=False, filetype=None)

What a convention may need to know about an object besides its access.

Some rules depend on the kind of object: directories on most Acorn filing systems carry only the locked bit, and the UnixFS rules derive execute permission from a file’s filetype.

oaknut.file.DIRECTORY_CONTEXT = AccessContext(is_directory=True, filetype=None)

What a convention may need to know about an object besides its access.

Some rules depend on the kind of object: directories on most Acorn filing systems carry only the locked bit, and the UnixFS rules derive execute permission from a file’s filetype.

oaknut.file.translate_access(access, *, destination, context=AccessContext(is_directory=False, filetype=None), grant_public=False, override=None, warn=None)

The access a file copied with access will hold on destination.

access is the source’s canonical access. With grant_public the owner’s read and write rights are extended to the public (WR to WR/WR, LR to LR/R). override — typically a transform from parse_access_spec() — is applied next.

A run-only file (owner E without R) copied to a destination that cannot store execute becomes readable instead: the copy protection cannot be kept, and a file no one can run or read is of no use. warn, when given, is called with a message saying so.

The result is then settled by the destination convention, so it reports what the destination can actually store.

Parameters:
Return type:

Access

PiEconetBridge stores permissions in its own perm byte, whose lock and execute bits are swapped relative to the Acorn byte. The PiEB INF and user.econet_* xattr formats translate through this convention:

class oaknut.file.PiEconetBridgeAccessConvention

PiEconetBridge perm: owner and other R/W, locked, execute-only, hidden.

Owner and other read and write map to the canonical owner and public bits. The PiEB lock bit (0x04) is L; its execute-only bit (0x08) is run-only, owner E without R; its hidden bit (0x80) is the HIDDEN attribute.

oaknut.file.PIEB_ACCESS = <oaknut.file.pieb.PiEconetBridgeAccessConvention object>

owner and other R/W, locked, execute-only, hidden.

Owner and other read and write map to the canonical owner and public bits. The PiEB lock bit (0x04) is L; its execute-only bit (0x08) is run-only, owner E without R; its hidden bit (0x80) is the HIDDEN attribute.

Type:

PiEconetBridge perm

INF sidecars

Reading and writing the .inf sidecar lines that carry metadata alongside a plain data file, in both the traditional and PiEconetBridge flavours.

oaknut.file.parse_inf_line(line, *, encoding='latin-1')

Parse an INF sidecar line, auto-detecting the format.

Returns (source_label, metadata) or None if the line cannot be parsed. Only the first line of line is read. line is INF text in INF_ENCODING, one character per byte. encoding is the name codec of the medium the file belongs to: a name’s bytes, raw or percent-encoded, are decoded with it. Bytes it cannot decode are kept as their Latin-1 characters, for the destination’s own name rules to judge.

The source_label is "inf-trad" or "inf-pieb".

Parameters:
Return type:

tuple[str, AcornMeta] | None

oaknut.file.format_trad_inf_line(filename, load_address, exec_address, length, attr=None, *, encoding='latin-1')

Format a traditional INF line, per the Stardot producer rules.

Addresses and length are 8-digit hex and the access byte 2-digit hex; attribute bits above the access byte (bits 8–10) are not written. A name that is empty, literally TAPE, starts with a double quote, or holds a space or any character outside printable 7-bit ASCII is quoted, with ", % and such characters percent-encoded. encoding is the name codec of the medium the file comes from: the name is written as its bytes in that codec, and the rules above are applied to those bytes, as the Stardot specification requires. Returns a string like "HELLO    00001900 00008023 00000100 03".

Parameters:
Return type:

str

oaknut.file.format_pieb_inf_line(load_address, exec_address, attr=None, owner=0)

Format a PiEconetBridge INF line.

attr is canonical access, written in PiEB’s own perm layout; None gives PiEB’s default for a new file, WR/R. Returns a string like "0 ffffdd00 ffffdd00 13".

Parameters:
Return type:

str

oaknut.file.read_inf_file(filepath, *, encoding='latin-1')

Read and parse an INF sidecar file.

Returns (source_label, metadata) or None if the file does not exist or cannot be parsed. encoding is the name codec of the medium the file is bound for, as for parse_inf_line().

Parameters:
Return type:

tuple[str, AcornMeta] | None

oaknut.file.write_inf_file(filepath, content)

Write an INF sidecar file.

Parameters:
Return type:

None

Filename encoding

Metadata encoded into the filename itself — the name,xxx filetype suffix and the name,load-exec load/exec form, with the name,llllllll,eeeeeeee form read as well. See Acorn metadata on host filesystems.

oaknut.file.parse_encoded_filename(filename)

Strip metadata suffix from a filename.

Tries each encoding scheme in order: fixed-width load/exec, hyphenated load/exec, filetype. Returns (clean_filename, metadata) where metadata is None if no encoding was found.

Parameters:

filename (str)

Return type:

tuple[str, AcornMeta | None]

oaknut.file.build_filename_suffix(meta, *, typed_metadata=True)

Build a RISC OS filename encoding suffix.

Returns ,xxx for filetype-stamped files, or ,load-exec for literal load/exec addresses — the forms RISC OS LanManFS and the HostFS modules read.

The &FFF filetype marker also matches genuine I/O-processor addresses such as &FFFF1900, so typed_metadata says which the words hold: pass False for a file from an 8-bit filing system, and its words are written as ,load-exec whatever their top bits. Writing ,load-exec for a filetyped file loses nothing, whereas writing ,xxx for a genuine address loses the address.

Parameters:
Return type:

str

oaknut.file.build_loadexec_filename_suffix(meta)

Build a load/exec filename encoding suffix.

Returns ,load-exec with variable-width lowercase hex, whether or not the file is filetype-stamped, so a filetype’s datestamp survives in the name.

Parameters:

meta (AcornMeta)

Return type:

str

oaknut.file.build_mos_filename_suffix(meta)

Deprecated alias for build_loadexec_filename_suffix().

Parameters:

meta (AcornMeta)

Return type:

str

Extended attributes

Reading and writing metadata in host filesystem extended attributes, under both the user.acorn.* namespace and the PiEconetBridge user.econet_* convention.

oaknut.file.read_acorn_xattrs(filepath)

Read Acorn file metadata from extended attributes.

Tries the user.acorn.* namespace first; falls back to user.econet_* if the preferred namespace is absent. Returns None if neither namespace is present.

Parameters:

filepath (str | Path)

Return type:

AcornMeta | None

oaknut.file.write_acorn_xattrs(filepath, load_address, exec_address, attr=None)

Write Acorn file metadata as extended attributes.

Writes user.acorn.load, user.acorn.exec, and optionally user.acorn.attr as uppercase hex strings.

Parameters:
Return type:

None

oaknut.file.read_econet_xattrs(filepath)

Read PiEconetBridge extended attributes.

Returns None if no Econet attributes are present.

Parameters:

filepath (str | Path)

Return type:

AcornMeta | None

oaknut.file.write_econet_xattrs(filepath, load_address, exec_address, attr=None, owner=0)

Write PiEconetBridge-compatible extended attributes.

Writes the four user.econet_* attributes used by PiEconetBridge. attr is canonical access, written in PiEB’s own perm layout. When attr is None, PiEB’s default for a new file, WR/R, is written.

Parameters:
Return type:

None

The acorn text codec

Importing oaknut.file registers an acorn text codec, so data.decode("acorn") works anywhere; these are the direct entry points for the same conversion.

oaknut.file.decode_text(data, *, encoding='acorn', newline=None)

Decode data as text, optionally normalising line endings.

Parameters:
  • data (bytes) – Raw bytes to decode.

  • encoding (str) – Text encoding. Defaults to "acorn" — the BBC character set, registered as a Python codec by oaknut.file.acorn_encoding.

  • newline (str | None) –

    Line-ending translation policy.

    • None (the default): universal newlines — "\r\n", "\r" and "\n" all become "\n" in the returned string.

    • "": pass the decoded text through unchanged.

Return type:

str

oaknut.file.encode_text(text, *, encoding='acorn', newline='\r')

Encode text as bytes, optionally translating line endings.

Parameters:
  • text (str) – String to encode.

  • encoding (str) – Text encoding. Defaults to "acorn" — the BBC character set, registered as a Python codec by oaknut.file.acorn_encoding.

  • newline (str | None) –

    Line-ending translation policy.

    • "\r" (the default): every "\n" in text is replaced with "\r" before encoding. A natural Python multiline string lands on the disc with the Acorn-native line terminator.

    • "" or None: pass text through unchanged.

    • Any other string: replace each "\n" with the given sequence before encoding.

Return type:

bytes

Metadata source labels

String labels naming where a piece of metadata was resolved from. The parsing helpers return one of these, and the CLI reports it.

oaknut.file.SOURCE_DIR = 'dir'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_FILENAME = 'filename'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_INF_TRAD = 'inf-trad'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_INF_PIEB = 'inf-pieb'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_SPARKFS = 'sparkfs'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_XATTR_ACORN = 'xattr-acorn'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

oaknut.file.SOURCE_XATTR_PIEB = 'xattr-pieb'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

Default metadata formats

The formats the host-bridge helpers fall back to; the import cascade is discussed under File metadata.

oaknut.file.DEFAULT_EXPORT_META_FORMAT = MetaFormat.INF_TRAD

Supported metadata output formats.

FILENAME_MOS is a deprecated alias for FILENAME_LOADEXEC, and MetaFormat("filename-mos") resolves to it with a DeprecationWarning.

oaknut.file.DEFAULT_IMPORT_META_FORMATS = (MetaFormat.INF_TRAD, MetaFormat.XATTR_ACORN, MetaFormat.FILENAME_RISCOS)

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

oaknut.file.DEPRECATED_META_FORMATS = {'filename-mos': MetaFormat.FILENAME_LOADEXEC}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Host filesystem helpers

oaknut.file.copy_file(src, dst, **write_kwargs)

Copy a single file from src to dst.

Reads data and metadata (load address, exec address, access attributes) from src and writes them to dst. Both arguments must be path-like objects supporting read_bytes(), stat(), exists(), is_dir(), and write_bytes(data, ...).

Additional keyword arguments override source metadata.

Raises:
Parameters:
Return type:

None

class oaknut.file.Stat(*args, **kwargs)

Uniform metadata shape returned by every oaknut path’s stat().

Six fields, all required:

  • length — byte length of the file’s contents (0 for directories).

  • load_address — Acorn load address (32-bit unsigned).

  • exec_address — Acorn exec address (32-bit unsigned).

  • access — canonical Access flags synthesised from whatever the source filesystem stores natively.

  • is_directory — True if this entry is a directory.

  • date — entry date stamp, or None where the format does not store one. Type is the source filesystem’s date type (AFS uses oaknut.afs.AfsDate); callers that need to compare across filesystems should check is None first.

Stat is decorated with typing.runtime_checkable() so isinstance(st, Stat) works for ducktype tests, but the cheapest check in cross-filesystem code is still attribute access.

oaknut.file.resolving_io(method)

Decorator: resolve ^ components before calling an I/O method.

Wraps a path-class I/O method so any literal carets stored in the path are collapsed via AcornPath.resolve() before the underlying body runs. If the path has no carets, the call goes straight through.

Apply to every method on a concrete path class whose answer depends on the disc — read_bytes(), exists(), stat(), iterdir(), and the rest. Pure path ops (__str__, parts, parent) stay un-decorated because they should preserve the literal form.

Parameters:

method (_F)

Return type:

_F