68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
|
import type { CommandIO } from "@core/command_io";
|
|
import { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
|
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
|
import { getCurrentSession } from "@core/session_manager";
|
|
import type { ShellState } from "@core/shell_state";
|
|
import type { PathResolutionError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
|
import { resolvePath } from "@core/util/path_resolver";
|
|
|
|
export const COMMAND_NAME = "cat";
|
|
|
|
//Need to implement escape sequences
|
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
|
for (const arg of args) {
|
|
const inode = resolvePath(state, arg);
|
|
if (inode === -1) {
|
|
return {
|
|
state,
|
|
result: createErrorResult(
|
|
"PathResolutionError",
|
|
"No such file or directory",
|
|
{ path: arg },
|
|
COMMAND_NAME,
|
|
),
|
|
} satisfies CommandOutput<PathResolutionError>;
|
|
}
|
|
|
|
// Casting to TreeNode because the resolvePath already ensures the inode is correct;
|
|
const node = state.filesystem.getNode(inode) as TreeNode;
|
|
|
|
if (node.type != TreeNodeType.File) {
|
|
return {
|
|
state,
|
|
result: createErrorResult(
|
|
"PathResolutionError",
|
|
`${node.name} is a directory`,
|
|
{ path: arg },
|
|
COMMAND_NAME,
|
|
),
|
|
} satisfies CommandOutput<PathResolutionError>;
|
|
}
|
|
|
|
const session = getCurrentSession(state);
|
|
|
|
if (!state.filesystem.canRead(inode, session.user)) {
|
|
return {
|
|
state,
|
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
|
|
} satisfies CommandOutput<PermissionDeniedError>;
|
|
}
|
|
|
|
node as FileNode;
|
|
io.writeStdout(node.content.toArray());
|
|
}
|
|
|
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
|
|
|
return {
|
|
state: state,
|
|
result,
|
|
};
|
|
}
|
|
|
|
export const descriptor: CommandDescriptor = {
|
|
fn: main,
|
|
name: COMMAND_NAME,
|
|
};
|