diff options
| author | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 08:40:08 +0000 |
|---|---|---|
| committer | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 08:40:08 +0000 |
| commit | b92ef57d9cfb3b8b51848d3a2940b0b2251c0529 (patch) | |
| tree | 0ad31ed29a5175bf142e45a5d93a9a37b2ad4c41 | |
| parent | 379cdbd946dfb035e61f96653db618cba4906864 (diff) | |
| download | shell-zig-b92ef57d9cfb3b8b51848d3a2940b0b2251c0529.tar.gz shell-zig-b92ef57d9cfb3b8b51848d3a2940b0b2251c0529.zip | |
codecrafters submit [skip ci]
| -rw-r--r-- | src/builtins.zig | 13 | ||||
| -rw-r--r-- | src/shell.zig | 8 |
2 files changed, 20 insertions, 1 deletions
diff --git a/src/builtins.zig b/src/builtins.zig index a0d844b..8ce4a6f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -168,3 +168,16 @@ pub fn executeHistoryRead(allocator: std.mem.Allocator, stdout: anytype, file_pa } } } + +pub fn executeHistoryWrite(stdout: anytype, file_path: []const u8, history_list: []const []const u8) !void { + const file = std.fs.cwd().createFile(file_path, .{}) catch { + try stdout.print("history: cannot write to {s}: error\n", .{file_path}); + return; + }; + defer file.close(); + + for (history_list) |cmd| { + try file.writeAll(cmd); + try file.writeAll("\n"); + } +} diff --git a/src/shell.zig b/src/shell.zig index fd72288..5a848af 100644 --- a/src/shell.zig +++ b/src/shell.zig @@ -24,7 +24,7 @@ pub fn executeCommand( if (std.mem.eql(u8, cmd_name, "exit")) return builtins.executeExit(); if (std.mem.eql(u8, cmd_name, "history")) { - // Check if args contain -r flag for reading from file + // Check if args contain -r or -w flag for reading/writing file if (args) |a| { const trimmed = std.mem.trim(u8, a, " "); if (std.mem.startsWith(u8, trimmed, "-r ")) { @@ -33,6 +33,12 @@ pub fn executeCommand( try builtins.executeHistoryRead(allocator, stdout, file_path, history); } return .continue_loop; + } else if (std.mem.startsWith(u8, trimmed, "-w ")) { + const file_path = std.mem.trim(u8, trimmed[3..], " "); + if (file_path.len > 0) { + try builtins.executeHistoryWrite(stdout, file_path, history.items); + } + return .continue_loop; } } |