Fix cd command

This commit is contained in:
Alex Gleason committed 2025-09-20 10:53:56 -05:00
1 parent ba24edc7fe
commit ace3e0b3ac
3 files changed
+27 -12

No files matched your search

+3 -2
View File
@@ -78,15 +78,16 @@ Change the current working directory.
**Examples:**
```bash
cd # Go to project root
cd # Stay in current directory
cd src/ # Change to src directory
cd .. # Go to parent directory
cd . # Stay in current directory
cd /projects/my-project # Change to absolute path
```
**Features:**
- Changes working directory for subsequent commands
- Supports relative paths (., .., subdirectories)
- Supports both relative and absolute paths
- Validates target exists and is a directory
- Updates shell working directory state
+16 -2
View File
@@ -98,11 +98,25 @@ describe('CdCommand', () => {
expect(result.stderr).toContain('Not a directory');
});
it('should reject absolute paths', async () => {
it('should handle absolute paths to non-existent directories', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await cdCommand.execute(['/absolute/path'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('No such file or directory');
});
it('should handle absolute paths to existing directories', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
const result = await cdCommand.execute(['/projects/my-project'], testCwd);
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe('/projects/my-project');
});
it('should reject too many arguments', async () => {
+8 -8
View File
@@ -2,6 +2,7 @@ import { join, resolve, dirname } from "@std/path";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath } from "../security";
/**
* Implementation of the 'cd' command
@@ -31,20 +32,19 @@ export class CdCommand implements ShellCommand {
return createErrorResult(`${this.name}: too many arguments`);
}
// Handle absolute paths
if (targetPath.startsWith('/') || targetPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(targetPath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${targetPath}`);
}
// Resolve the new path
// Handle both absolute and relative paths
let newCwd: string;
if (targetPath === '.') {
if (isAbsolutePath(targetPath)) {
// Absolute path - use it directly
newCwd = targetPath;
} else if (targetPath === '.') {
// Current directory
newCwd = cwd;
} else if (targetPath === '..') {
// Parent directory
const parentPath = dirname(cwd);
// Don't allow going above the project root
// Don't allow going above the filesystem root
if (parentPath === cwd) {
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
}