summaryrefslogtreecommitdiff
path: root/src/cli/util.zig
blob: abdedd17fc2ef55a290dc27b4c1100c5011abfc4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//! What every command needs.
const std = @import("std");

pub fn fail(comptime fmt: []const u8, args: anytype) noreturn {
    std.debug.print(fmt, args);
    std.process.exit(2);
}

/// `name` as a path: itself with a slash in it, else the first match in PATH.
pub fn resolve(init: std.process.Init, name: [:0]const u8) ![*:0]const u8 {
    if (std.mem.indexOfScalar(u8, name, '/') != null) return name.ptr;
    const arena = init.arena.allocator();
    var dirs = std.mem.tokenizeScalar(u8, init.environ_map.get("PATH") orelse "/usr/bin:/bin", ':');
    while (dirs.next()) |dir| {
        const candidate = try std.fs.path.joinZ(arena, &.{ dir, name });
        std.Io.Dir.cwd().access(init.io, candidate, .{ .execute = true }) catch continue;
        return candidate.ptr;
    }
    fail("{s}: not found in PATH\n", .{name});
}

/// The arguments after a command's own, as the target's argv.
pub fn targetArgv(arena: std.mem.Allocator, args: []const [:0]const u8) ![:null]?[*:0]const u8 {
    const argv = try arena.allocSentinel(?[*:0]const u8, args.len, null);
    for (argv, args) |*dst, s| dst.* = s.ptr;
    return argv;
}