api.zig

11.4 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}244245pub fn searchOptions(gpa: std.mem.Allocator, io: std.Io, query: []const u8) ![]NixOption {246    const result = std.process.run(gpa, io, .{247        .argv = &.{ "nix", "eval", "--json", "nixpkgs#lib.optionAttrSetToDocList", "nixpkgs#nixosModules" },248    }) catch return error.SearchFailed;249    defer gpa.free(result.stderr);250    defer gpa.free(result.stdout);251252    switch (result.term) {253        .exited => |code| if (code != 0) return error.SearchFailed,254        else => return error.SearchFailed,255    }256257    return filterOptions(gpa, result.stdout, query);258}259260pub const NixOption = struct {261    name: []const u8,262    type_str: []const u8,263    default: ?[]const u8,264    description: []const u8,265};266267fn filterOptions(gpa: std.mem.Allocator, json_str: []const u8, query: []const u8) ![]NixOption {268    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.SearchFailed;269    defer parsed.deinit();270271    if (parsed.value != .array) return error.SearchFailed;272273    var opts: std.ArrayList(NixOption) = .empty;274    for (parsed.value.array.items) |item| {275        if (item != .object) continue;276        const name = if (item.object.get("name")) |v| if (v == .string) v.string else continue else continue;277        if (query.len > 0 and std.mem.indexOf(u8, name, query) == null) continue;278279        const type_str = if (item.object.get("type")) |v| if (v == .string) v.string else "any" else "any";280        const description = if (item.object.get("description")) |v| if (v == .string) v.string else "" else "";281        const default_val: ?[]const u8 = if (item.object.get("default")) |v| switch (v) {282            .string => |s| s,283            else => null,284        } else null;285286        try opts.append(gpa, .{287            .name = try gpa.dupe(u8, name),288            .type_str = try gpa.dupe(u8, type_str),289            .default = if (default_val) |d| try gpa.dupe(u8, d) else null,290            .description = try gpa.dupe(u8, description),291        });292    }293294    return opts.toOwnedSlice(gpa);295}296297pub fn findSystemPackagesLine(io: std.Io, config_path: []const u8) ?u32 {298    var buf: [65536]u8 = undefined;299    const content = std.Io.Dir.readFile(.cwd(), io, config_path, &buf) catch return null;300    var lines = std.mem.splitScalar(u8, content, '\n');301    var line_num: u32 = 1;302    while (lines.next()) |line| : (line_num += 1) {303        if (std.mem.indexOf(u8, line, "systemPackages") != null) return line_num;304    }305    return null;306}