- implemented the rest of long-format compatible ls flags

- split path_resolver functions to 3 separate functions that prioritize different points of relativity
- added a `convertToUnit`function to convert from bytes to higher units of messurement
- revert change: excluded inode 0 from tree traversal results
This commit is contained in:
2026-08-30 17:35:20 +02:00
parent 4776232377
commit 8e054a220d
5 changed files with 243 additions and 108 deletions
+201 -99
View File
@@ -6,7 +6,8 @@ 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 { dnTraverseTree } from "@core/util/tree_traversal";
import { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
import { convertToUnit } from "@termos/util/format_unit";
export const COMMAND_NAME = "ls";
@@ -16,8 +17,8 @@ async function main(
flags: string[],
args: string[],
): Promise<CommandOutput<ShellError>> {
const nodes: number[] = [];
const entries: { inode: number; path: string }[] = [];
const e = new TextEncoder();
const vars = flags.filter(
// Match at least 1 character between each side of a singular = character
f =>
@@ -36,77 +37,125 @@ async function main(
}
const session = getCurrentSession(state);
const timeVar = vars.find(f => f.startsWith("time"))?.split("=")[1];
const sortVar = vars.find(f => f.startsWith("sort"))?.split("=")[1];
nodes.push(session.cwd);
let sortBy: SortTreeNodeBy = sortVar && isValidSortMethod(sortVar) ? sortVar : SortTreeNodeBy.NAME;
let timestamp: SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME =
timeVar && isValidTimestamp(timeVar) ? timeVar : SortTreeNodeBy.ATIME;
for (const arg of args) {
let inode;
try {
inode = resolvePath(state.filesystem, session.cwd, arg);
} catch {
return {
state,
result: createErrorResult(
"PathResolutionError",
`No such file or directory`,
{ path: arg },
COMMAND_NAME,
),
};
}
nodes.push(inode);
}
if (fSet.has("R") || fSet.has("recursive")) {
const treeArray = [];
for (const inode of nodes) {
treeArray.push(...dnTraverseTree(state.filesystem, inode));
}
nodes.length = 0;
nodes.push(...treeArray.filter(node => state.filesystem.getNode(node)?.type !== TreeNodeType.File));
}
for (let i = 0; i < nodes.length; i++) {
const treenode: DirectoryNode = state.filesystem.getNode(nodes[i]!) as DirectoryNode;
io.writeStdout(new TextEncoder().encode(`total ${Object.entries(treenode.children).length}\n`));
// Object.entries returns the touple of Record<string, number> so we get the number by doing c[1] as index 1 in the touple is the number
// We do null assertion because we already made sure in the recursive check that all inodes are correct
let children: TreeNode[] = Object.entries(treenode.children).map(c => state.filesystem.getNode(c[1])!);
if (fSet.has("A")) children = children.filter(c => !c.name.startsWith("."));
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
longMode(io, state, children, fSet);
io.writeStdout(new TextEncoder().encode("\n"));
if (args.length === 0) {
entries.push({ inode: session.cwd, path: "." });
} else {
for (const arg of args) {
let inode;
try {
inode = resolvePath(state, arg);
} catch {
return {
state,
result: createErrorResult(
"PathResolutionError",
`No such file or directory`,
{ path: arg },
COMMAND_NAME,
),
};
}
entries.push({ inode: inode, path: arg });
}
}
io.writeStdout(new TextEncoder().encode("\n"));
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
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`));
}
io.writeStdout(e.encode("\n"));
return {
state,
result: createSuccessResult(COMMAND_NAME),
};
function listDirEntries(entry: { inode: number; path: string }): void {
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
// This method of evaluating flags is faulty, it doesnt respect order;
if (fSet.has("t")) sortBy = timestamp;
if (fSet.has("S")) sortBy = SortTreeNodeBy.SIZE;
if (fSet.has("X")) sortBy = SortTreeNodeBy.EXTENSION;
if (fSet.has("R") || fSet.has("recursive")) io.writeStdout(e.encode(`${entry.path}:\n`));
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!);
if (!fSet.has("f") || !fSet.has("U"))
children = sortTreeNodes(state, children, fSet.has("r") || fSet.has("reverse"), sortBy);
if (fSet.has("a") || fSet.has("A") || fSet.has("all") || fSet.has("almost-all") || fSet.has("f"))
children = children.filter(c => !c.name.startsWith("."));
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
longMode(io, state, children, fSet);
io.writeStdout(e.encode("\n"));
}
if (fSet.has("R") || fSet.has("recursive")) {
for (const child of children) {
if (child.type === TreeNodeType.Directory) {
let path;
if (entry.path === "/") {
path = "/" + child.name;
} else if (entry.path.endsWith("/")) {
path = entry.path + child.name;
} else path = entry.path + "/" + child.name;
listDirEntries({ inode: child.inode, path });
}
}
}
}
}
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Set<string>): void {
const e = new TextEncoder();
if (flags.has("a") || flags.has("all") || flags.has("f")) {
const cwdNode = state.filesystem.getNode(nodes[0]!.parent)!;
const parentNode = state.filesystem.getNode(cwdNode.parent)!;
const parent: TreeNode = { ...parentNode, name: ".." };
nodes.unshift(parent);
const cwd: TreeNode = { ...cwdNode, name: "." };
nodes.unshift(cwd);
}
// 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.inode.toString().length));
const maxSizeWidth = Math.max(
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
);
const maxChildrenWidth = Math.max(
...nodes.map(c =>
c.type === TreeNodeType.Directory ? Object.entries(c.children).length.toString().length : 2,
),
);
for (const node of nodes) {
if (flags.has("i") || flags.has("inode")) {
io.writeStdout(e.encode(node.inode.toString() + " "));
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
io.writeStdout(e.encode(inode + " "));
}
const mode: string = parseMode(node.mode);
@@ -120,31 +169,74 @@ function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Se
break;
}
if (node.type === TreeNodeType.File) {
io.writeStdout(e.encode("0" + " "));
const childAmnt =
node.type === TreeNodeType.Directory
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
: `${"10".padStart(maxChildrenWidth, " ")} `;
io.writeStdout(e.encode(childAmnt));
if (flags.has("o") || flags.has("G") || flags.has("no-group")) {
io.writeStdout(e.encode(`${state.users.get(node.owner)?.username} `));
} else if (flags.has("g")) {
io.writeStdout(e.encode(`${state.groups.get(node.group)?.groupname} `));
} else if (flags.has("n") || flags.has("numeric-uid-gid")) {
io.writeStdout(e.encode(`${node.owner} ${node.group} `));
} else {
io.writeStdout(e.encode(Object.entries(node.children).length.toString() + " "));
io.writeStdout(
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
);
}
io.writeStdout(
e.encode(state.users.get(node.owner)?.username + " " + state.groups.get(node.group)?.groupname + " "),
);
// 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
const size =
node.type === TreeNodeType.File
? node.content.byteSize().toString().padStart(maxSizeWidth, " ") + " "
: "4096".padStart(maxSizeWidth, " ") + " ";
let size;
if (flags.has("h") || flags.has("human-readable")) {
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
size = convertToUnit(bytes, 1, flags.has("si") ? 1000 : 1024);
} else {
size =
node.type === TreeNodeType.File
? `${node.content.byteSize().toString().padStart(maxSizeWidth, " ")} `
: `${"4096".padStart(maxSizeWidth, " ")} `;
}
io.writeStdout(e.encode(size));
// for now only mtime, need a helper function for all the formatting later on
const mtime = new Date(node.mtime);
io.writeStdout(
// Month + 1 because January is 0
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}-${mtime.getMinutes()} `),
);
io.writeStdout(e.encode(node.name + "\n"));
if (flags.has("full-time")) {
io.writeStdout(
// Month + 1 because January is 0
e.encode(
`${mtime.getFullYear()}-${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `,
),
);
} else {
io.writeStdout(
// Month + 1 because January is 0
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `),
);
}
const appendSlash = flags.has("p");
if (flags.has("Q") || flags.has("quote-name")) {
io.writeStdout(
e.encode(
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (appendSlash ? "/" : "") : node.name + '"'}\n`,
),
);
} else if (!flags.has("N") || !flags.has("literal")) {
io.writeStdout(
e.encode(
`${node.type === TreeNodeType.Directory ? node.name + (appendSlash ? "/" : "") : node.name}\n`,
),
);
} else {
const name = `${node.name.includes(" ") ? "'" + node.name + "'" : node.name}`;
io.writeStdout(
e.encode(`${node.type === TreeNodeType.Directory ? name + (appendSlash ? "/" : "") : name}\n`),
);
}
}
}
@@ -164,49 +256,59 @@ function parseMode(mode: number) {
return map(owner) + map(group) + map(other);
}
function isValidSortMethod(value: string): value is SortTreeNodeBy {
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
}
function isValidTimestamp(value: string): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
return Object.values(SortTreeNodeBy).includes(
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
);
}
export const descriptor: CommandDescriptor = {
fn: main,
flags: [
{ name: "l" },
{ name: "a" },
{ name: "A" },
{ name: "l" }, // done
{ name: "a" }, // done
{ name: "A" }, // done
{ name: "c" },
{ name: "U" },
{ name: "g" },
{ name: "G" },
{ name: "h" },
{ name: "f" },
{ name: "U" }, // done
{ name: "g" }, // done
{ name: "G" }, // done
{ name: "h" }, // done
{ name: "f" }, // done
{ name: "x" },
{ name: "X" },
{ name: "X" }, // done
{ name: "u" },
{ name: "t" },
{ name: "S" },
{ name: "r" },
{ name: "R" },
{ name: "Q" },
{ name: "p" },
{ name: "o" },
{ name: "n" },
{ name: "N" },
{ 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" },
{ name: "sort", takesValue: true },
{ name: "time", takesValue: true },
{ name: "i" }, // done
{ name: "sort", takesValue: true }, // done
{ name: "time", takesValue: true }, // done
{ name: "help" },
{ name: "all" },
{ name: "almost-all" },
{ name: "no-group" },
{ name: "human-readable" },
{ name: "reverse" },
{ name: "recursive" },
{ name: "quote-name" },
{ name: "indicator-style" },
{ name: "literal" },
{ name: "numeric-uid-gid" },
{ name: "inode" },
{ name: "si" },
{ 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: COMMAND_NAME,
name: "ls",
};