main.zig

11.6 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");1112const Args = struct {13    command: []const u8 = "",14    sub: []const u8 = "",15    rest: []const []const u8 = &.{},16    machine: ?[]const u8 = null,17    version: bool = false,18    dry: bool = false,19    check: bool = false,20    no_apply: bool = false,21    all: bool = false,22    json: bool = false,23    last: u32 = 50,24};2526pub fn main(startup: std.process.Init) !void {27    const arena = startup.arena.allocator();28    const gpa = startup.gpa;29    const io = startup.io;3031    // Command allocations go through an arena freed when main returns. nina is a32    // one-shot CLI that exits after one command, and std.process.exit skips33    // defers, so per-allocation frees were easy to miss — the arena guarantees34    // everything is released in one shot, eliminating exit-time leak reports.35    var cmd_arena = std.heap.ArenaAllocator.init(gpa);36    defer cmd_arena.deinit();37    const ca = cmd_arena.allocator();3839    // Initialize output module with buffered stdout writer. Streaming (not the40    // default positional) mode: stdout may be a terminal, pipe, or a redirected41    // regular file. Positional mode pwrites from offset 0 and ignores the fd's42    // inherited offset, which corrupts `{ echo h; nina x; } > f` and `>>` append43    // by overwriting from the start. Streaming honors the current file offset.44    var stdout_buf: [16384]u8 = undefined;45    var stdout_fw: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);46    output.init(&stdout_fw.interface, io, startup.environ_map, true);47    defer output.flush();4849    const argv = try startup.minimal.args.toSlice(arena);50    const args = try parseArgs(arena, argv);5152    if (args.version) {53        output.version();54        return;55    }5657    // Help and hello work without config58    if (args.command.len == 0 or std.mem.eql(u8, args.command, "help")) {59        output.help();60        return;61    }6263    // setup and update run before config so they work without ~/.nina.conf64    if (std.mem.eql(u8, args.command, "setup") or std.mem.eql(u8, args.command, "update")) {65        const dummy_machine: types.Machine = .{ .name = "local", .local = true };66        const dummy_cfg: types.NinaConfig = .{};67        const pre_ctx = commands.Ctx{68            .gpa = ca,69            .io = io,70            .environ = startup.environ_map,71            .machine = dummy_machine,72            .cfg = dummy_cfg,73            .args = args.rest,74            .sub = args.sub,75            .dry = args.dry,76            .check = args.check,77            .no_apply = args.no_apply,78            .all = args.all,79            .last = args.last,80            .json = args.json,81        };82        if (std.mem.eql(u8, args.command, "setup")) {83            commands.setup(ca, io, startup.environ_map) catch |err| {84                const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);85                const detail = errors.error_info.getDetail();86                const suggestion = errors.error_info.getSuggestion();87                output.printError(msg, detail, suggestion);88                output.flush();89                std.process.exit(1);90            };91        } else {92            dispatch(pre_ctx, args.command) catch |err| {93                const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);94                const detail = errors.error_info.getDetail();95                const suggestion = errors.error_info.getSuggestion();96                output.printError(msg, detail, suggestion);97                output.flush();98                std.process.exit(1);99            };100        }101        return;102    }103104    // Load config and resolve machine105    const cfg = config.load(arena, io, startup.environ_map) catch |err| {106        const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);107        const detail = errors.error_info.getDetail();108        const suggestion = errors.error_info.getSuggestion();109        output.printError(msg, detail, suggestion);110        output.flush();111        std.process.exit(1);112    };113114    output.setTeach(cfg.teach);115116    const machine = config.resolveMachine(&cfg, args.machine) catch |err| {117        const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);118        const detail = errors.error_info.getDetail();119        const suggestion = errors.error_info.getSuggestion();120        output.printError(msg, detail, suggestion);121        output.flush();122        std.process.exit(1);123    };124125    const ctx = commands.Ctx{126        .gpa = ca,127        .io = io,128        .environ = startup.environ_map,129        .machine = machine,130        .cfg = cfg,131        .args = args.rest,132        .sub = args.sub,133        .dry = args.dry,134        .check = args.check,135        .no_apply = args.no_apply,136        .all = args.all,137        .last = args.last,138        .json = args.json,139    };140141    dispatch(ctx, args.command) catch |err| {142        const msg = errors.error_info.getMessage() orelse errors.staticMessage(err);143        const detail = errors.error_info.getDetail();144        const suggestion = errors.error_info.getSuggestion();145        output.printError(msg, detail, suggestion);146        output.flush();147        std.process.exit(1);148    };149}150151fn dispatch(ctx: commands.Ctx, cmd: []const u8) !void {152    if (std.mem.eql(u8, cmd, "apply")) return commands.apply(ctx);153    if (std.mem.eql(u8, cmd, "check")) return commands.check(ctx);154    if (std.mem.eql(u8, cmd, "back")) return commands.back(ctx);155    if (std.mem.eql(u8, cmd, "go")) return commands.go(ctx);156    if (std.mem.eql(u8, cmd, "history")) return commands.history(ctx);157    if (std.mem.eql(u8, cmd, "gen")) return commands.genCmd(ctx);158    if (std.mem.eql(u8, cmd, "clean")) return commands.clean(ctx);159    if (std.mem.eql(u8, cmd, "status")) return commands.statusCmd(ctx);160    if (std.mem.eql(u8, cmd, "diff")) return commands.diff(ctx);161    if (std.mem.eql(u8, cmd, "doctor")) return commands.doctor(ctx);162    if (std.mem.eql(u8, cmd, "mood")) return commands.mood(ctx);163    if (std.mem.eql(u8, cmd, "update")) return commands.update(ctx);164    if (std.mem.eql(u8, cmd, "upgrade")) return commands.upgrade(ctx);165    if (std.mem.eql(u8, cmd, "log")) return commands.log(ctx);166    if (std.mem.eql(u8, cmd, "edit")) return commands.edit(ctx);167    if (std.mem.eql(u8, cmd, "fmt")) return commands.fmt(ctx);168    if (std.mem.eql(u8, cmd, "repl")) return commands.repl(ctx);169    if (std.mem.eql(u8, cmd, "develop")) return commands.develop(ctx);170    if (std.mem.eql(u8, cmd, "info")) return commands.info(ctx);171    if (std.mem.eql(u8, cmd, "boot")) return commands.boot(ctx);172    if (std.mem.eql(u8, cmd, "search")) return commands.searchCmd(ctx);173    if (std.mem.eql(u8, cmd, "option")) return commands.optionCmd(ctx);174    if (std.mem.eql(u8, cmd, "install")) return commands.install(ctx);175    if (std.mem.eql(u8, cmd, "remove")) return commands.remove(ctx);176    if (std.mem.eql(u8, cmd, "list")) return commands.list(ctx);177    if (std.mem.eql(u8, cmd, "try")) return commands.tryCmd(ctx);178    if (std.mem.eql(u8, cmd, "service")) return commands.service(ctx);179    if (std.mem.eql(u8, cmd, "flake")) return commands.flake(ctx);180    if (std.mem.eql(u8, cmd, "store")) return commands.store(ctx);181    if (std.mem.eql(u8, cmd, "channel")) return commands.channel(ctx);182    if (std.mem.eql(u8, cmd, "profile")) return commands.profile(ctx);183    if (std.mem.eql(u8, cmd, "pkg")) return commands.pkg(ctx);184    if (std.mem.eql(u8, cmd, "pin")) return commands.pin(ctx);185    if (std.mem.eql(u8, cmd, "unpin")) return commands.unpin(ctx);186    if (std.mem.eql(u8, cmd, "hash")) return commands.hash(ctx);187    if (std.mem.eql(u8, cmd, "fetch")) return commands.fetch(ctx);188    if (std.mem.eql(u8, cmd, "build")) return commands.build(ctx);189    if (std.mem.eql(u8, cmd, "run")) return commands.runCmd(ctx);190    if (std.mem.eql(u8, cmd, "goodbye")) return commands.goodbye(ctx);191    if (std.mem.eql(u8, cmd, "hello")) return commands.hello(ctx);192    if (std.mem.eql(u8, cmd, "help")) { output.help(); return; }193194    errors.error_info.setMessage("unknown command: {s}", .{cmd});195    errors.error_info.setSuggestion("nina help", .{});196    return error.Internal;197}198199fn parseArgs(arena: std.mem.Allocator, argv: []const [:0]const u8) !Args {200    var result = Args{};201    var rest: std.ArrayList([]const u8) = .empty;202    var i: usize = 1; // skip program name203204    // First positional = command205    if (i < argv.len and argv[i][0] != '-') {206        result.command = argv[i];207        i += 1;208    }209210    // Second positional (if not a flag) = subcommand for multi-word commands211    if (i < argv.len and argv[i][0] != '-') {212        const multi_word = isMultiWord(result.command);213        if (multi_word) {214            result.sub = argv[i];215            i += 1;216        }217    }218219    while (i < argv.len) : (i += 1) {220        const a = argv[i];221        if (std.mem.eql(u8, a, "--on") or std.mem.eql(u8, a, "-on")) {222            i += 1;223            if (i < argv.len) result.machine = argv[i];224        } else if (std.mem.eql(u8, a, "--dry")) {225            result.dry = true;226        } else if (std.mem.eql(u8, a, "--check")) {227            result.check = true;228        } else if (std.mem.eql(u8, a, "--version")) {229            result.version = true;230        } else if (std.mem.eql(u8, a, "--no-apply")) {231            result.no_apply = true;232        } else if (std.mem.eql(u8, a, "--all")) {233            result.all = true;234        } else if (std.mem.eql(u8, a, "--json")) {235            result.json = true;236        } else if (std.mem.eql(u8, a, "--last")) {237            i += 1;238            if (i < argv.len) result.last = std.fmt.parseInt(u32, argv[i], 10) catch 50;239        } else if (std.mem.eql(u8, a, "-f")) {240            // -f flag for service logs follow241            try rest.append(arena, "-f");242        } else if (a.len > 0 and a[0] != '-') {243            try rest.append(arena, a);244        }245        // Ignore unknown flags silently246    }247248    result.rest = try rest.toOwnedSlice(arena);249    return result;250}251252fn isMultiWord(cmd: []const u8) bool {253    const multi = [_][]const u8{ "service", "flake", "store", "channel", "profile", "pkg", "gen", "develop", "edit" };254    for (multi) |m| {255        if (std.mem.eql(u8, cmd, m)) return true;256    }257    return false;258}259260test "parse args basic" {261    const gpa = std.testing.allocator;262    const argv = [_][:0]const u8{ "nina", "apply", "--dry" };263    const args = try parseArgs(gpa, &argv);264    defer gpa.free(args.rest);265    try std.testing.expectEqualStrings("apply", args.command);266    try std.testing.expect(args.dry);267}268269test "parse args with machine" {270    const gpa = std.testing.allocator;271    const argv = [_][:0]const u8{ "nina", "status", "--on", "build-server" };272    const args = try parseArgs(gpa, &argv);273    defer gpa.free(args.rest);274    try std.testing.expectEqualStrings("status", args.command);275    try std.testing.expectEqualStrings("build-server", args.machine.?);276}277278test "parse subcommand" {279    const gpa = std.testing.allocator;280    const argv = [_][:0]const u8{ "nina", "service", "list" };281    const args = try parseArgs(gpa, &argv);282    defer gpa.free(args.rest);283    try std.testing.expectEqualStrings("service", args.command);284    try std.testing.expectEqualStrings("list", args.sub);285}286287test "parse version flag" {288    const gpa = std.testing.allocator;289    const argv = [_][:0]const u8{ "nina", "--version" };290    const args = try parseArgs(gpa, &argv);291    defer gpa.free(args.rest);292    try std.testing.expect(args.version);293}