Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
480 lines
21 KiB
Zig
480 lines
21 KiB
Zig
//! Configuration: defaults, TOML file loading, `ZAG_<SECTION>_<KEY>` environment overrides
|
|
//! and validation. Port of barn's `ConfigLoader` and `*Config` records.
|
|
//!
|
|
//! Precedence (lowest to highest): built-in defaults, system file, user file, explicit
|
|
//! `--config` file, environment. Files merge per key.
|
|
const std = @import("std");
|
|
const builtin = @import("builtin");
|
|
const Io = std.Io;
|
|
const Allocator = std.mem.Allocator;
|
|
const Environ = std.process.Environ;
|
|
const toml = @import("toml.zig");
|
|
|
|
pub const LogLevel = enum {
|
|
debug,
|
|
info,
|
|
warn,
|
|
@"error",
|
|
};
|
|
|
|
pub const Service = struct {
|
|
log_level: LogLevel = .info,
|
|
/// Deprecated: superseded by `[load_levels]`.
|
|
max_concurrent_jobs: u32 = 4,
|
|
heartbeat_interval_seconds: u32 = 5,
|
|
/// Defaults to `<storage.base_dir>/zag.sock` when unset.
|
|
ipc_socket: ?[]const u8 = null,
|
|
stale_heartbeat_threshold_seconds: u32 = 30,
|
|
};
|
|
|
|
pub const LoadLevels = struct {
|
|
max_high_jobs: u32 = 2,
|
|
max_medium_jobs: u32 = 8,
|
|
max_low_jobs: u32 = 32,
|
|
};
|
|
|
|
pub const Jobs = struct {
|
|
default_timeout_seconds: u32 = 3600,
|
|
max_retries: u32 = 3,
|
|
retry_delay_seconds: u32 = 30,
|
|
retry_backoff_multiplier: f64 = 2.0,
|
|
/// Empty means every non-zero exit code is retryable.
|
|
retry_on_exit_codes: []const i32 = &.{},
|
|
};
|
|
|
|
pub const Cleanup = struct {
|
|
enabled: bool = true,
|
|
max_age_hours: u32 = 72,
|
|
cleanup_interval_minutes: u32 = 60,
|
|
keep_failed_jobs: bool = true,
|
|
keep_failed_jobs_hours: u32 = 168,
|
|
};
|
|
|
|
pub const Storage = struct {
|
|
base_dir: []const u8 = default_base_dir,
|
|
max_disk_usage_gb: u32 = 50,
|
|
preserve_work_dir: bool = false,
|
|
};
|
|
|
|
pub const default_base_dir = if (builtin.os.tag == .windows) "%TEMP%\\zag" else "/tmp/zag";
|
|
|
|
pub const Config = struct {
|
|
service: Service = .{},
|
|
jobs: Jobs = .{},
|
|
cleanup: Cleanup = .{},
|
|
storage: Storage = .{},
|
|
load_levels: LoadLevels = .{},
|
|
|
|
/// Socket path: explicit `service.ipc_socket`, else `<base_dir>/zag.sock`.
|
|
pub fn ipcSocketPath(self: Config, arena: Allocator) ![]const u8 {
|
|
if (self.service.ipc_socket) |p| return p;
|
|
return std.fmt.allocPrint(arena, "{s}/zag.sock", .{self.storage.base_dir});
|
|
}
|
|
|
|
pub fn validate(self: Config, diag: ?*Diagnostic) Error!void {
|
|
const checks = .{
|
|
.{ "service", "heartbeat_interval_seconds", self.service.heartbeat_interval_seconds, 1 },
|
|
.{ "service", "stale_heartbeat_threshold_seconds", self.service.stale_heartbeat_threshold_seconds, 1 },
|
|
.{ "service", "max_concurrent_jobs", self.service.max_concurrent_jobs, 1 },
|
|
.{ "load_levels", "max_high_jobs", self.load_levels.max_high_jobs, 1 },
|
|
.{ "load_levels", "max_medium_jobs", self.load_levels.max_medium_jobs, 1 },
|
|
.{ "load_levels", "max_low_jobs", self.load_levels.max_low_jobs, 1 },
|
|
.{ "jobs", "default_timeout_seconds", self.jobs.default_timeout_seconds, 1 },
|
|
.{ "cleanup", "max_age_hours", self.cleanup.max_age_hours, 1 },
|
|
.{ "cleanup", "cleanup_interval_minutes", self.cleanup.cleanup_interval_minutes, 1 },
|
|
.{ "cleanup", "keep_failed_jobs_hours", self.cleanup.keep_failed_jobs_hours, 1 },
|
|
.{ "storage", "max_disk_usage_gb", self.storage.max_disk_usage_gb, 1 },
|
|
};
|
|
inline for (checks) |c| {
|
|
if (c[2] < c[3]) return fail(diag, c[0], c[1], error.OutOfRange);
|
|
}
|
|
if (self.jobs.retry_backoff_multiplier < 1.0)
|
|
return fail(diag, "jobs", "retry_backoff_multiplier", error.OutOfRange);
|
|
if (self.storage.base_dir.len == 0) return fail(diag, "storage", "base_dir", error.OutOfRange);
|
|
}
|
|
};
|
|
|
|
pub const Error = error{ InvalidValue, OutOfRange, ParseFailed, ReadFailed, OutOfMemory };
|
|
|
|
/// Describes what went wrong; strings are static or borrowed from the loaded document.
|
|
pub const Diagnostic = struct {
|
|
section: []const u8 = "",
|
|
key: []const u8 = "",
|
|
/// Set for `ParseFailed`: the file and 1-based line.
|
|
path: []const u8 = "",
|
|
line: usize = 0,
|
|
};
|
|
|
|
fn fail(diag: ?*Diagnostic, section: []const u8, key: []const u8, err: Error) Error {
|
|
if (diag) |d| {
|
|
d.section = section;
|
|
d.key = key;
|
|
}
|
|
return err;
|
|
}
|
|
|
|
// -- value conversion ------------------------------------------------------------------
|
|
|
|
fn convert(arena: Allocator, comptime T: type, v: toml.Value) Error!T {
|
|
switch (@typeInfo(T)) {
|
|
.optional => |o| return try convert(arena, o.child, v),
|
|
.bool => return switch (v) {
|
|
.boolean => |b| b,
|
|
.string => |s| if (std.ascii.eqlIgnoreCase(s, "true")) true else if (std.ascii.eqlIgnoreCase(s, "false")) false else error.InvalidValue,
|
|
else => error.InvalidValue,
|
|
},
|
|
.int => return switch (v) {
|
|
.int => |n| std.math.cast(T, n) orelse error.OutOfRange,
|
|
.float => |f| std.math.cast(T, @as(i64, @intFromFloat(f))) orelse error.OutOfRange,
|
|
.string => |s| std.fmt.parseInt(T, s, 10) catch error.InvalidValue,
|
|
else => error.InvalidValue,
|
|
},
|
|
.float => return switch (v) {
|
|
.float => |f| f,
|
|
.int => |n| @floatFromInt(n),
|
|
.string => |s| std.fmt.parseFloat(T, s) catch error.InvalidValue,
|
|
else => error.InvalidValue,
|
|
},
|
|
.@"enum" => {
|
|
const s = switch (v) {
|
|
.string => |s| s,
|
|
else => return error.InvalidValue,
|
|
};
|
|
inline for (@typeInfo(T).@"enum".fields) |f| {
|
|
if (std.ascii.eqlIgnoreCase(s, f.name)) return @field(T, f.name);
|
|
}
|
|
return error.InvalidValue;
|
|
},
|
|
.pointer => |p| {
|
|
if (p.size != .slice) @compileError("unsupported config type " ++ @typeName(T));
|
|
if (p.child == u8) return switch (v) {
|
|
.string => |s| s,
|
|
else => error.InvalidValue,
|
|
};
|
|
const arr = switch (v) {
|
|
.array => |a| a,
|
|
else => return error.InvalidValue,
|
|
};
|
|
const out = try arena.alloc(p.child, arr.len);
|
|
for (arr, out) |item, *slot| slot.* = try convert(arena, p.child, item);
|
|
return out;
|
|
},
|
|
else => @compileError("unsupported config type " ++ @typeName(T)),
|
|
}
|
|
}
|
|
|
|
fn applySection(arena: Allocator, comptime T: type, name: []const u8, section: ?toml.Section, out: *T, diag: ?*Diagnostic) Error!void {
|
|
const s = section orelse return;
|
|
inline for (@typeInfo(T).@"struct".fields) |f| {
|
|
if (s.get(f.name)) |v| {
|
|
@field(out, f.name) = convert(arena, f.type, v) catch |err| return fail(diag, name, f.name, err);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Builds a `Config` from a merged TOML document (unknown sections/keys are ignored).
|
|
pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config {
|
|
var cfg: Config = .{};
|
|
try applySection(arena, Service, "service", doc.get("service"), &cfg.service, diag);
|
|
try applySection(arena, Jobs, "jobs", doc.get("jobs"), &cfg.jobs, diag);
|
|
try applySection(arena, Cleanup, "cleanup", doc.get("cleanup"), &cfg.cleanup, diag);
|
|
try applySection(arena, Storage, "storage", doc.get("storage"), &cfg.storage, diag);
|
|
try applySection(arena, LoadLevels, "load_levels", doc.get("load_levels"), &cfg.load_levels, diag);
|
|
try cfg.validate(diag);
|
|
return cfg;
|
|
}
|
|
|
|
// -- merging ---------------------------------------------------------------------------
|
|
|
|
/// Copies every key of `src` into `dst`, overriding existing keys.
|
|
pub fn mergeInto(arena: Allocator, dst: *toml.Doc, src: toml.Doc) Allocator.Error!void {
|
|
var it = src.iterator();
|
|
while (it.next()) |entry| {
|
|
const gop = try dst.getOrPut(arena, entry.key_ptr.*);
|
|
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
|
var kit = entry.value_ptr.iterator();
|
|
while (kit.next()) |kv| try gop.value_ptr.put(arena, kv.key_ptr.*, kv.value_ptr.*);
|
|
}
|
|
}
|
|
|
|
const env_prefix = "ZAG_";
|
|
const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{
|
|
.{ .name = "load_levels", .canonical = "load_levels" },
|
|
.{ .name = "loadlevels", .canonical = "load_levels" },
|
|
.{ .name = "service", .canonical = "service" },
|
|
.{ .name = "jobs", .canonical = "jobs" },
|
|
.{ .name = "cleanup", .canonical = "cleanup" },
|
|
.{ .name = "storage", .canonical = "storage" },
|
|
};
|
|
|
|
/// Applies `ZAG_<SECTION>_<KEY>=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5` or
|
|
/// `ZAG_LOAD_LEVELS_MAX_HIGH_JOBS=1`. Values are typed as bool, int, float, else string.
|
|
pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map) Allocator.Error!void {
|
|
for (env.keys(), env.values()) |name, value| {
|
|
if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue;
|
|
const rest = name[env_prefix.len..];
|
|
for (env_sections) |sec| {
|
|
if (rest.len <= sec.name.len + 1) continue;
|
|
if (!std.ascii.eqlIgnoreCase(rest[0..sec.name.len], sec.name) or rest[sec.name.len] != '_') continue;
|
|
const key = try std.ascii.allocLowerString(arena, rest[sec.name.len + 1 ..]);
|
|
const gop = try doc.getOrPut(arena, sec.canonical);
|
|
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
|
try gop.value_ptr.put(arena, key, try parseEnvValue(arena, value));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn parseEnvValue(arena: Allocator, text: []const u8) Allocator.Error!toml.Value {
|
|
if (std.ascii.eqlIgnoreCase(text, "true")) return .{ .boolean = true };
|
|
if (std.ascii.eqlIgnoreCase(text, "false")) return .{ .boolean = false };
|
|
if (std.fmt.parseInt(i64, text, 10)) |n| return .{ .int = n } else |_| {}
|
|
if (std.fmt.parseFloat(f64, text)) |f| {
|
|
if (std.math.isFinite(f)) return .{ .float = f };
|
|
} else |_| {}
|
|
return .{ .string = try arena.dupe(u8, text) };
|
|
}
|
|
|
|
// -- platform paths --------------------------------------------------------------------
|
|
|
|
pub fn systemConfigDir(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const u8 {
|
|
if (builtin.os.tag == .windows) {
|
|
const pd = env.get("PROGRAMDATA") orelse "C:\\ProgramData";
|
|
return std.fmt.allocPrint(arena, "{s}\\zag", .{pd});
|
|
}
|
|
return "/etc/zag";
|
|
}
|
|
|
|
pub fn userConfigDir(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const u8 {
|
|
const home = env.get("HOME") orelse env.get("USERPROFILE") orelse "";
|
|
switch (builtin.os.tag) {
|
|
.windows => {
|
|
if (env.get("APPDATA")) |ad| return std.fmt.allocPrint(arena, "{s}\\zag", .{ad});
|
|
return std.fmt.allocPrint(arena, "{s}\\AppData\\Roaming\\zag", .{home});
|
|
},
|
|
.macos => return std.fmt.allocPrint(arena, "{s}/Library/Application Support/zag", .{home}),
|
|
else => return std.fmt.allocPrint(arena, "{s}/.config/zag", .{home}),
|
|
}
|
|
}
|
|
|
|
pub const conf_name = "zag.conf";
|
|
|
|
/// `[system zag.conf, user zag.conf]`, lowest precedence first.
|
|
pub fn searchPaths(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const []const u8 {
|
|
const sep = if (builtin.os.tag == .windows) "\\" else "/";
|
|
const paths = try arena.alloc([]const u8, 2);
|
|
paths[0] = try std.fmt.allocPrint(arena, "{s}{s}{s}", .{ try systemConfigDir(arena, env), sep, conf_name });
|
|
paths[1] = try std.fmt.allocPrint(arena, "{s}{s}{s}", .{ try userConfigDir(arena, env), sep, conf_name });
|
|
return paths;
|
|
}
|
|
|
|
// -- loading ---------------------------------------------------------------------------
|
|
|
|
/// Reads and parses one file. Returns null when it does not exist.
|
|
pub fn loadFile(arena: Allocator, io: Io, path: []const u8, diag: ?*Diagnostic) Error!?toml.Doc {
|
|
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) {
|
|
error.FileNotFound => return null,
|
|
error.OutOfMemory => return error.OutOfMemory,
|
|
else => {
|
|
if (diag) |d| d.path = path;
|
|
return error.ReadFailed;
|
|
},
|
|
};
|
|
var td: toml.Diagnostic = .{};
|
|
return toml.parse(arena, text, &td) catch |err| switch (err) {
|
|
error.OutOfMemory => return error.OutOfMemory,
|
|
else => {
|
|
if (diag) |d| {
|
|
d.path = path;
|
|
d.line = td.line;
|
|
}
|
|
return error.ParseFailed;
|
|
},
|
|
};
|
|
}
|
|
|
|
pub const LoadOptions = struct {
|
|
/// Overrides the system/user search (used by tests).
|
|
search_paths: ?[]const []const u8 = null,
|
|
/// `--config <file>`; a bad explicit file is an error, a missing one is ignored.
|
|
explicit_path: ?[]const u8 = null,
|
|
};
|
|
|
|
/// Loads the effective configuration. Unreadable or malformed *implicit* files (system/user)
|
|
/// are skipped like barn does; an explicit file that fails to parse is reported.
|
|
pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic) Error!Config {
|
|
var merged: toml.Doc = .empty;
|
|
const paths = opts.search_paths orelse try searchPaths(arena, env);
|
|
for (paths) |p| {
|
|
const doc = loadFile(arena, io, p, null) catch |err| switch (err) {
|
|
error.OutOfMemory => return error.OutOfMemory,
|
|
else => continue,
|
|
};
|
|
if (doc) |d| try mergeInto(arena, &merged, d);
|
|
}
|
|
if (opts.explicit_path) |p| {
|
|
if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d);
|
|
}
|
|
try applyEnvironment(arena, &merged, env);
|
|
return fromDoc(arena, merged, diag);
|
|
}
|
|
|
|
// -- tests -----------------------------------------------------------------------------
|
|
|
|
fn testDoc(arena: Allocator, text: []const u8) !toml.Doc {
|
|
return toml.parse(arena, text, null);
|
|
}
|
|
|
|
test "defaults match barn" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const cfg = try fromDoc(arena.allocator(), .empty, null);
|
|
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
|
|
try std.testing.expectEqual(@as(u32, 5), cfg.service.heartbeat_interval_seconds);
|
|
try std.testing.expectEqual(@as(u32, 30), cfg.service.stale_heartbeat_threshold_seconds);
|
|
try std.testing.expectEqual(@as(u32, 2), cfg.load_levels.max_high_jobs);
|
|
try std.testing.expectEqual(@as(u32, 8), cfg.load_levels.max_medium_jobs);
|
|
try std.testing.expectEqual(@as(u32, 32), cfg.load_levels.max_low_jobs);
|
|
try std.testing.expectEqual(@as(u32, 3600), cfg.jobs.default_timeout_seconds);
|
|
try std.testing.expectEqual(@as(u32, 3), cfg.jobs.max_retries);
|
|
try std.testing.expectEqual(@as(f64, 2.0), cfg.jobs.retry_backoff_multiplier);
|
|
try std.testing.expect(cfg.cleanup.enabled and cfg.cleanup.keep_failed_jobs);
|
|
try std.testing.expectEqual(@as(u32, 72), cfg.cleanup.max_age_hours);
|
|
try std.testing.expectEqual(@as(u32, 168), cfg.cleanup.keep_failed_jobs_hours);
|
|
try std.testing.expectEqual(@as(u32, 50), cfg.storage.max_disk_usage_gb);
|
|
try std.testing.expectEqualStrings("/tmp/zag/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
|
}
|
|
|
|
test "embedded default zag.conf parses to the built-in defaults" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const defaults = @import("defaults.zig");
|
|
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), defaults.zag_conf), null);
|
|
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
|
|
try std.testing.expectEqual((Config{}).load_levels, cfg.load_levels);
|
|
try std.testing.expectEqual((Config{}).cleanup, cfg.cleanup);
|
|
try std.testing.expectEqual(@as(usize, 0), cfg.jobs.retry_on_exit_codes.len);
|
|
try std.testing.expectEqualStrings("/tmp/zag", cfg.storage.base_dir);
|
|
}
|
|
|
|
test "values, arrays and enums convert" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(),
|
|
\\[service]
|
|
\\log_level = "DEBUG"
|
|
\\ipc_socket = "/run/zag.sock"
|
|
\\[jobs]
|
|
\\retry_on_exit_codes = [1, 137]
|
|
\\retry_backoff_multiplier = 3
|
|
\\[storage]
|
|
\\base_dir = "/var/lib/zag"
|
|
\\preserve_work_dir = true
|
|
), null);
|
|
try std.testing.expectEqual(LogLevel.debug, cfg.service.log_level);
|
|
try std.testing.expectEqualStrings("/run/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
|
try std.testing.expectEqualSlices(i32, &.{ 1, 137 }, cfg.jobs.retry_on_exit_codes);
|
|
try std.testing.expectEqual(@as(f64, 3.0), cfg.jobs.retry_backoff_multiplier);
|
|
try std.testing.expect(cfg.storage.preserve_work_dir);
|
|
}
|
|
|
|
test "ipc socket follows a custom base_dir" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), "[storage]\nbase_dir = \"/data/zag\"\n"), null);
|
|
try std.testing.expectEqualStrings("/data/zag/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
|
}
|
|
|
|
test "validation rejects bad values and names the key" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const a = arena.allocator();
|
|
var diag: Diagnostic = .{};
|
|
|
|
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[load_levels]\nmax_high_jobs = 0\n"), &diag));
|
|
try std.testing.expectEqualStrings("max_high_jobs", diag.key);
|
|
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"), &diag));
|
|
try std.testing.expectEqualStrings("retry_backoff_multiplier", diag.key);
|
|
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[service]\nlog_level = \"loud\"\n"), &diag));
|
|
try std.testing.expectEqualStrings("log_level", diag.key);
|
|
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nmax_retries = -1\n"), &diag));
|
|
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag));
|
|
}
|
|
|
|
test "environment overrides, including load_levels" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const a = arena.allocator();
|
|
var env = Environ.Map.init(std.testing.allocator);
|
|
defer env.deinit();
|
|
try env.put("ZAG_JOBS_MAX_RETRIES", "7");
|
|
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
|
|
try env.put("ZAG_LOADLEVELS_MAX_LOW_JOBS", "4");
|
|
try env.put("ZAG_CLEANUP_ENABLED", "false");
|
|
try env.put("ZAG_SERVICE_LOG_LEVEL", "warn");
|
|
try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5");
|
|
try env.put("ZAG_BASE_DIR", "ignored");
|
|
try env.put("OTHER_JOBS_MAX_RETRIES", "99");
|
|
|
|
var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n");
|
|
try applyEnvironment(a, &doc, &env);
|
|
const cfg = try fromDoc(a, doc, null);
|
|
try std.testing.expectEqual(@as(u32, 7), cfg.jobs.max_retries);
|
|
try std.testing.expectEqual(@as(u32, 1), cfg.load_levels.max_high_jobs);
|
|
try std.testing.expectEqual(@as(u32, 4), cfg.load_levels.max_low_jobs);
|
|
try std.testing.expect(!cfg.cleanup.enabled);
|
|
try std.testing.expectEqual(LogLevel.warn, cfg.service.log_level);
|
|
try std.testing.expectEqual(@as(f64, 1.5), cfg.jobs.retry_backoff_multiplier);
|
|
}
|
|
|
|
test "files merge per key with explicit file and env on top" {
|
|
const io = std.testing.io;
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
const a = arena.allocator();
|
|
var tmp = std.testing.tmpDir(.{});
|
|
defer tmp.cleanup();
|
|
|
|
try tmp.dir.writeFile(io, .{ .sub_path = "system.conf", .data = "[jobs]\nmax_retries = 1\nretry_delay_seconds = 10\n[cleanup]\nmax_age_hours = 10\n" });
|
|
try tmp.dir.writeFile(io, .{ .sub_path = "user.conf", .data = "[jobs]\nmax_retries = 2\n" });
|
|
try tmp.dir.writeFile(io, .{ .sub_path = "explicit.conf", .data = "[cleanup]\nmax_age_hours = 20\n" });
|
|
try tmp.dir.writeFile(io, .{ .sub_path = "broken.conf", .data = "[jobs\n" });
|
|
|
|
const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
|
|
const paths = [_][]const u8{
|
|
try std.fmt.allocPrint(a, "{s}/system.conf", .{base}),
|
|
try std.fmt.allocPrint(a, "{s}/missing.conf", .{base}),
|
|
try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}), // skipped, not fatal
|
|
try std.fmt.allocPrint(a, "{s}/user.conf", .{base}),
|
|
};
|
|
var env = Environ.Map.init(std.testing.allocator);
|
|
defer env.deinit();
|
|
try env.put("ZAG_JOBS_RETRY_DELAY_SECONDS", "99");
|
|
|
|
const cfg = try load(a, io, &env, .{
|
|
.search_paths = &paths,
|
|
.explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}),
|
|
}, null);
|
|
try std.testing.expectEqual(@as(u32, 2), cfg.jobs.max_retries); // user beats system
|
|
try std.testing.expectEqual(@as(u32, 99), cfg.jobs.retry_delay_seconds); // env beats files
|
|
try std.testing.expectEqual(@as(u32, 20), cfg.cleanup.max_age_hours); // explicit beats system
|
|
|
|
var diag: Diagnostic = .{};
|
|
try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{
|
|
.search_paths = &.{},
|
|
.explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}),
|
|
}, &diag));
|
|
try std.testing.expectEqual(@as(usize, 1), diag.line);
|
|
}
|
|
|
|
test "search paths point at zag.conf" {
|
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
defer arena.deinit();
|
|
var env = Environ.Map.init(std.testing.allocator);
|
|
defer env.deinit();
|
|
try env.put("HOME", "/home/dan");
|
|
const paths = try searchPaths(arena.allocator(), &env);
|
|
try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]);
|
|
try std.testing.expectEqualStrings("/home/dan/.config/zag/zag.conf", paths[1]);
|
|
}
|