about summary refs log tree commit diff
path: root/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig46
1 files changed, 43 insertions, 3 deletions
diff --git a/src/main.zig b/src/main.zig
index 64b76d9..e6ed977 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -364,14 +364,54 @@ fn genSite(ctx: *Context) !void {
     }
 }
 
+const FileSwapper = struct {
+    allocator: std.mem.Allocator,
+    target_path: []const u8,
+    tmp_path: []const u8,
+    tmp: std.fs.File,
+
+    fn createAt(allocator: std.mem.Allocator, path: []const u8) !FileSwapper {
+        const target_dir = std.fs.path.dirname(path) orelse ".";
+        const target_name = std.fs.path.basename(path);
+
+        const tmp_name = try std.fmt.allocPrint(allocator, ".{s}", .{target_name});
+        defer allocator.free(tmp_name);
+
+        const tmp_path = try std.fs.path.join(allocator, &.{ target_dir, tmp_name });
+
+        const f = try std.fs.cwd().createFile(tmp_path, .{});
+
+        return .{
+            .allocator = allocator,
+            .target_path = path,
+            .tmp_path = tmp_path,
+            .tmp = f,
+        };
+    }
+
+    fn writer(self: FileSwapper) std.fs.File.Writer {
+        return self.tmp.writer();
+    }
+
+    fn close(self: FileSwapper) void {
+        defer self.allocator.free(self.tmp_path);
+        defer self.tmp.close();
+
+        self.tmp.sync() catch @panic("sync tmp file");
+
+        std.debug.print("??? {s} => {s}\n", .{ self.tmp_path, self.target_path });
+        std.fs.rename(std.fs.cwd(), self.tmp_path, std.fs.cwd(), self.target_path) catch @panic("rename tmp file");
+    }
+};
+
 fn genIndexHtml(ctx: *Context) !void {
     const srcpathIndex = try joinIn(ctx.allocator, &.{PAGE_PATH}, &.{"index.htm"});
     defer ctx.allocator.free(srcpathIndex);
 
-    const f = try std.fs.cwd().createFile(srcpathIndex, .{});
+    const f = try FileSwapper.createAt(ctx.allocator, srcpathIndex);
     defer f.close();
 
-    try f.writeAll(
+    try f.writer().writeAll(
         \\<ul class="col2 captial">
         \\
     );
@@ -404,7 +444,7 @@ fn genIndexHtml(ctx: *Context) !void {
         });
     }
 
-    try f.writeAll(
+    try f.writer().writeAll(
         \\</ul>
         \\
     );