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:
AcornMeta— the canonical per-file metadata record — and theAccessandBootOptionflag enums: see File metadata.MetaFormat, naming the host side-channels, with theexport_with_metadata()andimport_with_metadata()helpers that move bytes plus metadata across the host boundary: also File metadata.AcornPath, the path type the filesystems return: see Path objects.
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 defaultExitCodeisExitCode.DATA_ERRinherited fromDataError; specific subclasses override_exit_codeto a more precise code.
- 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
withblock 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.
- 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.
- 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 —
0xhex,0ooctal,0bbinary, or none for decimal. Input that is not a valid literal (non-numeric text, or the Acorn&hex sigil) raises this. As anFSErrorit carries the data-error exit code and is rendered by the CLI boundary without a traceback.
Load and execution addresses¶
- oaknut.file.parse_address(text)¶
Parse a load/exec address literal, honouring its base prefix.
0x1900is hex,0o14400octal,0b1binary, and a bare6400decimal. RaisesInvalidAddressErrorif text is not a valid integer literal.
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
Accessvalue.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).Pbefore the slash andLafter it are the same bit 7, whichformat_access_text()writes asP(BeebWikiFNf_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
InvalidAccessErroron unrecognised input (a subclass ofValueError, so existingexcept ValueErrorhandlers keep working, while the CLI boundary renders it cleanly without a traceback).
- 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 byparse_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/-lettersclauses applied left to right. Each clause uses the same owner/public slash convention as the absolute form, so+Llocks,-Wremoves owner write,+R/Radds owner and public read,-/Rremoves public read, and+L-Wcombines 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
InvalidAccessErrorimmediately — even when the resulting transform is later applied to no files.
- oaknut.file.format_access_text(attr)¶
Format attributes as a human-readable access string.
Returns
"owner/public"form, e.g."LWR/R", after BeebWiki’sFNf_access. The ownerEis shown only when the owner has neitherRnorW— a run-only file readsE/— since most filing systems treat a readable file as executable anyway; the publicElikewise. Bit 7 leads the owner part asP. Bits 8–10 are attributes, not access, and are not shown.
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 anAccess. It makes no policy choices; those belong totranslate_access().- abstractmethod to_canonical(native, context=AccessContext(is_directory=False, filetype=None))¶
Read a native access value as the canonical word.
- Parameters:
native (Native)
context (AccessContext)
- Return type:
- 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:
access (Access)
context (AccessContext)
current (Native | None)
- Return type:
Native
- settle(access, context=AccessContext(is_directory=False, filetype=None))¶
The canonical access this convention would hold if given access.
- Parameters:
access (Access)
context (AccessContext)
- Return type:
- 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.
- 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 (
WRtoWR/WR,LRtoLR/R). override — typically a transform fromparse_access_spec()— is applied next.A run-only file (owner
EwithoutR) 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.
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) isL; its execute-only bit (0x08) is run-only, ownerEwithoutR; its hidden bit (0x80) is theHIDDENattribute.
- 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) isL; its execute-only bit (0x08) is run-only, ownerEwithoutR; its hidden bit (0x80) is theHIDDENattribute.- 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)orNoneif the line cannot be parsed. Only the first line of line is read. line is INF text inINF_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".
- 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".
- 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
permlayout;Nonegives PiEB’s default for a new file,WR/R. Returns a string like"0 ffffdd00 ffffdd00 13".
- oaknut.file.read_inf_file(filepath, *, encoding='latin-1')¶
Read and parse an INF sidecar file.
Returns
(source_label, metadata)orNoneif the file does not exist or cannot be parsed. encoding is the name codec of the medium the file is bound for, as forparse_inf_line().
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 isNoneif no encoding was found.
- oaknut.file.build_filename_suffix(meta, *, typed_metadata=True)¶
Build a RISC OS filename encoding suffix.
Returns
,xxxfor filetype-stamped files, or,load-execfor literal load/exec addresses — the forms RISC OS LanManFS and the HostFS modules read.The
&FFFfiletype marker also matches genuine I/O-processor addresses such as&FFFF1900, so typed_metadata says which the words hold: passFalsefor a file from an 8-bit filing system, and its words are written as,load-execwhatever their top bits. Writing,load-execfor a filetyped file loses nothing, whereas writing,xxxfor a genuine address loses the address.
- oaknut.file.build_loadexec_filename_suffix(meta)¶
Build a load/exec filename encoding suffix.
Returns
,load-execwith variable-width lowercase hex, whether or not the file is filetype-stamped, so a filetype’s datestamp survives in the name.
- oaknut.file.build_mos_filename_suffix(meta)¶
Deprecated alias for
build_loadexec_filename_suffix().
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 touser.econet_*if the preferred namespace is absent. ReturnsNoneif neither namespace is present.
- 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 optionallyuser.acorn.attras uppercase hex strings.
- oaknut.file.read_econet_xattrs(filepath)¶
Read PiEconetBridge extended attributes.
Returns
Noneif no Econet attributes are present.
- 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 ownpermlayout. When attr is None, PiEB’s default for a new file,WR/R, is written.
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
dataas 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 byoaknut.file.acorn_encoding.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:
- oaknut.file.encode_text(text, *, encoding='acorn', newline='\r')¶
Encode
textas 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 byoaknut.file.acorn_encoding.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.""orNone: pass text through unchanged.Any other string: replace each
"\n"with the given sequence before encoding.
- Return type:
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_MOSis a deprecated alias forFILENAME_LOADEXEC, andMetaFormat("filename-mos")resolves to it with aDeprecationWarning.
- 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(), andwrite_bytes(data, ...).Additional keyword arguments override source metadata.
- Raises:
FileNotFoundError – If src does not exist.
ValueError – If src is a directory.
- Parameters:
- Return type:
- 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— canonicalAccessflags synthesised from whatever the source filesystem stores natively.is_directory—Trueif this entry is a directory.date— entry date stamp, orNonewhere the format does not store one. Type is the source filesystem’s date type (AFS usesoaknut.afs.AfsDate); callers that need to compare across filesystems should checkis Nonefirst.
Statis decorated withtyping.runtime_checkable()soisinstance(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