config.zig

10.1 KB · raw

1const std = @import("std");2const types = @import("types.zig");3const errors = @import("errors.zig");4const exec = @import("exec.zig");5const output = @import("output.zig");67// Resolve the config file path: $XDG_CONFIG_HOME/nina/config, falling back to8// ~/.config/nina/config. nina historically stored ~/.nina.conf; that legacy9// location is auto-migrated to this path on load (see migrateLegacyConfig).10pub fn configPath(arena: std.mem.Allocator, environ: *const std.process.Environ.Map) ![]const u8 {11    if (environ.get("XDG_CONFIG_HOME")) |xdg| {12        if (xdg.len > 0) return std.fs.path.join(arena, &.{ xdg, "nina", "config" });13    }14    const home = environ.get("HOME") orelse {15        errors.error_info.setSuggestion("set HOME environment variable", .{});16        return error.ConfigNotFound;17    };18    return std.fs.path.join(arena, &.{ home, ".config", "nina", "config" });19}2021fn legacyPath(arena: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {22    const home = environ.get("HOME") orelse return null;23    return std.fmt.allocPrint(arena, "{s}/.nina.conf", .{home}) catch null;24}2526fn fileExists(io: std.Io, path: []const u8) bool {27    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;28    f.close(io);29    return true;30}3132// One-time migration of the legacy ~/.nina.conf to the XDG path. Runs only when33// the old file exists and the new one does not, so it's idempotent and a no-op34// for fresh installs. Best-effort: any failure leaves the legacy file in place35// so the next load still finds it.36pub fn migrateLegacyConfig(arena: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) void {37    const new_path = configPath(arena, environ) catch return;38    if (fileExists(io, new_path)) return;39    const legacy = legacyPath(arena, environ) orelse return;40    const content = std.Io.Dir.readFileAlloc(.cwd(), io, legacy, arena, .unlimited) catch return;4142    if (std.fs.path.dirname(new_path)) |dir| exec.ensureDir(arena, io, dir);43    const f = std.Io.Dir.createFile(.cwd(), io, new_path, .{}) catch return;44    f.writePositionalAll(io, content, 0) catch {45        f.close(io);46        return;47    };48    f.close(io);49    std.Io.Dir.deleteFile(.cwd(), io, legacy) catch {};50    output.configMigrated(homeShort(arena, new_path, environ));51}5253// Collapse a leading $HOME to ~ for display only. Returns the input unchanged on54// any mismatch or allocation failure.55fn homeShort(arena: std.mem.Allocator, path: []const u8, environ: *const std.process.Environ.Map) []const u8 {56    const home = environ.get("HOME") orelse return path;57    if (home.len == 0 or !std.mem.startsWith(u8, path, home)) return path;58    return std.fmt.allocPrint(arena, "~{s}", .{path[home.len..]}) catch path;59}6061pub fn load(arena: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !types.NinaConfig {62    migrateLegacyConfig(arena, io, environ);6364    const path = try configPath(arena, environ);65    const home = environ.get("HOME") orelse "";6667    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, arena, .unlimited) catch {68        errors.error_info.setSuggestion("run nina to set up", .{});69        return error.ConfigNotFound;70    };71    const cfg = try parse(arena, content, home);72    if (environ.contains("NINA_DEBUG")) debugDumpConfig(cfg);73    return cfg;74}7576fn parse(arena: std.mem.Allocator, input: []const u8, home: []const u8) !types.NinaConfig {77    var config = types.NinaConfig{};78    var machines: std.ArrayList(types.Machine) = .empty;79    var current: ?types.Machine = null;8081    var lines = std.mem.splitScalar(u8, input, '\n');82    while (lines.next()) |line| {83        const trimmed = std.mem.trim(u8, line, " \t\r");84        if (trimmed.len == 0 or trimmed[0] == '#') continue;8586        if (std.mem.eql(u8, trimmed, "[machine]")) {87            if (current) |m| try machines.append(arena, m);88            current = .{};89            continue;90        }9192        const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue;93        const key = std.mem.trim(u8, trimmed[0..eq], " \t");94        const val = std.mem.trim(u8, trimmed[eq + 1 ..], " \t");9596        if (current) |*m| {97            setMachineField(arena, m, key, val, home) catch {};98        } else {99            setConfigField(arena, &config, key, val) catch {};100        }101    }102103    if (current) |m| try machines.append(arena, m);104    config.machines = try machines.toOwnedSlice(arena);105    return config;106}107108fn setConfigField(arena: std.mem.Allocator, config: *types.NinaConfig, key: []const u8, val: []const u8) !void {109    if (std.mem.eql(u8, key, "editor")) {110        config.editor = try arena.dupe(u8, val);111    } else if (std.mem.eql(u8, key, "generations")) {112        config.generations = std.fmt.parseInt(u32, val, 10) catch 5;113    } else if (std.mem.eql(u8, key, "confirm")) {114        config.confirm = parseBool(val, true);115    } else if (std.mem.eql(u8, key, "teach")) {116        config.teach = parseBool(val, false);117    } else if (std.mem.eql(u8, key, "color")) {118        config.color = parseBool(val, true);119    }120}121122fn setMachineField(arena: std.mem.Allocator, m: *types.Machine, key: []const u8, val: []const u8, home: []const u8) !void {123    if (std.mem.eql(u8, key, "name")) {124        m.name = try arena.dupe(u8, val);125    } else if (std.mem.eql(u8, key, "config")) {126        m.config_path = try arena.dupe(u8, val);127    } else if (std.mem.eql(u8, key, "local")) {128        m.local = parseBool(val, true);129    } else if (std.mem.eql(u8, key, "default")) {130        m.default = parseBool(val, false);131    } else if (std.mem.eql(u8, key, "host")) {132        m.host = try arena.dupe(u8, val);133        // A machine with a host is remote unless explicitly marked local. The134        // Machine struct defaults local=true, so without this a [machine] block135        // that only sets host/user/ssh_key would render as "local".136        m.local = false;137    } else if (std.mem.eql(u8, key, "user")) {138        m.user = try arena.dupe(u8, val);139    } else if (std.mem.eql(u8, key, "ssh_key")) {140        m.ssh_key = try expandHome(arena, val, home);141    }142}143144fn parseBool(val: []const u8, default: bool) bool {145    if (std.mem.eql(u8, val, "true") or std.mem.eql(u8, val, "yes") or std.mem.eql(u8, val, "y") or std.mem.eql(u8, val, "on") or std.mem.eql(u8, val, "1")) {146        return true;147    }148    if (std.mem.eql(u8, val, "false") or std.mem.eql(u8, val, "no") or std.mem.eql(u8, val, "n") or std.mem.eql(u8, val, "off") or std.mem.eql(u8, val, "0")) {149        return false;150    }151    return default;152}153154fn debugDumpConfig(cfg: types.NinaConfig) void {155    std.debug.print("NINA_DEBUG config\n", .{});156    std.debug.print("editor={s}\n", .{cfg.editor});157    std.debug.print("generations={d}\n", .{cfg.generations});158    std.debug.print("confirm={}\n", .{cfg.confirm});159    std.debug.print("teach={}\n", .{cfg.teach});160    std.debug.print("color={}\n", .{cfg.color});161    for (cfg.machines, 0..) |m, i| {162        std.debug.print("machine[{d}].name={s}\n", .{ i, m.name });163        std.debug.print("machine[{d}].config={s}\n", .{ i, m.config_path });164        std.debug.print("machine[{d}].local={}\n", .{ i, m.local });165        std.debug.print("machine[{d}].default={}\n", .{ i, m.default });166        if (m.host) |host| std.debug.print("machine[{d}].host={s}\n", .{ i, host });167        if (m.user) |user| std.debug.print("machine[{d}].user={s}\n", .{ i, user });168    }169}170171fn expandHome(arena: std.mem.Allocator, path: []const u8, home: []const u8) ![]const u8 {172    if (!std.mem.startsWith(u8, path, "~")) return arena.dupe(u8, path);173    return std.fmt.allocPrint(arena, "{s}{s}", .{ home, path[1..] });174}175176pub fn resolveMachine(config: *const types.NinaConfig, name: ?[]const u8) !types.Machine {177    if (name) |n| {178        for (config.machines) |m| {179            if (std.mem.eql(u8, m.name, n)) return m;180        }181        errors.error_info.setMessage("'{s}' is not in your config", .{n});182        errors.error_info.setSuggestion("check ~/.nina.conf", .{});183        return error.MachineNotFound;184    }185    for (config.machines) |m| {186        if (m.default) return m;187    }188    if (config.machines.len > 0) return config.machines[0];189    // No machines defined — return a default local machine190    return .{};191}192193test "parse basic config" {194    const input =195        \\editor = hx196        \\generations = 3197        \\confirm = false198        \\teach = true199        \\200        \\[machine]201        \\name = test-box202        \\local = true203        \\default = true204    ;205    const config = try parse(std.testing.allocator, input, "/home/test");206    defer std.testing.allocator.free(config.machines);207208    try std.testing.expectEqualStrings("hx", config.editor);209    try std.testing.expectEqual(@as(u32, 3), config.generations);210    try std.testing.expect(!config.confirm);211    try std.testing.expect(config.teach);212    try std.testing.expectEqual(@as(usize, 1), config.machines.len);213    try std.testing.expectEqualStrings("test-box", config.machines[0].name);214}215216test "parse alternate booleans" {217    const input =218        \\confirm = y219        \\teach = no220        \\color = 1221        \\222        \\[machine]223        \\name = test-box224        \\local = n225        \\default = on226    ;227    const config = try parse(std.testing.allocator, input, "/home/test");228    defer std.testing.allocator.free(config.machines);229230    try std.testing.expect(config.confirm);231    try std.testing.expect(!config.teach);232    try std.testing.expect(config.color);233    try std.testing.expect(!config.machines[0].local);234    try std.testing.expect(config.machines[0].default);235}236237test "resolve machine by name" {238    var machines = [_]types.Machine{239        .{ .name = "alpha", .default = true },240        .{ .name = "beta" },241    };242    const config = types.NinaConfig{ .machines = &machines };243    const m = try resolveMachine(&config, "beta");244    try std.testing.expectEqualStrings("beta", m.name);245}246247test "resolve default machine" {248    var machines = [_]types.Machine{249        .{ .name = "alpha", .default = true },250        .{ .name = "beta" },251    };252    const config = types.NinaConfig{ .machines = &machines };253    const m = try resolveMachine(&config, null);254    try std.testing.expectEqualStrings("alpha", m.name);255}