Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Where `ci-top` looks, with what token, and how often: from its flags, then//! the environment, then its configuration file, the first that says winning.//!//! The token itself is never a flag, so that it is never in `ps`: it comes//! from `CI_TOP_TOKEN`, or from a file that `--token-file`,//! `CI_TOP_TOKEN_FILE` or the configuration names.//!//! The configuration file is JSON, `ci-top/config.json` under the user's//! configuration directory -- `$XDG_CONFIG_HOME`, or `~/.config` -- which is//! what the Home Manager module writes://!//! ```json//! { "url": "https://ci.example.org", "token_file": "/run/secrets/ci-top", "interval": 5 }//! ```//!//! Unknown fields in it are an error rather than ignored, as they are in the//! daemon's: a misspelt option silently dropped would leave its default in//! force with nothing to say so.//!//! A file's path, wherever it came from, may use `$NAME`, `${NAME}` and a//! leading `~/`, as sops-nix writes a Home Manager secret's path://! `/run/user/$UID/secrets/ci-top`. `UID` is the shell's and is not//! exported, so it is answered here when the environment has none.
const std = @import("std");const Allocator = std.mem.Allocator;
/// The configuration file's fields. Every one is optional.pub const File = struct { /// Where the daemon's public listener is reached: its `public_url`. url: ?[]const u8 = null, /// A file holding the status token. token_file: ?[]const u8 = null, /// Seconds between refreshes. interval: ?u32 = null, /// How many hours of finished work to show. hours: ?u32 = null, /// The most finished droplets, and runs, to show. limit: ?u32 = null,};
/// What the command line said.pub const Flags = struct { url: ?[]const u8 = null, token_file: ?[]const u8 = null, interval: ?u32 = null, hours: ?u32 = null, limit: ?u32 = null, /// A configuration file to read in place of the default one. config: ?[]const u8 = null, help: bool = false,};
pub const Token = union(enum) { value: []const u8, file: []const u8,};
/// Everything settled.pub const Options = struct { /// With no trailing slash. url: []const u8, token: Token, interval: u32, hours: u32, limit: u32,};
pub const default_interval = 5;pub const default_hours = 24;pub const default_limit = 50;
pub const usage = \\usage: ci-top [options] \\ \\Watch ci-autoscaler: the work waiting, the droplet each job is on, and \\what finished lately, from the daemon's GET /status. \\ \\options: \\ --url URL the daemon's public URL (CI_TOP_URL) \\ --token-file PATH a file holding the status token (CI_TOP_TOKEN_FILE, \\ or the token itself in CI_TOP_TOKEN) \\ --interval SECS seconds between refreshes (default 5) \\ --hours N hours of finished work to show (default 24) \\ --limit N the most finished droplets to show (default 50) \\ --config PATH read this configuration file rather than \\ ci-top/config.json in the configuration directory \\ -h, --help show this \\ \\keys: q quit, r refresh, tab/shift-tab switch list, j/k or arrows move, \\ g/G first/last, enter details, esc close \\;
pub const ParseError = error{ UnknownFlag, MissingValue, BadNumber };
/// Reads the flags in `args`, which does not include the program's name./// `bad` is set to the argument at fault on an error.pub fn parseFlags(args: []const []const u8, bad: *[]const u8) ParseError!Flags { var flags: Flags = .{}; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; bad.* = arg; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { flags.help = true; continue; } // `--name value` or `--name=value`. const eq = std.mem.findScalar(u8, arg, '='); const name = if (eq) |e| arg[0..e] else arg; const known = [_][]const u8{ "--url", "--token-file", "--config", "--interval", "--hours", "--limit" }; for (known) |k| { if (std.mem.eql(u8, name, k)) break; } else return error.UnknownFlag; const value: []const u8 = if (eq) |e| arg[e + 1 ..] else blk: { i += 1; if (i >= args.len) return error.MissingValue; break :blk args[i]; }; if (std.mem.eql(u8, name, "--url")) { flags.url = value; } else if (std.mem.eql(u8, name, "--token-file")) { flags.token_file = value; } else if (std.mem.eql(u8, name, "--config")) { flags.config = value; } else if (std.mem.eql(u8, name, "--interval")) { flags.interval = try number(value); } else if (std.mem.eql(u8, name, "--hours")) { flags.hours = try number(value); } else if (std.mem.eql(u8, name, "--limit")) { flags.limit = try number(value); } else unreachable; } return flags;}
fn number(text: []const u8) ParseError!u32 { return std.fmt.parseInt(u32, text, 10) catch error.BadNumber;}
pub const FileError = error{InvalidConfig} || Allocator.Error;
/// Parses a configuration file's text. Everything returned lives in `arena`.pub fn parseFile(arena: Allocator, text: []const u8, diagnostic: *[]const u8) FileError!File { return std.json.parseFromSliceLeaky(File, arena, text, .{ .ignore_unknown_fields = false, .allocate = .alloc_always, }) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, else => { diagnostic.* = @errorName(err); return error.InvalidConfig; }, };}
pub const ResolveError = error{ NoUrl, NoToken, BadUrl, BadInterval };
/// Settles every option: flags first, then the environment, then the file.pub fn resolve(flags: Flags, env: *const std.process.Environ.Map, file: File) ResolveError!Options { var url = flags.url orelse env.get("CI_TOP_URL") orelse file.url orelse return error.NoUrl; if (!std.mem.startsWith(u8, url, "https://") and !std.mem.startsWith(u8, url, "http://")) return error.BadUrl; while (std.mem.endsWith(u8, url, "/")) url = url[0 .. url.len - 1];
const token: Token = if (flags.token_file) |f| .{ .file = f } else if (env.get("CI_TOP_TOKEN")) |t| .{ .value = t } else if (env.get("CI_TOP_TOKEN_FILE")) |f| .{ .file = f } else if (file.token_file) |f| .{ .file = f } else return error.NoToken;
const interval = flags.interval orelse file.interval orelse default_interval; if (interval == 0) return error.BadInterval; return .{ .url = url, .token = token, .interval = interval, .hours = flags.hours orelse file.hours orelse default_hours, .limit = flags.limit orelse file.limit orelse default_limit, };}
/// What to tell the user about a `ResolveError`.pub fn explain(err: ResolveError) []const u8 { return switch (err) { error.NoUrl => "no URL: give --url, set CI_TOP_URL, or put \"url\" in the configuration file", error.NoToken => "no token: give --token-file, set CI_TOP_TOKEN or CI_TOP_TOKEN_FILE, or put \"token_file\" in the configuration file", error.BadUrl => "the URL is neither https:// nor http://", error.BadInterval => "the interval must be at least a second", };}
pub const ExpandError = error{UnknownVariable} || Allocator.Error;
/// `path` with `$NAME`, `${NAME}` and a leading `~/` put in from `env`. `uid`/// answers `$UID` when the environment does not. `bad` is set to the name/// that could not be.pub fn expandPath(arena: Allocator, path: []const u8, env: *const std.process.Environ.Map, uid: ?u32, bad: *[]const u8) ExpandError![]const u8 { var out: std.ArrayList(u8) = .empty; var rest = path; if (std.mem.startsWith(u8, rest, "~/")) { bad.* = "HOME"; try out.appendSlice(arena, env.get("HOME") orelse return error.UnknownVariable); rest = rest[1..]; } while (std.mem.findScalar(u8, rest, '$')) |at| { try out.appendSlice(arena, rest[0..at]); rest = rest[at + 1 ..]; const name, const after = if (std.mem.startsWith(u8, rest, "{")) blk: { const close = std.mem.findScalar(u8, rest, '}') orelse { bad.* = rest; return error.UnknownVariable; }; break :blk .{ rest[1..close], rest[close + 1 ..] }; } else blk: { var n: usize = 0; while (n < rest.len and (std.ascii.isAlphanumeric(rest[n]) or rest[n] == '_')) n += 1; break :blk .{ rest[0..n], rest[n..] }; }; bad.* = name; if (name.len == 0) return error.UnknownVariable; if (env.get(name)) |value| { try out.appendSlice(arena, value); } else if (std.mem.eql(u8, name, "UID") and uid != null) { try out.print(arena, "{d}", .{uid.?}); } else return error.UnknownVariable; rest = after; } try out.appendSlice(arena, rest); return out.items;}
/// A token as it sits in a file: surrounding whitespace is not part of it.pub fn trimToken(text: []const u8) []const u8 { return std.mem.trim(u8, text, " \t\r\n");}
const testing = std.testing;
test "flags, in either spelling" { var bad: []const u8 = ""; const flags = try parseFlags(&.{ "--url", "https://ci.example.org", "--interval=10", "--token-file", "/t" }, &bad); try testing.expectEqualStrings("https://ci.example.org", flags.url.?); try testing.expectEqual(@as(?u32, 10), flags.interval); try testing.expectEqualStrings("/t", flags.token_file.?);
try testing.expectError(error.UnknownFlag, parseFlags(&.{"--token=secret"}, &bad)); try testing.expectEqualStrings("--token=secret", bad); try testing.expectError(error.UnknownFlag, parseFlags(&.{"--bogus"}, &bad)); try testing.expectError(error.MissingValue, parseFlags(&.{"--url"}, &bad)); try testing.expectError(error.BadNumber, parseFlags(&.{ "--hours", "a day" }, &bad)); try testing.expect((try parseFlags(&.{"-h"}, &bad)).help);}
test "flags win over the environment, and the environment over the file" { var env: std.process.Environ.Map = .init(testing.allocator); defer env.deinit(); const file: File = .{ .url = "https://file.example.org/", .token_file = "/file-token", .interval = 30, .hours = 2 };
// The file alone. var o = try resolve(.{}, &env, file); try testing.expectEqualStrings("https://file.example.org", o.url); try testing.expectEqualStrings("/file-token", o.token.file); try testing.expectEqual(@as(u32, 30), o.interval); try testing.expectEqual(@as(u32, 2), o.hours); try testing.expectEqual(@as(u32, default_limit), o.limit);
// The environment over it, and a token in the environment over a file // named anywhere but on the command line. try env.put("CI_TOP_URL", "https://env.example.org"); try env.put("CI_TOP_TOKEN_FILE", "/env-token-file"); o = try resolve(.{}, &env, file); try testing.expectEqualStrings("https://env.example.org", o.url); try testing.expectEqualStrings("/env-token-file", o.token.file); try env.put("CI_TOP_TOKEN", "secret"); o = try resolve(.{}, &env, file); try testing.expectEqualStrings("secret", o.token.value);
// The flags over both. o = try resolve(.{ .url = "http://[::1]:8094", .token_file = "/flag-token", .interval = 1 }, &env, file); try testing.expectEqualStrings("http://[::1]:8094", o.url); try testing.expectEqualStrings("/flag-token", o.token.file); try testing.expectEqual(@as(u32, 1), o.interval);}
test "what cannot be settled is said" { var env: std.process.Environ.Map = .init(testing.allocator); defer env.deinit(); try testing.expectError(error.NoUrl, resolve(.{}, &env, .{})); try testing.expectError(error.NoToken, resolve(.{ .url = "https://ci.example.org" }, &env, .{})); try testing.expectError(error.BadUrl, resolve(.{ .url = "ci.example.org", .token_file = "/t" }, &env, .{})); try testing.expectError(error.BadInterval, resolve(.{ .url = "https://ci.example.org", .token_file = "/t", .interval = 0 }, &env, .{}));}
test "paths may name variables, as sops-nix writes them" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); var env: std.process.Environ.Map = .init(testing.allocator); defer env.deinit(); try env.put("HOME", "/home/jeff"); try env.put("XDG_RUNTIME_DIR", "/run/user/1000"); var bad: []const u8 = "";
try testing.expectEqualStrings("/run/user/1000/secrets/ci-top-token", try expandPath(a, "/run/user/$UID/secrets/ci-top-token", &env, 1000, &bad)); try testing.expectEqualStrings("/run/user/1000/s/t", try expandPath(a, "${XDG_RUNTIME_DIR}/s/t", &env, null, &bad)); try testing.expectEqualStrings("/home/jeff/.config/ci-top/token", try expandPath(a, "~/.config/ci-top/token", &env, null, &bad)); try testing.expectEqualStrings("/plain/path", try expandPath(a, "/plain/path", &env, null, &bad));
// The environment's UID, when it has one, over the process's. try env.put("UID", "42"); try testing.expectEqualStrings("/run/user/42", try expandPath(a, "/run/user/$UID", &env, 1000, &bad));
try testing.expectError(error.UnknownVariable, expandPath(a, "/x/$NOPE/y", &env, null, &bad)); try testing.expectEqualStrings("NOPE", bad); try testing.expectError(error.UnknownVariable, expandPath(a, "/x/${OPEN", &env, null, &bad)); try testing.expectError(error.UnknownVariable, expandPath(a, "/x/$/y", &env, null, &bad));}
test "the configuration file refuses what it does not know" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: []const u8 = ""; const file = try parseFile(arena.allocator(), "{\"url\":\"https://ci.example.org\",\"interval\":10}", &diagnostic); try testing.expectEqual(@as(?u32, 10), file.interval); try testing.expectError(error.InvalidConfig, parseFile(arena.allocator(), "{\"intervall\":10}", &diagnostic)); try testing.expectEqualStrings("secret", trimToken(" \tsecret\n"));}
test { std.testing.refAllDecls(@This());}