// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Shell completion, answered by zfj itself //! (docs/adr/0007-completion-is-answered-by-zfj.md). //! //! A completion script hands `zfj __complete` every word after `zfj`, the //! last being the one being completed, which may be empty. The answer is the //! candidates that word could become, one to a line as //! `valuedescription`, and then one directive line saying what the //! shell is to do besides: `:files` or `:dirs` to complete paths too, and //! `:none` for nothing more. What may come next is read from the same specs //! the commands parse with, so completion offers exactly what parses. //! Nothing is asked of the instance, and nothing is ever written to stderr. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const args = @import("args.zig"); const Config = @import("Config.zig"); const Context = @import("Context.zig"); const Exit = Context.Exit; const git = @import("git.zig"); const op = @import("op.zig"); const porcelain = @import("porcelain.zig"); /// One of the words that can follow the global options. pub const Entry = struct { name: []const u8, /// How `zfj --help` shows it: `issue []`. synopsis: []const u8, /// What `zfj --help` says of it; up to a `;`, also what completion does. summary: []const u8, completes: Completes, }; /// What the words after an entry's name are. pub const Completes = union(enum) { /// A group's command, and then that command's options. group: []const porcelain.Command, /// An operation, and then its params. operations, /// The entry's own options and positional words. spec: args.Spec, }; pub const Directive = enum { files, dirs, none, fn of(source: args.Complete) Directive { return switch (source) { .files => .files, .dirs => .dirs, .none, .instances, .workflows => .none, }; } }; pub const Candidate = struct { value: []const u8, description: []const u8 = "", }; pub const Answer = struct { candidates: std.ArrayList(Candidate) = .empty, directive: Directive = .none, /// Adds `value` if it begins with what has been typed of it. fn offer(answer: *Answer, arena: Allocator, typed: []const u8, value: []const u8, description: []const u8) !void { if (!std.mem.startsWith(u8, value, typed)) return; try answer.candidates.append(arena, .{ .value = value, .description = description }); } /// One candidate to a line, `valuedescription`, and the directive. /// A description is one line, and holds no tab. pub fn write(answer: Answer, writer: *Io.Writer) Io.Writer.Error!void { for (answer.candidates.items) |candidate| { try writer.writeAll(candidate.value); if (candidate.description.len != 0) { try writer.writeByte('\t'); for (candidate.description) |c| try writer.writeByte(if (c == '\t' or c == '\n' or c == '\r') ' ' else c); } try writer.writeByte('\n'); } try writer.print(":{t}\n", .{answer.directive}); } }; /// Where the values only zfj can find out come from: the configured /// instances, and the workflows of the clone. Asked for only when a word /// wants them, and nothing when they cannot be had. pub const Local = struct { data: *anyopaque, instancesFn: *const fn (data: *anyopaque, arena: Allocator) []const []const u8, workflowsFn: *const fn (data: *anyopaque, arena: Allocator) []const []const u8, /// Nothing at all. pub const none: Local = .{ .data = undefined, .instancesFn = nothing, .workflowsFn = nothing }; fn nothing(_: *anyopaque, _: Allocator) []const []const u8 { return &.{}; } fn values(local: Local, arena: Allocator, source: args.Complete) []const []const u8 { return switch (source) { .instances => local.instancesFn(local.data, arena), .workflows => local.workflowsFn(local.data, arena), .none, .files, .dirs => &.{}, }; } /// The real ones, found as the command would find them. pub fn of(ctx: *Context) Local { return .{ .data = ctx, .instancesFn = contextInstances, .workflowsFn = contextWorkflows }; } fn contextInstances(data: *anyopaque, arena: Allocator) []const []const u8 { const ctx: *Context = @ptrCast(@alignCast(data)); // Read here rather than through ctx.config(), which reports what is // wrong with the file -- onto the line being typed. const path = Config.path(arena, ctx.environ) catch return &.{}; var message: []const u8 = ""; const config = Config.load(ctx.gpa, arena, ctx.io, Io.Dir.cwd(), path, &message) catch return &.{}; return instanceNames(arena, config) catch &.{}; } fn contextWorkflows(data: *anyopaque, arena: Allocator) []const []const u8 { const ctx: *Context = @ptrCast(@alignCast(data)); const top = git.topLevel(arena, ctx.io) orelse return &.{}; var dir = Io.Dir.cwd().openDir(ctx.io, top, .{}) catch return &.{}; defer dir.close(ctx.io); return workflowFiles(arena, ctx.io, dir) catch &.{}; } }; fn instanceNames(arena: Allocator, config: Config) ![]const []const u8 { const names = try arena.alloc([]const u8, config.instances.len); for (config.instances, names) |instance, *name| name.* = instance.name; return names; } /// The workflow files in the clone whose top level is `top`, by the names /// Forgejo knows them by: those in `.forgejo/workflows`, or when there is /// no such directory, in `.gitea/workflows`. Sorted, so that every shell /// offers them alike. fn workflowFiles(arena: Allocator, io: Io, top: Io.Dir) ![]const []const u8 { var dir = top.openDir(io, ".forgejo/workflows", .{ .iterate = true }) catch |err| switch (err) { error.FileNotFound => top.openDir(io, ".gitea/workflows", .{ .iterate = true }) catch return &.{}, else => return &.{}, }; defer dir.close(io); var names: std.ArrayList([]const u8) = .empty; var iterator = dir.iterate(); while (try iterator.next(io)) |entry| { if (entry.kind != .file and entry.kind != .sym_link) continue; if (!std.mem.endsWith(u8, entry.name, ".yaml") and !std.mem.endsWith(u8, entry.name, ".yml")) continue; try names.append(arena, try arena.dupe(u8, entry.name)); } std.mem.sortUnstable([]const u8, names.items, {}, lessThan); return names.items; } fn lessThan(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b); } /// What the last of `words` could become. `words` are every word after /// `zfj`; with none, it is as though the one being completed were empty. pub fn complete(arena: Allocator, entries: []const Entry, global: args.Spec, local: Local, words: []const []const u8) !Answer { var answer: Answer = .{}; const all: []const []const u8 = if (words.len == 0) &.{""} else words; const typed = all[all.len - 1]; const before = all[0 .. all.len - 1]; // The global options, which end at the first word that is not one // (docs/adr/0003-global-options-before-the-command.md). var index: usize = 0; while (index < before.len) : (index += 1) { const word = before[index]; if (!std.mem.startsWith(u8, word, "--") or word.len == 2) break; const field = global.option(flagName(word)) orelse continue; if (field.takes_value and std.mem.findScalar(u8, word, '=') == null) { index += 1; if (index == before.len) { try offerValues(&answer, arena, local, field, typed, ""); return answer; } } } if (index == before.len) { if (std.mem.startsWith(u8, typed, "-")) { try offerOptions(&answer, arena, global, typed, false); } else { for (entries) |entry| try answer.offer(arena, typed, entry.name, beforeSemicolon(entry.summary)); } return answer; } const name = before[index]; const rest = all[index + 1 ..]; const entry = for (entries) |entry| { if (std.mem.eql(u8, entry.name, name)) break entry; } else return answer; switch (entry.completes) { .spec => |spec| try completeSpec(&answer, arena, local, spec, rest), .group => |commands| { if (rest.len == 1) { for (commands) |command| try answer.offer(arena, typed, command.name, command.summary); return answer; } for (commands) |command| { if (std.mem.eql(u8, command.name, rest[0])) try completeSpec(&answer, arena, local, command.spec, rest[1..]); } }, .operations => { if (rest.len == 1) { for (op.operations) |operation| try answer.offer(arena, typed, operation.name, operation.summary); return answer; } if (op.find(rest[0])) |operation| try completeSpec(&answer, arena, local, operation.spec, rest[1..]); }, } return answer; } /// What the last of `words` could become, among a command's options and /// positional words. fn completeSpec(answer: *Answer, arena: Allocator, local: Local, spec: args.Spec, words: []const []const u8) !void { const typed = words[words.len - 1]; const before = words[0 .. words.len - 1]; var positional: usize = 0; var index: usize = 0; while (index < before.len) : (index += 1) { const word = before[index]; if (std.mem.eql(u8, word, "--")) { if (spec.rest) { // Another program's words, which zfj knows nothing of. answer.directive = .files; return; } positional += 1; continue; } const field = optionOf(spec, word) orelse { if (!isFlag(word)) positional += 1; continue; }; if (field.takes_value and std.mem.findScalar(u8, word, '=') == null) { index += 1; if (index == before.len) return offerValues(answer, arena, local, field, typed, ""); } } if (std.mem.startsWith(u8, typed, "--")) { if (std.mem.findScalar(u8, typed, '=')) |equals| { const field = spec.option(typed[2..equals]) orelse return; return offerValues(answer, arena, local, field, typed[equals + 1 ..], typed[0 .. equals + 1]); } } if (std.mem.startsWith(u8, typed, "-")) return offerOptions(answer, arena, spec, typed, true); if (positional < spec.positionals.len) { const field = spec.positionals[positional]; if (field.values.len != 0 or field.complete != .none) return offerValues(answer, arena, local, field, typed, ""); } // A positional word nobody can guess at, or none left to fill: on an // empty word, what options there are. if (typed.len == 0) try offerOptions(answer, arena, spec, typed, true); } fn offerValues(answer: *Answer, arena: Allocator, local: Local, field: args.Spec.Field, typed: []const u8, prefix: []const u8) !void { const found = local.values(arena, field.complete); for (try std.mem.concat(arena, []const u8, &.{ field.values, found })) |value| { const whole = if (prefix.len == 0) value else try std.mem.concat(arena, u8, &.{ prefix, value }); try answer.offer(arena, if (prefix.len == 0) typed else try std.mem.concat(arena, u8, &.{ prefix, typed }), whole, ""); } answer.directive = .of(field.complete); } fn offerOptions(answer: *Answer, arena: Allocator, spec: args.Spec, typed: []const u8, help: bool) !void { for (spec.options) |field| { try answer.offer(arena, typed, try std.mem.concat(arena, u8, &.{ "--", field.name }), field.description); } if (help) try answer.offer(arena, typed, "--help", "say what this takes"); } /// The option `word` names, long or short, or null when it is none. fn optionOf(spec: args.Spec, word: []const u8) ?args.Spec.Field { if (std.mem.startsWith(u8, word, "--") and word.len > 2) return spec.option(flagName(word)); if (word.len == 2 and word[0] == '-' and word[1] != '-') return spec.shortOption(word[1]); return null; } fn isFlag(word: []const u8) bool { return word.len >= 2 and word[0] == '-'; } /// `--name` or `--name=value`'s name. fn flagName(word: []const u8) []const u8 { const flag = word[2..]; return flag[0 .. std.mem.findScalar(u8, flag, '=') orelse flag.len]; } fn beforeSemicolon(text: []const u8) []const u8 { return text[0 .. std.mem.findScalar(u8, text, ';') orelse text.len]; } /// `zfj __complete ...`: the answer for `words`, written out. Any /// failure is fewer candidates, never a message, and it always exits 0. pub fn respond(ctx: *Context, entries: []const Entry, global: args.Spec, words: []const []const u8) Exit { const answer = complete(ctx.arena, entries, global, .of(ctx), words) catch return .ok; answer.write(ctx.stdout) catch return .ok; ctx.stdout.flush() catch {}; return .ok; } pub const Shell = enum { fish, bash, zsh, powershell, fn script(shell: Shell) []const u8 { return switch (shell) { .fish => @embedFile("completions/zfj.fish"), .bash => @embedFile("completions/zfj.bash"), .zsh => @embedFile("completions/_zfj"), .powershell => @embedFile("completions/zfj.ps1"), }; } }; const Options = struct { shell: Shell, pub const positional: []const []const u8 = &.{"shell"}; pub const notes = [_]args.Note{.{ .description = "the shell to complete in" }}; }; pub const command_spec = args.spec(Options, &Options.notes); /// `zfj completion `: the completion script for `shell`, to be /// loaded by it. pub fn main(ctx: *Context, words: []const []const u8) !Exit { for (words) |word| if (std.mem.eql(u8, word, "--help")) { try ctx.stdout.writeAll("usage: zfj completion \n\nPrints the completion script for a shell, for it to load.\n\n"); try args.writeHelp(Options, ctx.stdout, &Options.notes); return .ok; }; var diagnostic: args.Diagnostic = .{}; const o = (args.parse(Options, ctx.arena, words, .all, &diagnostic) catch |err| switch (err) { error.Usage => return ctx.usage("completion takes the shell to complete in, one of " ++ shell_names ++ ": {s}", .{diagnostic.message()}), else => |e| return e, }).value; try ctx.stdout.writeAll(o.shell.script()); return .ok; } const shell_names = blk: { var names: []const u8 = ""; for (@typeInfo(Shell).@"enum".field_names, 0..) |name, i| names = names ++ (if (i == 0) "" else ", ") ++ name; break :blk names; }; const testing = std.testing; const Example = struct { state: []const u8 = "open", body: ?[]const u8 = null, @"body-file": ?[]const u8 = null, number: ?i64 = null, directory: ?[]const u8 = null, json: bool = false, on: ?[]const u8 = null, workflow: ?[]const u8 = null, passed: []const []const u8 = &.{}, pub const short = .{ .s = "state", .F = "body-file" }; pub const positional: []const []const u8 = &.{ "number", "directory" }; pub const rest = "passed"; }; const example_commands = [_]porcelain.Command{ .{ .name = "list", .summary = "list things", .run = undefined, .spec = args.spec(Example, &.{ .{ .description = "which", .allowed = &.{ "open", "closed", "all" } }, .{ .description = "the text" }, .{ .description = "read the text from a file", .complete = .files }, .{}, .{ .description = "where", .complete = .dirs }, .{}, .{ .description = "the instance", .complete = .instances }, .{ .description = "the workflow", .complete = .workflows }, }), }, .{ .name = "lock", .summary = "lock a thing", .run = undefined, .spec = .{} }, }; const example_global = args.spec(struct { instance: ?[]const u8 = null, color: enum { auto, always, never } = .auto, debug: bool = false, }, &.{ .{ .description = "the instance" }, .{ .description = "when to color" } }); const Fixed = struct { fn instances(_: *anyopaque, _: Allocator) []const []const u8 { return &.{ "home", "codeberg" }; } fn workflows(_: *anyopaque, _: Allocator) []const []const u8 { return &.{ "release.yaml", "test.yaml" }; } }; const example_local: Local = .{ .data = undefined, .instancesFn = Fixed.instances, .workflowsFn = Fixed.workflows }; const example_entries = [_]Entry{ .{ .name = "issue", .synopsis = "", .summary = "work with issues; and more", .completes = .{ .group = &example_commands } }, .{ .name = "instances", .synopsis = "", .summary = "list the instances", .completes = .{ .spec = .{} } }, .{ .name = "op", .synopsis = "", .summary = "perform an operation", .completes = .operations }, }; fn expectAnswer(words: []const []const u8, expected: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const answer = try complete(arena.allocator(), &example_entries, example_global, example_local, words); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try answer.write(&out.writer); try testing.expectEqualStrings(expected, out.written()); } test "the first word is a command, described up to its semicolon" { try expectAnswer(&.{"i"}, "issue\twork with issues\ninstances\tlist the instances\n:none\n"); try expectAnswer(&.{}, "issue\twork with issues\ninstances\tlist the instances\nop\tperform an operation\n:none\n"); } test "global options come before the command, and only there" { try expectAnswer(&.{"--d"}, "--debug\n:none\n"); try expectAnswer(&.{ "--color", "a" }, "auto\nalways\n:none\n"); try expectAnswer(&.{ "--debug", "--color=never", "--instance", "x", "is" }, "issue\twork with issues\n:none\n"); try expectAnswer(&.{ "issue", "list", "--de" }, ":none\n"); } test "a group's commands, and then a command's options" { try expectAnswer(&.{ "issue", "l" }, "list\tlist things\nlock\tlock a thing\n:none\n"); try expectAnswer(&.{ "issue", "list", "--st" }, "--state\twhich\n:none\n"); try expectAnswer(&.{ "issue", "lock", "--" }, "--help\tsay what this takes\n:none\n"); try expectAnswer(&.{ "issue", "nonesuch", "--" }, ":none\n"); } test "a flag that takes a value completes that value, however it is spelled" { try expectAnswer(&.{ "issue", "list", "--state", "c" }, "closed\n:none\n"); try expectAnswer(&.{ "issue", "list", "-s", "" }, "open\nclosed\nall\n:none\n"); try expectAnswer(&.{ "issue", "list", "--state=a" }, "--state=all\n:none\n"); try expectAnswer(&.{ "issue", "list", "-F", "" }, ":files\n"); // A value that looks like a flag is still the value. try expectAnswer(&.{ "issue", "list", "--body", "--json", "--j" }, "--json\n:none\n"); } test "positional words take their place in order, and the rest is another program's" { // The number is anyone's guess, so an empty word is offered the options. try expectAnswer(&.{ "issue", "list", "4" }, ":none\n"); try expectAnswer(&.{ "issue", "list", "-s", "all", "42", "" }, ":dirs\n"); try expectAnswer(&.{ "issue", "list", "42", "there", "--", "--dep" }, ":files\n"); } test "an empty word where nothing can be guessed is offered the options" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const answer = try complete(arena.allocator(), &example_entries, example_global, example_local, &.{ "issue", "list", "" }); try testing.expectEqualStrings("--state", answer.candidates.items[0].value); try testing.expectEqualStrings("--help", answer.candidates.items[answer.candidates.items.len - 1].value); } test "an operation, and then its params" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const names = try complete(arena.allocator(), &example_entries, example_global, example_local, &.{ "op", "repoGe" }); try testing.expect(names.candidates.items.len > 1); var found = false; for (names.candidates.items) |candidate| { try testing.expect(std.mem.startsWith(u8, candidate.value, "repoGe")); if (std.mem.eql(u8, candidate.value, "repoGet")) found = true; } try testing.expect(found); const params = try complete(arena.allocator(), &example_entries, example_global, example_local, &.{ "op", "repoGet", "--ow" }); try testing.expectEqualStrings("--owner", params.candidates.items[0].value); try testing.expectEqualStrings("owner of the repo", params.candidates.items[0].description); } test "instances and workflows are offered from what zfj finds" { try expectAnswer(&.{ "issue", "list", "--on", "c" }, "codeberg\n:none\n"); try expectAnswer(&.{ "issue", "list", "--workflow=t" }, "--workflow=test.yaml\n:none\n"); // Nothing found is nothing offered, rather than a failure. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const answer = try complete(arena.allocator(), &example_entries, example_global, .none, &.{ "issue", "list", "--on", "" }); try testing.expectEqual(@as(usize, 0), answer.candidates.items.len); } test "workflow files are those Forgejo reads, .forgejo's before .gitea's" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try testing.expectEqual(@as(usize, 0), (try workflowFiles(arena.allocator(), testing.io, tmp.dir)).len); try tmp.dir.createDirPath(testing.io, ".gitea/workflows"); try tmp.dir.writeFile(testing.io, .{ .sub_path = ".gitea/workflows/old.yml", .data = "" }); const gitea = try workflowFiles(arena.allocator(), testing.io, tmp.dir); try testing.expectEqual(@as(usize, 1), gitea.len); try testing.expectEqualStrings("old.yml", gitea[0]); try tmp.dir.createDirPath(testing.io, ".forgejo/workflows"); try tmp.dir.writeFile(testing.io, .{ .sub_path = ".forgejo/workflows/test.yaml", .data = "" }); try tmp.dir.writeFile(testing.io, .{ .sub_path = ".forgejo/workflows/release.yaml", .data = "" }); try tmp.dir.writeFile(testing.io, .{ .sub_path = ".forgejo/workflows/README.md", .data = "" }); const forgejo = try workflowFiles(arena.allocator(), testing.io, tmp.dir); try testing.expectEqual(@as(usize, 2), forgejo.len); try testing.expectEqualStrings("release.yaml", forgejo[0]); try testing.expectEqualStrings("test.yaml", forgejo[1]); } test "the instances are offered by name" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const names = try instanceNames(arena.allocator(), .{ .instances = &.{ .{ .name = "home", .url = "https://git.example.org", .token = "" }, .{ .name = "codeberg", .url = "https://codeberg.org", .token = "" }, } }); try testing.expectEqualStrings("home", names[0]); try testing.expectEqualStrings("codeberg", names[1]); } test "a description is one line with no tab in it" { var answer: Answer = .{}; defer answer.candidates.deinit(testing.allocator); try answer.offer(testing.allocator, "", "x", "one\ttwo"); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try answer.write(&out.writer); try testing.expectEqualStrings("x\tone two\n:none\n", out.written()); }