diff options
| author | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 05:59:38 +0000 |
|---|---|---|
| committer | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 05:59:38 +0000 |
| commit | 083c82e259ad508a04617cdfccc40ce728a43195 (patch) | |
| tree | 895aea6dfdc1b825f9991b8f1071816bde3d64d6 /src | |
| parent | 350625683c066a4790f41cb91c8c05ac4fb5dd4f (diff) | |
| download | shell-zig-083c82e259ad508a04617cdfccc40ce728a43195.tar.gz shell-zig-083c82e259ad508a04617cdfccc40ce728a43195.zip | |
codecrafters submit [skip ci]
Diffstat (limited to 'src')
| -rw-r--r-- | src/builtins.zig | 14 | ||||
| -rw-r--r-- | src/shell.zig | 5 |
2 files changed, 18 insertions, 1 deletions
diff --git a/src/builtins.zig b/src/builtins.zig index ea34f19..07c278b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,7 +1,7 @@ const std = @import("std"); const path = @import("path.zig"); -const BUILTINS = [_][]const u8{ "exit", "echo", "type", "pwd" }; +const BUILTINS = [_][]const u8{ "exit", "echo", "type", "pwd", "cd" }; pub const CommandResult = enum { continue_loop, @@ -33,6 +33,18 @@ pub fn executePwd(allocator: std.mem.Allocator, stdout: anytype) !void { try stdout.print("{s}\n", .{cwd}); } +pub fn executeCd(stdout: anytype, args: ?[]const u8) !void { + if (args == null or args.?.len == 0) { + try stdout.print("cd: missing argument\n", .{}); + return; + } + + const dir = std.mem.trim(u8, args.?, " "); + std.posix.chdir(dir) catch { + try stdout.print("cd: {s}: No such file or directory\n", .{dir}); + }; +} + pub fn executeType(allocator: std.mem.Allocator, stdout: anytype, args: ?[]const u8) !void { if (args) |a| { if (isBuiltin(a)) { diff --git a/src/shell.zig b/src/shell.zig index 2494fda..56ca991 100644 --- a/src/shell.zig +++ b/src/shell.zig @@ -22,6 +22,11 @@ pub fn executeCommand( return .continue_loop; } + if (std.mem.eql(u8, cmd_name, "cd")) { + try builtins.executeCd(stdout, args); + return .continue_loop; + } + if (std.mem.eql(u8, cmd_name, "type")) { try builtins.executeType(allocator, stdout, args); return .continue_loop; |