|
| 1 | +const std = @import("std"); |
| 2 | +const testing = std.testing; |
| 3 | + |
| 4 | +name: []const u8, |
| 5 | +content: Content, |
| 6 | +allocator: std.mem.Allocator, |
| 7 | + |
| 8 | +const Section = @This(); |
| 9 | + |
| 10 | +pub fn init(allocator: std.mem.Allocator, name: []const u8, content: Content) Section { |
| 11 | + return .{ |
| 12 | + .allocator = allocator, |
| 13 | + .name = name, |
| 14 | + .content = content, |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +const Content = union(enum) { |
| 19 | + raw: []const u8, |
| 20 | + file_path: []const u8, |
| 21 | + |
| 22 | + pub fn get(self: Content, allocator: std.mem.Allocator) ![]const u8 { |
| 23 | + switch (self) { |
| 24 | + .file_path => |f| return try readFileToString(allocator, f), |
| 25 | + .raw => |r| return r, |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + fn readFileToString(allocator: std.mem.Allocator, file_path: []const u8) ![]const u8 { |
| 30 | + var file = try std.fs.openFileAbsolute(file_path, .{}); |
| 31 | + defer file.close(); |
| 32 | + |
| 33 | + const file_size = try file.getEndPos(); |
| 34 | + var buffer = try allocator.alloc(u8, file_size); |
| 35 | + errdefer allocator.free(buffer); |
| 36 | + |
| 37 | + const read = try file.readAll(buffer); |
| 38 | + return buffer[0..read]; |
| 39 | + } |
| 40 | + |
| 41 | + pub fn isFile(self: Content) bool { |
| 42 | + switch (self) { |
| 43 | + .file_path => return true, |
| 44 | + .raw => return false, |
| 45 | + } |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +test "section raw" { |
| 50 | + const alloc = testing.allocator; |
| 51 | + |
| 52 | + const raw = |
| 53 | + \\ <h1>Title</h2> |
| 54 | + \\ <p>Something</p> |
| 55 | + ; |
| 56 | + |
| 57 | + var section = Section.init(alloc, "chapter1", .{ .raw = raw }); |
| 58 | + try testing.expectEqualStrings(raw, try section.content.get(alloc)); |
| 59 | +} |
| 60 | + |
| 61 | +test "section file" { |
| 62 | + const alloc = testing.allocator; |
| 63 | + |
| 64 | + const cwd_path = try std.fs.cwd().realpathAlloc(alloc, "."); |
| 65 | + defer alloc.free(cwd_path); |
| 66 | + const absolute_path = try std.fs.path.resolve(alloc, &.{ cwd_path, "README.md" }); |
| 67 | + defer alloc.free(absolute_path); |
| 68 | + |
| 69 | + var section = Section.init(alloc, "chapter2", .{ .file_path = absolute_path }); |
| 70 | + const value = try section.content.get(alloc); |
| 71 | + defer alloc.free(value); |
| 72 | + try testing.expectEqualStrings("zig-epub", value[2..10]); |
| 73 | +} |
| 74 | + |
| 75 | +test "section file error" { |
| 76 | + const alloc = testing.allocator; |
| 77 | + var section = Section.init(alloc, "chapter3", .{ .file_path = "/no_existent" }); |
| 78 | + try testing.expectError(error.FileNotFound, section.content.get(alloc)); |
| 79 | +} |
0 commit comments