config: support nested/recursive config-file keys

This commit is contained in:
Paul Jimenez
2023-11-08 09:57:34 -05:00
parent 3113f9d8af
commit b8bfb66ad8

View File

@ -1136,17 +1136,22 @@ pub fn loadCliArgs(self: *Config, alloc_gpa: Allocator) !void {
/// Load and parse the config files that were added in the "config-file" key.
pub fn loadRecursiveFiles(self: *Config, alloc: Allocator) !void {
// TODO(mitchellh): support nesting (config-file in a config file)
// TODO(mitchellh): detect cycles when nesting
if (self.@"config-file".list.items.len == 0) return;
const arena_alloc = self._arena.?.allocator();
var loaded = std.StringHashMap(void).init(alloc);
defer loaded.deinit();
const cfgdir = getConfigDir(alloc);
more_found: while (true) {
const len = self.@"config-file".list.items.len;
for (self.@"config-file".list.items) |path| {
var file = cfgdir.openFile(path, .{}) catch |err| {
const cfgpath = cfgdir.realpathAlloc(arena_alloc, path) catch path;
if (loaded.contains(cfgpath)) continue;
try loaded.put(cfgpath, {});
var file = cfgdir.openFile(path, .{}) catch |err| {
try self._errors.add(arena_alloc, .{
.message = try std.fmt.allocPrintZ(
arena_alloc,
@ -1158,23 +1163,19 @@ pub fn loadRecursiveFiles(self: *Config, alloc: Allocator) !void {
};
defer file.close();
log.info("loading config-file path={s}", .{cfgpath});
var buf_reader = std.io.bufferedReader(file.reader());
var iter = cli.args.lineIterator(buf_reader.reader());
try cli.args.parse(Config, alloc, self, &iter);
// We don't currently support adding more config files to load
// from within a loaded config file. This can be supported
// later.
// Added more config files, so the list's backing array might have
// been resized, so start the iteration over
if (self.@"config-file".list.items.len > len) {
try self._errors.add(arena_alloc, .{
.message = try std.fmt.allocPrintZ(
arena_alloc,
"config-file cannot be used in a config-file. Found in {s}",
.{path},
),
});
continue :more_found;
}
}
break;
}
}
pub fn finalize(self: *Config) !void {