Simplify file creation branch of process_rule.zig

Still not quite where I want it, but definitely better than what it was
This commit is contained in:
mitteneer 2025-04-19 15:36:51 -04:00
parent 5383b69eb6
commit baf9ef38a4

View file

@ -20,18 +20,25 @@ pub fn run(allocator: std.mem.Allocator, params: *jetzig.data.Value, env: jetzig
};
const Rules = struct {
rules: []Rule,
rules: []const Rule,
};
const rule = try std.json.parseFromSliceLeaky(Rule, allocator, try params.toJson(), .{ .ignore_unknown_fields = true });
const file_read: std.fs.File = std.fs.cwd().openFile("rules.json", .{}) catch |read_err| switch (read_err) {
error.FileNotFound => std.fs.cwd().createFile("rules.json", .{ .read = true, .exclusive = true }) catch |write_err| switch (write_err) {
error.PathAlreadyExists => unreachable,
else => {
std.log.debug("{any} while writing file", .{write_err});
return;
},
error.FileNotFound => {
const file = std.fs.cwd().createFile("rules.json", .{ .read = true, .exclusive = true }) catch |write_err| switch (write_err) {
error.PathAlreadyExists => unreachable,
else => {
std.log.debug("{any} while writing file", .{write_err});
return;
},
};
const out_rules = Rules{ .rules = &[_]Rule{rule} };
const out = try std.json.stringifyAlloc(allocator, out_rules, .{});
try file.writeAll(out);
file.close();
return;
},
else => {
std.log.debug("{any} while reading file", .{read_err});
@ -40,16 +47,19 @@ pub fn run(allocator: std.mem.Allocator, params: *jetzig.data.Value, env: jetzig
};
var rules = std.ArrayList(Rule).init(allocator);
defer rules.deinit();
const file_content = try file_read.readToEndAlloc(allocator, 16_000_000);
if (file_content.len != 0) {
const content: Rules = try std.json.parseFromSliceLeaky(Rules, allocator, file_content, .{});
try rules.appendSlice(content.rules);
}
const content: Rules = try std.json.parseFromSliceLeaky(Rules, allocator, file_content, .{});
try rules.appendSlice(content.rules);
try rules.append(rule);
file_read.close();
const file_write: std.fs.File = try std.fs.cwd().openFile("rules.json", .{ .mode = .write_only });
const out_rules = Rules{ .rules = rules.items };
const out = try std.json.stringifyAlloc(allocator, out_rules, .{});
try file_write.writeAll(out);
file_write.close();
return;
}