robin/cdl

cute fetch client written in zig

git clone https://git.robinwobin.dev/robin/cdl

robinwip: init4a5e316

main
1.2 KiB46 linesraw
1const std = @import("std");
2
3const cdl = @import("root.zig");
4
5pub const Options = struct {
6    trimmed: bool = false,
7};
8
9pub fn spawn(argv: []const []const u8, opts: ?Options) ![]const u8 {
10    if (!std.process.can_spawn) {
11        return error.NoChildProcess;
12    }
13
14    var child = try std.process.spawn(cdl.io, .{
15        .argv = argv,
16        .environ_map = cdl.environ_map,
17        .stdin = .ignore,
18        .stdout = .pipe,
19        .stderr = .ignore,
20    });
21
22    var stdout_reader = child.stdout.?.readerStreaming(cdl.io, &.{});
23    const stdout = stdout_reader.interface.allocRemaining(cdl.gpa, .limited(0x100)) catch return error.ReadFailure;
24    errdefer cdl.gpa.free(stdout);
25
26    const term = try child.wait(cdl.io);
27
28    const raw = blk: switch (term) {
29        .exited => |code| {
30            if (code != 0) {
31                return error.ExitCodeFailure;
32            }
33            break :blk stdout;
34        },
35        .signal, .stopped => return error.ProcessTerminated,
36        .unknown => return error.ProcessTerminated,
37    };
38    if (opts == null) return raw;
39
40    if (opts) |o| if (o.trimmed) {
41        defer cdl.gpa.free(raw);
42        return try cdl.gpa.dupe(u8, std.mem.trim(u8, raw, " \n\r"));
43    };
44
45    return raw;
46}