A SpaceTraders Agent
1const std = @import("std");
2const kf = @import("known-folders");
3
4const Auth = @import("st").http.Auth;
5
6pub const Config = struct {
7 auth: Auth = .{
8 .account = "Bearer <TOKEN>",
9 .agent = "Bearer <TOKEN>",
10 },
11};
12
13const log = std.log.scoped(.agent);
14
15pub fn load(io: std.Io, allocator: std.mem.Allocator) !Config {
16 log.debug("Loading config", .{});
17
18 const dir = try kf.open(io, allocator, .roaming_configuration, .{ .follow_symlinks = true }) orelse return error.NoConfigFolder;
19 var file: ?std.Io.File = null;
20 defer if (file) |f| f.close(io);
21
22 _ = dir.statPath(io, "space/config.zon", .{ .follow_symlinks = true }) catch {
23 file = try create(io, dir);
24 };
25
26 if (file == null) file = try dir.openFile(io, "space/config.zon", .{});
27 const stat = try file.?.stat(io);
28
29 const source = try allocator.allocSentinel(u8, stat.size, 0);
30 defer allocator.free(source);
31
32 var buffer: [64]u8 = undefined;
33 var reader = file.?.reader(io, &buffer);
34 try reader.interface.readSliceAll(source);
35
36 return std.zon.parse.fromSliceAlloc(Config, allocator, source, null, .{});
37}
38
39pub fn create(io: std.Io, dir: std.Io.Dir) !std.Io.File {
40 log.warn("Creating new config file", .{});
41 const config = Config{};
42
43 try dir.makePath(io, "space");
44 const file = try dir.createFile(io, "space/config.zon", .{ .read = true });
45 const file_old = std.fs.File.adaptFromNewApi(file);
46
47 var buffer: [64]u8 = undefined;
48 var writer = file_old.writer(&buffer);
49
50 try std.zon.stringify.serializeArbitraryDepth(config, .{}, &writer.interface);
51 try writer.interface.flush();
52
53 return file;
54}
55
56pub fn free(allocator: std.mem.Allocator, config: Config) void {
57 std.zon.parse.free(allocator, config);
58}