// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What every command is run with: the allocators, the standard streams, the //! global options, and the client, made the first time a command asks for //! it. Every way a command can fail is reported from here, so that what it //! says and what it exits with stay in step. const Context = @This(); const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Io = std.Io; const zfj = @import("zfj"); const Config = @import("Config.zig"); const git = @import("git.zig"); /// What the process exits with. pub const Exit = enum(u8) { ok = 0, /// The instance answered with an error status. api_error = 1, /// The command line, or a request body, was wrong. usage = 2, /// No instance or token to use, or the request never got an answer. environment = 3, /// Under `--strict`, the instance answered successfully with something /// that does not parse into the model the specification documents. response_mismatch = 4, /// With `--exit-status`, a run that did not succeed. run_failed = 5, }; pub const Color = enum { auto, always, never }; /// The options read ahead of the command. See /// docs/adr/0003-global-options-before-the-command.md for why nowhere else. pub const Global = struct { /// The instance to reach: a configured instance's name, or a URL. instance: ?[]const u8 = null, color: Color = .auto, /// Log each request and its response's status to stderr. debug: bool = false, /// Fail when a response does not parse into its documented model. strict: bool = false, /// Follow a list operation through every page, and print them as one. paginate: bool = false, help: bool = false, version: bool = false, }; gpa: Allocator, /// Freed when the process exits; anything a single command allocates. arena: Allocator, io: Io, environ: *const std.process.Environ.Map, /// The environment as the process was given it, for what takes one rather /// than a map. process_environ: std.process.Environ = .empty, stdout: *Io.Writer, stderr: *Io.Writer, global: Global, zfj_client: ?zfj.Client = null, loaded_config: ?Config = null, config_path: ?[]const u8 = null, chosen: ?Config.Target = null, remote_looked_for: bool = false, found_remote: ?git.Remote = null, pub fn deinit(ctx: *Context) void { if (ctx.zfj_client) |*c| c.deinit(); } pub fn usage(ctx: *Context, comptime format: []const u8, args: anytype) Exit { ctx.report(format, args); return .usage; } pub fn environment(ctx: *Context, comptime format: []const u8, args: anytype) Exit { ctx.report(format, args); return .environment; } /// The request was not answered at all. pub fn transport(ctx: *Context, operation: []const u8, err: anyerror) Exit { return ctx.environment("{s}: {s}", .{ operation, @errorName(err) }); } /// The instance answered with an error status. Its body goes to stderr, so /// that stdout only ever holds a successful response. pub fn apiError(ctx: *Context, operation: []const u8, status: std.http.Status, body: []const u8) Exit { ctx.stderr.print("zfj: {s}: HTTP {d} {s}\n", .{ operation, @backingInt(status), status.phrase() orelse "" }) catch {}; if (body.len != 0) { ctx.stderr.writeAll(body) catch {}; if (body[body.len - 1] != '\n') ctx.stderr.writeByte('\n') catch {}; } ctx.stderr.flush() catch {}; return .api_error; } /// The instance answered, but has no such thing: what a 404 would have /// said, for a lookup that cannot get one. pub fn notFound(ctx: *Context, comptime format: []const u8, args: anytype) Exit { ctx.report(format, args); return .api_error; } /// A successful response that does not parse into its documented model: a /// warning, unless `--strict` makes it a failure. pub fn parseFailure(ctx: *Context, operation: []const u8, model: []const u8, error_name: []const u8) Exit { ctx.report("{s}: {s}: the response does not parse as {s}: {s}", .{ if (ctx.global.strict) "error" else "warning", operation, model, error_name, }); return if (ctx.global.strict) .response_mismatch else .ok; } fn report(ctx: *Context, comptime format: []const u8, args: anytype) void { ctx.stderr.print("zfj: " ++ format ++ "\n", args) catch {}; ctx.stderr.flush() catch {}; } /// All of stdin, which lives as long as the command. pub fn readStdin(ctx: *Context) ![]u8 { const stdin: Io.File = .stdin(); if (try stdin.isTty(ctx.io)) ctx.report("reading the request body from stdin; end it with Ctrl-D", .{}); var buffer: [4096]u8 = undefined; var reader = stdin.reader(ctx.io, &buffer); return reader.interface.allocRemaining(ctx.arena, .unlimited); } /// The configuration file, read the first time it is asked for. pub fn config(ctx: *Context) error{Reported}!*Config { if (ctx.loaded_config) |*c| return c; const file_path = try ctx.configPath(); var message: []const u8 = ""; ctx.loaded_config = Config.load(ctx.gpa, ctx.arena, ctx.io, .cwd(), file_path, &message) catch |err| switch (err) { error.OutOfMemory => { _ = ctx.environment("out of memory", .{}); return error.Reported; }, error.Invalid, error.Unreadable => { _ = ctx.environment("{s}", .{std.mem.trimEnd(u8, message, "\n")}); return error.Reported; }, }; return &ctx.loaded_config.?; } pub fn saveConfig(ctx: *Context) error{Reported}!void { const c = try ctx.config(); const file_path = try ctx.configPath(); c.save(ctx.io, .cwd(), file_path) catch |err| { _ = ctx.environment("cannot write {s}: {s}", .{ file_path, @errorName(err) }); return error.Reported; }; } fn configPath(ctx: *Context) error{Reported}![]const u8 { if (ctx.config_path) |p| return p; ctx.config_path = Config.path(ctx.arena, ctx.environ) catch |err| { _ = ctx.environment("cannot find the configuration file: {s}", .{switch (err) { error.NoHome => if (builtin.os.tag == .windows) "none of XDG_CONFIG_HOME, APPDATA or HOME is set" else "neither XDG_CONFIG_HOME nor HOME is set", error.OutOfMemory => "out of memory", }}); return error.Reported; }; return ctx.config_path.?; } /// The clone's git remote, `upstream` or else `origin`, looked for the first /// time it is asked for. pub fn gitRemote(ctx: *Context) ?git.Remote { if (!ctx.remote_looked_for) { ctx.remote_looked_for = true; ctx.found_remote = git.findRemote(ctx.arena, ctx.io); } return ctx.found_remote; } /// The instance a command reaches: `--instance`, else `ZFJ_INSTANCE`, else /// the configured instance on the git remote's host, else the default. /// Fails with `error.Reported`, having said why, when there is none. pub fn target(ctx: *Context) error{Reported}!Config.Target { if (ctx.chosen) |t| return t; const choice = ctx.global.instance orelse ctx.environ.get("ZFJ_INSTANCE"); const c = try ctx.config(); const remote_host = if (choice == null) if (ctx.gitRemote()) |r| r.host else null else null; ctx.chosen = c.select(choice, remote_host, ctx.environ.get("FORGEJO_TOKEN")) catch |err| { switch (err) { error.NoInstance => _ = ctx.environment( "no instance; log in with `zfj login `, or name one with --instance ", .{}, ), error.UnknownInstance => if (choice) |name| { _ = ctx.environment("no instance named '{s}'; `zfj instances` lists them", .{name}); } else { _ = ctx.environment("the default instance '{s}' is not configured; `zfj default ` sets another", .{c.default.?}); }, } return error.Reported; }; return ctx.chosen.?; } /// The client for the chosen instance; see `target`. pub fn client(ctx: *Context) error{Reported}!*zfj.Client { if (ctx.zfj_client) |*c| return c; const t = try ctx.target(); return ctx.makeClient(t.url, t.token); } pub const Repository = struct { owner: []const u8, name: []const u8, }; /// How a command that could not go on has already been reported, and so /// what it exits with. pub const Failure = error{ Usage, Environment }; pub fn exitFor(err: Failure) Exit { return switch (err) { error.Usage => .usage, error.Environment => .environment, }; } /// The repository a porcelain command acts on: `-R /`, or else /// the one the clone's git remote names -- which must then be on the /// instance the command reaches, or the command would act on a repository of /// the same name somewhere else. pub fn repository(ctx: *Context, flag: ?[]const u8) Failure!Repository { if (flag) |text| { if (parseRepository(text)) |named| return named; _ = ctx.usage("-R takes /, not '{s}'", .{text}); return error.Usage; } return ctx.remoteRepository(.flag); } /// `/`, or null when `text` is anything else. pub fn parseRepository(text: []const u8) ?Repository { const at = std.mem.findScalar(u8, text, '/') orelse return null; const owner = text[0..at]; const name = text[at + 1 ..]; if (owner.len == 0 or name.len == 0 or std.mem.findScalar(u8, name, '/') != null) return null; return .{ .owner = owner, .name = name }; } /// How a command names a repository when it does: what to tell somebody /// whose clone cannot say which one it is. pub const Naming = enum { /// `-R /`, where the repository is only where the thing /// the command acts on lives. flag, /// An argument, where the repository is the thing itself. argument, }; /// The repository the clone's git remote names, which must be on the /// instance the command reaches. pub fn remoteRepository(ctx: *Context, naming: Naming) Failure!Repository { const name_it = switch (naming) { .flag => "with -R", .argument => "as /", }; const remote = ctx.gitRemote() orelse { switch (naming) { .flag => _ = ctx.usage("no -R /, and no upstream or origin remote to read the repository from", .{}), .argument => _ = ctx.usage("no /, and no upstream or origin remote to read the repository from", .{}), } return error.Usage; }; const t = ctx.target() catch return error.Environment; const host = git.urlHost(t.url) orelse ""; if (!std.ascii.eqlIgnoreCase(host, remote.host)) { if (t.by == .choice) { _ = ctx.usage("the {s} remote is on {s}, not {s}; name the repository {s}", .{ remote.name, remote.host, t.url, name_it }); } else { _ = ctx.usage("the {s} remote is on {s}, which no instance is configured for; `zfj login` to it, or name the repository {s}", .{ remote.name, remote.host, name_it }); } return error.Usage; } return .{ .owner = remote.owner, .name = remote.repo }; } pub fn stdoutIsTty(ctx: *Context) bool { const stdout: Io.File = .stdout(); return stdout.isTty(ctx.io) catch false; } /// Whether to color what is written to stdout: `--color`, and for `auto`, /// a terminal and no `NO_COLOR`. pub fn colored(ctx: *Context) bool { return switch (ctx.global.color) { .always => true, .never => false, .auto => ctx.stdoutIsTty() and ctx.environ.get("NO_COLOR") == null, }; } /// Writes `text` to stdout, through a pager when stdout is a terminal: /// `$ZFJ_PAGER`, else `$PAGER`, else `less` -- except on Windows, which has no /// pager to count on, so there only `$ZFJ_PAGER` is used. `LESS` is set to /// `FRX` unless it says otherwise, so that what fits on one screen is just /// printed. An empty pager, or one that cannot be started, writes it /// directly. pub fn page(ctx: *Context, text: []const u8) !void { const pager = ctx.environ.get("ZFJ_PAGER") orelse if (builtin.os.tag == .windows) "" else ctx.environ.get("PAGER") orelse "less"; const argv = try splitCommand(ctx.arena, pager); if (!ctx.stdoutIsTty() or argv.len == 0) { try ctx.stdout.writeAll(text); return ctx.stdout.flush(); } try ctx.stdout.flush(); var environ = try ctx.environ.clone(ctx.arena); if (environ.get("LESS") == null) try environ.put("LESS", "FRX"); var child = std.process.spawn(ctx.io, .{ .argv = argv, .environ_map = &environ, .stdin = .pipe, }) catch { try ctx.stdout.writeAll(text); return ctx.stdout.flush(); }; var buffer: [4096]u8 = undefined; var writer = child.stdin.?.writer(ctx.io, &buffer); // A pager quit before the end closes its end of the pipe; what was not // read was not wanted. writer.interface.writeAll(text) catch {}; writer.interface.flush() catch {}; child.stdin.?.close(ctx.io); child.stdin = null; _ = child.wait(ctx.io) catch {}; } /// A client for `url` with `token`, which becomes the context's client. pub fn makeClient(ctx: *Context, url: []const u8, token: []const u8) error{Reported}!*zfj.Client { const base_url = apiBaseUrl(ctx.arena, url) catch { _ = ctx.environment("out of memory", .{}); return error.Reported; }; if (ctx.zfj_client) |*old| old.deinit(); ctx.zfj_client = zfj.Client.init(ctx.gpa, ctx.io, token); const c = &ctx.zfj_client.?; c.withBaseUrl(base_url); if (ctx.global.debug) c.http_observer = .{ .ctx = ctx, .onRequest = logRequest, .onResponse = logResponse, .onError = logError, }; return c; } /// An instance's URL with the API's path on the end. A URL that already /// names the API is taken as it is. fn apiBaseUrl(arena: Allocator, instance: []const u8) Allocator.Error![]const u8 { const trimmed = std.mem.trimEnd(u8, instance, "/"); if (std.mem.endsWith(u8, trimmed, "/api/v1")) return trimmed; return std.fmt.allocPrint(arena, "{s}/api/v1", .{trimmed}); } // The debug log never shows headers, so a token cannot reach it. fn logRequest(opaque_ctx: ?*anyopaque, method: std.http.Method, url: []const u8, _: []const std.http.Header, body: ?[]const u8) void { const ctx: *Context = @ptrCast(@alignCast(opaque_ctx.?)); ctx.report("> {s} {s}{s}", .{ @tagName(method), url, if (body != null) " (with a body)" else "" }); } fn logResponse(opaque_ctx: ?*anyopaque, _: std.http.Method, _: []const u8, status: std.http.Status, _: []const std.http.Header, body: []const u8, duration_ns: u64) void { const ctx: *Context = @ptrCast(@alignCast(opaque_ctx.?)); ctx.report("< {d} {s}, {d} bytes in {d} ms", .{ @backingInt(status), status.phrase() orelse "", body.len, duration_ns / std.time.ns_per_ms, }); } fn logError(opaque_ctx: ?*anyopaque, method: std.http.Method, url: []const u8, err_name: []const u8) void { const ctx: *Context = @ptrCast(@alignCast(opaque_ctx.?)); ctx.report("! {s} {s}: {s}", .{ @tagName(method), url, err_name }); } /// A command line, as `$EDITOR` and `$PAGER` hold one, split into a /// program and its arguments without a shell: at spaces and tabs, with a /// double-quoted stretch kept whole, so that `"C:\Program Files\Vim\vim.exe"` /// is one word. pub fn splitCommand(arena: Allocator, command: []const u8) Allocator.Error![]const []const u8 { var words: std.ArrayList([]const u8) = .empty; var word: std.ArrayList(u8) = .empty; var in_word = false; var quoted = false; for (command) |c| { if (c == '"') { quoted = !quoted; in_word = true; } else if (!quoted and (c == ' ' or c == '\t')) { if (in_word) try words.append(arena, try word.toOwnedSlice(arena)); in_word = false; } else { try word.append(arena, c); in_word = true; } } if (in_word) try words.append(arena, try word.toOwnedSlice(arena)); return words.items; } const testing = std.testing; test "a command line splits into words, keeping quoted stretches whole" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const code = try splitCommand(a, "code --wait"); try testing.expectEqual(@as(usize, 2), code.len); try testing.expectEqualStrings("code", code[0]); try testing.expectEqualStrings("--wait", code[1]); const vim = try splitCommand(a, "\"C:\\Program Files\\Vim\\vim.exe\" -f"); try testing.expectEqualStrings("C:\\Program Files\\Vim\\vim.exe", vim[0]); try testing.expectEqualStrings("-f", vim[1]); try testing.expectEqual(@as(usize, 0), (try splitCommand(a, " ")).len); } test "the API path is added to an instance's URL once" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); try testing.expectEqualStrings("https://git.jcollie.dev/api/v1", try apiBaseUrl(a, "https://git.jcollie.dev")); try testing.expectEqualStrings("https://git.jcollie.dev/api/v1", try apiBaseUrl(a, "https://git.jcollie.dev/")); try testing.expectEqualStrings("https://example.org/forge/api/v1", try apiBaseUrl(a, "https://example.org/forge/api/v1/")); }