api.zig

6.8 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, 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            errors.error_info.setSuggestion("run nix-channel --update and try again", .{});52            return error.SearchFailed;53        },54        else => return error.SearchFailed,55    }5657    return parseSearchJson(gpa, result.stdout);58}5960fn parseSearchJson(gpa: std.mem.Allocator, json_str: []const u8) ![]types.NixPackage {61    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.SearchFailed;62    defer parsed.deinit();6364    if (parsed.value != .object) return error.SearchFailed;6566    var packages: std.ArrayList(types.NixPackage) = .empty;67    var it = parsed.value.object.iterator();68    while (it.next()) |entry| {69        const key = entry.key_ptr.*;70        const val = entry.value_ptr.*;71        if (val != .object) continue;7273        // Key format: "legacyPackages.x86_64-linux.firefox"74        const last_dot = std.mem.lastIndexOfScalar(u8, key, '.') orelse continue;75        const attr = key[last_dot + 1 ..];7677        const pname = if (val.object.get("pname")) |v|78            if (v == .string) v.string else attr79        else80            attr;8182        const version = if (val.object.get("version")) |v|83            if (v == .string) v.string else ""84        else85            "";8687        const description = if (val.object.get("description")) |v|88            if (v == .string) v.string else ""89        else90            "";9192        try packages.append(gpa, .{93            .attr = try gpa.dupe(u8, attr),94            .pname = try gpa.dupe(u8, pname),95            .version = try gpa.dupe(u8, version),96            .description = try gpa.dupe(u8, description),97        });98    }99100    return packages.toOwnedSlice(gpa);101}102103pub fn getLicense(gpa: std.mem.Allocator, io: std.Io, attr: []const u8) ?[]const u8 {104    const expr = std.fmt.allocPrint(gpa, "nixpkgs#{s}.meta.license.shortName", .{attr}) catch return null;105    defer gpa.free(expr);106107    const result = std.process.run(gpa, io, .{108        .argv = &.{ "nix", "eval", "--raw", expr },109    }) catch return null;110    defer gpa.free(result.stderr);111112    switch (result.term) {113        .exited => |code| if (code != 0) {114            gpa.free(result.stdout);115            return null;116        },117        else => {118            gpa.free(result.stdout);119            return null;120        },121    }122123    const license = std.mem.trim(u8, result.stdout, " \t\n\r");124    if (license.len == 0) {125        gpa.free(result.stdout);126        return null;127    }128    return license;129}130131pub fn searchOptions(gpa: std.mem.Allocator, io: std.Io, query: []const u8) ![]NixOption {132    const result = std.process.run(gpa, io, .{133        .argv = &.{ "nix", "eval", "--json", "nixpkgs#lib.optionAttrSetToDocList", "nixpkgs#nixosModules" },134    }) catch return error.SearchFailed;135    defer gpa.free(result.stderr);136    defer gpa.free(result.stdout);137138    switch (result.term) {139        .exited => |code| if (code != 0) return error.SearchFailed,140        else => return error.SearchFailed,141    }142143    return filterOptions(gpa, result.stdout, query);144}145146pub const NixOption = struct {147    name: []const u8,148    type_str: []const u8,149    default: ?[]const u8,150    description: []const u8,151};152153fn filterOptions(gpa: std.mem.Allocator, json_str: []const u8, query: []const u8) ![]NixOption {154    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.SearchFailed;155    defer parsed.deinit();156157    if (parsed.value != .array) return error.SearchFailed;158159    var opts: std.ArrayList(NixOption) = .empty;160    for (parsed.value.array.items) |item| {161        if (item != .object) continue;162        const name = if (item.object.get("name")) |v| if (v == .string) v.string else continue else continue;163        if (query.len > 0 and std.mem.indexOf(u8, name, query) == null) continue;164165        const type_str = if (item.object.get("type")) |v| if (v == .string) v.string else "any" else "any";166        const description = if (item.object.get("description")) |v| if (v == .string) v.string else "" else "";167        const default_val: ?[]const u8 = if (item.object.get("default")) |v| switch (v) {168            .string => |s| s,169            else => null,170        } else null;171172        try opts.append(gpa, .{173            .name = try gpa.dupe(u8, name),174            .type_str = try gpa.dupe(u8, type_str),175            .default = if (default_val) |d| try gpa.dupe(u8, d) else null,176            .description = try gpa.dupe(u8, description),177        });178    }179180    return opts.toOwnedSlice(gpa);181}182183pub fn findSystemPackagesLine(io: std.Io, config_path: []const u8) ?u32 {184    var buf: [65536]u8 = undefined;185    const content = std.Io.Dir.readFile(.cwd(), io, config_path, &buf) catch return null;186    var lines = std.mem.splitScalar(u8, content, '\n');187    var line_num: u32 = 1;188    while (lines.next()) |line| : (line_num += 1) {189        if (std.mem.indexOf(u8, line, "systemPackages") != null) return line_num;190    }191    return null;192}