xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / platform.zig

2.0 KB
1const std = @import("std");
2
3const max_io_threads = 4;
4
5pub var io: std.Io = undefined;
6pub var gpa: std.mem.Allocator = undefined;
7pub var env: *std.process.Environ.Map = undefined;
8pub var args: std.process.Args = undefined;
9
10var threaded: std.Io.Threaded = undefined;
11
12pub fn setup(init: std.process.Init) void {
13    gpa = init.gpa;
14    env = init.environ_map;
15    args = init.minimal.args;
16    threaded = std.Io.Threaded.init(init.gpa, .{
17        .argv0 = .init(init.minimal.args),
18        .environ = init.minimal.environ,
19        .async_limit = .limited(max_io_threads),
20    });
21    io = threaded.io();
22}
23
24pub fn getEnv(key: []const u8) ?[]const u8 {
25    return env.get(key);
26}
27
28pub fn home() ?[]const u8 {
29    if (getEnv("HOME")) |h| {
30        if (h.len > 0) return h;
31    }
32    const pw = std.c.getpwuid(std.c.getuid()) orelse return null;
33    const dir = pw.dir orelse return null;
34    return std.mem.sliceTo(dir, 0);
35}
36
37pub fn reRaise(sig: std.posix.SIG) noreturn {
38    const act = std.posix.Sigaction{
39        .handler = .{ .handler = std.posix.SIG.DFL },
40        .mask = std.posix.sigemptyset(),
41        .flags = 0,
42    };
43    std.posix.sigaction(sig, &act, null);
44    std.posix.raise(sig) catch {};
45    std.process.exit(1);
46}
47
48pub fn onSignal(sig: std.posix.SIG, handler: *const fn (std.posix.SIG) callconv(.c) void) void {
49    const act = std.posix.Sigaction{
50        .handler = .{ .handler = handler },
51        .mask = std.posix.sigemptyset(),
52        .flags = 0,
53    };
54    std.posix.sigaction(sig, &act, null);
55}
56
57pub fn writeOut(bytes: []const u8) void {
58    std.Io.File.stdout().writeStreamingAll(io, bytes) catch {};
59}
60
61pub fn writeErr(bytes: []const u8) void {
62    std.Io.File.stderr().writeStreamingAll(io, bytes) catch {};
63}
64
65pub fn printErr(comptime fmt: []const u8, fmt_args: anytype) void {
66    var buf: [512]u8 = undefined;
67    const s = std.fmt.bufPrint(&buf, fmt, fmt_args) catch {
68        const heap = std.fmt.allocPrint(gpa, fmt, fmt_args) catch return;
69        defer gpa.free(heap);
70        writeErr(heap);
71        return;
72    };
73    writeErr(s);
74}