From 4c194047d210ad9cf571c6019731d00d1e3615a4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 6 Nov 2026 12:14:58 -0300 Subject: idioms #4, string chains are an enum and a switch: main's flags (each exact one a Flag, the prefixed ones as they were), --ps's rows and manage's verb, the daemon's verbs on both ends and its registry's rows, an upgrade record's words, the window driver's mouse kinds and finger names, a frame script's click target and a mount name's reserved words go through std.meta.stringToEnum; with them main asks std.Io for its working directory, its chdir, a directory's access and /proc's comm, not libc Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/main.zig | 162 ++++++++++++++++++++++++++--------------------------------- 1 file changed, 71 insertions(+), 91 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 5cbfa7f4..7b6fd6d4 100644 --- a/src/main.zig +++ b/src/main.zig @@ -150,7 +150,7 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const // The pane's directory: this one, unless its name could not be one line // of a ctl (a newline, a control byte): then the session's. var cwd_buf: [4096]u8 = undefined; - const cwd: []const u8 = if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]u8, @ptrCast(c))) else ""; + const cwd: []const u8 = cwd_buf[0 .. std.process.currentPath(io, &cwd_buf) catch 0]; // ...or the session's when this one may not be written (`git log` in // /usr/src), which /pager refuses: the text is paged all the same. const plain = for (cwd) |c| { @@ -403,8 +403,44 @@ fn nativeMain(std_init: std.process.Init) !void { var i: usize = if (resuming) 2 else 1; while (i < args.len) : (i += 1) { const a = args[i]; - if (std.mem.eql(u8, a, "--tty")) { - explicit_tty = true; + const Flag = enum { @"--tty", @"-n", @"-l", @"--9p", @"--9p-tcp", @"--nested", @"-w", @"--wait", @"--detach", @"--attach", @"--ps", @"--kill-all", @"-h", @"--help", @"--version", @"--" }; + if (std.meta.stringToEnum(Flag, a)) |flag| switch (flag) { + .@"--tty" => explicit_tty = true, + .@"-n" => { + session_only = false; + new_session = true; + i += 1; + if (i >= args.len) badArgs(init.io, "-n needs a count after it: 1 or 3", .{}); + opts.shells = std.fmt.parseInt(u8, args[i], 10) catch + badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{args[i]}); + }, + .@"-l" => { + session_only = false; + new_session = true; + i += 1; + if (i >= args.len) badArgs(init.io, "-l needs the path of a dump to load", .{}); + opts.load_path = args[i]; + }, + .@"--9p" => badArgs(init.io, "--9p needs a socket name: --9p=", .{}), + .@"--9p-tcp" => badArgs(init.io, "--9p-tcp needs tcp!!", .{}), + .@"--nested" => opts.nested = true, + .@"-w", .@"--wait" => wait = true, + .@"--detach" => detach = "", + .@"--attach" => attach = "", + .@"--ps" => manage(init.io, .list, ""), + .@"--kill-all" => manage(init.io, .killall, ""), + .@"-h", .@"--help" => return std.Io.File.stdout().writeStreamingAll(init.io, help_text), + .@"--version" => return std.Io.File.stdout().writeStreamingAll(init.io, version_text), + .@"--" => { + // The end of options: what follows is a name, `-dash.txt` too. + for (args[i + 1 ..]) |name| { + if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); + if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name}); + session_only = false; + positional = name; + } + break; + }, } else if (std.mem.eql(u8, a, "--tty-toggle") or std.mem.startsWith(u8, a, "--tty-toggle=")) { session_only = false; new_session = true; @@ -414,21 +450,6 @@ fn nativeMain(std_init: std.process.Init) !void { break :next args[i]; }; opts.tty_toggle = parseCtrlKey(key) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{key}); - } else if (std.mem.eql(u8, a, "-n")) { - session_only = false; - new_session = true; - i += 1; - if (i >= args.len) badArgs(init.io, "-n needs a count after it: 1 or 3", .{}); - opts.shells = std.fmt.parseInt(u8, args[i], 10) catch - badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{args[i]}); - } else if (std.mem.eql(u8, a, "-l")) { - session_only = false; - new_session = true; - i += 1; - if (i >= args.len) badArgs(init.io, "-l needs the path of a dump to load", .{}); - opts.load_path = args[i]; - } else if (std.mem.eql(u8, a, "--9p")) { - badArgs(init.io, "--9p needs a socket name: --9p=", .{}); } else if (std.mem.startsWith(u8, a, "--9p=")) { new_session = true; const name = a["--9p=".len..]; @@ -444,8 +465,6 @@ fn nativeMain(std_init: std.process.Init) !void { badArgs(init.io, "--9p-tcp needs tcp!!", .{}); if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{}); opts.ninep_tcp = dial; - } else if (std.mem.eql(u8, a, "--9p-tcp")) { - badArgs(init.io, "--9p-tcp needs tcp!!", .{}); } else if (std.mem.startsWith(u8, a, "--mount=")) { new_session = true; const mount = a["--mount=".len..]; @@ -464,41 +483,14 @@ fn nativeMain(std_init: std.process.Init) !void { mounts_len += 1; } else if (std.mem.startsWith(u8, a, "--geometry=")) { opts.geometry = a["--geometry=".len..]; - } else if (std.mem.eql(u8, a, "--nested")) { - opts.nested = true; - } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) { - wait = true; - } else if (std.mem.eql(u8, a, "--detach")) { - detach = ""; } else if (std.mem.startsWith(u8, a, "--detach=")) { detach = a["--detach=".len..]; - } else if (std.mem.eql(u8, a, "--attach")) { - attach = ""; } else if (std.mem.startsWith(u8, a, "--attach=")) { attach = a["--attach=".len..]; - } else if (std.mem.eql(u8, a, "--ps")) { - manage(init.io, "list", ""); } else if (std.mem.startsWith(u8, a, "--kill=")) { const name = a["--kill=".len..]; if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{}); - manage(init.io, "kill", name); - } else if (std.mem.eql(u8, a, "--kill-all")) { - manage(init.io, "killall", ""); - } else if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) { - try std.Io.File.stdout().writeStreamingAll(init.io, help_text); - return; - } else if (std.mem.eql(u8, a, "--version")) { - try std.Io.File.stdout().writeStreamingAll(init.io, version_text); - return; - } else if (std.mem.eql(u8, a, "--")) { - // The end of options: what follows is a name, `-dash.txt` too. - for (args[i + 1 ..]) |name| { - if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); - if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name}); - session_only = false; - positional = name; - } - break; + manage(init.io, .kill, name); } else if (a.len > 0 and (a[0] != '-' or std.mem.eql(u8, a, "-")) and positional == null) { // `-` is stdin, as for cat and vim: a text to show. session_only = false; @@ -645,9 +637,8 @@ fn nativeMain(std_init: std.process.Init) !void { // Its directory not there either: the name made absolute as // written, and the pane's Save makes the directories. var cwd_buf: [4096]u8 = undefined; - if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) Refuse.with(init.io, word, error.NoWorkingDirectory); - const cwd = std.mem.sliceTo(&cwd_buf, 0); - const absolute = std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + const cwd = cwd_buf[0 .. std.process.currentPath(init.io, &cwd_buf) catch Refuse.with(init.io, word, error.NoWorkingDirectory)]; + const absolute = std.Io.Dir.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); // Missing because one above may not be searched or written: // its Save could never make it, so refused now. if (pardes.filesystem.deniedAbove(std.Io.Dir.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable); @@ -655,13 +646,7 @@ fn nativeMain(std_init: std.process.Init) !void { }; // A directory that is there but may not be read or written: a // pane for the name could only fail at its Save, so refused now. - var dir_z_buf: [4096]u8 = undefined; - if (std.fmt.bufPrintSentinel(&dir_z_buf, "{s}", .{dir.path}, 0)) |dir_z| { - const R_OK = 4; - const W_OK = 2; - const X_OK = 1; - if (std.c.access(dir_z.ptr, R_OK | W_OK | X_OK) != 0) Refuse.with(init.io, word, error.DirectoryNotWritable); - } else |_| {} + std.Io.Dir.cwd().access(init.io, dir.path, .{ .read = true, .write = true, .execute = true }) catch Refuse.with(init.io, word, error.DirectoryNotWritable); break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); }; var made_serial: ?u32 = null; @@ -714,12 +699,12 @@ fn nativeMain(std_init: std.process.Init) !void { { opts.file = try arena.dupe(u8, target.path); opts.file_line = target.at.line; - } else if (std.c.chdir(a.ptr) != 0) { + } else if (std.meta.isError(std.process.setCurrentPath(init.io, a))) { var cwdbuf: [4096]u8 = undefined; - const cwd = std.c.getcwd(&cwdbuf, cwdbuf.len) orelse - badArgs(init.io, "this shell's working directory is gone; cd somewhere that exists", .{}); + const cwd = cwdbuf[0 .. std.process.currentPath(init.io, &cwdbuf) catch + badArgs(init.io, "this shell's working directory is gone; cd somewhere that exists", .{})]; var realbuf: [4096]u8 = undefined; - switch (@import("look.zig").resolve(null, a, std.mem.span(@as([*:0]u8, @ptrCast(cwd))), &realbuf)) { + switch (@import("look.zig").resolve(null, a, cwd, &realbuf)) { .file => |t| { opts.file = try arena.dupe(u8, t.path); opts.file_line = t.at.line; @@ -727,7 +712,7 @@ fn nativeMain(std_init: std.process.Init) !void { .kind => |t| opts.file = try arena.dupe(u8, t.path), .none => opts.missing = .{ .word = try arena.dupe(u8, a), - .dir = try arena.dupe(u8, std.mem.span(@as([*:0]u8, @ptrCast(cwd)))), + .dir = try arena.dupe(u8, cwd), }, .url => badArgs(init.io, "a URL is not something a launch can open; start pardes and click it", .{}), .pane => badArgs(init.io, "@pN addresses a pane of a running pardes, so there is none yet", .{}), @@ -831,17 +816,17 @@ extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; /// `pardes --ps`: what the per-user daemon keeps, as a tree; `--kill=` /// and `--kill-all`: those sessions ended with their shells, a TERM and, /// for one still there 2 s later, a KILL. -fn manage(io: std.Io, verb: []const u8, name: []const u8) noreturn { +fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) noreturn { if (comptime !daemon.supported) die(io, "this system has no pardes daemon", .{}); var words_buf: [300]u8 = undefined; - const words = if (std.mem.eql(u8, verb, "kill")) + const words = if (verb == .kill) std.fmt.bufPrint(&words_buf, "kill {s}", .{name}) catch die(io, "that name is too long", .{}) else - verb; + @tagName(verb); var buf: [4096]u8 = undefined; const said = daemon.ask(words, &buf) orelse die(io, "no pardes daemon is running", .{}); if (std.mem.startsWith(u8, said, "no ")) die(io, "{s}", .{said[3..]}); - if (std.mem.eql(u8, verb, "list")) { + if (verb == .list) { var out: [8192]u8 = undefined; var w: std.Io.Writer = .fixed(&out); var lines = std.mem.tokenizeScalar(u8, said, '\n'); @@ -851,21 +836,21 @@ fn manage(io: std.Io, verb: []const u8, name: []const u8) noreturn { const what = it.next() orelse continue; const pid = it.next() orelse continue; var comm_buf: [64]u8 = undefined; - const comm = commOf(pid, &comm_buf); - if (std.mem.eql(u8, what, "daemon")) { - w.print("pardes daemon {s}\n", .{pid}) catch break; - } else if (std.mem.eql(u8, what, "session")) { - const kind = it.next() orelse ""; - const state = it.next() orelse ""; - w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, state }) catch break; - } else if (std.mem.eql(u8, what, "client")) { - w.print(" client {s} {s}\n", .{ pid, comm }) catch break; - } else if (std.mem.eql(u8, what, "shell")) { - w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; - } else if (std.mem.eql(u8, what, "orphan")) { - if (!orphans) w.writeAll(" shells no session holds (Adopt takes them, --kill-all ends them)\n") catch break; - orphans = true; - w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; + const comm = commOf(io, pid, &comm_buf); + switch (std.meta.stringToEnum(enum { daemon, session, client, shell, orphan }, what) orelse continue) { + .daemon => w.print("pardes daemon {s}\n", .{pid}) catch break, + .session => { + const kind = it.next() orelse ""; + const state = it.next() orelse ""; + w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, state }) catch break; + }, + .client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break, + .shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break, + .orphan => { + if (!orphans) w.writeAll(" shells no session holds (Adopt takes them, --kill-all ends them)\n") catch break; + orphans = true; + w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; + }, } } std.Io.File.stdout().writeStreamingAll(io, w.buffered()) catch {}; @@ -909,15 +894,10 @@ fn manage(io: std.Io, verb: []const u8, name: []const u8) noreturn { } /// The command `pid` runs, as /proc says it (Linux); empty where it does not. -fn commOf(pid: []const u8, buf: *[64]u8) []const u8 { +fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 { var path_buf: [64]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{s}/comm", .{pid}, 0) catch return ""; - const fd = std.c.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(std.c.mode_t, 0)); - if (fd < 0) return ""; - defer _ = std.c.close(fd); - const got = std.c.read(fd, buf, buf.len); - if (got <= 0) return ""; - return std.mem.trimEnd(u8, buf[0..@intCast(got)], "\n"); + const path = std.fmt.bufPrint(&path_buf, "/proc/{s}/comm", .{pid}) catch return ""; + return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n"); } /// The replica client of this build's frontend: a terminal's (tui.zig) or a @@ -1007,7 +987,7 @@ fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, Ssh.path = here; _ = atexit(Ssh.end); var waited: u32 = 0; - while (std.c.access(here, std.c.F_OK) != 0) : (waited += 1) { + while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) { var status: c_int = 0; if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) { Ssh.child = 0; -- cgit v1.3