From baf9ef38a4c83fb4588d7c12f883cec294f1bd95 Mon Sep 17 00:00:00 2001 From: mitteneer Date: Sat, 19 Apr 2025 15:36:51 -0400 Subject: [PATCH] Simplify file creation branch of process_rule.zig Still not quite where I want it, but definitely better than what it was --- src/app/jobs/process_rule.zig | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/src/app/jobs/process_rule.zig b/src/app/jobs/process_rule.zig index 93d1279..7cb1a71 100644 --- a/src/app/jobs/process_rule.zig +++ b/src/app/jobs/process_rule.zig @@ -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; }