dymokomi/luce-prism
Source of release 0.6.0
0.6.0 / src / file_access.lucb
## Explicit bounded file access and durable atomic replacement.
from luce_std import files
import strings
import memory
import c
import interop
import codecs.api as codecs
from document import Document
from storage import Buffer, List, close_names, text_copy
from types import invalid, max_bytes
pub func read(path: str) -> Buffer!:
with memory.heap:
let name = try strings.copy(path)
defer strings.release(name)
let bytes = try files.read((c.str)name, limit = max_bytes)
defer bytes.release()
var out: Buffer
errdefer out.close()
try out.put(bytes.value)
return out
pub func write(path: str, bytes: const u8[]) -> !:
with memory.heap:
let name = try strings.copy(path)
defer strings.release(name)
try files.write_atomic((c.str)name, bytes, synchronize = true)
pub func exists(path: str) -> bool!:
with memory.heap:
let name = try strings.copy(path)
defer strings.release(name)
_ = files.metadata((c.str)name) catch failure: return false
return true
pub func load(path: str, codec: codecs.Codec = codecs.Codec.auto) -> interop.Reference[Document]!:
var bytes = try read(path)
defer bytes.close()
return try codecs.decode(bytes.bytes(), try codecs.codec_for_path(path) if codec == codecs.Codec.auto else codec)
pub func save(doc: interop.Reference[Document], path: str, codec: codecs.Codec = codecs.Codec.auto) -> !:
let bytes = try codecs.encode(doc, try codecs.codec_for_path(path) if codec == codecs.Codec.auto else codec)
defer bytes.release()
try write(path, (try bytes.get()).bytes())
pub func join(dir: str, name: str) -> Buffer!:
if name.length == 0 or name == "." or name == "..":
error(invalid, "invalid Prism dump basename")
for byte in name.bytes:
if byte == '/' or byte == 0:
error(invalid, "invalid Prism dump basename")
var out: Buffer
errdefer out.close()
try out.text(dir)
if dir.length > 0 and dir.bytes[dir.length - 1] != '/':
try out.byte((u8)'/')
try out.text(name)
return out
## Create the directory at `path`; its parent must exist.
pub func create_directory(path: str) -> !:
with memory.heap:
let name = try strings.copy(path)
defer strings.release(name)
try files.create_directory((c.str)name)
## Ensure the directory at `path` exists, with its parents.
pub func ensure_directory(path: str) -> !:
try files.ensure_directory(path)
## Remove the file at `path`.
pub func remove(path: str) -> !:
with memory.heap:
let name = try strings.copy(path)
defer strings.release(name)
try files.remove_file((c.str)name)
## The names in the directory at `path`, sorted.
pub func list_names(path: str) -> List[Buffer]!:
let name = try strings.copy(path)
defer strings.release(name)
let listing = try files.list((c.str)name)
defer listing.release()
var out: List[Buffer]
errdefer close_names(&out)
for entry in listing.value:
var copy = try text_copy(entry)
out.push(copy) catch failure:
copy.close()
error(failure.code, failure.message)
return out