diff --git a/src/main.zig b/src/main.zig index a54a7c5..502c52b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -28,12 +28,6 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: var) !void { const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); - var file = try std.fs.File.openWrite(scri_path); - defer file.close(); - - var out = file.outStream(); - var stream = &out.stream; - // the thing here is that 'load :0' would load the scri_path, since we // now have a 'repl' argument right before it. to counteract that, the // initial repl buffer contains 'load :1' instead. @@ -49,6 +43,37 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: var) !void { defer cmds.deinit(); + // if the scri file already had commands, we add them up on the cmd list + var file_read = try std.fs.openReead(scri_path); + const total_bytes = try file_read.getEndPos(); + + if (total_bytes > 0) { + var scri_existing = try allocator.alloc(u8, total_bytes); + defer allocator.free(scri_existing); + + _ = try file.read(slice); + file_read.close(); + + var existing_cmds = try lang.parse(scri_existing); + defer existing_cmds.deinit(); + + // copy the existing command list into the repl's command list + var it = existing_cmds.iterator(); + while (it.next()) |existing_cmd| { + try cmds.append(existing_cmd); + } + } + + var file = try std.fs.File.openWrite(scri_path); + defer file.close(); + + var out = file.outStream(); + var stream = &out.stream; + + // since we opened the file for writing, it becomes empty, so, to ensure + // we don't fuck up later on, we print cmds before starting the repl + try printer.printList(cmds, stream); + // we keep // - a CommandList with the full commands we have right now // - a Command with the current last typed successful command @@ -99,6 +124,8 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: var) !void { try printer.printList(cmds, stdout); continue; } else if (std.mem.eql(u8, line, "save")) { + // seek to 0 instead of appending the new command + // NOTE appending single command might be faster try file.seekTo(0); try printer.printList(cmds, stream); continue;