import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandIO } from "@core/command_io"; import { NodePointer, NodeType, type DirectoryNode, type FileNode, type Node } from "@core/filesystem/node"; import { createErrorResult, createSuccessResult } from "@core/result"; import { getCurrentSession } from "@core/session_manager"; import type { ShellState } from "@core/shell_state"; import type { ShellError } from "@core/util/errors"; import { resolvePath } from "@core/util/path_resolver"; import { SortNodeBy, sortNodes } from "@core/util/sort"; import { concatUint8Arrays } from "@termos/util/concat"; import { convertToUnit } from "@termos/util/format_unit"; export const COMMAND_NAME = "ls"; interface DirEntry { name: string; ptr: NodePointer; } async function main(io: CommandIO, state: ShellState, args: string[]): Promise> { const entries: { ptr: NodePointer; path: string }[] = []; const paths: string[] = []; const e = new TextEncoder(); let options = { all: false, almostAll: false, long: false, noSort: false, noOwner: false, noGroup: false, sortBy: SortNodeBy.NAME, humanReadable: false, f: false, x: false, timestamp: "atime", reverse: false, recursive: false, quoteName: false, appendIndicator: false, numericUidGid: false, literal: false, inode: false, si: false, dereference: false, fullTime: false, }; for (let arg of args) { let val; if (arg.startsWith("--")) { arg = arg.slice(2); if (arg.match(/\w+[=]{1}\w+/g)) { const flag = arg.split("=")[0]; val = arg.split("=")[1] ?? ""; if (flag === "time" && isValidTimestamp(val)) { options.timestamp = val; continue; } if (flag === "sort" && isValidSortMethod(val)) { options.sortBy = val as SortNodeBy; continue; } return { state, result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME), }; } switch (arg) { case "all": options.all = true; break; case "almost-all": options.almostAll = true; break; case "no-group": options.noGroup = true; break; case "human-readable": options.humanReadable = true; break; case "reverse": options.reverse = true; break; case "recursive": options.recursive = true; break; case "quote-name": options.quoteName = true; break; case "numeric-uid-gid": options.numericUidGid = true; break; case "inode": options.inode = true; break; case "dereference": options.dereference = true; break; case "literal": options.literal = true; break; case "si": options.si = true; options.humanReadable = true; break; case "full-time": options.fullTime = true; break; case "help": // handled separately break; default: return { state, result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME), }; break; } } else if (arg.startsWith("-")) { arg = arg.slice(1); for (const c of arg) { switch (c) { case "l": options.long = true; break; case "a": options.all = true; break; case "A": options.almostAll = true; break; case "c": options.timestamp = "ctime"; break; case "U": options.noSort = true; break; case "g": options.noOwner = true; options.long = true; break; case "G": options.noGroup = true; break; case "h": options.humanReadable = true; break; case "f": options.f = true; options.noSort = true; options.all = true; break; case "x": options.x = true; break; case "X": options.sortBy = SortNodeBy.EXTENSION; break; case "u": options.timestamp = "atime"; break; case "t": options.sortBy = options.timestamp as SortNodeBy; break; case "S": options.sortBy = SortNodeBy.SIZE; break; case "r": options.reverse = true; break; case "R": options.recursive = true; break; case "Q": options.quoteName = true; break; case "p": options.appendIndicator = true; break; case "o": options.noGroup = true; options.long = true; break; case "n": options.numericUidGid = true; break; case "N": options.literal = true; break; case "i": options.inode = true; break; case "L": options.dereference = true; break; case "m": // -m: comma separated list (not in options yet) break; default: return { state, result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME), }; } } } else { paths.push(arg); } } const session = getCurrentSession(state); if (paths.length === 0) { entries.push({ ptr: session.cwd, path: "." }); } else { for (const path of paths) { let ptr; try { ptr = resolvePath(state, path); } catch { return { state, result: createErrorResult( "PathResolutionError", `No such file or directory`, { path }, COMMAND_NAME, ), }; } entries.push({ ptr, path }); } } if (options.long) { for (const entry of entries) { listDirEntries(entry); } } else { for (const entry of entries) { //shortDirEntries(entry); } io.writeStdout(e.encode(`No support for short format yet\n`)); } return { state, result: createSuccessResult(COMMAND_NAME), }; function listDirEntries(entry: { ptr: NodePointer; path: string }): void { const node = state.filesystem.getNode(entry.ptr) as DirectoryNode; if (options.recursive) io.writeStdout(e.encode(`${entry.path}:\n`)); io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`)); let children: DirEntry[] = Array.from(node.children.entries()).map(([name, inode]) => ({ name, ptr: NodePointer.of(entry.ptr.device, inode), })); if (!options.noSort) children = sortNodes(state, children, options.reverse, options.sortBy); if (!options.all && !options.almostAll) { children = children.filter(c => !c.name.startsWith(".")); } if (options.long) { longMode(io, state, children); if (options.recursive) io.writeStdout(e.encode("\n")); } if (options.recursive) { for (const c of children) { if (c.name.match(/^[.]{1,2}$/)) continue; const child = state.filesystem.getNode(c.ptr)!; if (child.type === NodeType.Directory) { let path; if (entry.path === "/") { path = "/" + c.name; } else if (entry.path.endsWith("/")) { path = entry.path + c.name; } else path = entry.path + "/" + c.name; listDirEntries({ ptr: c.ptr, path }); } } } } function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void { const e = new TextEncoder(); const buff: Uint8Array[] = []; const nodes: DirEntry[] = [...children]; // Calculate the string size of the biggerst node in the array; // Sets 4 length for directories because the arbitrary size is 4096 later in the code const maxInodeWidth = Math.max(...nodes.map(c => c.ptr.inode.toString().length)); const maxSizeWidth = Math.max( ...nodes.map(c => state.filesystem.getNode(c.ptr)!.type === NodeType.File ? (state.filesystem.getNode(c.ptr) as FileNode).size.toString().length : 4, ), ); const maxLinksWidth = Math.max( ...nodes.map((c): number => { const node = state.filesystem.getNode(c.ptr)!; const o = node.link_count.toString().length; return o; }), ); const namePadding = nodes.every(c => !c.name.includes(" ")); for (const n of nodes) { const node = state.filesystem.getNode(n.ptr)!; if (options.inode) { const inode = node.inode.toString().padStart(maxInodeWidth, " "); buff.push(e.encode(inode + " ")); } // Mode const mode: string = parseMode(node.mode); switch (node.type) { case NodeType.Directory: buff.push(e.encode("d" + mode + " ")); break; case NodeType.File: buff.push(e.encode("-" + mode + " ")); break; } //Link count const linkCount = node.link_count.toString().padStart(maxLinksWidth, " ") + " "; buff.push(e.encode(linkCount)); // owner group if (options.noGroup) { buff.push(e.encode(`${state.users.get(node.owner)?.username} `)); } else if (options.noOwner) { buff.push(e.encode(`${state.groups.get(node.group)?.groupname} `)); } else if (options.numericUidGid) { buff.push(e.encode(`${node.owner} ${node.group} `)); } else { buff.push( e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `), ); } //Size // Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows // Sets the folder size to an arbitrary 4096, could change it later to smth else let size; if (options.humanReadable) { const bytes = node.type === NodeType.File ? node.size : 4096; size = convertToUnit(bytes, 1, options.si ? 1000 : 1024); } else { size = node.type === NodeType.File ? `${node.size.toString().padStart(maxSizeWidth, " ")} ` : `${"4096".padStart(maxSizeWidth, " ")} `; } buff.push(e.encode(size)); //Timestamp const date = getDateTimestamp(node, options.timestamp); if (options.fullTime) { buff.push( // Month + 1 because January is 0 e.encode( `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `, ), ); } else { buff.push( // Month + 1 because January is 0 e.encode(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()} `), ); } //Name if (options.quoteName) { buff.push( e.encode( `"${node.type === NodeType.Directory ? n.name + '"' + (options.appendIndicator ? "/" : "") : n.name + '"'}\n`, ), ); } else { const unpadded = `${n.name.includes(" ") && !options.literal ? "'" + n.name + "'" : n.name}`; const name = `${!namePadding ? (unpadded.includes(" ") ? unpadded : " " + unpadded) : unpadded}`; buff.push( e.encode( `${node.type === NodeType.Directory ? name + (options.appendIndicator ? "/" : "") : name}\n`, ), ); } } const out = concatUint8Arrays(buff); io.writeStdout(out); } function getDateTimestamp(node: Node, ts: string): Date { if (ts === "atime") return new Date(node.atime); if (ts === "ctime") return new Date(node.ctime); if (ts === "mtime") return new Date(node.mtime); return new Date(); } function parseMode(mode: number) { const owner = (mode >> 6) & 7; const group = (mode >> 3) & 7; const other = mode & 7; const map = (bits: number) => { let s = ""; s += bits & 4 ? "r" : "-"; s += bits & 2 ? "w" : "-"; s += bits & 1 ? "x" : "-"; return s; }; return map(owner) + map(group) + map(other); } function isValidSortMethod(value: string): value is SortNodeBy { return Object.values(SortNodeBy).includes(value as SortNodeBy); } function isValidTimestamp(value: string): value is SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME { return Object.values(SortNodeBy).includes(value as SortNodeBy.ATIME | SortNodeBy.MTIME | SortNodeBy.CTIME); } } //function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {} export const descriptor: CommandDescriptor = { fn: main, flags: [ { name: "l" }, // done { name: "a" }, // done { name: "A" }, // done { name: "c" }, { name: "U" }, // done { name: "g" }, // done { name: "G" }, // done { name: "h" }, // done { name: "f" }, // done { name: "x" }, { name: "X" }, // done { name: "u" }, { name: "t" }, // done { name: "S" }, // done { name: "r" }, // done { name: "R" }, // done { name: "Q" }, // done { name: "p" }, // done { name: "o" }, // done { name: "n" }, // done { name: "N" }, // done { name: "L" }, { name: "m" }, { name: "i" }, // done { name: "sort", takesValue: true }, // done { name: "time", takesValue: true }, // done { name: "help" }, { name: "all" }, // done { name: "almost-all" }, // done { name: "full-time" }, // done { name: "no-group" }, // done { name: "human-readable" }, // done { name: "reverse" }, // done { name: "recursive" }, // done { name: "quote-name" }, // done { name: "literal" }, // done { name: "numeric-uid-gid" }, // done { name: "inode" }, // done { name: "si" }, // done { name: "dereference" }, ], name: "ls", };