Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162//! What the prototypes keep between runs: one small file per name in//! $XDG_STATE_HOME/parcel, or ~/.local/state/parcel. It is state the UI//! changes, such as Desk's columns, not configuration someone edits. The//! tests and the shot renderer pass none, so they start from the defaults//! and write nothing.
const std = @import("std");const Io = std.Io;const Environ = std.process.Environ;const mem = std.mem;const log = std.log.scoped(.settings);
const Settings = @This();
io: Io,dir: Io.Dir,
/// Opens the directory, creating it. Null, logged, when there is no home/// directory to put it in or it cannot be made.pub fn open(io: Io, environ: *const Environ.Map) ?Settings { var buf: [Io.Dir.max_path_bytes]u8 = undefined; const path = if (environ.get("XDG_STATE_HOME")) |state| mem.print(&buf, "{s}/parcel", .{state}) catch return null else if (environ.get("HOME")) |home| mem.print(&buf, "{s}/.local/state/parcel", .{home}) catch return null else { log.warn("neither XDG_STATE_HOME nor HOME is set; nothing will be saved", .{}); return null; }; const dir = Io.Dir.cwd().createDirPathOpen(io, path, .{}) catch |err| { log.warn("{s}: {t}; nothing will be saved", .{ path, err }); return null; }; return .{ .io = io, .dir = dir };}
pub fn close(self: Settings) void { self.dir.close(self.io);}
/// What was saved under `name`, read into `buf`; null if nothing was.pub fn load(self: Settings, name: []const u8, buf: []u8) ?[]u8 { return self.dir.readFile(self.io, name, buf) catch |err| { if (err != error.FileNotFound) log.warn("{s}: {t}", .{ name, err }); return null; };}
/// Saves `bytes` under `name`, replacing the file whole so a crash midway/// leaves the old one. A failure is logged: losing a preference should not/// stop the app.pub fn save(self: Settings, name: []const u8, bytes: []const u8) void { write(self, name, bytes) catch |err| log.warn("{s}: {t}", .{ name, err });}
fn write(self: Settings, name: []const u8, bytes: []const u8) !void { var file = try self.dir.createFileAtomic(self.io, name, .{ .replace = true }); defer file.deinit(self.io); try file.file.writeStreamingAll(self.io, bytes); try file.replace(self.io);}