// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `vaultctl` — a small command line front end for the library in `root.zig`, //! and a worked example of using it. //! //! It reads its configuration from the same environment variables as the //! official `vault` CLI, so on a machine where `vault kv get` works this //! should too. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const vault = @import("vault"); const usage = \\vaultctl — read and write secrets in HashiCorp Vault \\ \\Usage: \\ vaultctl get [options] [field] Read a secret, or one field of it \\ vaultctl put [options] k=v... Write a secret, replacing it \\ vaultctl patch [options] k=v... Change some fields, keep the rest \\ vaultctl delete [options] Delete a secret (KV v2: reversible) \\ vaultctl destroy [options] Delete every version, permanently \\ vaultctl list [options] List the keys under a path \\ vaultctl raw [options] GET an arbitrary /v1/ endpoint \\ vaultctl health [options] Report whether the server is usable \\ vaultctl lookup [options] Show the token's own lease and policies \\ vaultctl renew [options] Extend the token's lease \\ vaultctl revoke [options] Revoke the token immediately \\ \\Options: \\ -a, --address URL Vault address (default: $VAULT_ADDR) \\ -n, --namespace NS Vault namespace (default: $VAULT_NAMESPACE) \\ -m, --mount MOUNT Secret engine mount point (default: secret, or kv with --kv1) \\ --kv1 Treat the mount as a version 1 key/value engine \\ --version N Read a specific KV v2 version (default: the latest) \\ --cas N Write only if the current version is N; 0 means \\ "only if the secret does not exist yet" \\ --json Take the payload as a JSON object on stdin instead \\ of key=value arguments \\ --credentials Take the address and token from the systemd \\ credentials named vault-address and vault-token \\ --increment N Seconds of extra life to ask for when renewing; \\ Vault caps this at the token's maximum TTL \\ -h, --help Show this message \\ \\The address and token come from $VAULT_ADDR and $VAULT_TOKEN, or from \\OpenBao's $BAO_ADDR and $BAO_TOKEN when those are unset, or from \\$HOME/.vault-token which both `vault login` and `bao login` write, or \\from the file $BAO_TOKEN_PATH names. $VAULT_CACERT and $VAULT_CAPATH add \\trusted certificates, which private clusters with self-signed \\certificates need. $VAULT_NAMESPACE sets the namespace. Each of those \\has a $BAO_ spelling too, used when the $VAULT_ one is unset. \\ \\--credentials ignores all of that and reads the systemd credentials \\instead, which is how a unit should pass a token: an environment variable \\is visible in /proc and inherited by child processes, a credential is not. \\A unit sets them with, for example: \\ \\ LoadCredential=vault-token:/etc/myapp/vault-token \\ SetCredential=vault-address:https://vault.example.com:8200 \\ \\--address still wins over the vault-address credential if both are given. \\ \\Examples: \\ vaultctl get myapp/config Print every field as JSON \\ vaultctl get myapp/config password Print one field, unquoted \\ vaultctl get --version 2 myapp/config Print an older version \\ vaultctl list myapp Print the child keys, one per line \\ vaultctl put myapp/config user=admin password=hunter2 \\ vaultctl put --cas 0 myapp/new token=abc Create it, or fail if it exists \\ vaultctl patch myapp/config port=5433 Leave the other fields alone \\ vaultctl put --json myapp/config < config.json \\ vaultctl lookup Show the token's lease and policies \\ vaultctl renew --increment 3600 Ask for another hour of token life \\ \\`put` replaces the whole secret: fields you leave out are gone from the new \\version, though earlier versions still hold them. `patch` changes only the \\fields you name. Values given as k=v are stored as strings; use --json for \\numbers, booleans or nested objects. \\ \\`delete` on a KV v2 mount is reversible through the Vault CLI or API; on \\KV v1, and with `destroy` on either, the data is gone for good. \\ \\Exit status: 0 success, 1 error, 2 bad command line, 3 secret or field not found. \\ ; const Command = enum { get, put, patch, delete, destroy, list, raw, health, lookup, renew, revoke }; const Args = struct { command: Command, positionals: [][]const u8, address: ?[]const u8 = null, namespace: ?[]const u8 = null, mount: ?[]const u8 = null, kv1: bool = false, version: ?u64 = null, cas: ?u64 = null, json: bool = false, increment: ?u64 = null, credentials: bool = false, }; pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = init.gpa; const io = init.io; var stderr_buffer: [4096]u8 = undefined; var stderr_file_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); const stderr = &stderr_file_writer.interface; defer stderr.flush() catch {}; var stdout_buffer: [4096]u8 = undefined; var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file_writer.interface; const argv = try init.minimal.args.toSlice(arena); const args = parseArgs(arena, argv[1..]) catch |err| switch (err) { error.HelpRequested => { try stdout.writeAll(usage); try stdout.flush(); return 0; }, error.OutOfMemory => |e| return e, else => |e| { try stderr.print("vaultctl: {s}\n\n{s}", .{ describeUsageError(e), usage }); return 2; }, }; var client: vault.Client = openClient(io, gpa, init.environ_map, args) catch |err| { try stderr.print("vaultctl: {s}\n", .{describeError(err)}); return 1; }; defer client.deinit(); run(&client, args, stdout, .{ .arena = arena, .io = io }) catch |err| { try stderr.print("vaultctl: {s}\n", .{describeError(err)}); if (client.last_error) |message| try stderr.print(" vault said: {s}\n", .{message}); return exitCode(err); }; try stdout.flush(); return 0; } fn openClient( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, args: Args, ) !vault.Client { if (!args.credentials) { return vault.Client.initFromEnv(io, gpa, env, .{ .address = args.address, .namespace = args.namespace, }); } return vault.Client.initFromCredentials(io, gpa, env, .{ // An explicit --address wins, and then there is no credential to read. .address_credential = if (args.address == null) "vault-address" else null, .address = args.address orelse vault.Client.default_address, .namespace = args.namespace, }); } /// A missing secret or field is a routine outcome for a script, so it gets a /// status of its own rather than being lumped in with connection failures. fn exitCode(err: anyerror) u8 { return switch (err) { error.SecretNotFound, error.FieldNotFound, error.SecretDeleted => 3, else => 1, }; } /// The bits of the process environment the subcommands need beyond the client /// itself: stdin for `--json`, and an arena for what is read from it. const Context = struct { arena: Allocator, io: Io }; fn run(client: *vault.Client, args: Args, stdout: *Io.Writer, ctx: Context) !void { switch (args.command) { .get => try runGet(client, args, stdout), .put, .patch => try runWrite(client, args, stdout, ctx), .delete, .destroy => try runDelete(client, args), .list => try runList(client, args, stdout), .raw => { var parsed = try client.read(args.positionals[0], null); defer parsed.deinit(); try stdout.print("{f}\n", .{std.json.fmt(parsed.value, .{ .whitespace = .indent_2 })}); }, .health => { const ok = try client.healthy(); try stdout.print("{s}\n", .{if (ok) "ok" else "unavailable"}); if (!ok) return error.Sealed; }, .lookup => try runLookup(client, stdout), .renew => try runRenew(client, args, stdout), .revoke => try vault.token.revokeSelf(client), } } fn runLookup(client: *vault.Client, stdout: *Io.Writer) !void { var lookup = try vault.token.lookupSelf(client); defer lookup.deinit(); const info = lookup.info(); try stdout.print("accessor {s}\n", .{info.accessor}); try stdout.print("display name {s}\n", .{info.display_name}); try stdout.print("type {s}\n", .{info.type}); try stdout.print("renewable {}\n", .{info.renewable}); if (lookup.neverExpires()) { try stdout.writeAll("ttl never expires\n"); } else { try stdout.print("ttl {d}s (expires {s})\n", .{ info.ttl, info.expire_time orelse "unknown", }); } try stdout.writeAll("policies "); for (info.policies) |policy| try stdout.print(" {s}", .{policy}); try stdout.writeAll("\n"); } fn runRenew(client: *vault.Client, args: Args, stdout: *Io.Writer) !void { var renewal = try vault.token.renewSelf(client, .{ .increment_s = args.increment }); defer renewal.deinit(); const auth = renewal.auth(); try stdout.print("ttl {d}s, renewable {}\n", .{ auth.lease_duration, auth.renewable }); // A renewal that comes back with nothing left means the maximum TTL is // reached; saying so beats printing "ttl 0s" and looking like success. if (auth.lease_duration == 0 or !auth.renewable) return error.TokenNotRenewable; } fn runGet(client: *vault.Client, args: Args, stdout: *Io.Writer) !void { const path = args.positionals[0]; const field: ?[]const u8 = if (args.positionals.len > 1) args.positionals[1] else null; if (args.kv1) { var secret = try vault.kv1.read(client, path, .{ .mount = args.mount orelse "kv" }); defer secret.deinit(); try printSecret(stdout, secret.values(), field); } else { var secret = try vault.kv2.read(client, path, .{ .mount = args.mount orelse "secret", .version = args.version, }); defer secret.deinit(); try printSecret(stdout, secret.values(), field); } } /// Prints one field verbatim, or the whole map as JSON. A field is printed /// without quotes so that `PASSWORD=$(vaultctl get app pw)` does the obvious /// thing. fn printSecret(stdout: *Io.Writer, values: ?std.json.ObjectMap, field: ?[]const u8) !void { const object = values orelse return error.SecretDeleted; const name = field orelse { try stdout.print("{f}\n", .{std.json.fmt(std.json.Value{ .object = object }, .{ .whitespace = .indent_2, })}); return; }; const value = object.get(name) orelse return error.FieldNotFound; switch (value) { .string => |s| try stdout.print("{s}\n", .{s}), else => try stdout.print("{f}\n", .{std.json.fmt(value, .{})}), } } fn runWrite(client: *vault.Client, args: Args, stdout: *Io.Writer, ctx: Context) !void { const path = args.positionals[0]; const pairs = args.positionals[1..]; // Either form ends up as a `std.json.Value` object, which is what both // engines' write helpers stringify. var parsed_stdin: ?std.json.Parsed(std.json.Value) = null; defer if (parsed_stdin) |p| p.deinit(); const data: std.json.Value = if (args.json) blk: { if (pairs.len != 0) return error.JsonTakesNoPairs; parsed_stdin = try readJsonStdin(ctx); if (parsed_stdin.?.value != .object) return error.PayloadNotAnObject; break :blk parsed_stdin.?.value; } else blk: { if (pairs.len == 0) return error.NothingToWrite; break :blk try parsePairs(ctx.arena, pairs); }; if (args.kv1) { if (args.command == .patch) return error.PatchNeedsKv2; if (args.cas != null) return error.CasNeedsKv2; try vault.kv1.write(client, path, data, .{ .mount = args.mount orelse "kv" }); return; } const options: vault.kv2.WriteOptions = .{ .mount = args.mount orelse "secret", .cas = args.cas, }; var result = switch (args.command) { .put => try vault.kv2.write(client, path, data, options), .patch => try vault.kv2.patch(client, path, data, options), else => unreachable, }; defer result.deinit(); try stdout.print("version {d}\n", .{result.version()}); } fn runDelete(client: *vault.Client, args: Args) !void { const path = args.positionals[0]; if (args.kv1) { // KV v1 keeps no history, so both commands mean the same thing. return vault.kv1.delete(client, path, .{ .mount = args.mount orelse "kv" }); } const options: vault.kv2.Options = .{ .mount = args.mount orelse "secret" }; return switch (args.command) { .delete => vault.kv2.delete(client, path, options), .destroy => vault.kv2.deleteMetadata(client, path, options), else => unreachable, }; } /// Turns `key=value` arguments into a JSON object of strings, which is what /// `vault kv put` stores too. Anything richer needs `--json`. fn parsePairs(arena: Allocator, pairs: []const []const u8) !std.json.Value { var object: std.json.ObjectMap = .empty; for (pairs) |pair| { const split = std.mem.findScalar(u8, pair, '=') orelse return error.NotAKeyValuePair; if (split == 0) return error.NotAKeyValuePair; try object.put(arena, pair[0..split], .{ .string = pair[split + 1 ..] }); } return .{ .object = object }; } fn readJsonStdin(ctx: Context) !std.json.Parsed(std.json.Value) { var stdin_buffer: [4096]u8 = undefined; var stdin_file_reader: Io.File.Reader = .init(.stdin(), ctx.io, &stdin_buffer); const text = try stdin_file_reader.interface.allocRemaining(ctx.arena, .limited(1 << 20)); return std.json.parseFromSlice(std.json.Value, ctx.arena, text, .{}); } fn runList(client: *vault.Client, args: Args, stdout: *Io.Writer) !void { var listing = if (args.kv1) try vault.kv1.list(client, args.positionals[0], .{ .mount = args.mount orelse "kv" }) else try vault.kv2.list(client, args.positionals[0], .{ .mount = args.mount orelse "secret" }); defer listing.deinit(); for (listing.keys()) |key| try stdout.print("{s}\n", .{key}); } const UsageError = error{ HelpRequested, MissingCommand, UnknownCommand, UnknownOption, MissingOptionValue, InvalidVersion, InvalidCas, InvalidIncrement, MissingPath, TooManyArguments, OutOfMemory, }; fn parseArgs(arena: Allocator, argv: []const []const u8) UsageError!Args { var positionals: std.ArrayList([]const u8) = .empty; var command: ?Command = null; var address: ?[]const u8 = null; var namespace: ?[]const u8 = null; var mount: ?[]const u8 = null; var kv1 = false; var version: ?u64 = null; var cas: ?u64 = null; var json = false; var increment: ?u64 = null; var credentials = false; var i: usize = 0; while (i < argv.len) : (i += 1) { const arg = argv[i]; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) return error.HelpRequested; if (arg.len > 1 and arg[0] == '-') { const value = struct { fn next(list: []const []const u8, index: *usize) UsageError![]const u8 { if (index.* + 1 >= list.len) return error.MissingOptionValue; index.* += 1; return list[index.*]; } }.next; if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--address")) { address = try value(argv, &i); } else if (std.mem.eql(u8, arg, "-n") or std.mem.eql(u8, arg, "--namespace")) { namespace = try value(argv, &i); } else if (std.mem.eql(u8, arg, "-m") or std.mem.eql(u8, arg, "--mount")) { mount = try value(argv, &i); } else if (std.mem.eql(u8, arg, "--kv1")) { kv1 = true; } else if (std.mem.eql(u8, arg, "--version")) { version = std.fmt.parseInt(u64, try value(argv, &i), 10) catch return error.InvalidVersion; } else if (std.mem.eql(u8, arg, "--cas")) { cas = std.fmt.parseInt(u64, try value(argv, &i), 10) catch return error.InvalidCas; } else if (std.mem.eql(u8, arg, "--increment")) { increment = std.fmt.parseInt(u64, try value(argv, &i), 10) catch return error.InvalidIncrement; } else if (std.mem.eql(u8, arg, "--json")) { json = true; } else if (std.mem.eql(u8, arg, "--credentials")) { credentials = true; } else { return error.UnknownOption; } continue; } if (command == null) { command = std.meta.stringToEnum(Command, arg) orelse return error.UnknownCommand; } else { try positionals.append(arena, arg); } } const cmd = command orelse return error.MissingCommand; const required: usize = switch (cmd) { .get, .put, .patch, .delete, .destroy, .list, .raw => 1, .health, .lookup, .renew, .revoke => 0, }; // Null means variadic: `put` and `patch` take a path plus any number of // key=value arguments. const allowed: ?usize = switch (cmd) { .get => 2, // path, and an optional field .put, .patch => null, .delete, .destroy, .list, .raw => 1, .health, .lookup, .renew, .revoke => 0, }; if (positionals.items.len < required) return error.MissingPath; if (allowed) |max| if (positionals.items.len > max) return error.TooManyArguments; return .{ .command = cmd, .positionals = positionals.items, .address = address, .namespace = namespace, .mount = mount, .kv1 = kv1, .version = version, .cas = cas, .json = json, .increment = increment, .credentials = credentials, }; } fn describeUsageError(err: UsageError) []const u8 { return switch (err) { error.HelpRequested => unreachable, error.OutOfMemory => "out of memory", error.MissingCommand => "no command given", error.UnknownCommand => "unknown command", error.UnknownOption => "unknown option", error.MissingOptionValue => "option is missing its value", error.InvalidVersion => "--version expects a number", error.InvalidCas => "--cas expects a number", error.InvalidIncrement => "--increment expects a number of seconds", error.MissingPath => "no path given", error.TooManyArguments => "too many arguments", }; } fn describeError(err: anyerror) []const u8 { return switch (err) { error.MissingToken => "no token; set VAULT_TOKEN or BAO_TOKEN, or run `vault login`", error.InvalidAddress => "VAULT_ADDR or BAO_ADDR is not a valid http(s) URL", error.InvalidRequest => "Vault rejected the request as malformed", error.PermissionDenied => "permission denied; the token is missing, expired, or lacks a policy for this path", error.SecretNotFound => "no secret at that path (or the token may not read it)", error.UnsupportedOperation => "the mount does not support this operation", error.NotYetReplicated => "a standby node has not replicated this data yet; try again", error.Unavailable => "Vault is rate limiting or this node cannot serve the request", error.PerformanceStandby => "a performance standby could not forward the request", error.InternalError => "Vault reported an internal error", error.BadGateway => "Vault could not reach a backing service", error.Sealed => "Vault is sealed or unavailable", error.Redirected => "that node redirected the request; point --address at the active node", error.UnexpectedStatus => "Vault returned an unexpected status", error.ResponseTooLarge => "the response exceeded the size limit", error.MalformedResponse, error.SyntaxError, error.UnexpectedEndOfInput => "Vault returned a response this client could not parse", error.NoCredentialsDirectory => "no systemd credentials here; $CREDENTIALS_DIRECTORY is unset, so run this from a unit with LoadCredential= or SetCredential=", error.CredentialNotFound => "systemd passed no credential by that name; check LoadCredential= in the unit", error.CredentialUnreadable => "a systemd credential could not be read", error.InvalidCredentialName => "a credential name cannot contain a slash", error.CertificateBundleLoadFailure => "could not load the certificates named by $VAULT_CACERT/$BAO_CACERT or $VAULT_CAPATH/$BAO_CAPATH", error.SecretDeleted => "that version of the secret has been deleted", error.CheckAndSetMismatch => "the secret changed since you read it; re-read it and retry, or drop --cas", error.NothingToWrite => "give at least one key=value argument, or use --json", error.JsonTakesNoPairs => "--json reads the whole payload from stdin; drop the key=value arguments", error.NotAKeyValuePair => "arguments after the path must look like key=value", error.PayloadNotAnObject => "the JSON on stdin must be an object", error.PatchNeedsKv2 => "patch needs a KV v2 mount; --kv1 engines have no merge endpoint", error.CasNeedsKv2 => "--cas needs a KV v2 mount; --kv1 engines have no versions", error.TokenNotRenewable => "the token cannot be extended further; a new one has to be issued", error.FieldNotFound => "the secret has no such field", error.ConnectionRefused => "could not connect to Vault", error.TlsInitializationFailed => "the TLS handshake failed; VAULT_CACERT may be needed for a self-signed certificate", error.OutOfMemory => "out of memory", else => @errorName(err), }; } const testing = std.testing; test "parseArgs reads a command, its options and its positionals" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const args = try parseArgs(arena.allocator(), &.{ "get", "--mount", "kv", "--version", "3", "myapp/config", "password", }); try testing.expectEqual(Command.get, args.command); try testing.expectEqualStrings("kv", args.mount.?); try testing.expectEqual(@as(?u64, 3), args.version); try testing.expectEqualStrings("myapp/config", args.positionals[0]); try testing.expectEqualStrings("password", args.positionals[1]); } test "parseArgs accepts options before the command" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const args = try parseArgs(arena.allocator(), &.{ "-a", "https://vault.example.com:8200", "--kv1", "list", "myapp", }); try testing.expectEqual(Command.list, args.command); try testing.expect(args.kv1); try testing.expectEqualStrings("https://vault.example.com:8200", args.address.?); } test "parseArgs rejects malformed command lines" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); try testing.expectError(error.MissingCommand, parseArgs(a, &.{})); try testing.expectError(error.UnknownCommand, parseArgs(a, &.{"fetch"})); try testing.expectError(error.UnknownOption, parseArgs(a, &.{ "get", "--wat" })); try testing.expectError(error.MissingOptionValue, parseArgs(a, &.{ "get", "--mount" })); try testing.expectError(error.InvalidVersion, parseArgs(a, &.{ "get", "--version", "x", "p" })); try testing.expectError(error.MissingPath, parseArgs(a, &.{"get"})); try testing.expectError(error.TooManyArguments, parseArgs(a, &.{ "list", "a", "b" })); try testing.expectError(error.HelpRequested, parseArgs(a, &.{ "get", "--help" })); } test "health takes no positionals" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const args = try parseArgs(arena.allocator(), &.{"health"}); try testing.expectEqual(@as(usize, 0), args.positionals.len); try testing.expectError(error.TooManyArguments, parseArgs(arena.allocator(), &.{ "health", "x" })); } test "parseArgs accepts a variadic put with key=value arguments" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const args = try parseArgs(arena.allocator(), &.{ "put", "--cas", "0", "myapp/config", "user=admin", "password=hunter2", }); try testing.expectEqual(Command.put, args.command); try testing.expectEqual(@as(?u64, 0), args.cas); try testing.expectEqual(@as(usize, 3), args.positionals.len); try testing.expectEqualStrings("password=hunter2", args.positionals[2]); } test "parseArgs rejects a put with no data and a bad --cas" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); try testing.expectError(error.MissingPath, parseArgs(a, &.{"put"})); try testing.expectError(error.InvalidCas, parseArgs(a, &.{ "put", "--cas", "x", "p", "k=v" })); try testing.expectError(error.TooManyArguments, parseArgs(a, &.{ "delete", "a", "b" })); } test "parsePairs builds a JSON object of strings" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const value = try parsePairs(arena.allocator(), &.{ "user=admin", "password=hunter2" }); try testing.expectEqualStrings("admin", value.object.get("user").?.string); try testing.expectEqualStrings("hunter2", value.object.get("password").?.string); // A value may itself contain '=' — only the first one splits. const padded = try parsePairs(arena.allocator(), &.{"token=abc=="}); try testing.expectEqualStrings("abc==", padded.object.get("token").?.string); try testing.expectError(error.NotAKeyValuePair, parsePairs(arena.allocator(), &.{"nope"})); try testing.expectError(error.NotAKeyValuePair, parsePairs(arena.allocator(), &.{"=novalue"})); } /// The completion files are hand-written, which reads better than anything /// generated but can fall out of step with this file. The tests below check /// both directions, so adding a command or an option without completing it is /// a test failure rather than a slow discovery. const fish_completion = @embedFile("fish_completion"); const bash_completion = @embedFile("bash_completion"); /// Asserts that `parseArgs` knows the option a completion file offers. fn expectParserAccepts(allocator: Allocator, flag: []const u8) !void { // A numeric value suits the options that take one and is harmless as a // positional for the options that do not. const result = parseArgs(allocator, &.{ "get", flag, "1", "some/path" }); if (result) |_| {} else |err| switch (err) { error.UnknownOption => { std.debug.print("a completion offers '{s}', which parseArgs rejects\n", .{flag}); return error.CompletionOffersUnknownOption; }, error.HelpRequested => {}, // --help is real, it just short-circuits else => |e| return e, } } fn expectCommandOffered(completion: []const u8, offered: []const []const u8, name: []const u8) !void { for (offered) |candidate| { if (std.mem.eql(u8, candidate, name)) return; } std.debug.print("no completion offers the '{s}' command\n", .{name}); _ = completion; return error.CommandNotCompleted; } /// The subcommands a fish completion file offers, which are the `-a` values on /// the lines guarded by `__fish_use_subcommand`. The `-a` used for path /// completion is on a different line and is deliberately not one of these. fn fishOfferedCommands(allocator: Allocator, completion: []const u8) ![]const []const u8 { var found: std.ArrayList([]const u8) = .empty; var lines = std.mem.splitScalar(u8, completion, '\n'); while (lines.next()) |line| { if (std.mem.find(u8, line, "__fish_use_subcommand") == null) continue; const at = std.mem.find(u8, line, " -a ") orelse continue; const rest = line[at + 4 ..]; const end = std.mem.findAny(u8, rest, " \t") orelse rest.len; try found.append(allocator, rest[0..end]); } return found.items; } /// The subcommands the bash completion offers, taken from its `commands` list. fn bashOfferedCommands(allocator: Allocator, completion: []const u8) ![]const []const u8 { const marker = "local commands='"; const at = std.mem.find(u8, completion, marker) orelse return error.CommandListMissing; const rest = completion[at + marker.len ..]; const end = std.mem.findScalar(u8, rest, '\'') orelse return error.CommandListMissing; var found: std.ArrayList([]const u8) = .empty; var words = std.mem.tokenizeScalar(u8, rest[0..end], ' '); while (words.next()) |word| try found.append(allocator, word); return found.items; } test "both completions offer exactly the commands the CLI has" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const fish = try fishOfferedCommands(a, fish_completion); const bash = try bashOfferedCommands(a, bash_completion); inline for (@typeInfo(Command).@"enum".fields) |field| { try expectCommandOffered(fish_completion, fish, field.name); try expectCommandOffered(bash_completion, bash, field.name); } // The other direction: a completion listing a command that no longer // exists would send people down a dead end. try testing.expectEqual(@typeInfo(Command).@"enum".fields.len, fish.len); try testing.expectEqual(@typeInfo(Command).@"enum".fields.len, bash.len); for (bash) |name| { if (std.meta.stringToEnum(Command, name) == null) { std.debug.print("bash completion offers '{s}', which is not a command\n", .{name}); return error.UnknownCommandCompleted; } } } test "every option the fish completion offers is one the parser accepts" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var checked: usize = 0; var lines = std.mem.splitScalar(u8, fish_completion, '\n'); while (lines.next()) |line| { // Only `complete` lines declare options. `set -l` also contains "-l ", // and a variable is not something the parser has ever heard of. if (!std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), "complete ")) continue; const found = std.mem.find(u8, line, " -l ") orelse continue; const rest = line[found + 4 ..]; const end = std.mem.findAny(u8, rest, " \t") orelse rest.len; const flag = try std.fmt.allocPrint(arena.allocator(), "--{s}", .{rest[0..end]}); try expectParserAccepts(arena.allocator(), flag); checked += 1; } // A completion file that stopped listing options would otherwise pass. try testing.expect(checked >= 9); } test "every option the bash completion offers is one the parser accepts" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var seen: std.StringHashMapUnmanaged(void) = .empty; var index: usize = 0; while (std.mem.findPos(u8, bash_completion, index, "--")) |found| { index = found + 2; const rest = bash_completion[index..]; var end: usize = 0; while (end < rest.len and (std.ascii.isLower(rest[end]) or std.ascii.isDigit(rest[end]) or rest[end] == '-')) : (end += 1) {} // A bare `--`, as in `compgen -W ... -- "$current"`, is a separator. if (end == 0) continue; try seen.put(arena.allocator(), rest[0..end], {}); } var it = seen.keyIterator(); while (it.next()) |name| { const flag = try std.fmt.allocPrint(arena.allocator(), "--{s}", .{name.*}); try expectParserAccepts(arena.allocator(), flag); } try testing.expect(seen.count() >= 9); }