main.zig

18.1 KB · raw

1// main.zig — entry point, arg parsing, dispatch, error handler2// THE ONLY FILE that creates the Io.Writer and passes it to output.init().3const std = @import("std");4const Io = std.Io;56const types = @import("types.zig");7const errors = @import("errors.zig");8const config = @import("config.zig");9const commands = @import("commands.zig");10const output = @import("output.zig");11const man = @import("man.zig");1213const Args = struct {14    command: []const u8 = "",15    sub: []const u8 = "",16    rest: []const []const u8 = &.{},17    passthrough: []const []const u8 = &.{}, // unrecognized flags (e.g. --refresh), forwarded to the wrapped nix command18    machine: ?[]const u8 = null,19    version: bool = false,20    dry: bool = false,21    check: bool = false,22    no_apply: bool = false,23    all: bool = false,24    json: bool = false,25    last: u32 = 50,26    user: bool = false,27};2829pub fn main(startup: std.process.Init) !void {30    const arena = startup.arena.allocator();31    const gpa = startup.gpa;32    const io = startup.io;3334    // Command allocations go through an arena freed when main returns. nina is a35    // one-shot CLI that exits after one command, and std.process.exit skips36    // defers, so per-allocation frees were easy to miss — the arena guarantees37    // everything is released in one shot, eliminating exit-time leak reports.38    var cmd_arena = std.heap.ArenaAllocator.init(gpa);39    defer cmd_arena.deinit();40    const ca = cmd_arena.allocator();4142    // Initialize output module with buffered stdout writer. Streaming (not the43    // default positional) mode: stdout may be a terminal, pipe, or a redirected44    // regular file. Positional mode pwrites from offset 0 and ignores the fd's45    // inherited offset, which corrupts `{ echo h; nina x; } > f` and `>>` append46    // by overwriting from the start. Streaming honors the current file offset.47    var stdout_buf: [16384]u8 = undefined;48    var stdout_fw: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);49    output.init(&stdout_fw.interface, io, startup.environ_map, true);50    defer output.flush();5152    const argv = try startup.minimal.args.toSlice(arena);53    const args = try parseArgs(arena, argv);5455    if (args.version) {56        output.version();57        return;58    }5960    // Help and hello work without config61    if (args.command.len == 0 or std.mem.eql(u8, args.command, "help")) {62        output.help();63        return;64    }6566    // man works without a config — it's pure docs, no machine context needed.67    if (std.mem.eql(u8, args.command, "man")) {68        const topic: []const u8 = if (args.rest.len > 0) args.rest[0] else "";69        man.run(io, topic) catch {};70        return;71    }7273    // setup and update run before config so they work without ~/.nina.conf74    if (std.mem.eql(u8, args.command, "setup") or std.mem.eql(u8, args.command, "update")) {75        const dummy_machine: types.Machine = .{ .name = "local", .local = true };76        const dummy_cfg: types.NinaConfig = .{};77        const pre_ctx = commands.Ctx{78            .gpa = ca,79            .io = io,80            .environ = startup.environ_map,81            .machine = dummy_machine,82            .cfg = dummy_cfg,83            .args = args.rest,84            .passthrough = args.passthrough,85            .sub = args.sub,86            .dry = args.dry,87            .check = args.check,88            .no_apply = args.no_apply,89            .all = args.all,90            .last = args.last,91            .json = args.json,92            .user = args.user,93        };94        if (std.mem.eql(u8, args.command, "setup")) {95            commands.setup(ca, io, startup.environ_map) catch |err| {96                const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);97                const detail = errors.error_info.getDetail();98                const suggestion = errors.error_info.getSuggestion();99                output.printError(msg, detail, suggestion);100                output.flush();101                std.process.exit(1);102            };103        } else {104            dispatch(pre_ctx, args.command) catch |err| {105                reportError(err, ca);106                output.flush();107                std.process.exit(1);108            };109        }110        return;111    }112113    // Load config and resolve machine. On first run with no config file, offer114    // the setup wizard when stdout is a TTY; skip silently in piped/scripted mode.115    const cfg = cfg_blk: {116        if (config.load(arena, io, startup.environ_map)) |c| {117            break :cfg_blk c;118        } else |err| {119            if (err == error.ConfigNotFound and (std.Io.File.stdout().isTty(io) catch false)) {120                commands.firstRunWizard(ca, io, startup.environ_map) catch |wizard_err| {121                    const msg = errors.error_info.getMessage() orelse errors.staticMessage(wizard_err);122                    const detail = errors.error_info.getDetail();123                    const suggestion = errors.error_info.getSuggestion();124                    output.printError(msg, detail, suggestion);125                    output.flush();126                    std.process.exit(1);127                };128                errors.error_info.reset();129                break :cfg_blk config.load(arena, io, startup.environ_map) catch |err2| {130                    const msg = errors.error_info.getMessage() orelse errors.staticMessage(err2);131                    const detail = errors.error_info.getDetail();132                    const suggestion = errors.error_info.getSuggestion();133                    output.printError(msg, detail, suggestion);134                    output.flush();135                    std.process.exit(1);136                };137            }138            const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);139            const detail = errors.error_info.getDetail();140            const suggestion = errors.error_info.getSuggestion();141            output.printError(msg, detail, suggestion);142            output.flush();143            std.process.exit(1);144        }145    };146147    output.setTeach(cfg.teach);148149    const machine = config.resolveMachine(&cfg, args.machine) catch |err| {150        const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);151        const detail = errors.error_info.getDetail();152        const suggestion = errors.error_info.getSuggestion();153        output.printError(msg, detail, suggestion);154        output.flush();155        std.process.exit(1);156    };157158    const ctx = commands.Ctx{159        .gpa = ca,160        .io = io,161        .environ = startup.environ_map,162        .machine = machine,163        .cfg = cfg,164        .args = args.rest,165        .passthrough = args.passthrough,166        .sub = args.sub,167        .dry = args.dry,168        .check = args.check,169        .no_apply = args.no_apply,170        .all = args.all,171        .last = args.last,172        .json = args.json,173        .user = args.user,174    };175176    dispatch(ctx, args.command) catch |err| {177        reportError(err, ca);178        output.flush();179        std.process.exit(1);180    };181}182183// Network/ssh/search failures are the machine's fault, not the user's — surface184// them with the sad kaomoji. BuildFailed is routed through the 3-layer185// translation pipeline. Everything else uses a plain error line.186fn reportError(err: anyerror, allocator: std.mem.Allocator) void {187    switch (err) {188        // abort message already printed by output.aborted() — just exit non-zero189        error.HookAborted => {},190        error.BuildFailed => {191            const stderr = errors.getBuildStderr();192            const translated = errors.translateError(allocator, stderr);193            output.buildError(translated);194        },195        error.NetworkError, error.SshFailed, error.SearchFailed => {196            const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);197            const detail = errors.error_info.getDetail();198            const suggestion = errors.error_info.getSuggestion();199            output.printSystemError(msg, detail, suggestion);200        },201        else => {202            const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);203            const detail = errors.error_info.getDetail();204            const suggestion = errors.error_info.getSuggestion();205            output.printError(msg, detail, suggestion);206        },207    }208}209210fn dispatch(ctx: commands.Ctx, cmd: []const u8) !void {211    if (std.mem.eql(u8, cmd, "apply")) return commands.apply(ctx);212    if (std.mem.eql(u8, cmd, "check")) return commands.check(ctx);213    if (std.mem.eql(u8, cmd, "back")) return commands.back(ctx);214    if (std.mem.eql(u8, cmd, "go")) return commands.go(ctx);215    if (std.mem.eql(u8, cmd, "history")) return commands.history(ctx);216    if (std.mem.eql(u8, cmd, "gen")) return commands.genCmd(ctx);217    if (std.mem.eql(u8, cmd, "clean")) return commands.clean(ctx);218    if (std.mem.eql(u8, cmd, "status")) return commands.statusCmd(ctx);219    if (std.mem.eql(u8, cmd, "diff")) return commands.diff(ctx);220    if (std.mem.eql(u8, cmd, "doctor")) return commands.doctor(ctx);221    if (std.mem.eql(u8, cmd, "mood")) return commands.mood(ctx);222    if (std.mem.eql(u8, cmd, "update")) return commands.update(ctx);223    if (std.mem.eql(u8, cmd, "upgrade")) return commands.upgrade(ctx);224    if (std.mem.eql(u8, cmd, "log")) return commands.log(ctx);225    if (std.mem.eql(u8, cmd, "edit")) return commands.edit(ctx);226    if (std.mem.eql(u8, cmd, "fmt")) return commands.fmt(ctx);227    if (std.mem.eql(u8, cmd, "repl")) return commands.repl(ctx);228    if (std.mem.eql(u8, cmd, "develop")) return commands.develop(ctx);229    if (std.mem.eql(u8, cmd, "info")) return commands.info(ctx);230    if (std.mem.eql(u8, cmd, "boot")) return commands.boot(ctx);231    if (std.mem.eql(u8, cmd, "search")) return commands.searchCmd(ctx);232    if (std.mem.eql(u8, cmd, "option")) return commands.optionCmd(ctx);233    if (std.mem.eql(u8, cmd, "install")) return commands.install(ctx);234    if (std.mem.eql(u8, cmd, "remove")) return commands.remove(ctx);235    if (std.mem.eql(u8, cmd, "list")) return commands.list(ctx);236    if (std.mem.eql(u8, cmd, "try")) return commands.tryCmd(ctx);237    if (std.mem.eql(u8, cmd, "service")) return commands.service(ctx);238    if (std.mem.eql(u8, cmd, "flake")) return commands.flake(ctx);239    if (std.mem.eql(u8, cmd, "store")) return commands.store(ctx);240    if (std.mem.eql(u8, cmd, "channel")) return commands.channel(ctx);241    if (std.mem.eql(u8, cmd, "profile")) return commands.profile(ctx);242    if (std.mem.eql(u8, cmd, "pkg")) return commands.pkg(ctx);243    if (std.mem.eql(u8, cmd, "why")) return commands.why(ctx);244    if (std.mem.eql(u8, cmd, "pin")) return commands.pin(ctx);245    if (std.mem.eql(u8, cmd, "unpin")) return commands.unpin(ctx);246    if (std.mem.eql(u8, cmd, "hash")) return commands.hash(ctx);247    if (std.mem.eql(u8, cmd, "fetch")) return commands.fetch(ctx);248    if (std.mem.eql(u8, cmd, "build")) return commands.build(ctx);249    if (std.mem.eql(u8, cmd, "run")) return commands.runCmd(ctx);250    if (std.mem.eql(u8, cmd, "home")) return commands.home(ctx);251    if (std.mem.eql(u8, cmd, "goodbye")) return commands.goodbye(ctx);252    if (std.mem.eql(u8, cmd, "hello")) return commands.hello(ctx);253    if (std.mem.eql(u8, cmd, "help")) { output.help(); return; }254255    errors.error_info.setMessage("unknown command: {s}", .{cmd});256    errors.error_info.setSuggestion("nina help", .{});257    return error.Internal;258}259260fn parseArgs(arena: std.mem.Allocator, argv: []const [:0]const u8) !Args {261    var result = Args{};262    var rest: std.ArrayList([]const u8) = .empty;263    var passthrough: std.ArrayList([]const u8) = .empty;264    var i: usize = 1; // skip program name265266    // First positional = command267    if (i < argv.len and argv[i][0] != '-') {268        result.command = argv[i];269        i += 1;270    }271272    // Second positional (if not a flag) = subcommand for multi-word commands273    if (i < argv.len and argv[i][0] != '-') {274        const multi_word = isMultiWord(result.command);275        if (multi_word) {276            result.sub = argv[i];277            i += 1;278        }279    }280281    while (i < argv.len) : (i += 1) {282        const a = argv[i];283        if (std.mem.eql(u8, a, "--on") or std.mem.eql(u8, a, "-on")) {284            i += 1;285            if (i < argv.len) result.machine = argv[i];286        } else if (std.mem.eql(u8, a, "--dry")) {287            result.dry = true;288        } else if (std.mem.eql(u8, a, "--check")) {289            result.check = true;290        } else if (std.mem.eql(u8, a, "--version")) {291            result.version = true;292        } else if (std.mem.eql(u8, a, "--no-apply")) {293            result.no_apply = true;294        } else if (std.mem.eql(u8, a, "--all")) {295            result.all = true;296        } else if (std.mem.eql(u8, a, "--user")) {297            result.user = true;298        } else if (std.mem.eql(u8, a, "--json")) {299            result.json = true;300        } else if (std.mem.eql(u8, a, "--last")) {301            i += 1;302            if (i < argv.len) result.last = std.fmt.parseInt(u32, argv[i], 10) catch 50;303        } else if (std.mem.eql(u8, a, "-f")) {304            // -f flag for service logs follow305            try rest.append(arena, "-f");306        } else if (std.mem.eql(u8, a, "--switch")) {307            // --switch flag for `home init` (activate after init)308            try rest.append(arena, "--switch");309        } else if (std.mem.eql(u8, a, "--dir")) {310            // --dir flag for `nina edit` (open the config directory)311            try rest.append(arena, "--dir");312        } else if (a.len > 0 and a[0] != '-') {313            try rest.append(arena, a);314        } else {315            // Unrecognized flag (e.g. --refresh) — forwarded verbatim to whatever316            // nix command the subcommand wraps, instead of being dropped silently.317            try passthrough.append(arena, a);318        }319    }320321    result.rest = try rest.toOwnedSlice(arena);322    result.passthrough = try passthrough.toOwnedSlice(arena);323    return result;324}325326fn isMultiWord(cmd: []const u8) bool {327    const multi = [_][]const u8{ "service", "flake", "store", "channel", "profile", "pkg", "gen", "develop", "edit", "home" };328    for (multi) |m| {329        if (std.mem.eql(u8, cmd, m)) return true;330    }331    return false;332}333334test "parse args basic" {335    const gpa = std.testing.allocator;336    const argv = [_][:0]const u8{ "nina", "apply", "--dry" };337    const args = try parseArgs(gpa, &argv);338    defer gpa.free(args.rest);339    try std.testing.expectEqualStrings("apply", args.command);340    try std.testing.expect(args.dry);341}342343test "parse args with machine" {344    const gpa = std.testing.allocator;345    const argv = [_][:0]const u8{ "nina", "status", "--on", "build-server" };346    const args = try parseArgs(gpa, &argv);347    defer gpa.free(args.rest);348    try std.testing.expectEqualStrings("status", args.command);349    try std.testing.expectEqualStrings("build-server", args.machine.?);350}351352test "parse args forwards unrecognized flags" {353    const gpa = std.testing.allocator;354    const argv = [_][:0]const u8{ "nina", "flake", "update", "--refresh" };355    const args = try parseArgs(gpa, &argv);356    defer gpa.free(args.rest);357    defer gpa.free(args.passthrough);358    try std.testing.expectEqualStrings("flake", args.command);359    try std.testing.expectEqualStrings("update", args.sub);360    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);361    try std.testing.expectEqualStrings("--refresh", args.passthrough[0]);362}363364test "parse args forwards apply --show-trace" {365    const gpa = std.testing.allocator;366    const argv = [_][:0]const u8{ "nina", "apply", "--show-trace" };367    const args = try parseArgs(gpa, &argv);368    defer gpa.free(args.rest);369    defer gpa.free(args.passthrough);370    try std.testing.expectEqualStrings("apply", args.command);371    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);372    try std.testing.expectEqualStrings("--show-trace", args.passthrough[0]);373}374375test "parse args forwards check --show-trace" {376    const gpa = std.testing.allocator;377    const argv = [_][:0]const u8{ "nina", "check", "--show-trace" };378    const args = try parseArgs(gpa, &argv);379    defer gpa.free(args.rest);380    defer gpa.free(args.passthrough);381    try std.testing.expectEqualStrings("check", args.command);382    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);383    try std.testing.expectEqualStrings("--show-trace", args.passthrough[0]);384}385386test "parse args forwards flake check --all-systems" {387    const gpa = std.testing.allocator;388    const argv = [_][:0]const u8{ "nina", "flake", "check", "--all-systems" };389    const args = try parseArgs(gpa, &argv);390    defer gpa.free(args.rest);391    defer gpa.free(args.passthrough);392    try std.testing.expectEqualStrings("flake", args.command);393    try std.testing.expectEqualStrings("check", args.sub);394    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);395    try std.testing.expectEqualStrings("--all-systems", args.passthrough[0]);396}397398test "parse args forwards build --print-build-logs" {399    const gpa = std.testing.allocator;400    const argv = [_][:0]const u8{ "nina", "build", "--print-build-logs" };401    const args = try parseArgs(gpa, &argv);402    defer gpa.free(args.rest);403    defer gpa.free(args.passthrough);404    try std.testing.expectEqualStrings("build", args.command);405    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);406    try std.testing.expectEqualStrings("--print-build-logs", args.passthrough[0]);407}408409test "parse args forwards develop --show-trace" {410    const gpa = std.testing.allocator;411    const argv = [_][:0]const u8{ "nina", "develop", "--show-trace" };412    const args = try parseArgs(gpa, &argv);413    defer gpa.free(args.rest);414    defer gpa.free(args.passthrough);415    try std.testing.expectEqualStrings("develop", args.command);416    try std.testing.expectEqual(@as(usize, 1), args.passthrough.len);417    try std.testing.expectEqualStrings("--show-trace", args.passthrough[0]);418}419420test "parse subcommand" {421    const gpa = std.testing.allocator;422    const argv = [_][:0]const u8{ "nina", "service", "list" };423    const args = try parseArgs(gpa, &argv);424    defer gpa.free(args.rest);425    try std.testing.expectEqualStrings("service", args.command);426    try std.testing.expectEqualStrings("list", args.sub);427}428429test "parse version flag" {430    const gpa = std.testing.allocator;431    const argv = [_][:0]const u8{ "nina", "--version" };432    const args = try parseArgs(gpa, &argv);433    defer gpa.free(args.rest);434    try std.testing.expect(args.version);435}