summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-16 23:37:54 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commitca602943e3fc9faad24e51497eeafb0ae7856800 (patch)
treedc35633094f5355d535587f388d6ffd3896dace1
parentc3b9938e9cb381bc7378fdca9073520ff1711ad6 (diff)
downloadsketchbook-ca602943e3fc9faad24e51497eeafb0ae7856800.tar.gz
sketchbook-ca602943e3fc9faad24e51497eeafb0ae7856800.zip
Keep a sketch's files in .sketchbook/, a shipped game's in XDG
zig build run, probe and export pass --state .sketchbook/<name>.state. The host makes that directory with a .gitignore of * (a sessions database grows, and the jj snapshot build_info takes would commit it while under a megabyte), and moves the state and store an older build kept beside it in once, with renameat2(NOREPLACE): when both exist nothing moves and the host says so. Without --state an interactive run keeps its files in $XDG_DATA_HOME/<name>/ (~/.local/share without it), not the cwd; a script or an export still uses sketch.state. test-paths checks all three cases. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--build.zig39
-rw-r--r--src/host/Host.zig22
-rw-r--r--src/host/root.zig38
3 files changed, 90 insertions, 9 deletions
diff --git a/build.zig b/build.zig
index f7a1aa9..809ddb1 100644
--- a/build.zig
+++ b/build.zig
@@ -386,6 +386,35 @@ pub fn build(b: *Build) void {
test_step.dependOn(&past.step);
b.step("test-past", "Replay past sessions, to a time and across a code change").dependOn(&past.step);
+ // Where files go. Without --state: the XDG data directory, state and
+ // sessions. In .sketchbook/ (`zig build run`'s): a .gitignore, and an
+ // older build's state moved in, once, never over a file there.
+ const paths = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2")
+ \\rm -rf "$d"/* "$d"/.sketchbook; cd "$d"
+ \\XDG_DATA_HOME="$d/data" "$exe" --headless --console quit "$lib"
+ \\test -s data/replay/replay.state; test -s data/replay/replay.xitdb
+ \\"$exe" --headless --state replay.state --console "set updates 7" --console quit "$lib"
+ \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
+ \\grep -q moved err; test ! -e replay.state; test ! -e replay.state.store; grep -qx '*' .sketchbook/.gitignore
+ \\printf 'expect updates 7\n' >check.script
+ \\"$exe" --headless --state .sketchbook/replay.state --script check.script "$lib"
+ \\"$exe" --headless --state replay.state --console quit "$lib"
+ \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
+ \\grep -q 'both exist' err; test -e replay.state
+ \\"$exe" --headless --state .sketchbook/replay.state --script check.script "$lib"
+ \\rm -rf "$d"/* "$d"/.sketchbook
+ });
+ paths.setName("state and sessions paths");
+ paths.addArtifactArg(host_exe);
+ paths.addArtifactArg(recorded);
+ _ = paths.addOutputDirectoryArg("paths");
+ paths.has_side_effects = true;
+ paths.expectExitCode(0);
+ test_step.dependOn(&paths.step);
+ b.step("test-paths", "Check where state and sessions files go").dependOn(&paths.step);
+
// Recorded input replays to the same state: played, seeked, stepped,
// and after a live pointer move (core host behaviour, not an API).
const replay = b.addRunArtifact(host_exe);
@@ -1293,7 +1322,9 @@ pub const App = struct {
}
pub const RunOptions = struct {
- /// State file, relative to the working directory.
+ /// State file, relative to the working directory;
+ /// `.sketchbook/<name>.state` by default, where the host keeps the
+ /// sessions database beside it, all ignored by git and jj.
state: ?[]const u8 = null,
/// Where relative asset paths resolve; the project root by default.
cwd: ?Build.LazyPath = null,
@@ -1306,7 +1337,7 @@ pub const App = struct {
const install = b.addInstallArtifact(library, .{});
const run = b.addRunArtifact(app.sb.host_exe);
run.step.dependOn(&install.step);
- run.addArgs(&.{ "--state", options.state orelse b.fmt("{s}.state", .{app.name}) });
+ run.addArgs(&.{ "--state", options.state orelse b.fmt(".sketchbook/{s}.state", .{app.name}) });
run.addFileArg(b.graph.path(.install_lib, library.out_filename));
run.setCwd(options.cwd orelse b.path("."));
run.stdio = .inherit;
@@ -1377,7 +1408,7 @@ pub const App = struct {
pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run {
const b = app.sb.b;
const run = b.addRunArtifact(app.sb.probe_exe);
- run.addArg(state orelse b.fmt("{s}.state", .{app.name}));
+ run.addArg(state orelse b.fmt(".sketchbook/{s}.state", .{app.name}));
run.setCwd(b.path("."));
run.stdio = .inherit;
run.addPassthruArgs();
@@ -1651,7 +1682,7 @@ pub const App = struct {
// `--export` takes the first argument after `--`.
const exporting = b.addRunArtifact(exe);
- exporting.addArgs(&.{ "--state", b.fmt("{s}.state", .{app.name}), "--export" });
+ exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{s}.state", .{app.name}), "--export" });
exporting.addPassthruArgs();
exporting.setCwd(b.path("."));
exporting.stdio = .inherit;
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 1c9d65a..d31f4b7 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -28,8 +28,9 @@ pub const Options = struct {
/// Local 9P control socket, opt-in.
ninep: ?[]const u8 = null,
/// State file; the sessions database goes next to it, `<name>.xitdb`
- /// for `<name>.state`.
- state: []const u8 = "sketch.state",
+ /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state`
+ /// (`~/.local/share` without it), for a shipped game.
+ state: []const u8 = "",
/// Playing a script: from fresh state, sessions go to memory only.
script: bool = false,
/// Offscreen video, silent audio, no vsync: for scripts and CI.
@@ -91,6 +92,8 @@ reloads: usize = 0,
/// file's inode, size and modification time): sessions' stretches carry it,
/// and `play` warns on a mismatch.
build: u64 = 0,
+/// The state file's path when the host chose it (`Options.state`), `gpa`'s.
+state_path: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
@@ -121,7 +124,8 @@ exported: u64 = 0,
dialog: Dialog = .{},
control: ?*Control = null,
-pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void {
+pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void {
+ var options = given;
if (options.headless) {
// Overriding: a plain hint loses to the environment, and a user's
// SDL_VIDEO_DRIVER=wayland would open real windows during tests.
@@ -165,6 +169,16 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
// Colors carry alpha: fills blend, as they do on the web.
_ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const state_path = if (given.state.len > 0) "" else blk: {
+ const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.state", .{ data, info.name, info.name });
+ errdefer gpa.free(path);
+ try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
+ break :blk path;
+ };
+ errdefer gpa.free(state_path);
+ if (state_path.len > 0) options.state = state_path;
var state = try memory.StateFile.open(gpa, options.state);
errdefer state.close();
var store_buf: [std.fs.max_path_bytes]u8 = undefined;
@@ -192,6 +206,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.sessions = .{ .gpa = gpa, .io = io },
.sketch = sketch,
.library = library,
+ .state_path = state_path,
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
.input = .{ .exporting = options.export_to != null },
@@ -253,6 +268,7 @@ pub fn deinit(self: *Host) void {
self.pending.deinit(self.gpa);
self.frame_arena.deinit();
self.info_arena.deinit();
+ self.gpa.free(self.state_path);
if (self.library) |*l| l.close();
c.SDL_Quit();
}
diff --git a/src/host/root.zig b/src/host/root.zig
index 618512b..5889b42 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -2,7 +2,8 @@
//! that it hot-reloads whenever a build replaces it.
//!
//! sketchbook [options] [LIBRARY]
-//! --state FILE persistent state (default: <name>.state)
+//! --state FILE persistent state (default: $XDG_DATA_HOME/<name>/<name>.state;
+//! sketch.state for a script or an export)
//! --headless offscreen video, silent audio
//! --script FILE play a script instead of reading devices
//! --fresh start from default state (sessions, marks and clips are kept)
@@ -99,8 +100,10 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
// removed instead: nothing reads them, and a player may have the given
// ones open.
var private_buf: [std.fs.max_path_bytes]u8 = undefined;
+ if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state";
const given = options.state;
const private = (script_path != null or options.export_to != null) and options.fresh;
+ if (!private) sketchbookDir(init.io, given);
if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
defer if (private) for ([_][]const u8{ "", ".store" }) |suffix| {
var from: [std.fs.max_path_bytes + 16]u8 = undefined;
@@ -128,7 +131,8 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
const usage =
\\usage: sketchbook [options] [LIBRARY]
\\ --9p SOCKET local 9P controls: ctl, status, log, screen.png
- \\ --state FILE persistent state (default: sketch.state)
+ \\ --state FILE persistent state; sessions are kept beside it (default:
+ \\ $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export)
\\ --headless offscreen video, silent audio, no vsync
\\ --script FILE play a script instead of reading devices
\\ --fresh start from default state (sessions, marks and clips are kept)
@@ -144,6 +148,36 @@ const usage =
\\
;
+/// A state file in a directory named `.sketchbook` (`zig build run`'s):
+/// the directory is made, with a `.gitignore` of `*` (its sessions database
+/// grows, and a jj snapshot would commit it), and the state and store files
+/// an older build kept beside it are moved in, once. A file is never
+/// replaced: when both exist, nothing moves.
+fn sketchbookDir(io: std.Io, state: []const u8) void {
+ const dir = std.fs.path.dirname(state) orelse return;
+ if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return;
+ const cwd = std.Io.Dir.cwd();
+ cwd.createDirPath(io, dir) catch return;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return;
+ cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {};
+ for ([_][]const u8{ "", ".store" }) |suffix| {
+ var from_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var to_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const parent = std.fs.path.dirname(dir) orelse ".";
+ const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}{s}", .{ parent, std.fs.path.basename(state), suffix }, 0) catch return;
+ const to = std.fmt.bufPrintSentinel(&to_buf, "{s}{s}", .{ state, suffix }, 0) catch return;
+ switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
+ .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
+ .EXIST => {
+ std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to });
+ return;
+ },
+ else => {},
+ }
+ }
+}
+
fn fatal(message: []const u8) noreturn {
std.debug.print("sketchbook: {s}\n", .{message});
std.process.exit(2);