79 lines
2.5 KiB
TypeScript
79 lines
2.5 KiB
TypeScript
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
|
import type { CommandIO } from "@core/command_io";
|
|
import type { NodePointer } from "@core/filesystem/node";
|
|
import { createErrorResult, createSuccessResult } from "@core/result";
|
|
import { getCurrentSession } from "@core/session_manager";
|
|
import { ShellState, withCwd } from "@core/shell_state";
|
|
import {
|
|
type InvalidArgumentsError,
|
|
type PathResolutionError,
|
|
type PermissionDeniedError,
|
|
type ShellError,
|
|
} from "@core/util/errors";
|
|
import { resolvePath } from "@core/util/path_resolver";
|
|
|
|
export const COMMAND_NAME = "cd";
|
|
|
|
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
|
if (args.length > 1) {
|
|
return {
|
|
state,
|
|
result: createErrorResult(
|
|
"InvalidArguments",
|
|
"The maximum ammount of arguments for this command is 1",
|
|
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
|
COMMAND_NAME,
|
|
),
|
|
} satisfies CommandOutput<InvalidArgumentsError>;
|
|
}
|
|
|
|
let ptr: NodePointer;
|
|
const session = getCurrentSession(state);
|
|
|
|
if (args[0] === undefined) {
|
|
ptr = session.user.home;
|
|
} else if (args[0] === "-") {
|
|
ptr = session.pwd;
|
|
} else {
|
|
try {
|
|
ptr = resolvePath(state, args[0]);
|
|
} catch (e) {
|
|
return {
|
|
state,
|
|
result: createErrorResult(
|
|
"PathResolutionError",
|
|
"No such file or directory",
|
|
{ path: args[0]! },
|
|
COMMAND_NAME,
|
|
),
|
|
} satisfies CommandOutput<PathResolutionError>;
|
|
}
|
|
}
|
|
|
|
if (state.filesystem.isFile(ptr)) {
|
|
return {
|
|
state,
|
|
result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME),
|
|
} satisfies CommandOutput<PathResolutionError>;
|
|
}
|
|
|
|
if (!state.filesystem.canExecute(ptr, session.user)) {
|
|
return {
|
|
state,
|
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
|
|
} satisfies CommandOutput<PermissionDeniedError>;
|
|
}
|
|
|
|
const returnState = withCwd(state, ptr);
|
|
|
|
return {
|
|
state: returnState,
|
|
result: createSuccessResult(COMMAND_NAME),
|
|
};
|
|
}
|
|
|
|
export const descriptor: CommandDescriptor = {
|
|
fn: main,
|
|
name: COMMAND_NAME,
|
|
};
|