const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const paths = @import("../paths.zig"); const formatDosPath = paths.formatDosPath; const types = @import("./lib/types.zig"); const CommandStatus = types.CommandStatus; const CommandContext = types.CommandContext; pub const Chdir = struct { path: []const u8, pub fn eval(chdir: Chdir, ctx: CommandContext) !CommandStatus { if (chdir.path.len == 0) { // No arguments - display current directory const cwd = std.fs.cwd().realpathAlloc(ctx.allocator, ".") catch { const error_msg = "Unable to determine current directory\n"; if (ctx.output_capture) |capture| { try capture.write(error_msg); } else { print("{s}", .{error_msg}); } return CommandStatus{ .Code = 1 }; }; defer ctx.allocator.free(cwd); const formatted_path = try formatDosPath(ctx.allocator, cwd); defer ctx.allocator.free(formatted_path); const output = try std.fmt.allocPrint(ctx.allocator, "{s}\n", .{formatted_path}); defer ctx.allocator.free(output); if (ctx.output_capture) |capture| { try capture.write(output); } else { print("{s}", .{output}); } return CommandStatus{ .Code = 0 }; } else { // Change directory const target_path = chdir.path; // Handle special cases if (std.mem.eql(u8, target_path, "..")) { // Go to parent directory std.process.changeCurDir("..") catch { const error_msg = "The system cannot find the path specified.\n"; if (ctx.output_capture) |capture| { try capture.write(error_msg); } else { print("{s}", .{error_msg}); } return CommandStatus{ .Code = 1 }; }; } else if (std.mem.eql(u8, target_path, "\\") or std.mem.eql(u8, target_path, "/")) { // Go to root directory - simplified to just go to "/" std.process.changeCurDir("/") catch { const error_msg = "The system cannot find the path specified.\n"; if (ctx.output_capture) |capture| { try capture.write(error_msg); } else { print("{s}", .{error_msg}); } return CommandStatus{ .Code = 1 }; }; } else { // Regular directory change // Make sure the path doesn't contain null bytes for (target_path) |ch| { if (ch == 0) { const error_msg = "Invalid path: contains null character\n"; if (ctx.output_capture) |capture| { try capture.write(error_msg); } else { print("{s}", .{error_msg}); } return CommandStatus{ .Code = 1 }; } } std.process.changeCurDir(target_path) catch { const error_msg = "The system cannot find the path specified.\n"; if (ctx.output_capture) |capture| { try capture.write(error_msg); } else { print("{s}", .{error_msg}); } return CommandStatus{ .Code = 1 }; }; } return CommandStatus{ .Code = 0 }; } } };