diff --git a/src/commands/builtin_command_runner.ts b/src/commands/builtin_command_runner.ts index 5ca69b6..10af44a 100644 --- a/src/commands/builtin_command_runner.ts +++ b/src/commands/builtin_command_runner.ts @@ -19,12 +19,23 @@ export class BuiltinCommandRunner implements ICommandRunner { if (args.length < 1) { // Do nothing. return; + } else if (args.length > 1) { + throw new Error("cd: too many arguments") + } + + let path = args[0] + if (path == "-") { + const oldPwd = context.environment.get("OLDPWD") + if (oldPwd === null) { + throw new Error("cd: OLDPWD not set") + } + path = oldPwd } - const path = args[0] // Ignore other arguments? - // Need to handle path of "-". Maybe previous path is in an env var? "OLDPWD" const { FS } = context.fileSystem + const oldPwd = FS.cwd() FS.chdir(path) + context.environment.set("OLDPWD", oldPwd) context.environment.set("PWD", FS.cwd()) } } diff --git a/tests/commands/cd.test.ts b/tests/commands/cd.test.ts index 3899e07..f3e54b1 100644 --- a/tests/commands/cd.test.ts +++ b/tests/commands/cd.test.ts @@ -1,11 +1,55 @@ import { shell_setup_simple } from "../shell_setup" describe("cd command", () => { + it("should do nothing if no arguments", async () => { + const { shell, output } = await shell_setup_simple() + await shell._runCommands("cd") + expect(output.text).toEqual("") + }) + + it("should error if more than one argument", async () => { + const { shell, output } = await shell_setup_simple() + await shell._runCommands("cd a b") + expect(output.text).toMatch(/cd: too many arguments/) + }) + + it("should change directory", async () => { + const { shell, output } = await shell_setup_simple() + + await shell._runCommands("pwd") + expect(output.text).toEqual("/drive\r\n") + output.clear() + + await shell._runCommands("cd dirA") + await shell._runCommands("pwd") + expect(output.text).toEqual("/drive/dirA\r\n") + }) + it("should update PWD", async () => { const { shell } = await shell_setup_simple() const { environment } = shell + expect(environment.get("PWD")).toEqual("/drive") await shell._runCommands("cd dirA") expect(environment.get("PWD")).toEqual("/drive/dirA") }) + + it("should support cd -", async () => { + const { shell } = await shell_setup_simple() + const { environment } = shell + + expect(environment.get("OLDPWD")).toBeNull() + await shell._runCommands("cd dirA") + expect(environment.get("PWD")).toEqual("/drive/dirA") + expect(environment.get("OLDPWD")).toEqual("/drive") + await shell._runCommands("cd -") + expect(environment.get("PWD")).toEqual("/drive") + expect(environment.get("OLDPWD")).toEqual("/drive/dirA") + }) + + it("should error if use cd - and OLDPWD not set", async () => { + const { shell, output } = await shell_setup_simple() + await shell._runCommands("cd -") + expect(output.text).toMatch(/cd: OLDPWD not set/) + }) })