Files

52 lines
2.0 KiB
Plaintext
Raw Permalink Normal View History

2026-10-26 10:14:11 -05:00
#! @file output.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how a build writes its files: each in place of any file there, as a
#! C compiler replaces what it writes over, even an executable a program is
#! running from.
import std::io;
import system;
module sakura::native;
#! Writes bytes to a file, made with permissions, in place of any file there,
#! as `create_replacing` replaces it.
#! @param path The file.
#! @param bytes The bytes.
#! @param mode The permissions.
#! @returns Whether it was written.
pub def write_bytes(path: strview, bytes: span<u8>, mode: u32): bool {
var at_path := path::parse(path) else (_) { return false; };
var made := create_replacing(&at_path, mode) else (_) { return false; };
made.write(bytes) else (_) { return false; };
made.close();
set_permissions(&at_path, mode) else (_) { return false; };
return true;
}
#! Opens a file to write in place of any file at a path, as a C compiler
#! replaces what it writes over. One that cannot be opened where it is, as an
#! executable a program runs from, is moved aside first, to its path with
#! `.old` added, then removed from there. A program running from it keeps
#! running: Linux removes the file once the program ends, and Windows keeps it
#! until a file is next written in its place, which moves this one over it.
#! @param at The path of the file.
#! @param mode The permissions a file this makes is given, less the mask.
#! @returns The open file, or why it could not be opened.
pub def create_replacing(at: &path, mode: u32): result<file, io_error> {
var made := file::create(at, mode) else (why) {
var aside := path::parse($"{at.span}.old".span) else (_) { return why; };
io::rename(at, &aside) else (_) { return why; };
var fresh := file::create(at, mode) else (again) {
_ = io::rename(&aside, at);
return again;
};
_ = io::remove(&aside);
return move(&mut fresh);
};
return move(&mut made);
}