api.zig

16.2 KB · raw

1// api.zig — nix data access: search, eval, options2// No HTTP. No curl. nix is on PATH by definition on NixOS.3const std = @import("std");4const types = @import("types.zig");5const errors = @import("errors.zig");6const output = @import("output.zig");78// Pin the nixpkgs registry once so `nix search nixpkgs` resolves locally instead9// of refetching github on every query. Gated by a ~/.nina-registry-pinned flag:10// absent -> pin + announce + create the flag; present -> no-op, silent. Failure11// to pin is non-fatal — search still runs (just slower), and the flag is left12// absent so a later run retries.13pub fn ensureRegistryPinned(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) void {14    const home = environ.get("HOME") orelse return;15    const flag_path = std.fmt.allocPrint(gpa, "{s}/.nina-registry-pinned", .{home}) catch return;16    defer gpa.free(flag_path);1718    if (std.Io.Dir.openFile(.cwd(), io, flag_path, .{})) |f| {19        f.close(io);20        return; // already pinned21    } else |_| {}2223    output.pinningRegistry();2425    const r = std.process.run(gpa, io, .{26        .argv = &.{ "nix", "registry", "pin", "nixpkgs" },27    }) catch return;28    defer gpa.free(r.stdout);29    defer gpa.free(r.stderr);30    switch (r.term) {31        .exited => |code| if (code != 0) return,32        else => return,33    }3435    const file = std.Io.Dir.createFile(.cwd(), io, flag_path, .{}) catch return;36    file.close(io);37}3839pub fn searchPackages(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, query: []const u8) ![]types.NixPackage {40    const result = std.process.run(gpa, io, .{41        .argv = &.{ "nix", "search", "nixpkgs", query, "--json", "--no-update-lock-file" },42    }) catch {43        errors.error_info.setSuggestion("run nix-channel --update and try again", .{});44        return error.SearchFailed;45    };46    defer gpa.free(result.stderr);47    defer gpa.free(result.stdout);4849    switch (result.term) {50        .exited => |code| if (code != 0) {51            // nix evaluates nixpkgs.legacyPackages during search and rejects unfree52            // packages even when the user has allowUnfree set system-wide. Retry53            // with NIXPKGS_ALLOW_UNFREE=1 so the package appears in results, and54            // tag it so the install step can pass the same override.55            if (isSearchUnfreeError(result.stderr)) {56                return searchPackagesUnfree(gpa, io, environ, query);57            }58            errors.error_info.setSuggestion("run nix-channel --update and try again", .{});59            return error.SearchFailed;60        },61        else => return error.SearchFailed,62    }6364    return parseSearchJson(gpa, result.stdout, false);65}6667fn isSearchUnfreeError(stderr: []const u8) bool {68    return std.mem.indexOf(u8, stderr, "requires unfree license") != null or69        std.mem.indexOf(u8, stderr, "has an unfree license") != null;70}7172fn searchPackagesUnfree(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, query: []const u8) ![]types.NixPackage {73    var env = try environ.clone(gpa);74    defer env.deinit();75    try env.put("NIXPKGS_ALLOW_UNFREE", "1");7677    const result = std.process.run(gpa, io, .{78        // --impure allows builtins.getEnv in nixpkgs's unfree check to read79        // NIXPKGS_ALLOW_UNFREE from the environment; pure flake eval ignores it.80        .argv = &.{ "nix", "search", "nixpkgs", query, "--json", "--no-update-lock-file", "--impure" },81        .environ_map = &env,82    }) catch {83        errors.error_info.setSuggestion("run nix-channel --update and try again", .{});84        return error.SearchFailed;85    };86    defer gpa.free(result.stderr);87    defer gpa.free(result.stdout);8889    switch (result.term) {90        .exited => |code| if (code != 0) {91            errors.error_info.setSuggestion("run nix-channel --update and try again", .{});92            return error.SearchFailed;93        },94        else => return error.SearchFailed,95    }9697    return parseSearchJson(gpa, result.stdout, true);98}99100fn parseSearchJson(gpa: std.mem.Allocator, json_str: []const u8, unfree: bool) ![]types.NixPackage {101    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.SearchFailed;102    defer parsed.deinit();103104    if (parsed.value != .object) return error.SearchFailed;105106    var packages: std.ArrayList(types.NixPackage) = .empty;107    var it = parsed.value.object.iterator();108    while (it.next()) |entry| {109        const key = entry.key_ptr.*;110        const val = entry.value_ptr.*;111        if (val != .object) continue;112113        // Key format: "legacyPackages.x86_64-linux.firefox"114        const last_dot = std.mem.lastIndexOfScalar(u8, key, '.') orelse continue;115        const attr = key[last_dot + 1 ..];116117        const pname = if (val.object.get("pname")) |v|118            if (v == .string) v.string else attr119        else120            attr;121122        const version = if (val.object.get("version")) |v|123            if (v == .string) v.string else ""124        else125            "";126127        const description = if (val.object.get("description")) |v|128            if (v == .string) v.string else ""129        else130            "";131132        try packages.append(gpa, .{133            .attr = try gpa.dupe(u8, attr),134            .pname = try gpa.dupe(u8, pname),135            .version = try gpa.dupe(u8, version),136            .description = try gpa.dupe(u8, description),137            .unfree = unfree,138        });139    }140141    return packages.toOwnedSlice(gpa);142}143144pub fn getLicense(gpa: std.mem.Allocator, io: std.Io, attr: []const u8) ?[]const u8 {145    const expr = std.fmt.allocPrint(gpa, "nixpkgs#{s}.meta.license.shortName", .{attr}) catch return null;146    defer gpa.free(expr);147148    const result = std.process.run(gpa, io, .{149        .argv = &.{ "nix", "eval", "--raw", expr },150    }) catch return null;151    defer gpa.free(result.stderr);152153    switch (result.term) {154        .exited => |code| if (code != 0) {155            gpa.free(result.stdout);156            return null;157        },158        else => {159            gpa.free(result.stdout);160            return null;161        },162    }163164    const license = std.mem.trim(u8, result.stdout, " \t\n\r");165    if (license.len == 0) {166        gpa.free(result.stdout);167        return null;168    }169    return license;170}171172pub const PkgMeta = struct {173    homepage: []const u8 = "",174    license: []const u8 = "",175};176177// Evaluate a package's meta for the expanded search detail pane. One178// `nix eval --json .meta` call; returns null if the package can't be evaluated179// (broken, renamed, etc.). Returned strings are duped into `arena`.180pub fn packageMeta(arena: std.mem.Allocator, io: std.Io, attr: []const u8) ?PkgMeta {181    const ref = std.fmt.allocPrint(arena, "nixpkgs#{s}.meta", .{attr}) catch return null;182    const result = std.process.run(arena, io, .{183        .argv = &.{ "nix", "eval", "--json", ref },184    }) catch return null;185    switch (result.term) {186        .exited => |code| if (code != 0) return null,187        else => return null,188    }189    const parsed = std.json.parseFromSlice(std.json.Value, arena, result.stdout, .{}) catch return null;190    defer parsed.deinit();191    if (parsed.value != .object) return null;192    const o = parsed.value.object;193    return .{194        .homepage = jsonFirstString(arena, o.get("homepage")),195        .license = licenseStr(arena, o.get("license")),196    };197}198199// homepage is usually a string but occasionally a list — take the first string.200fn jsonFirstString(arena: std.mem.Allocator, v: ?std.json.Value) []const u8 {201    const val = v orelse return "";202    switch (val) {203        .string => |s| return arena.dupe(u8, s) catch "",204        .array => |arr| {205            if (arr.items.len > 0 and arr.items[0] == .string) return arena.dupe(u8, arr.items[0].string) catch "";206            return "";207        },208        else => return "",209    }210}211212// license may be a single attrset, a list of attrsets, or a bare string. Join the213// fullName (or shortName) fields into one readable line. Result is duped into arena.214fn licenseStr(arena: std.mem.Allocator, v: ?std.json.Value) []const u8 {215    const val = v orelse return "";216    switch (val) {217        .string => |s| return arena.dupe(u8, s) catch "",218        .object => |obj| return arena.dupe(u8, licenseName(obj)) catch "",219        .array => |arr| {220            var buf: std.ArrayList(u8) = .empty;221            for (arr.items) |item| {222                if (item != .object) continue;223                const name = licenseName(item.object);224                if (name.len == 0) continue;225                if (buf.items.len > 0) buf.appendSlice(arena, ", ") catch {};226                buf.appendSlice(arena, name) catch {};227            }228            return buf.toOwnedSlice(arena) catch "";229        },230        else => return "",231    }232}233234// Returns a slice into the parsed JSON arena (caller dupes before that frees).235fn licenseName(obj: std.json.ObjectMap) []const u8 {236    if (obj.get("fullName")) |n| {237        if (n == .string) return n.string;238    }239    if (obj.get("shortName")) |n| {240        if (n == .string) return n.string;241    }242    return "";243}244245// nix eval takes exactly one installable/expression and its result must be246// JSON-serializable, so (unlike searchPackages) this can't point straight at a247// flake attribute: lib.optionAttrSetToDocList is a function, not a value, and248// nixpkgs#nixosModules isn't an output path nix eval can resolve at all. This249// builds a minimal NixOS system from an empty module list and feeds its250// accumulated options tree to optionAttrSetToDocList ourselves — the same251// technique nixos-option and the NixOS manual generator use. --impure is252// required for builtins.getFlake on the bare registry name and for253// builtins.currentSystem.254//255// NOTE: not exercised against real nix (none available on this host/dev256// machine); verified only via the fixture-driven parsing test below against257// hand-written JSON shaped like optionAttrSetToDocList's documented output.258// Needs a real-host / VM run before this is considered fully resolved.259const OPTIONS_DOC_LIST_EXPR =260    \\let261    \\  flake = builtins.getFlake "nixpkgs";262    \\  eval = flake.lib.nixosSystem {263    \\    system = builtins.currentSystem;264    \\    modules = [ { } ];265    \\  };266    \\in267    \\  flake.lib.optionAttrSetToDocList eval.options268;269270pub fn searchOptions(gpa: std.mem.Allocator, io: std.Io, query: []const u8) ![]NixOption {271    const result = std.process.run(gpa, io, .{272        .argv = &.{ "nix", "eval", "--json", "--impure", "--expr", OPTIONS_DOC_LIST_EXPR },273    }) catch return error.SearchFailed;274    defer gpa.free(result.stderr);275    defer gpa.free(result.stdout);276277    switch (result.term) {278        .exited => |code| if (code != 0) return error.SearchFailed,279        else => return error.SearchFailed,280    }281282    return filterOptions(gpa, result.stdout, query);283}284285pub const NixOption = struct {286    name: []const u8,287    type_str: []const u8,288    default: ?[]const u8,289    description: []const u8,290};291292// optionAttrSetToDocList's "default" field is a plain string on older293// nixpkgs, or a { _type = "literalExpression"; text = "..."; } wrapper on294// nixos-render-docs era nixpkgs. Handle both; anything else (e.g. a295// submodule's structured default) renders as "no default" rather than296// guessing at a representation.297fn optionDefaultText(v: std.json.Value) ?[]const u8 {298    return switch (v) {299        .string => |s| s,300        .object => |obj| if (obj.get("text")) |t| (if (t == .string) t.string else null) else null,301        else => null,302    };303}304305fn filterOptions(gpa: std.mem.Allocator, json_str: []const u8, query: []const u8) ![]NixOption {306    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.SearchFailed;307    defer parsed.deinit();308309    if (parsed.value != .array) return error.SearchFailed;310311    var opts: std.ArrayList(NixOption) = .empty;312    for (parsed.value.array.items) |item| {313        if (item != .object) continue;314        const name = if (item.object.get("name")) |v| if (v == .string) v.string else continue else continue;315        if (query.len > 0 and std.mem.indexOf(u8, name, query) == null) continue;316317        const type_str = if (item.object.get("type")) |v| if (v == .string) v.string else "any" else "any";318        const description = if (item.object.get("description")) |v| if (v == .string) v.string else "" else "";319        const default_val: ?[]const u8 = if (item.object.get("default")) |v| optionDefaultText(v) else null;320321        try opts.append(gpa, .{322            .name = try gpa.dupe(u8, name),323            .type_str = try gpa.dupe(u8, type_str),324            .default = if (default_val) |d| try gpa.dupe(u8, d) else null,325            .description = try gpa.dupe(u8, description),326        });327    }328329    return opts.toOwnedSlice(gpa);330}331332pub fn findSystemPackagesLine(io: std.Io, config_path: []const u8) ?u32 {333    var buf: [65536]u8 = undefined;334    const content = std.Io.Dir.readFile(.cwd(), io, config_path, &buf) catch return null;335    var lines = std.mem.splitScalar(u8, content, '\n');336    var line_num: u32 = 1;337    while (lines.next()) |line| : (line_num += 1) {338        if (std.mem.indexOf(u8, line, "systemPackages") != null) return line_num;339    }340    return null;341}342343// ─── Tests ───────────────────────────────────────────────────────────────────344//345// searchOptions itself is not exercised here (no nix on this host); these346// pin filterOptions's parsing against JSON shaped like optionAttrSetToDocList's347// real output (NINA-009), covering both the modern literalExpression-wrapped348// default and the older plain-string default.349350test "filterOptions extracts a known option from realistic doc-list JSON (NINA-009)" {351    const fixture =352        \\[353        \\  {354        \\    "name": "services.openssh.enable",355        \\    "type": "boolean",356        \\    "default": { "_type": "literalExpression", "text": "false" },357        \\    "description": "Whether to enable the OpenSSH secure shell daemon."358        \\  },359        \\  {360        \\    "name": "services.nginx.enable",361        \\    "type": "boolean",362        \\    "default": { "_type": "literalExpression", "text": "false" },363        \\    "description": "Whether to enable nginx."364        \\  }365        \\]366    ;367368    const opts = try filterOptions(std.testing.allocator, fixture, "openssh");369    defer {370        for (opts) |o| {371            std.testing.allocator.free(o.name);372            std.testing.allocator.free(o.type_str);373            std.testing.allocator.free(o.description);374            if (o.default) |d| std.testing.allocator.free(d);375        }376        std.testing.allocator.free(opts);377    }378379    try std.testing.expectEqual(@as(usize, 1), opts.len);380    try std.testing.expectEqualStrings("services.openssh.enable", opts[0].name);381    try std.testing.expectEqualStrings("boolean", opts[0].type_str);382    try std.testing.expect(opts[0].default != null);383    try std.testing.expectEqualStrings("false", opts[0].default.?);384    try std.testing.expect(std.mem.indexOf(u8, opts[0].description, "OpenSSH") != null);385}386387test "filterOptions still reads a plain-string default (pre-literalExpression nixpkgs)" {388    const fixture =389        \\[390        \\  {391        \\    "name": "services.openssh.ports",392        \\    "type": "list of signed integer",393        \\    "default": "[ 22 ]",394        \\    "description": "Ports on which to listen."395        \\  }396        \\]397    ;398399    const opts = try filterOptions(std.testing.allocator, fixture, "");400    defer {401        for (opts) |o| {402            std.testing.allocator.free(o.name);403            std.testing.allocator.free(o.type_str);404            std.testing.allocator.free(o.description);405            if (o.default) |d| std.testing.allocator.free(d);406        }407        std.testing.allocator.free(opts);408    }409410    try std.testing.expectEqual(@as(usize, 1), opts.len);411    try std.testing.expectEqualStrings("[ 22 ]", opts[0].default.?);412}413414test "filterOptions returns no match for a query that isn't a substring of any option name" {415    const fixture =416        \\[417        \\  { "name": "services.openssh.enable", "type": "boolean", "default": null, "description": "" }418        \\]419    ;420421    const opts = try filterOptions(std.testing.allocator, fixture, "postgres");422    defer std.testing.allocator.free(opts);423    try std.testing.expectEqual(@as(usize, 0), opts.len);424}