const std = @import("std"); const whitespace = " \t\r\n"; pub const FileLoadResult = struct { source: []u8, env_lookup: std.StringHashMapUnmanaged([]const u8) = .empty, pub fn deinit(self: *FileLoadResult, allocator: std.mem.Allocator) void { allocator.free(self.source); var iter = self.env_lookup.iterator(); while (iter.next()) |entry| { allocator.free(entry.key_ptr.*); allocator.free(entry.value_ptr.*); } self.env_lookup.deinit(allocator); self.* = undefined; } }; pub fn loadExpandedConfigSource(allocator: std.mem.Allocator, path: []const u8, max_bytes: usize) !FileLoadResult { var stack = std.ArrayList([]u8).empty; defer { for (stack.items) |item| allocator.free(item); stack.deinit(allocator); } var output = std.ArrayList(u8).empty; errdefer output.deinit(allocator); var env_lookup: std.StringHashMapUnmanaged([]const u8) = .empty; errdefer { var iter = env_lookup.iterator(); while (iter.next()) |entry| { allocator.free(entry.key_ptr.*); allocator.free(entry.value_ptr.*); } env_lookup.deinit(allocator); } const absolute_path = try std.fs.cwd().realpathAlloc(allocator, path); defer allocator.free(absolute_path); try appendExpandedConfigFile(allocator, &output, &env_lookup, &stack, absolute_path, max_bytes); return .{ .source = try output.toOwnedSlice(allocator), .env_lookup = env_lookup, }; } fn appendExpandedConfigFile( allocator: std.mem.Allocator, output: *std.ArrayList(u8), env_lookup: *std.StringHashMapUnmanaged([]const u8), stack: *std.ArrayList([]u8), absolute_path: []const u8, max_bytes: usize, ) !void { for (stack.items) |entry| { if (std.mem.eql(u8, entry, absolute_path)) return error.IncludeCycle; } try stack.append(allocator, try allocator.dupe(u8, absolute_path)); defer allocator.free(stack.pop().?); const source = try std.fs.cwd().readFileAlloc(allocator, absolute_path, max_bytes); defer allocator.free(source); var line_iter = std.mem.splitScalar(u8, source, '\n'); while (line_iter.next()) |raw_line| { const line_without_comment = stripComment(raw_line); const trimmed = std.mem.trim(u8, line_without_comment, whitespace); if (trimmed.len != 0 and trimmed[0] != '[') { const assignment = splitAssignment(trimmed) catch null; if (assignment != null and std.mem.eql(u8, std.mem.trim(u8, assignment.?.key, whitespace), "include")) { const include_literal = try parseString(allocator, assignment.?.value); defer allocator.free(include_literal); const resolved_include = try resolveIncludePath(allocator, absolute_path, include_literal); defer allocator.free(resolved_include); try appendExpandedConfigFile(allocator, output, env_lookup, stack, resolved_include, max_bytes); continue; } if (assignment != null and std.mem.eql(u8, std.mem.trim(u8, assignment.?.key, whitespace), "env_file")) { const env_file_literal = try parseString(allocator, assignment.?.value); defer allocator.free(env_file_literal); const resolved_env_file = try resolveIncludePath(allocator, absolute_path, env_file_literal); defer allocator.free(resolved_env_file); try loadEnvFile(allocator, env_lookup, resolved_env_file, max_bytes); continue; } } try output.appendSlice(allocator, raw_line); try output.append(allocator, '\n'); } } fn resolveIncludePath(allocator: std.mem.Allocator, current_file: []const u8, include_path: []const u8) ![]u8 { if (std.fs.path.isAbsolute(include_path)) { return std.fs.cwd().realpathAlloc(allocator, include_path); } const current_dir = std.fs.path.dirname(current_file) orelse "."; const joined = try std.fs.path.resolve(allocator, &.{ current_dir, include_path }); defer allocator.free(joined); return std.fs.cwd().realpathAlloc(allocator, joined); } fn loadEnvFile( allocator: std.mem.Allocator, env_lookup: *std.StringHashMapUnmanaged([]const u8), absolute_path: []const u8, max_bytes: usize, ) !void { const source = try std.fs.cwd().readFileAlloc(allocator, absolute_path, max_bytes); defer allocator.free(source); var line_iter = std.mem.splitScalar(u8, source, '\n'); while (line_iter.next()) |raw_line| { const trimmed = std.mem.trim(u8, raw_line, whitespace); if (trimmed.len == 0 or trimmed[0] == '#') continue; var line = trimmed; if (std.mem.startsWith(u8, line, "export ")) { line = std.mem.trimLeft(u8, line["export ".len..], whitespace); } const equals_index = std.mem.indexOfScalar(u8, line, '=') orelse return error.InvalidEnvFileEntry; const key = std.mem.trim(u8, line[0..equals_index], whitespace); if (key.len == 0) return error.InvalidEnvFileEntry; const raw_value = std.mem.trim(u8, line[equals_index + 1 ..], whitespace); const value = if (raw_value.len >= 2 and raw_value[0] == '"' and raw_value[raw_value.len - 1] == '"') try parseString(allocator, raw_value) else try allocator.dupe(u8, raw_value); errdefer allocator.free(value); const owned_key = try allocator.dupe(u8, key); errdefer allocator.free(owned_key); const entry = try env_lookup.getOrPut(allocator, owned_key); if (entry.found_existing) { allocator.free(owned_key); allocator.free(entry.value_ptr.*); } entry.key_ptr.* = if (entry.found_existing) entry.key_ptr.* else owned_key; entry.value_ptr.* = value; } } fn parseString(allocator: std.mem.Allocator, raw: []const u8) (std.mem.Allocator.Error || error{InvalidString})![]const u8 { const value = std.mem.trim(u8, raw, whitespace); if (value.len < 2 or value[0] != '"' or value[value.len - 1] != '"') return error.InvalidString; return std.zig.string_literal.parseAlloc(allocator, value) catch return error.InvalidString; } fn splitAssignment(line: []const u8) error{InvalidAssignment}!struct { key: []const u8, value: []const u8 } { const equals_index = findTopLevelChar(line, '=') orelse return error.InvalidAssignment; const key = std.mem.trim(u8, line[0..equals_index], whitespace); const value = std.mem.trim(u8, line[equals_index + 1 ..], whitespace); if (key.len == 0 or value.len == 0) return error.InvalidAssignment; return .{ .key = key, .value = value }; } fn findTopLevelChar(line: []const u8, needle: u8) ?usize { var in_string = false; var escape = false; var brace_depth: usize = 0; for (line, 0..) |char, index| { if (in_string) { if (escape) { escape = false; continue; } switch (char) { '\\' => escape = true, '"' => in_string = false, else => {}, } continue; } switch (char) { '"' => in_string = true, '{' => brace_depth += 1, '}' => { if (brace_depth > 0) brace_depth -= 1; }, else => {}, } if (brace_depth == 0 and char == needle) return index; } return null; } fn stripComment(raw_line: []const u8) []const u8 { var in_string = false; var escape = false; var brace_depth: usize = 0; for (raw_line, 0..) |char, index| { if (in_string) { if (escape) { escape = false; continue; } switch (char) { '\\' => escape = true, '"' => in_string = false, else => {}, } continue; } switch (char) { '"' => in_string = true, '{' => brace_depth += 1, '}' => { if (brace_depth > 0) brace_depth -= 1; }, '#' => if (brace_depth == 0) return raw_line[0..index], else => {}, } } return raw_line; }