Lightpanda: the headless browser designed for AI and automation
Add shell completion for bash, fish and zsh
Adrià Arrufatd26e1e2f5549
diff --git a/README.md b/README.mdindex c06432927..f348448a9 100644--- a/README.md+++ b/README.md@@ -246,6 +246,16 @@ longer clobber each other's page:A skill is available in [lightpanda-io/agent-skill](https://github.com/lightpanda-io/agent-skill).+### Shell completion++`lightpanda completion <bash | fish | zsh>` prints a completion script for commands, flags and their values:++```console+lightpanda completion fish > ~/.config/fish/completions/lightpanda.fish+lightpanda completion bash > ~/.local/share/bash-completion/completions/lightpanda+lightpanda completion zsh > ~/.zfunc/_lightpanda # with fpath=(~/.zfunc $fpath) before compinit+```+### TelemetryBy default, Lightpanda collects and sends usage telemetry. This can be disabled by setting an environment variable `LIGHTPANDA_DISABLE_TELEMETRY=true`. You can read Lightpanda's privacy policy at: [https://lightpanda.io/privacy-policy](https://lightpanda.io/privacy-policy).diff --git a/src/Config.zig b/src/Config.zigindex 8bbad8b10..b87230171 100644--- a/src/Config.zig+++ b/src/Config.zig@@ -273,9 +273,9 @@ const CommonOptions = .{.{ .name = "log_filter", .type = log.FilterRule, .multiple = true, .validator = logFilterValidator },.{ .name = "log_filter_scopes", .type = log.FilterRule, .multiple = true, .validator = logFilterValidator, .deprecated = "use --log-filter" },.{ .name = "user_agent_suffix", .type = ?[]const u8 },- .{ .name = "http_cache_dir", .type = ?[]const u8 },+ .{ .name = "http_cache_dir", .type = ?[]const u8, .path = true },.{ .name = "http_cache_entry_limit", .type = ?u32, .default = 1000 },- .{ .name = "web_bot_auth_key_file", .type = ?[]const u8 },+ .{ .name = "web_bot_auth_key_file", .type = ?[]const u8, .path = true },.{ .name = "web_bot_auth_keyid", .type = ?[]const u8 },.{ .name = "web_bot_auth_domain", .type = ?[]const u8 },.{ .name = "user_agent", .type = ?[]const u8, .validator = userAgentValidator },@@ -284,9 +284,9 @@ const CommonOptions = .{.{ .name = "block_private_networks", .type = bool },.{ .name = "block_cidrs", .type = ?[]const u8, .validator = accumulateValidator },.{ .name = "block_urls", .type = ?[]const u8, .validator = accumulateValidator },- .{ .name = "adblock_lists", .type = ?[]const u8, .validator = accumulateValidator },- .{ .name = "cookie", .type = ?[]const u8 },- .{ .name = "cookie_jar", .type = ?[]const u8 },+ .{ .name = "adblock_lists", .type = ?[]const u8, .validator = accumulateValidator, .path = true },+ .{ .name = "cookie", .type = ?[]const u8, .path = true },+ .{ .name = "cookie_jar", .type = ?[]const u8, .path = true },.{ .name = "disable_subframes", .type = bool, .deprecated = "subframes are now disabled by default, use \"--load-resources iframe\" to enable" },.{ .name = "disable_workers", .type = bool, .deprecated = "workers are now disabled by default, use \"--load-resources worker\" to enable" },.{ .name = "enable_external_stylesheets", .type = bool, .deprecated = "use \"--load-resources stylesheet\" to enable" },@@ -304,6 +304,7 @@ const CommonOptions = .{},.default = Cert{},.validator = caCertValidator,+ .path = true,},.{.name = "ca_path",@@ -314,6 +315,7 @@ const CommonOptions = .{},.default = Cert{},.validator = caPathValidator,+ .path = true,},};@@ -396,7 +398,7 @@ fn injectScriptFileValidator(}/// Definition for all the commands and its arguments. See @cli.zig for further.-const Commands = cli.Builder(.{+pub const Commands = cli.Builder(.{.{.name = "serve",.options = .{@@ -432,7 +434,7 @@ const Commands = cli.Builder(.{.name = "wait_script",.type = ?[:0]const u8,.variants = .{- .{ .name = "wait_script_file", .validator = waitScriptFileValidator },+ .{ .name = "wait_script_file", .validator = waitScriptFileValidator, .path = true },},},.{ .name = "wait_selector", .type = ?[:0]const u8 },@@ -441,7 +443,7 @@ const Commands = cli.Builder(.{.type = []const u8,.multiple = true,.variants = .{- .{ .name = "inject_script_file", .validator = injectScriptFileValidator },+ .{ .name = "inject_script_file", .validator = injectScriptFileValidator, .path = true },},},.{ .name = "terminate_ms", .type = ?u32 },@@ -462,15 +464,15 @@ const Commands = cli.Builder(.{},.{.name = "agent",- .positional = .{ .name = "script_file", .type = ?[:0]const u8 },+ .positional = .{ .name = "script_file", .type = ?[:0]const u8, .path = true },.options = .{.{ .name = "provider", .type = ?AiProvider },.{ .name = "model", .type = ?[:0]const u8 },.{ .name = "base_url", .type = ?[:0]const u8 },.{ .name = "system_prompt", .type = ?[:0]const u8 },.{ .name = "task", .type = ?[]const u8 },- .{ .name = "save", .type = ?[]const u8 },- .{ .name = "attach", .short = 'a', .type = []const u8, .multiple = true },+ .{ .name = "save", .type = ?[]const u8, .path = true },+ .{ .name = "attach", .short = 'a', .type = []const u8, .multiple = true, .path = true },.{ .name = "verbosity", .type = ?AgentVerbosity },.{ .name = "effort", .type = ?Effort },.{ .name = "search_engine", .type = ?SearchEngine },@@ -483,13 +485,18 @@ const Commands = cli.Builder(.{.{// Normalized to `.agent` in `parseArgs`; intentionally no LLM options..name = "run",- .positional = .{ .name = "script_file", .type = ?[:0]const u8 },+ .positional = .{ .name = "script_file", .type = ?[:0]const u8, .path = true },.options = .{},.shared_options = CommonOptions,},.{ .name = "version", .options = .{.{ .name = "check", .type = bool },} },+ .{+ .name = "completion",+ .positional = .{ .name = "shell", .type = ?Shell },+ .options = .{},+ },});const RunMode = Commands.Enum;@@ -968,6 +975,8 @@ pub const DumpFormat = enum {semantic_tree_text,};+pub const Shell = enum { bash, fish, zsh };+pub const WaitUntil = enum {load,domcontentloaded,@@ -1140,8 +1149,8 @@ pub fn printUsageAndExit(self: *const Config, allocator: Allocator, help_for: Ru, .{ @field(Help, @tagName(tag)), Help.common_options });break :text try std.fmt.allocPrint(allocator, template, .{ exec_name, info_or_warn, pretty_or_logfmt });},- .version => text: {- const template = Help.version ++ "\n";+ inline .version, .completion => |tag| text: {+ const template = @field(Help, @tagName(tag)) ++ "\n";break :text try std.fmt.allocPrint(allocator, template, .{exec_name});},};diff --git a/src/cli.zig b/src/cli.zigindex e5e9abedc..6fac039cb 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -65,10 +65,11 @@ const string = @import("string.zig");/// - `positional: struct` (optional) — a positional argument with `.name`/// and `.type` that may appear anywhere in argv. By default it holds a/// single value: `.type` must be an optional pointer-to-u8 slice (e.g.-/// `?[:0]const u8`), it defaults to `null`, and passing it more than once-/// returns `error.TooManyPositionalArguments`. With `.multiple = true`,-/// `.type` is the (non-optional) element slice (e.g. `[:0]const u8`), the-/// field becomes a `std.ArrayList(type)`, and each occurrence appends.+/// `?[:0]const u8`) or enum, it defaults to `null`, and passing it more+/// than once returns `error.TooManyPositionalArguments`. With+/// `.multiple = true`, `.type` is the (non-optional) element type (e.g.+/// `[:0]const u8`), the field becomes a `std.ArrayList(type)`, and each+/// occurrence appends.////// ## Option descriptor fields///@@ -91,6 +92,9 @@ const string = @import("string.zig");/// the same field. See the variants section below./// - `deprecated: []const u8` (optional) — the option still parses, but/// each use logs a warning carrying this note.+/// - `path: bool` (optional) — the value is a file or directory path, so+/// shell completion offers files. Also allowed on a variant and on a+/// positional.////// ## Supported types and their defaults///@@ -190,9 +194,10 @@ const string = @import("string.zig");/// .help => |tag| printHelp(tag),/// }/// ```+/// Tag names of an enum, or field names of a (packed) struct option.pub fn tagNames(comptime E: type) []const []const u8 {return comptime blk: {- const fields = @typeInfo(E).@"enum".fields;+ const fields = std.meta.fields(E);var names: [fields.len][]const u8 = undefined;for (fields, &names) |f, *n| n.* = f.name;const frozen = names;@@ -200,6 +205,37 @@ pub fn tagNames(comptime E: type) []const []const u8 {};}+pub const Completion = struct {+ pub const Command = struct {+ name: []const u8,+ positional: ?Positional,+ flags: []const Flag,+ };++ pub const Positional = struct {+ name: []const u8,+ values: Values,+ multiple: bool,+ };++ pub const Flag = struct {+ /// Long form, kebab-case, with the leading `--`.+ name: []const u8,+ short: ?u8 = null,+ values: Values,+ };++ pub const Values = union(enum) {+ /// A switch; takes no argument.+ none,+ any,+ path,+ one_of: []const []const u8,+ /// A comma-separated list of these (packed-struct options).+ list_of: []const []const u8,+ };+};+pub fn Builder(comptime commands: anytype) type {return struct {const Self = @This();@@ -531,22 +567,92 @@ pub fn Builder(comptime commands: anytype) type {return output;}- /// Short aliases are left out: a one-letter candidate sits within two- /// edits of nearly any typo.- fn optionNames(comptime options: anytype) []const []const u8 {- return comptime blk: {- // toKebabCase walks every byte of every name.- @setEvalBranchQuota(50_000);- var names: []const []const u8 = &.{};- for (options) |option| {- names = names ++ &[_][]const u8{"--" ++ toKebabCase(option.name)};- if (@hasField(@TypeOf(option), "variants")) {- for (option.variants) |variant| {- names = names ++ &[_][]const u8{"--" ++ toKebabCase(variant.name)};- }+ /// Every command's flags and their accepted values, for generating+ /// shell completion scripts. Deprecated options are left out.+ pub const completion_spec: []const Completion.Command = blk: {+ @setEvalBranchQuota(200_000);+ var specs: [commands.len + 1]Completion.Command = undefined;+ for (commands, specs[0..commands.len]) |command, *spec| {+ const Command = @TypeOf(command);+ spec.* = .{+ .name = command.name,+ .positional = if (@hasField(Command, "positional")) .{+ .name = command.positional.name,+ .values = completionValues(command.positional),+ .multiple = @hasField(@TypeOf(command.positional), "multiple") and command.positional.multiple,+ } else null,+ .flags = commandFlags(command),+ };+ }+ specs[commands.len] = .{+ .name = "help",+ .positional = .{ .name = "command", .values = .{ .one_of = command_names }, .multiple = false },+ .flags = &.{},+ };+ const frozen = specs;+ break :blk &frozen;+ };++ /// The command's flags, for completion and "did you mean" suggestions.+ /// Deprecated options are left out.+ fn commandFlags(comptime command: anytype) []const Completion.Flag {+ @setEvalBranchQuota(200_000);+ const options = if (@hasField(@TypeOf(command), "shared_options"))+ command.options ++ command.shared_options+ else+ command.options;++ var flags: []const Completion.Flag = &.{};+ outer: for (options) |option| {+ if (@hasField(@TypeOf(option), "deprecated")) continue;+ const name = "--" ++ toKebabCase(option.name);+ // A shared option the command redefines is listed once.+ for (flags) |flag| {+ if (std.mem.eql(u8, flag.name, name)) continue :outer;+ }+ const values = completionValues(option);+ flags = flags ++ &[_]Completion.Flag{.{+ .name = name,+ .short = if (@hasField(@TypeOf(option), "short")) option.short else null,+ .values = values,+ }};+ if (@hasField(@TypeOf(option), "variants")) {+ for (option.variants) |variant| {+ flags = flags ++ &[_]Completion.Flag{.{+ .name = "--" ++ toKebabCase(variant.name),+ .values = if (@hasField(@TypeOf(variant), "path") and variant.path) .path else values,+ }};}}- break :blk names;+ }+ return flags;+ }++ /// Takes an option or a positional.+ fn completionValues(comptime option: anytype) Completion.Values {+ if (@hasField(@TypeOf(option), "path") and option.path) return .path;+ const T = if (@typeInfo(@TypeOf(option.type)) == .@"struct") option.type.cli else option.type;+ const Child = switch (@typeInfo(T)) {+ .optional => |optional| optional.child,+ else => T,+ };+ return switch (@typeInfo(Child)) {+ .bool => .none,+ .@"enum" => .{ .one_of = tagNames(Child) },+ .@"struct" => |s| if (s.layout == .@"packed") .{ .list_of = tagNames(Child) } else .any,+ else => .any,+ };+ }++ fn parseEnum(comptime E: type, arg: []const u8, str: []const u8) error{InvalidArgument}!E {+ return std.meta.stringToEnum(E, str) orelse {+ const value = log.red(str);+ if (string.closest(str, tagNames(E), 2)) |near| {+ log.fatal(.app, "invalid option choice", .{ .arg = arg, .value = value, .did_you_mean = log.green(near) });+ } else {+ log.fatal(.app, "invalid option choice", .{ .arg = arg, .value = value });+ }+ return error.InvalidArgument;};}@@ -689,15 +795,7 @@ pub fn Builder(comptime commands: anytype) type {};const str = args.next() orelse return error.MissingArgument;- const v = std.meta.stringToEnum(E, str) orelse {- const value = log.red(str);- if (string.closest(str, tagNames(E), 2)) |near| {- log.fatal(.app, "invalid option choice", .{ .arg = kebab_cased, .value = value, .did_you_mean = log.green(near) });- } else {- log.fatal(.app, "invalid option choice", .{ .arg = kebab_cased, .value = value });- }- return error.InvalidArgument;- };+ const v = try parseEnum(E, kebab_cased, str);if (is_multiple) {try target.append(allocator, v);@@ -800,7 +898,13 @@ pub fn Builder(comptime commands: anytype) type {// Encountered an option we don't know of.if (std.mem.startsWith(u8, option_name, "--")) {- const names = comptime optionNames(options) ++ &[_][]const u8{"--help"};+ // Short aliases are left out: a one-letter candidate sits+ // within two edits of nearly any typo.+ const names = comptime blk: {+ var names: []const []const u8 = &.{"--help"};+ for (commandFlags(command)) |flag| names = names ++ &[_][]const u8{flag.name};+ break :blk names;+ };const arg = log.red(option_name);if (string.closest(option_name, names, 2)) |near| {log.fatal(.app, "unknown argument", .{ .mode = command.name, .arg = arg, .did_you_mean = log.green(near) });@@ -857,6 +961,14 @@ pub fn Builder(comptime commands: anytype) type {@field(c, positional.name) = v;}},+ .@"enum" => {+ const v = try parseEnum(Child, positional.name, str);+ if (is_multiple) {+ try @field(c, positional.name).append(allocator, v);+ } else {+ @field(c, positional.name) = v;+ }+ },inline else => @compileError("not supported"),}} else {@@ -881,21 +993,48 @@ pub fn Builder(comptime commands: anytype) type {};}-test "cli: optionNames" {- const options = .{- .{ .name = "dump", .type = bool },+test "cli: completion_spec" {+ const Strip = packed struct(u2) { js: bool = false, css: bool = false };+ const Format = enum { html, markdown };+ const shared = .{+ .{ .name = "verbose", .type = bool },+ .{ .name = "old", .type = bool, .deprecated = "gone" },+ .{ .name = "host", .type = []const u8, .default = "0.0.0.0" },+ };+ const Cli = Builder(.{.{- .name = "wait_script",- .type = ?[]const u8,- .variants = .{- .{ .name = "wait_script_file" },+ .name = "fetch",+ .positional = .{ .name = "url", .type = [:0]const u8, .multiple = true },+ .options = .{+ .{ .name = "host", .type = []const u8, .default = "127.0.0.1" },+ .{ .name = "dump", .type = ?Format },+ .{ .name = "strip_mode", .type = Strip, .default = Strip{} },+ .{ .name = "attach", .short = 'a', .type = []const u8, .multiple = true },+ .{ .name = "wait_script", .type = ?[]const u8, .variants = .{.{ .name = "wait_script_file", .path = true }} },},+ .shared_options = shared,},- };- const Cli = Builder(.{- .{ .name = "fetch", .options = options },+ .{ .name = "version", .options = .{} },});- const expected = [_][]const u8{ "--dump", "--wait-script", "--wait-script-file" };- try std.testing.expectEqualDeep(&expected, Cli.optionNames(options));+ const spec = Cli.completion_spec;+ try std.testing.expectEqual(3, spec.len);+ try std.testing.expectEqualDeep(Completion.Positional{ .name = "url", .values = .any, .multiple = true }, spec[0].positional.?);+ try std.testing.expectEqual(null, spec[1].positional);+ try std.testing.expectEqual(0, spec[1].flags.len);+ try std.testing.expectEqualStrings("help", spec[2].name);+ try std.testing.expectEqualDeep(Completion.Values{ .one_of = &.{ "fetch", "version", "help" } }, spec[2].positional.?.values);++ const flags = spec[0].flags;+ const names = [_][]const u8{ "--host", "--dump", "--strip-mode", "--attach", "--wait-script", "--wait-script-file", "--verbose" };+ try std.testing.expectEqual(names.len, flags.len);+ for (names, flags) |name, flag| try std.testing.expectEqualStrings(name, flag.name);++ try std.testing.expectEqual(.any, flags[0].values);+ try std.testing.expectEqualDeep(Completion.Values{ .one_of = &.{ "html", "markdown" } }, flags[1].values);+ try std.testing.expectEqualDeep(Completion.Values{ .list_of = &.{ "js", "css" } }, flags[2].values);+ try std.testing.expectEqual('a', flags[3].short.?);+ try std.testing.expectEqual(.any, flags[4].values);+ try std.testing.expectEqual(.path, flags[5].values);+ try std.testing.expectEqual(.none, flags[6].values);}diff --git a/src/completion.zig b/src/completion.zignew file mode 100644index 000000000..3896ff505--- /dev/null+++ b/src/completion.zig@@ -0,0 +1,417 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++//! Shell completion scripts for `lightpanda completion <shell>`, generated+//! from the CLI recipe (flags, accepted values, paths) and help.zon+//! (descriptions), so they can't drift from the parser.++const std = @import("std");+const Writer = std.Io.Writer;++const cli = @import("cli.zig");+const Config = @import("Config.zig");+const Help = @import("help.zon");++const Shell = Config.Shell;+const Values = cli.Completion.Values;++const commands = Config.Commands.completion_spec;++/// Each command's help.zon text, in `commands` order.+const help_texts = blk: {+ var texts: [commands.len][]const u8 = undefined;+ for (commands, &texts) |command, *text| text.* = @field(Help, command.name);+ const frozen = texts;+ break :blk &frozen;+};++const command_names = blk: {+ var names: [commands.len][]const u8 = undefined;+ for (commands, &names) |command, *name| name.* = command.name;+ const frozen = names;+ break :blk &frozen;+};++pub fn write(w: *Writer, shell: Shell, exec_name: []const u8) !void {+ return switch (shell) {+ .bash => writeBash(w, exec_name),+ .fish => writeFish(w, exec_name),+ .zsh => writeZsh(w, exec_name),+ };+}++fn writeFish(w: *Writer, exec_name: []const u8) !void {+ try w.print("complete -c {s} -f\n", .{exec_name});+ for (commands) |command| {+ try w.print("complete -c {s} -n __fish_use_subcommand -a {s} -d '", .{ exec_name, command.name });+ try writeText(w, commandSummary(command.name), exec_name, .fish);+ try w.writeAll("'\n");+ }++ for (commands, help_texts) |command, help_text| {+ const condition = "complete -c {s} -n '__fish_seen_subcommand_from {s}'";+ if (command.positional) |positional| switch (positional.values) {+ .none, .any => {},+ .path => try w.print(condition ++ " -F\n", .{ exec_name, command.name }),+ .one_of, .list_of => |values| {+ try w.print(condition ++ " -a '", .{ exec_name, command.name });+ try writeJoined(w, values);+ try w.writeAll("'\n");+ },+ };+ for (command.flags) |flag| {+ try w.print(condition ++ " -l {s}", .{ exec_name, command.name, flag.name[2..] });+ if (flag.short) |short| try w.print(" -s {c}", .{short});+ switch (flag.values) {+ .none => {},+ .any => try w.writeAll(" -x"),+ .path => try w.writeAll(" -r -F"),+ .one_of, .list_of => |values| {+ try w.writeAll(" -x -a '");+ try writeJoined(w, values);+ try w.writeAll("'");+ },+ }+ try w.writeAll(" -d '");+ try writeText(w, describe(help_text, flag.name), exec_name, .fish);+ try w.writeAll("'\n");+ }+ }+}++fn writeBash(w: *Writer, exec_name: []const u8) !void {+ try w.print(+ \\_{f}() {{+ \\ local cur prev cmd i+ \\ cur="${{COMP_WORDS[COMP_CWORD]}}"+ \\ prev="${{COMP_WORDS[COMP_CWORD-1]}}"+ \\ cmd=""+ \\ for ((i = 1; i < COMP_CWORD; i++)); do+ \\ case "${{COMP_WORDS[i]}}" in+ \\ -*) ;;+ \\ *) cmd="${{COMP_WORDS[i]}}"; break ;;+ \\ esac+ \\ done+ \\+ \\ if [[ -z $cmd ]]; then+ \\ COMPREPLY=($(compgen -W "+ , .{Ident{ .name = exec_name }});+ try writeJoined(w, command_names);+ try w.writeAll(+ \\" -- "$cur"))+ \\ return+ \\ fi+ \\+ \\ case "$cmd" in+ \\+ );++ for (commands) |command| {+ try w.print(" {s})\n case \"$prev\" in\n", .{command.name});+ for (command.flags) |flag| {+ if (flag.values == .none) continue;+ try w.print(" {s}", .{flag.name});+ if (flag.short) |short| try w.print("|-{c}", .{short});+ try w.writeAll(") ");+ try writeBashAction(w, flag.values);+ try w.writeAll("return ;;\n");+ }+ try w.writeAll(" esac\n if [[ $cur == -* ]]; then\n COMPREPLY=($(compgen -W \"");+ for (command.flags, 0..) |flag, i| {+ if (i > 0) try w.writeAll(" ");+ try w.writeAll(flag.name);+ if (flag.short) |short| try w.print(" -{c}", .{short});+ }+ try w.writeAll("\" -- \"$cur\"))\n");+ if (command.positional) |positional| if (positional.values != .any) {+ try w.writeAll(" else\n ");+ try writeBashAction(w, positional.values);+ try w.writeAll("\n");+ };+ try w.writeAll(" fi\n ;;\n");+ }++ try w.print(" esac\n}}\ncomplete -F _{f} {s}\n", .{ Ident{ .name = exec_name }, exec_name });+}++fn writeBashAction(w: *Writer, values: Values) !void {+ switch (values) {+ .none, .any => {},+ .path => try w.writeAll("compopt -o filenames 2>/dev/null; mapfile -t COMPREPLY < <(compgen -f -- \"$cur\"); "),+ .one_of => |one_of| {+ try w.writeAll("COMPREPLY=($(compgen -W \"");+ try writeJoined(w, one_of);+ try w.writeAll("\" -- \"$cur\")); ");+ },+ .list_of => |list_of| {+ // Complete the item after the last comma.+ try w.writeAll("COMPREPLY=($(compgen -P \"${cur%\"${cur##*,}\"}\" -W \"");+ try writeJoined(w, list_of);+ try w.writeAll("\" -- \"${cur##*,}\")); ");+ },+ }+}++fn writeZsh(w: *Writer, exec_name: []const u8) !void {+ const ident: Ident = .{ .name = exec_name };+ try w.print(+ \\#compdef {s}+ \\+ \\_{f}() {{+ \\ local curcontext="$curcontext" state line+ \\ typeset -A opt_args+ \\ _arguments -C '1: :->command' '*:: :->args'+ \\ case $state in+ \\ command)+ \\ local -a commands=(+ \\+ , .{ exec_name, ident });+ for (commands) |command| {+ try w.print(" '{s}:", .{command.name});+ try writeText(w, commandSummary(command.name), exec_name, .zsh);+ try w.writeAll("'\n");+ }+ try w.writeAll(+ \\ )+ \\ _describe -t commands command commands+ \\ ;;+ \\ args)+ \\ case $words[1] in+ \\+ );++ for (commands, help_texts) |command, help_text| {+ try w.print(" {s})\n _arguments -s", .{command.name});+ for (command.flags) |flag| {+ const description = describe(help_text, flag.name);+ try writeZshFlag(w, flag.name, flag.values, description, exec_name);+ if (flag.short) |short| {+ try writeZshFlag(w, &.{ '-', short }, flag.values, description, exec_name);+ }+ }+ if (command.positional) |positional| {+ try w.print(" \\\n '{s}", .{if (positional.multiple) "*" else "1"});+ try writeZshAction(w, positional.name, positional.values);+ try w.writeAll("'");+ }+ try w.writeAll("\n ;;\n");+ }++ try w.print(+ \\ esac+ \\ ;;+ \\ esac+ \\}}+ \\+ \\if [ "$funcstack[1]" = "_{f}" ]; then+ \\ _{f} "$@"+ \\else+ \\ compdef _{f} {s}+ \\fi+ \\+ , .{ ident, ident, ident, exec_name });+}++fn writeZshFlag(w: *Writer, name: []const u8, values: Values, description: []const u8, exec_name: []const u8) !void {+ // Every flag is repeatable: `multiple` ones collect, the rest keep the last.+ try w.print(" \\\n '*{s}[", .{name});+ try writeText(w, description, exec_name, .zsh);+ try w.writeAll("]");+ try writeZshAction(w, std.mem.trimStart(u8, name, "-"), values);+ try w.writeAll("'");+}++fn writeZshAction(w: *Writer, message: []const u8, values: Values) !void {+ switch (values) {+ .none => {},+ .any => try w.print(":{s}: ", .{message}),+ .path => try w.print(":{s}:_files", .{message}),+ .one_of => |one_of| {+ try w.print(":{s}:(", .{message});+ try writeJoined(w, one_of);+ try w.writeAll(")");+ },+ .list_of => |list_of| {+ try w.print(":{s}:_values -s , {s} ", .{ message, message });+ try writeJoined(w, list_of);+ },+ }+}++fn writeJoined(w: *Writer, items: []const []const u8) !void {+ for (items, 0..) |item, i| {+ if (i > 0) try w.writeAll(" ");+ try w.writeAll(item);+ }+}++/// An exec name as a shell function name, which can't hold `-` or `.`.+const Ident = struct {+ name: []const u8,++ pub fn format(self: Ident, w: *Writer) Writer.Error!void {+ for (self.name) |c| try w.writeByte(if (std.ascii.isAlphanumeric(c)) c else '_');+ }+};++/// Writes help.zon text into a single-quoted string: `{0s}` becomes the exec+/// name and each line break with its indentation a single space. zsh also+/// needs `[]` escaped, as descriptions sit inside `--flag[description]`.+fn writeText(w: *Writer, text: []const u8, exec_name: []const u8, comptime quoting: enum { fish, zsh }) !void {+ var i: usize = 0;+ while (i < text.len) : (i += 1) {+ if (std.mem.startsWith(u8, text[i..], "{0s}")) {+ try w.writeAll(exec_name);+ i += 3;+ continue;+ }+ const c = text[i];+ if (c == '\n') {+ while (i + 1 < text.len and text[i + 1] == ' ') i += 1;+ try w.writeByte(' ');+ continue;+ }+ switch (quoting) {+ .fish => switch (c) {+ '\\', '\'' => try w.print("\\{c}", .{c}),+ else => try w.writeByte(c),+ },+ .zsh => switch (c) {+ '\'' => try w.writeAll("'\\''"),+ '[', ']' => try w.print("\\{c}", .{c}),+ else => try w.writeByte(c),+ },+ }+ }+}++fn commandSummary(name: []const u8) []const u8 {+ var lines = std.mem.splitScalar(u8, Help.general, '\n');+ while (lines.next()) |line| {+ const trimmed = std.mem.trimStart(u8, line, " ");+ if (trimmed.len == line.len) continue;+ if (!std.mem.startsWith(u8, trimmed, name)) continue;+ const rest = trimmed[name.len..];+ if (rest.len == 0 or rest[0] != ' ') continue;+ return std.mem.trim(u8, rest, " ");+ }+ return "";+}++/// The first sentence of the flag's description, from the command's own help+/// or else the common options. It can span lines, as written in help.zon.+fn describe(help_text: []const u8, flag: []const u8) []const u8 {+ return findDescription(help_text, flag) orelse findDescription(Help.common_options, flag) orelse "";+}++fn findDescription(text: []const u8, flag: []const u8) ?[]const u8 {+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |line| {+ if (!std.mem.startsWith(u8, line, " -")) continue;+ var tokens = std.mem.tokenizeAny(u8, line, " ,");+ while (tokens.next()) |token| {+ if (std.mem.eql(u8, token, flag)) return firstSentence(lines.rest());+ }+ }+ return null;+}++/// `text` starts with the indented description lines that follow a flag.+fn firstSentence(text: []const u8) []const u8 {+ var end: usize = 0;+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |line| {+ const trimmed = std.mem.trimStart(u8, line, " ");+ if (trimmed.len == line.len or+ std.mem.startsWith(u8, trimmed, "Defaults") or+ std.mem.startsWith(u8, trimmed, "Allowed values") or+ std.mem.startsWith(u8, trimmed, "e.g.")) break;+ end = lines.index orelse text.len;+ }+ const body = std.mem.trim(u8, text[0..end], " \n");+ return body[0 .. sentenceEnd(body) orelse std.mem.trimEnd(u8, body, ".").len];+}++/// Index of the period closing the first sentence, skipping `e.g.`/`i.e.`.+fn sentenceEnd(text: []const u8) ?usize {+ var i: usize = 0;+ while (std.mem.indexOfScalarPos(u8, text, i, '.')) |dot| : (i = dot + 1) {+ if (dot + 1 < text.len and text[dot + 1] != ' ' and text[dot + 1] != '\n') continue;+ if (std.mem.endsWith(u8, text[0..dot], "e.g") or std.mem.endsWith(u8, text[0..dot], "i.e")) continue;+ return dot;+ }+ return null;+}++test "completion: every flag is documented" {+ for (commands, help_texts) |command, help_text| {+ for (command.flags) |flag| {+ if (describe(help_text, flag.name).len == 0) {+ std.debug.print("{s} {s} has no entry in help.zon\n", .{ command.name, flag.name });+ return error.Undocumented;+ }+ }+ try std.testing.expect(commandSummary(command.name).len > 0);+ }+}++test "completion: describe" {+ try std.testing.expectEqualStrings("Path to a file to load cookies from (read-only)", describe(Help.fetch, "--cookie"));+ // e.g. doesn't end the sentence.+ try std.testing.expectEqualStrings("The host to advertise, e.g. in the /json/version response", describe(Help.serve, "--advertise-host"));+ // Found in the common options.+ try std.testing.expectEqualStrings("The log level", describe(Help.serve, "--log-level"));+ try std.testing.expectEqualStrings("", describe(Help.serve, "--nope"));+}++test "completion: fish" {+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ try write(&out.writer, .fish, "lp");+ const script = out.written();++ const expected = [_][]const u8{+ "complete -c lp -n __fish_use_subcommand -a fetch -d 'fetches the specified URL'\n",+ "complete -c lp -n '__fish_seen_subcommand_from fetch' -l with-base -d ",+ "complete -c lp -n '__fish_seen_subcommand_from fetch' -l cookie -r -F -d ",+ "complete -c lp -n '__fish_seen_subcommand_from fetch' -l dump -x -a 'html markdown ",+ "complete -c lp -n '__fish_seen_subcommand_from agent' -l attach -s a -r -F -d ",+ "complete -c lp -n '__fish_seen_subcommand_from run' -F\n",+ "complete -c lp -n '__fish_seen_subcommand_from completion' -a 'bash fish zsh'\n",+ "complete -c lp -n '__fish_seen_subcommand_from help' -a 'serve fetch ",+ };+ for (expected) |line| {+ if (std.mem.indexOf(u8, script, line) == null) {+ std.debug.print("missing: {s}\n", .{line});+ return error.MissingLine;+ }+ }+ try std.testing.expect(std.mem.indexOf(u8, script, "disable-workers") == null);+ try std.testing.expect(std.mem.indexOf(u8, script, "{0s}") == null);+}++test "completion: bash and zsh" {+ inline for (.{ Shell.bash, Shell.zsh }) |shell| {+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ try write(&out.writer, shell, "light-panda");+ const script = out.written();+ try std.testing.expect(std.mem.indexOf(u8, script, "_light_panda()") != null);+ try std.testing.expect(std.mem.indexOf(u8, script, "--load-resources") != null);+ }+}diff --git a/src/help.zon b/src/help.zonindex 85a0c78c8..d3576a2b5 100644--- a/src/help.zon+++ b/src/help.zon@@ -5,6 +5,7 @@\\\\The commands are:\\ agent starts an interactive AI agent that can browse the web+ \\ completion prints a shell completion script (bash, fish, zsh)\\ fetch fetches the specified URL\\ help displays this message\\ mcp starts an MCP (Model Context Protocol) server (stdio or HTTP)@@ -362,6 +363,18 @@\\ found, prints the running version, the latest release, and how to\\ update.,+ .completion =+ \\usage: {0s} completion <bash | fish | zsh>+ \\+ \\Prints a shell completion script for {0s} to stdout.+ \\+ \\Examples:+ \\ {0s} completion fish | source+ \\ {0s} completion fish > ~/.config/fish/completions/{0s}.fish+ \\ {0s} completion bash > ~/.local/share/bash-completion/completions/{0s}+ \\ {0s} completion zsh > ~/.zfunc/_{0s}+ \\ then add `fpath=(~/.zfunc $fpath)` before `compinit` in ~/.zshrc+ ,.help =\\usage: {0s} help\\diff --git a/src/lightpanda.zig b/src/lightpanda.zigindex e51039aff..0c748e43f 100644--- a/src/lightpanda.zig+++ b/src/lightpanda.zig@@ -24,6 +24,7 @@ pub const App = @import("App.zig");pub const Arena = @import("Arena.zig");pub const Regex = @import("Regex.zig");pub const Config = @import("Config.zig");+pub const completion = @import("completion.zig");pub const cookies = @import("cookies.zig");pub const datetime = @import("datetime.zig");pub const core_dump = @import("core_dump.zig");diff --git a/src/main.zig b/src/main.zigindex 3d10ff3a7..cb3d4adf5 100644--- a/src/main.zig+++ b/src/main.zig@@ -77,6 +77,14 @@ fn run(allocator: Allocator, main_arena: Allocator, proc_args: std.process.Args)}return std.process.cleanExit(lp.io);},+ .completion => |opts| {+ const shell = opts.shell orelse return args.printUsageAndExit(main_arena, .completion, false);+ var buf: [4096]u8 = undefined;+ var stdout = std.Io.File.stdout().writerStreaming(lp.io, &buf);+ try lp.completion.write(&stdout.interface, shell, args.exec_name);+ try stdout.interface.flush();+ return std.process.cleanExit(lp.io);+ },.agent => |opts| if (opts.list_models) {try lp.Agent.listModels(allocator, opts);return std.process.cleanExit(lp.io);diff --git a/src/telemetry/lightpanda.zig b/src/telemetry/lightpanda.zigindex 85cd7fe22..eaa35ede9 100644--- a/src/telemetry/lightpanda.zig+++ b/src/telemetry/lightpanda.zig@@ -89,6 +89,7 @@ pub fn init(self: *LightPanda, app: *App, iid: ?[36]u8) !void {.mcp => "M",.version => "V",.help => "H",+ .completion => "C",},};}