//! Canonical rules-file writing (M1-UI-017, M1-UI-018). //! //! Saving from the editor rewrites the whole rules file rather than patching //! it, so this module defines the one shape a saved file has: schema header, //! then every rule in ascending name order, then nothing else. Comments and //! ordering a human put in the file do not survive a save; M1-UI-018 asks for //! a canonical form, and a canonical form is by definition the same bytes for //! the same rules (M1-SAFE-001). //! //! Names are quoted unless they are unmistakably plain. An unquoted `true` or //! `123` would resolve as a boolean or an integer on the way back in //! (M1-YAML-005), so the predicate here is deliberately stricter than YAML //! needs: quoting a name that did not need it costs nothing, while failing to //! quote one that did loses the rule. const std = @import("std"); pub const Error = error{ OutOfMemory, NoRules }; /// What a save writes for one rule. This is the editor's view, not /// `config.rules.Rule`: a rule reaching here has a usable action, because /// M1-UI-016 refuses to save an invalid ruleset. pub const Rule = struct { match: []const u8, name: []const u8, source_account: ?[]const u8, target_account: []const u8, }; fn lessThan(_: void, a: Rule, b: Rule) bool { return std.mem.order(u8, a.name, b.name) == .lt; } /// True when `name` can be written without quotes and read back unchanged. fn isPlain(name: []const u8) bool { if (name.len == 0) return false; if (!std.ascii.isAlphabetic(name[0]) and name[0] != '_') return false; for (name) |c| { if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-') return false; } // M1-YAML-005 resolves these to non-strings when they are unquoted. const reserved = [_][]const u8{ "true", "false", "null", "yes", "no", "on", "off", "y", "n" }; for (reserved) |word| { if (std.ascii.eqlIgnoreCase(name, word)) return false; } return true; } fn writeQuoted(out: *std.ArrayList(u8), gpa: std.mem.Allocator, text: []const u8) Error!void { try out.append(gpa, '"'); for (text) |c| { switch (c) { '"', '\\' => try out.appendSlice(gpa, &.{ '\\', c }), else => try out.append(gpa, c), } } try out.append(gpa, '"'); } fn writeName(out: *std.ArrayList(u8), gpa: std.mem.Allocator, name: []const u8) Error!void { if (isPlain(name)) return out.appendSlice(gpa, name); try writeQuoted(out, gpa, name); } /// Writes the condition as a literal block scalar. `|-` strips the trailing /// newline, so a single-line condition survives the round trip as exactly /// itself rather than gaining one. fn writeMatch(out: *std.ArrayList(u8), gpa: std.mem.Allocator, match: []const u8) Error!void { try out.appendSlice(gpa, " match: |-\n"); var lines = std.mem.splitScalar(u8, match, '\n'); while (lines.next()) |line| { // An all-whitespace line carries no content; indenting it would only // add trailing whitespace to the file. if (std.mem.trim(u8, line, " \t").len == 0) { try out.append(gpa, '\n'); continue; } try out.appendSlice(gpa, " "); try out.appendSlice(gpa, line); try out.append(gpa, '\n'); } } /// Renders the canonical rules file. The result is UTF-8 without a mark, /// LF-terminated (M1-JRN-010 applies to journals; a rules file we write holds /// to the same convention so it reads back through our own loader). pub fn rulesFile(arena: std.mem.Allocator, rules: []const Rule) Error![]const u8 { // M1-RULE-001: a rules file has at least one rule. M1-UI-019 keeps the // editor from reaching here with none, and this is the backstop. if (rules.len == 0) return error.NoRules; const sorted = try arena.dupe(Rule, rules); std.mem.sort(Rule, sorted, {}, lessThan); var out: std.ArrayList(u8) = .empty; try out.appendSlice(arena, "schema:\n version: 1\n\nrules:\n"); for (sorted) |rule| { try out.appendSlice(arena, " "); try writeName(&out, arena, rule.name); try out.appendSlice(arena, ":\n"); try writeMatch(&out, arena, rule.match); try out.appendSlice(arena, " set:\n targetAccount: "); try writeQuoted(&out, arena, rule.target_account); try out.append(arena, '\n'); if (rule.source_account) |account| { try out.appendSlice(arena, " sourceAccount: "); try writeQuoted(&out, arena, account); try out.append(arena, '\n'); } } return out.items; } // -- tests ------------------------------------------------------------------- const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; fn ruleOf(name: []const u8, match: []const u8, target: []const u8) Rule { return .{ .name = name, .match = match, .target_account = target, .source_account = null }; } fn emitted(arena: *std.heap.ArenaAllocator, rules: []const Rule) Error![]const u8 { return rulesFile(arena.allocator(), rules); } test "M1-UI-018: the whole file has this shape" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitted(&arena, &.{ruleOf("groceries", "posting == \"markt\"", "expenses:food")}); try expectEqualStrings(@embedFile("../testdata/yaml/the_whole_file_has_this_shape.yaml"), text); } test "M1-UI-018: rules come out in ascending name order by byte value" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitted(&arena, &.{ ruleOf("zebra", "a == \"1\"", "e:z"), ruleOf("Apple", "a == \"2\"", "e:a"), ruleOf("apple", "a == \"3\"", "e:b"), ruleOf("banana", "a == \"4\"", "e:c"), }); // Byte value, not locale: capitals sort before lowercase. const order = [_][]const u8{ "Apple:", "apple:", "banana:", "zebra:" }; var offset: usize = 0; for (order) |name| { const found = std.mem.findPos(u8, text, offset, name) orelse return error.NotFound; offset = found; } } test "M1-UI-018: an optional source account appears only when set" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const without = try emitted(&arena, &.{ruleOf("r", "a == \"1\"", "e:f")}); try expect(std.mem.find(u8, without, "sourceAccount") == null); const with = try emitted(&arena, &.{.{ .name = "r", .match = "a == \"1\"", .target_account = "e:f", .source_account = "assets:other", }}); try expect(std.mem.find(u8, with, "sourceAccount: \"assets:other\"") != null); } test "M1-UI-018: a multi-line expression keeps its shape" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const match = "a == \"1\" and (\n b == \"2\" or\n c == \"3\"\n)"; const text = try emitted(&arena, &.{ruleOf("r", match, "e:f")}); try expectEqualStrings(@embedFile("../testdata/yaml/a_multi_line_expression_keeps_its_shape.yaml"), text); } test "M1-UI-018: a blank line inside a condition gains no trailing whitespace" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // An editor that strips trailing whitespace would otherwise rewrite the // file we just declared canonical. const text = try emitted(&arena, &.{ruleOf("r", "a == \"1\" or\n\nb == \"2\"", "e:f")}); var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |line| { try expectEqualStrings(std.mem.trimEnd(u8, line, " \t"), line); } try expect(std.mem.find(u8, text, "|-\n a == \"1\" or\n\n b == \"2\"\n") != null); } test "M1-UI-018: a name that is not an identifier is quoted" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitted(&arena, &.{ ruleOf("plain", "a == \"1\"", "e:f"), ruleOf("with space", "a == \"2\"", "e:f"), ruleOf("with:colon", "a == \"3\"", "e:f"), ruleOf("true", "a == \"4\"", "e:f"), ruleOf("123", "a == \"5\"", "e:f"), }); try expect(std.mem.find(u8, text, "\n plain:\n") != null); try expect(std.mem.find(u8, text, "\n \"with space\":\n") != null); try expect(std.mem.find(u8, text, "\n \"with:colon\":\n") != null); // Unquoted these would resolve as a boolean and an integer (M1-YAML-005). try expect(std.mem.find(u8, text, "\n \"true\":\n") != null); try expect(std.mem.find(u8, text, "\n \"123\":\n") != null); } test "M1-UI-018: quotes and backslashes in an account are escaped" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitted(&arena, &.{ruleOf("r", "a == \"1\"", "e:say \"hi\"\\x")}); try expect(std.mem.find(u8, text, "\"e:say \\\"hi\\\"\\\\x\"") != null); } test "M1-JRN-010: the file is UTF-8 without a mark, LF, ending in LF" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const text = try emitted(&arena, &.{ruleOf("r", "a == \"1\"", "e:f")}); try expect(!std.mem.startsWith(u8, text, "\xEF\xBB\xBF")); try expect(std.mem.findScalar(u8, text, '\r') == null); try expect(std.mem.endsWith(u8, text, "\n")); } test "M1-SAFE-001: the same rules produce the same bytes" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const rules = [_]Rule{ ruleOf("b", "a == \"1\"", "e:f"), ruleOf("a", "a == \"2\"", "e:g"), }; try expectEqualStrings(try emitted(&arena, &rules), try emitted(&arena, &rules)); } test "M1-UI-018: what is written loads back as the same rules" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); const original = [_]Rule{ .{ .name = "with space", .match = "a == \"1\" and (\n b ~= /x/i\n)", .target_account = "expenses:food", .source_account = "assets:other", }, ruleOf("plain", "c != \"2\"", "expenses:rent"), }; const text = try rulesFile(alloc, &original); const rules = @import("../config/rules.zig"); const diag = @import("../diag.zig"); const diags = try diag.List.create(alloc); const loaded = try rules.load(alloc, "rules.yaml", text, diags); try expectEqual(@as(usize, 2), loaded.rules.len); // Ascending order, so "plain" precedes "with space". try expectEqualStrings("plain", loaded.rules[0].name); try expectEqualStrings("c != \"2\"", loaded.rules[0].match); try expectEqualStrings("with space", loaded.rules[1].name); try expectEqualStrings("a == \"1\" and (\n b ~= /x/i\n)", loaded.rules[1].match); try expectEqualStrings("assets:other", loaded.rules[1].action.?.source_account.?); } test "M1-UI-019: an empty ruleset is refused rather than written" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try std.testing.expectError(error.NoRules, rulesFile(arena.allocator(), &.{})); }