Compare commits
55
Commits
c39bbae091
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41739d7cf9 | ||
|
|
dbffe5375e | ||
|
|
57773fc2ef | ||
|
|
9a31a5985b | ||
|
|
d825299e26 | ||
|
|
2cf84ccd2f | ||
|
|
204d713f91 | ||
|
|
af6a9c8bda | ||
|
|
7310ae9671 | ||
|
|
031f8f7726 | ||
|
|
ed8c27677c | ||
|
|
f4a74f67cf | ||
|
|
2f25e44681 | ||
|
|
d4ec6b0c49 | ||
|
|
de1ce64226 | ||
|
|
d5566aa494 | ||
|
|
cb9cd7a67a | ||
|
|
b161e42b3f | ||
|
|
492f1ba372 | ||
|
|
00200b4c75 | ||
|
|
584e594726 | ||
|
|
4fa284de13 | ||
|
|
dd804f6f14 | ||
|
|
832fc6c759 | ||
|
|
2a6e6c57c3 | ||
|
|
f2b5f86a6c | ||
|
|
933b1fc5e8 | ||
|
|
849e0e61f5 | ||
|
|
d642ee6258 | ||
|
|
9c5bd71a5c | ||
|
|
ec13299e95 | ||
|
|
e2ade5de29 | ||
|
|
b75e691a0b | ||
|
|
776a93e21b | ||
|
|
6cc9727091 | ||
|
|
2715e5e28e | ||
|
|
8a349330b0 | ||
|
|
2e9227f6d8 | ||
|
|
8e054a220d | ||
|
|
4776232377 | ||
|
|
d0f8376244 | ||
|
|
f1b69bb282 | ||
|
|
1b3314ab87 | ||
|
|
96e15a87f2 | ||
|
|
55b5d3a873 | ||
|
|
1ee2a2fe7a | ||
|
|
310218663d | ||
|
|
20718604e4 | ||
|
|
dad18cd4cc | ||
|
|
48aac3c883 | ||
|
|
268729bb62 | ||
|
|
e313aa5b9d | ||
|
|
16a1805f25 | ||
|
|
075c999435 | ||
|
|
dfa393b4d9 |
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
Vendored
+33
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"file-explorer": true,
|
||||||
|
"global-search": true,
|
||||||
|
"switcher": true,
|
||||||
|
"graph": true,
|
||||||
|
"backlink": true,
|
||||||
|
"canvas": true,
|
||||||
|
"outgoing-link": true,
|
||||||
|
"tag-pane": true,
|
||||||
|
"footnotes": false,
|
||||||
|
"properties": true,
|
||||||
|
"page-preview": true,
|
||||||
|
"daily-notes": true,
|
||||||
|
"templates": true,
|
||||||
|
"note-composer": true,
|
||||||
|
"command-palette": true,
|
||||||
|
"slash-command": false,
|
||||||
|
"editor-status": true,
|
||||||
|
"bookmarks": true,
|
||||||
|
"markdown-importer": false,
|
||||||
|
"zk-prefixer": false,
|
||||||
|
"random-note": false,
|
||||||
|
"outline": true,
|
||||||
|
"word-count": true,
|
||||||
|
"slides": false,
|
||||||
|
"audio-recorder": false,
|
||||||
|
"workspaces": false,
|
||||||
|
"file-recovery": true,
|
||||||
|
"publish": false,
|
||||||
|
"sync": true,
|
||||||
|
"bases": true,
|
||||||
|
"webviewer": false
|
||||||
|
}
|
||||||
Vendored
+196
@@ -0,0 +1,196 @@
|
|||||||
|
{
|
||||||
|
"main": {
|
||||||
|
"id": "89ee32072433406f",
|
||||||
|
"type": "split",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "21d78959e637e988",
|
||||||
|
"type": "tabs",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "1db1d6b317bc05ae",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "markdown",
|
||||||
|
"state": {
|
||||||
|
"file": "README.md",
|
||||||
|
"mode": "source",
|
||||||
|
"source": false
|
||||||
|
},
|
||||||
|
"icon": "lucide-file",
|
||||||
|
"title": "README"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"direction": "vertical"
|
||||||
|
},
|
||||||
|
"left": {
|
||||||
|
"id": "6703a701fa3161c8",
|
||||||
|
"type": "split",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "59a1957ef4b6aa34",
|
||||||
|
"type": "tabs",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "af4cfba92021d1c8",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "file-explorer",
|
||||||
|
"state": {
|
||||||
|
"sortOrder": "alphabetical",
|
||||||
|
"autoReveal": false,
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": ""
|
||||||
|
},
|
||||||
|
"icon": "lucide-folder-closed",
|
||||||
|
"title": "Files"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "195ed2a7004c5679",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "search",
|
||||||
|
"state": {
|
||||||
|
"query": "",
|
||||||
|
"matchingCase": false,
|
||||||
|
"explainSearch": false,
|
||||||
|
"collapseAll": false,
|
||||||
|
"extraContext": false,
|
||||||
|
"sortOrder": "alphabetical"
|
||||||
|
},
|
||||||
|
"icon": "lucide-search",
|
||||||
|
"title": "Search"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "e0b0a93bee04adf7",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "bookmarks",
|
||||||
|
"state": {
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": ""
|
||||||
|
},
|
||||||
|
"icon": "lucide-bookmark",
|
||||||
|
"title": "Bookmarks"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"direction": "horizontal",
|
||||||
|
"width": 300
|
||||||
|
},
|
||||||
|
"right": {
|
||||||
|
"id": "cdb5787bc7b074a1",
|
||||||
|
"type": "split",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "4f7b084c90edcafa",
|
||||||
|
"type": "tabs",
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"id": "87c20e5388b56742",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "backlink",
|
||||||
|
"state": {
|
||||||
|
"file": "todo.md",
|
||||||
|
"collapseAll": false,
|
||||||
|
"extraContext": false,
|
||||||
|
"sortOrder": "alphabetical",
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": "",
|
||||||
|
"backlinkCollapsed": false,
|
||||||
|
"unlinkedCollapsed": true
|
||||||
|
},
|
||||||
|
"icon": "links-coming-in",
|
||||||
|
"title": "Backlinks"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "d06f3a18f218bb85",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "outgoing-link",
|
||||||
|
"state": {
|
||||||
|
"file": "todo.md",
|
||||||
|
"linksCollapsed": false,
|
||||||
|
"unlinkedCollapsed": true
|
||||||
|
},
|
||||||
|
"icon": "links-going-out",
|
||||||
|
"title": "Outgoing links"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5e8256b0c8cb4527",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "tag",
|
||||||
|
"state": {
|
||||||
|
"sortOrder": "frequency",
|
||||||
|
"useHierarchy": true,
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": ""
|
||||||
|
},
|
||||||
|
"icon": "lucide-tags",
|
||||||
|
"title": "Tags"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "c4c977be0ce05b9d",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "all-properties",
|
||||||
|
"state": {
|
||||||
|
"sortOrder": "frequency",
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": ""
|
||||||
|
},
|
||||||
|
"icon": "lucide-archive",
|
||||||
|
"title": "All properties"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bf5df26d52eb2371",
|
||||||
|
"type": "leaf",
|
||||||
|
"state": {
|
||||||
|
"type": "outline",
|
||||||
|
"state": {
|
||||||
|
"file": "todo.md",
|
||||||
|
"followCursor": false,
|
||||||
|
"showSearch": false,
|
||||||
|
"searchQuery": ""
|
||||||
|
},
|
||||||
|
"icon": "lucide-list",
|
||||||
|
"title": "Outline"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"direction": "horizontal",
|
||||||
|
"width": 300,
|
||||||
|
"collapsed": true
|
||||||
|
},
|
||||||
|
"left-ribbon": {
|
||||||
|
"hiddenItems": {
|
||||||
|
"switcher:Open quick switcher": false,
|
||||||
|
"graph:Open graph view": false,
|
||||||
|
"canvas:Create new canvas": false,
|
||||||
|
"daily-notes:Open today's daily note": false,
|
||||||
|
"templates:Insert template": false,
|
||||||
|
"command-palette:Open command palette": false,
|
||||||
|
"bases:Create new base": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"active": "1db1d6b317bc05ae",
|
||||||
|
"lastOpenFiles": [
|
||||||
|
"src/util/posix.ts",
|
||||||
|
"src/core/util/sort.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+1
-1
@@ -19,7 +19,7 @@
|
|||||||
"type": "node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
|
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/tsx",
|
||||||
"runtimeArgs": ["src/index.ts"],
|
"runtimeArgs": ["src/dev.ts"],
|
||||||
"cwd": "${workspaceFolder}",
|
"cwd": "${workspaceFolder}",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"skipFiles": ["<node_internals>/**"]
|
"skipFiles": ["<node_internals>/**"]
|
||||||
|
|||||||
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"typescript.validate.enable": true,
|
||||||
|
"typescript.tsserver.experimental.enableProjectDiagnostics": true
|
||||||
|
}
|
||||||
@@ -1,3 +1,64 @@
|
|||||||
# termos
|
# Termos
|
||||||
|
|
||||||
terminal emulation library that bases its functionality on the bash shell
|
This library allows running a fully contained unix-like operating system written in pure typescript.
|
||||||
|
|
||||||
|
It supports all the basic operations like saving and reading files, creating new files and folders.
|
||||||
|
It has support for users and permissions and can handle multiple user sessions at the same time.
|
||||||
|
It doesnt implement a website friendly interface on its own. Thats one of the desing choices in this project, to make it as versatile as possible. But it shares a easy to use interface that you can plug into your frontend code to interact with it properly.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Right now the project is still in alpha and this is just a small portion of whats to come that serves for demonstration purposes. The code and design will change in the future so most of this is not set in stone
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- [Node.js](https://nodejs.org/) installed (version 22 or higher)
|
||||||
|
- [pnpm](https://pnpm.io/) installed (version 12 or higher)
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> If youre using Windows or MacOS as your operating system then the installation process might be different.
|
||||||
|
> Refer to [this website][ref1] on how to install nodejs on your operating system
|
||||||
|
> and [this website][ref2] for pnpm accordingly.
|
||||||
|
|
||||||
|
[ref1]: https://nodejs.org/en/download
|
||||||
|
[ref2]: https://pnpm.io/installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm add "https://git.gornodox.dev/ChaosMaker/termos/releases/download/0.1.0/termos-0.1.0.tgz"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Minimal usecase
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Termos } from "termos";
|
||||||
|
|
||||||
|
const shell = await Termos.getShell({
|
||||||
|
filesystem: {
|
||||||
|
// an example json representation of the filesystem
|
||||||
|
json: `{"dev": [{"id":0,"tree": {"atime": 1788458541,"children": [{"atime": 1794947961,"children": [],"content": [87,101,108,99,111,109,101,32,116,111,32,84,101,114,109,111,115,33,32,240,144,148,140,213,158,46,32,46,213,158,240,144,166,175,10],"ctime": 1794948078,"group": 0,"inode": 1,"link_count": 1,"mode": 420,"mtime": 1794948078,"name": "hello_world.txt","owner": 0,"parent": 0,"size": 35,"type": "regular"}],"content": null,"ctime": 1794947961,"group": 0,"inode": 0,"link_count": 2,"mode": 493,"mtime": 1794947961,"name": "root","owner": 0,"parent": 0,"size": 29,"type": "directory"}}]}`,
|
||||||
|
},
|
||||||
|
users: [{ username: "root", groups: ["root"], home: "/" }],
|
||||||
|
groups: ["root"],
|
||||||
|
general: { user: "root" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Subscribtion needed to recive command results and print out error messages
|
||||||
|
shell.on("result", payload => {
|
||||||
|
if (payload.result.type === "error") {
|
||||||
|
console.log(payload.result.error.message + "\n");
|
||||||
|
}
|
||||||
|
process.stdout.write("\n" + "Hello~\n> ");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Subscribtion needed to recieve stdout buffer contents from shell
|
||||||
|
shell.on("stdout", payload => {
|
||||||
|
const decoded = new TextDecoder().decode(payload.data);
|
||||||
|
process.stdout.write(decoded);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Takes in a string and executes it as a command
|
||||||
|
shell.execute("ls -l");
|
||||||
|
```
|
||||||
|
|
||||||
|
For more information, reference the [wiki]()
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ export default [
|
|||||||
...functional.configs.recommended,
|
...functional.configs.recommended,
|
||||||
rules: {
|
rules: {
|
||||||
"functional/no-mixed-types": "off",
|
"functional/no-mixed-types": "off",
|
||||||
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__" }],
|
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^__", argsIgnorePattern: "^__" }],
|
||||||
"@typescript-eslint/no-restricted-imports": [
|
"@typescript-eslint/no-restricted-imports": [
|
||||||
"error",
|
"error",
|
||||||
{
|
{
|
||||||
|
|||||||
Generated
-3277
File diff suppressed because it is too large
Load Diff
+32
-7
@@ -1,22 +1,42 @@
|
|||||||
{
|
{
|
||||||
"name": "termos",
|
"name": "termos",
|
||||||
"version": "1.0.0",
|
"version": "0.1.1",
|
||||||
"description": "terminal emulation library that bases its functionality on the bash shell",
|
"description": "Emulation library for a unix-like operating-system written in pure typescript",
|
||||||
"main": "index.ts",
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"import": "./dist/index.js",
|
||||||
|
"default": "./dist/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"main": "./dist/index.js",
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "eslint . && vitest"
|
"test": "eslint . && vitest",
|
||||||
|
"dev": "pnpx tsx src/dev.ts",
|
||||||
|
"build": "tsup src/index.ts --format esm --dts --clean"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git"
|
"url": "ssh://git@git.gornodox.dev:2222/ChaosMaker/termos.git"
|
||||||
},
|
},
|
||||||
|
"devEngines": {
|
||||||
|
"packageManager": {
|
||||||
|
"name": "pnpm",
|
||||||
|
"version": "12^",
|
||||||
|
"onFail": "warn"
|
||||||
|
}
|
||||||
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "gornodox",
|
"author": "gornodox",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@types/node": "^26.1.0",
|
"@types/node": "^26.2.0",
|
||||||
"eslint": "^10.6.0",
|
"eslint": "^10.6.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-functional": "^10.0.0",
|
"eslint-plugin-functional": "^10.0.0",
|
||||||
@@ -27,10 +47,15 @@
|
|||||||
"vite-tsconfig-paths": "^6.1.1",
|
"vite-tsconfig-paths": "^6.1.1",
|
||||||
"vitest": "^4.1.10"
|
"vitest": "^4.1.10"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"peerDependenciesMeta": {
|
||||||
"zod": "^4.4.3"
|
"@types/node": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"allowScripts": {
|
"allowScripts": {
|
||||||
"esbuild@0.28.1": true
|
"esbuild@0.28.1": true
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"tsup": "^9.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+2699
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
+18
-9
@@ -1,11 +1,20 @@
|
|||||||
export interface TermosConfig {
|
export interface TermosConfig {
|
||||||
serverAddress: string;
|
groups: string[];
|
||||||
dbName: string;
|
users: {
|
||||||
idbName: string;
|
username: string;
|
||||||
|
groups: string[];
|
||||||
|
home: string;
|
||||||
|
}[];
|
||||||
|
general: {
|
||||||
|
user: string;
|
||||||
|
serverAddress?: string;
|
||||||
|
dbName?: string;
|
||||||
|
idbName?: string;
|
||||||
|
};
|
||||||
|
filesystem: {
|
||||||
|
json: string;
|
||||||
|
maxNameLength?: number;
|
||||||
|
maxPathLength?: number;
|
||||||
|
maxSymlinkDepth?: number;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const defaultConfig: TermosConfig = {
|
|
||||||
serverAddress: "",
|
|
||||||
dbName: "termos",
|
|
||||||
idbName: "cache",
|
|
||||||
};
|
|
||||||
|
|||||||
+2
-1
@@ -1,8 +1,9 @@
|
|||||||
|
import type { CommandIO } from "./command_io";
|
||||||
import type { Result } from "./result";
|
import type { Result } from "./result";
|
||||||
import type { ShellState } from "./shell_state";
|
import type { ShellState } from "./shell_state";
|
||||||
import type { ShellError } from "./util/errors";
|
import type { ShellError } from "./util/errors";
|
||||||
|
|
||||||
type CommandFn = (state: ShellState, flags: string[], args: string[]) => CommandOutput<ShellError>;
|
export type CommandFn = (io: CommandIO, state: ShellState, args: string[]) => Promise<CommandOutput<ShellError>>;
|
||||||
|
|
||||||
export interface CommandDescriptor {
|
export interface CommandDescriptor {
|
||||||
fn: CommandFn;
|
fn: CommandFn;
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { Input } from "@shell/shell";
|
||||||
|
|
||||||
|
export interface CommandIO {
|
||||||
|
writeStdout(data: Uint8Array): void;
|
||||||
|
writeStderr(data: Uint8Array): void;
|
||||||
|
onInput(): Promise<Input>;
|
||||||
|
}
|
||||||
@@ -1,11 +1,27 @@
|
|||||||
import type { CommandDescriptor } from "./command";
|
import type { CommandDescriptor } from "./command";
|
||||||
|
import { descriptor as cat } from "./commands/cat";
|
||||||
import { descriptor as cd } from "./commands/cd";
|
import { descriptor as cd } from "./commands/cd";
|
||||||
|
import { descriptor as clear } from "./commands/clear";
|
||||||
import { descriptor as echo } from "./commands/echo";
|
import { descriptor as echo } from "./commands/echo";
|
||||||
|
import { descriptor as help } from "./commands/help";
|
||||||
|
import { descriptor as ls } from "./commands/ls";
|
||||||
|
import { descriptor as pwd } from "./commands/pwd";
|
||||||
|
import { descriptor as testasync } from "./commands/testasync";
|
||||||
|
import { descriptor as touch } from "./commands/touch";
|
||||||
|
|
||||||
|
export type CommandRegistry = ReadonlyMap<string, CommandDescriptor>;
|
||||||
|
|
||||||
const reg = new Map<string, CommandDescriptor>();
|
const reg = new Map<string, CommandDescriptor>();
|
||||||
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
|
//reg.set(descriptor.name, descriptor <- imported const from command implementation file);
|
||||||
reg.set(echo.name, echo);
|
reg.set(echo.name, echo);
|
||||||
reg.set(cd.name, cd);
|
reg.set(cd.name, cd);
|
||||||
|
reg.set(testasync.name, testasync);
|
||||||
|
reg.set(ls.name, ls);
|
||||||
|
reg.set(cat.name, cat);
|
||||||
|
reg.set(pwd.name, pwd);
|
||||||
|
reg.set(clear.name, clear);
|
||||||
|
reg.set(touch.name, touch);
|
||||||
|
reg.set(help.name, help);
|
||||||
Object.freeze(reg);
|
Object.freeze(reg);
|
||||||
|
|
||||||
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
export const COMMAND_REGISTRY: ReadonlyMap<string, CommandDescriptor> = reg;
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "";
|
||||||
|
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import type { FileSystemCorruptionError } from "@core/filesystem/errors";
|
||||||
|
import { type NodePointer } from "@core/filesystem/node";
|
||||||
|
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) {
|
||||||
|
let ptr: NodePointer;
|
||||||
|
try {
|
||||||
|
ptr = resolvePath(state, arg);
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
"No such file or directory",
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.filesystem.isFile(ptr)) {
|
||||||
|
const entries = state.filesystem.getNodeEntries(ptr);
|
||||||
|
if (!entries) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing. FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
`${entries[0]!.name} is a directory`,
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
if (!state.filesystem.canRead(ptr, session.user)) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
|
||||||
|
} satisfies CommandOutput<PermissionDeniedError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = await state.filesystem.read(ptr);
|
||||||
|
|
||||||
|
io.writeStdout(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
+15
-45
@@ -1,5 +1,6 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import type { NodePointer } from "@core/filesystem/node";
|
||||||
import { createErrorResult, createSuccessResult } from "@core/result";
|
import { createErrorResult, createSuccessResult } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { ShellState, withCwd } from "@core/shell_state";
|
import { ShellState, withCwd } from "@core/shell_state";
|
||||||
@@ -9,12 +10,11 @@ import {
|
|||||||
type PermissionDeniedError,
|
type PermissionDeniedError,
|
||||||
type ShellError,
|
type ShellError,
|
||||||
} from "@core/util/errors";
|
} from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
|
||||||
|
|
||||||
export const COMMAND_NAME = "cd";
|
export const COMMAND_NAME = "cd";
|
||||||
|
|
||||||
function main(state: ShellState, __flags: string[], args: string[]): CommandOutput<ShellError> {
|
async function main(__io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
@@ -22,84 +22,54 @@ function main(state: ShellState, __flags: string[], args: string[]): CommandOutp
|
|||||||
"InvalidArguments",
|
"InvalidArguments",
|
||||||
"The maximum ammount of arguments for this command is 1",
|
"The maximum ammount of arguments for this command is 1",
|
||||||
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
{ expected: "cd <path>", actual: `cd ${args.toString().replace(/[,]/g, " ")}` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
} satisfies CommandOutput<InvalidArgumentsError>;
|
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
let inode: number;
|
let ptr: NodePointer;
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
if (args[0] === undefined) {
|
if (args[0] === undefined) {
|
||||||
inode = session.user.home;
|
ptr = session.user.home;
|
||||||
} else if (args[0] === "-") {
|
} else if (args[0] === "-") {
|
||||||
inode = session.pwd;
|
ptr = session.pwd;
|
||||||
} else {
|
} else {
|
||||||
const result = safeResolvePath(state.filesystem, session.cwd, args[0]);
|
try {
|
||||||
if (result.type === "error") {
|
ptr = resolvePath(state, args[0]);
|
||||||
|
} catch (e) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult(
|
||||||
"PathResolutionError",
|
"PathResolutionError",
|
||||||
"No such file or directory",
|
"No such file or directory",
|
||||||
{ path: args[0]! },
|
{ path: args[0]! },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
COMMAND_NAME,
|
||||||
),
|
),
|
||||||
} satisfies CommandOutput<PathResolutionError>;
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
}
|
}
|
||||||
inode = result.inode;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.filesystem.isFile(inode)) {
|
if (state.filesystem.isFile(ptr)) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult("PathResolutionError", "Not a directory", { path: args[0]! }, COMMAND_NAME),
|
||||||
"PathResolutionError",
|
|
||||||
"No such file or directory",
|
|
||||||
{ path: resolveInode(state.filesystem, inode) },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
|
||||||
),
|
|
||||||
} satisfies CommandOutput<PathResolutionError>;
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!state.filesystem.canExecute(inode, session.user)) {
|
if (!state.filesystem.canExecute(ptr, session.user)) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
result: createErrorResult(
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: args[0]! }, COMMAND_NAME),
|
||||||
"PermissionDenied",
|
|
||||||
"Permission denied",
|
|
||||||
{ resource: args[0]! },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
COMMAND_NAME,
|
|
||||||
),
|
|
||||||
} satisfies CommandOutput<PermissionDeniedError>;
|
} satisfies CommandOutput<PermissionDeniedError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const returnState = withCwd(state, inode);
|
const returnState = withCwd(state, ptr);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state: returnState,
|
state: returnState,
|
||||||
result: createSuccessResult(COMMAND_NAME),
|
result: createSuccessResult(COMMAND_NAME),
|
||||||
};
|
};
|
||||||
|
|
||||||
function safeResolvePath(
|
|
||||||
fs: FileSystem,
|
|
||||||
cwd: number,
|
|
||||||
path: string,
|
|
||||||
): { type: "success"; inode: number } | { type: "error" } {
|
|
||||||
try {
|
|
||||||
return { type: "success", inode: resolvePath(fs, cwd, path) };
|
|
||||||
} catch {
|
|
||||||
return { type: "error" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const descriptor: CommandDescriptor = {
|
export const descriptor: CommandDescriptor = {
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "clear";
|
||||||
|
|
||||||
|
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
const encoded = new TextEncoder().encode("\x1b[2J\x1b[0;0H");
|
||||||
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -1,25 +1,19 @@
|
|||||||
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
import type { ResultSuccess } from "@core/result";
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import type { ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
|
||||||
|
|
||||||
export const COMMAND_NAME = "echo";
|
export const COMMAND_NAME = "echo";
|
||||||
|
|
||||||
//Need to implement escape sequences
|
//Need to implement escape sequences
|
||||||
function main(state: ShellState, flags: string[], args: string[]): CommandOutput<ShellError> {
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
const joined = args.join(" ");
|
const joined = args.join(" ");
|
||||||
const encoded = new TextEncoder().encode(joined);
|
const encoded = new TextEncoder().encode(joined + "\n");
|
||||||
|
|
||||||
const stdout = createImmutableBuffer(encoded);
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
const result: ResultSuccess = {
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
type: "success",
|
|
||||||
exitCode: 0,
|
|
||||||
stdout,
|
|
||||||
stderr: createImmutableBuffer(new Uint8Array()),
|
|
||||||
commandName: COMMAND_NAME,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state: state,
|
state: state,
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { COMMAND_REGISTRY } from "@core/command_registry";
|
||||||
|
import { createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "help";
|
||||||
|
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
const e = new TextEncoder();
|
||||||
|
for (const entry of COMMAND_REGISTRY.keys()) {
|
||||||
|
io.writeStdout(e.encode(` ${entry}\n`));
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -0,0 +1,486 @@
|
|||||||
|
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<CommandOutput<ShellError>> {
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
listDirEntries(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
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`));
|
||||||
|
if (options.long) 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);
|
||||||
|
} else {
|
||||||
|
//shortMode(io, state, children);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.recursive) {
|
||||||
|
io.writeStdout(e.encode("\n"));
|
||||||
|
|
||||||
|
for (const c of children) {
|
||||||
|
// Skip if names match . or ..
|
||||||
|
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 shortMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {}
|
||||||
|
|
||||||
|
function longMode(io: CommandIO, state: ShellState, children: DirEntry[]): void {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
};
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { InvalidArgumentsError, ShellError } from "@core/util/errors";
|
||||||
|
import { resolvePointer } from "@core/util/path_resolver";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "pwd";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
if (args.length > 0) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"InvalidArguments",
|
||||||
|
`Expected aruments 0, got ${args.length}.`,
|
||||||
|
{ expected: "pwd", actual: `pwd ${args.toString().replace(/[,]/g, " ")}` },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<InvalidArgumentsError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
const path = resolvePointer(state, session.cwd);
|
||||||
|
|
||||||
|
io.writeStdout(new TextEncoder().encode(path));
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import type { ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError } from "@core/util/errors";
|
||||||
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
|
|
||||||
|
const COMMAND_NAME = "async";
|
||||||
|
|
||||||
|
async function main(io: CommandIO, state: ShellState, __args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
while (true) {
|
||||||
|
const sig = await io.onInput();
|
||||||
|
|
||||||
|
const encoded = new TextEncoder().encode(("user pressed: " + sig.sequence + "\n") as string);
|
||||||
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
|
if (sig.sequence === "\x03") {
|
||||||
|
const result: ResultSuccess = {
|
||||||
|
type: "success",
|
||||||
|
exitCode: 0,
|
||||||
|
stdout: createImmutableBuffer(new Uint8Array()),
|
||||||
|
stderr: createImmutableBuffer(new Uint8Array()),
|
||||||
|
commandName: COMMAND_NAME,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
} satisfies CommandDescriptor;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { NodeType } from "@core/filesystem/node";
|
||||||
|
import { createErrorResult, createSuccessResult, type ResultSuccess } 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";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "touch";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(io: CommandIO, state: ShellState, args: string[]): Promise<CommandOutput<ShellError>> {
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
for (const arg of args) {
|
||||||
|
try {
|
||||||
|
resolvePath(state, arg);
|
||||||
|
} catch {
|
||||||
|
const index = arg.lastIndexOf("/");
|
||||||
|
const fileName = arg.slice(index + 1);
|
||||||
|
const parentPath = index === -1 ? "./" : arg.slice(0, index + 1);
|
||||||
|
const pptr = resolvePath(state, parentPath);
|
||||||
|
|
||||||
|
state.filesystem.createNode(pptr, fileName, {
|
||||||
|
type: NodeType.File,
|
||||||
|
mode: 0o644,
|
||||||
|
owner: session.user.uid,
|
||||||
|
group: session.user.gid,
|
||||||
|
content: new Blob(),
|
||||||
|
size: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("AlreadyExists", "The file already exists", {}),
|
||||||
|
} satisfies CommandOutput<ShellError>;
|
||||||
|
}
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { TreeNodeType } from "./treenode";
|
import type { NodePointer, NodeType } from "./node";
|
||||||
|
|
||||||
export type FileSystemError =
|
export type FileSystemError =
|
||||||
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
|
NotADirectoryError | AlreadyExistsError | NodeNotFoundError | IllegalMutationError | FileSystemInitializationError;
|
||||||
@@ -14,7 +14,15 @@ export interface NotADirectoryError {
|
|||||||
message: string;
|
message: string;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
type: "NotADirectory";
|
type: "NotADirectory";
|
||||||
nodeType: TreeNodeType;
|
nodeType: NodeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotAFileError {
|
||||||
|
inode: number;
|
||||||
|
message: string;
|
||||||
|
timestamp: number;
|
||||||
|
type: "NotAFile";
|
||||||
|
nodeType: NodeType;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AlreadyExistsError {
|
export interface AlreadyExistsError {
|
||||||
@@ -28,7 +36,21 @@ export interface AlreadyExistsError {
|
|||||||
export interface NodeNotFoundError {
|
export interface NodeNotFoundError {
|
||||||
type: "NodeNotFound";
|
type: "NodeNotFound";
|
||||||
message: string;
|
message: string;
|
||||||
inode: number;
|
pointer: NodePointer;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceNotFoundError {
|
||||||
|
type: "DeviceNotFound";
|
||||||
|
message: string;
|
||||||
|
device_id: number;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MountPointNotFoundError {
|
||||||
|
type: "MountPointNotFound";
|
||||||
|
message: string;
|
||||||
|
pointer: NodePointer;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,3 +67,18 @@ export interface DirectoryLoopError {
|
|||||||
descendantInode: number;
|
descendantInode: number;
|
||||||
ancestorInode: number;
|
ancestorInode: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface InvalidNodeNameError {
|
||||||
|
type: "InvalidNodeName";
|
||||||
|
message: string;
|
||||||
|
timestamp: number;
|
||||||
|
pointer: NodePointer;
|
||||||
|
attemptedName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FileSystemCorruptionError {
|
||||||
|
type: "FileSystemCorruption";
|
||||||
|
message: string;
|
||||||
|
timestamp: number;
|
||||||
|
override?: {};
|
||||||
|
}
|
||||||
|
|||||||
+444
-374
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,120 @@
|
|||||||
|
export type Node = FileNode | DirectoryNode | SymlinkNode;
|
||||||
|
|
||||||
|
export type NodeHash = ReadonlyMap<number, Node>;
|
||||||
|
export type ShadowHash = ReadonlyMap<number, Node | null>;
|
||||||
|
|
||||||
|
export class NodePointer {
|
||||||
|
private static readonly _cache = new Map<string, NodePointer>();
|
||||||
|
|
||||||
|
private readonly _device_id: number;
|
||||||
|
private readonly _inode: number;
|
||||||
|
|
||||||
|
private constructor(device_id: number, inode: number) {
|
||||||
|
this._device_id = device_id;
|
||||||
|
this._inode = inode;
|
||||||
|
}
|
||||||
|
|
||||||
|
static of(device_id: number, inode: number): NodePointer {
|
||||||
|
const key = `${device_id}:${inode}`;
|
||||||
|
let p = NodePointer._cache.get(key);
|
||||||
|
if (!p) {
|
||||||
|
p = new NodePointer(device_id, inode);
|
||||||
|
NodePointer._cache.set(key, p);
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
static parse(s: string): NodePointer {
|
||||||
|
const m = /^(\d+):(\d+)$/.exec(s);
|
||||||
|
if (!m) throw new Error(`Invalid NodePointer: ${s}`);
|
||||||
|
let p = NodePointer._cache.get(s);
|
||||||
|
if (!p) {
|
||||||
|
p = new NodePointer(Number(m[1]), Number(m[2]));
|
||||||
|
NodePointer._cache.set(s, p);
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
get device(): number {
|
||||||
|
return this._device_id;
|
||||||
|
}
|
||||||
|
get inode(): number {
|
||||||
|
return this._inode;
|
||||||
|
}
|
||||||
|
toString(): string {
|
||||||
|
return `${this._device_id}:${this.inode}`;
|
||||||
|
}
|
||||||
|
equals(other: NodePointer): boolean {
|
||||||
|
return this._device_id === other._device_id && this.inode === other.inode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export type NodePointer = `${string}:${string}`;
|
||||||
|
|
||||||
|
export interface NodeEntry {
|
||||||
|
readonly pinode: number;
|
||||||
|
readonly pdevice_id: number;
|
||||||
|
readonly name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FileNode {
|
||||||
|
readonly type: NodeType.File;
|
||||||
|
readonly inode: number;
|
||||||
|
readonly link_count: number;
|
||||||
|
readonly mode: number;
|
||||||
|
readonly owner: number;
|
||||||
|
readonly group: number;
|
||||||
|
readonly mtime: number;
|
||||||
|
readonly ctime: number;
|
||||||
|
readonly atime: number;
|
||||||
|
readonly content: string;
|
||||||
|
readonly size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DirectoryNode {
|
||||||
|
readonly type: NodeType.Directory;
|
||||||
|
readonly inode: number;
|
||||||
|
readonly link_count: number;
|
||||||
|
readonly mode: number;
|
||||||
|
readonly owner: number;
|
||||||
|
readonly group: number;
|
||||||
|
readonly mtime: number;
|
||||||
|
readonly ctime: number;
|
||||||
|
readonly atime: number;
|
||||||
|
readonly children: Map<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SymlinkNode {
|
||||||
|
readonly type: NodeType.Symlink;
|
||||||
|
readonly inode: number;
|
||||||
|
readonly link_count: number;
|
||||||
|
readonly mode: number;
|
||||||
|
readonly owner: number;
|
||||||
|
readonly group: number;
|
||||||
|
readonly mtime: number;
|
||||||
|
readonly ctime: number;
|
||||||
|
readonly atime: number;
|
||||||
|
readonly target: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum NodeType {
|
||||||
|
File = 0,
|
||||||
|
Directory = 1,
|
||||||
|
Symlink = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
/* export function toPtr({ device_id, inode }: { device_id: number; inode: number }): NodePointer {
|
||||||
|
return `${device_id}:${inode}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fromPtr(ptr: NodePointer): { device_id: number; inode: number } {
|
||||||
|
if (!ptr.match(/^\d+[:]\d+$/)) {
|
||||||
|
//TODO: Make typed
|
||||||
|
throw new Error("Invalid node pointer format");
|
||||||
|
}
|
||||||
|
const arr = ptr.split(":");
|
||||||
|
return {
|
||||||
|
device_id: Number(arr[0]),
|
||||||
|
inode: Number(arr[1]),
|
||||||
|
};
|
||||||
|
} */
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import type { ImmutableBuffer } from "@core/util/immutable_buffer";
|
|
||||||
|
|
||||||
export type TreeNode = FileNode | DirectoryNode;
|
|
||||||
|
|
||||||
export interface FileNode {
|
|
||||||
readonly type: TreeNodeType.File;
|
|
||||||
readonly inode: number;
|
|
||||||
readonly name: string;
|
|
||||||
readonly parent: number;
|
|
||||||
readonly mode: number;
|
|
||||||
readonly owner: number;
|
|
||||||
readonly group: number;
|
|
||||||
readonly mtime: number;
|
|
||||||
readonly ctime: number;
|
|
||||||
readonly atime: number;
|
|
||||||
readonly content: ImmutableBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DirectoryNode {
|
|
||||||
readonly type: TreeNodeType.Directory;
|
|
||||||
readonly inode: number;
|
|
||||||
readonly name: string;
|
|
||||||
readonly parent: number;
|
|
||||||
readonly mode: number;
|
|
||||||
readonly owner: number;
|
|
||||||
readonly group: number;
|
|
||||||
readonly mtime: number;
|
|
||||||
readonly ctime: number;
|
|
||||||
readonly atime: number;
|
|
||||||
readonly children: Readonly<Record<string, number>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* export interface SymlinkNode {
|
|
||||||
readonly type: TreeNodeType.Symlink;
|
|
||||||
readonly inode: number;
|
|
||||||
readonly name: string;
|
|
||||||
readonly parent: number;
|
|
||||||
readonly mode: number;
|
|
||||||
readonly owner: number;
|
|
||||||
readonly group: number;
|
|
||||||
readonly mtime: number;
|
|
||||||
readonly ctime: number;
|
|
||||||
readonly atime: number;
|
|
||||||
readonly target: string;
|
|
||||||
} */
|
|
||||||
|
|
||||||
export enum TreeNodeType {
|
|
||||||
File = "0",
|
|
||||||
Directory = "1",
|
|
||||||
//Symlink = "2",
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,447 @@
|
|||||||
|
import { NodePointer, NodeType, type DirectoryNode, type Node, type NodeEntry, type NodeHash } from "./node";
|
||||||
|
|
||||||
|
export function DefaultVDiskConfig(id: number): VDiskConfig {
|
||||||
|
const base = new Map();
|
||||||
|
const root = {
|
||||||
|
type: NodeType.Directory,
|
||||||
|
inode: 0,
|
||||||
|
link_count: 2,
|
||||||
|
mode: 0o0555,
|
||||||
|
owner: 0,
|
||||||
|
group: 0,
|
||||||
|
mtime: 0,
|
||||||
|
ctime: 0,
|
||||||
|
atime: 0,
|
||||||
|
children: new Map(),
|
||||||
|
} satisfies DirectoryNode;
|
||||||
|
|
||||||
|
base.set(0, root);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
label: `disk-${id}`,
|
||||||
|
readonly: false,
|
||||||
|
size: Infinity,
|
||||||
|
base,
|
||||||
|
index: 0,
|
||||||
|
dataC: {
|
||||||
|
chunkSize: 8096,
|
||||||
|
cacheSize: 64 * 1024 * 1024,
|
||||||
|
cacheTTL: 60_000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VDiskConfig {
|
||||||
|
id: number;
|
||||||
|
label: string;
|
||||||
|
index: number;
|
||||||
|
readonly: boolean;
|
||||||
|
size: number;
|
||||||
|
base: NodeHash;
|
||||||
|
dataC: DataConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataConfig {
|
||||||
|
chunkSize: number;
|
||||||
|
cacheSize: number;
|
||||||
|
cacheTTL: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IDataStore {
|
||||||
|
read(uuid: string): Promise<Uint8Array>;
|
||||||
|
stream(uuid: string): ReadableStream;
|
||||||
|
put(uuid: string, blob: Blob): Promise<void>;
|
||||||
|
delete(uuid: string): Promise<void>;
|
||||||
|
has(uuid: string): Promise<boolean>;
|
||||||
|
list(): Promise<string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IMetaStore {
|
||||||
|
loadAll(): Promise<Map<number, Node | null>>;
|
||||||
|
write(entries: Array<[number, Node | null]>): Promise<void>;
|
||||||
|
delete(entries: Array<number>): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class VDisk {
|
||||||
|
private readonly _id: number;
|
||||||
|
private readonly _label: string;
|
||||||
|
private readonly _readonly: boolean;
|
||||||
|
private readonly _totalSize: number;
|
||||||
|
private readonly _base: NodeHash;
|
||||||
|
private readonly _dataStore: IDataStore;
|
||||||
|
private readonly _metaStore: IMetaStore;
|
||||||
|
|
||||||
|
private _iIndex: number;
|
||||||
|
private _rIndex: ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>>;
|
||||||
|
private _overlay: Map<number, Node | null>;
|
||||||
|
private _pending: Map<number, Node | null> | null;
|
||||||
|
|
||||||
|
private _rIndexInvalid: boolean;
|
||||||
|
private _flush: Promise<void>;
|
||||||
|
|
||||||
|
private constructor(config: VDiskConfig, data: IDataStore, meta: IMetaStore) {
|
||||||
|
this._id = config.id;
|
||||||
|
this._label = config.label;
|
||||||
|
this._readonly = config.readonly;
|
||||||
|
this._totalSize = config.size;
|
||||||
|
this._base = config.base;
|
||||||
|
this._iIndex = config.index;
|
||||||
|
|
||||||
|
this._dataStore = data;
|
||||||
|
this._metaStore = meta;
|
||||||
|
|
||||||
|
this._overlay = new Map();
|
||||||
|
this._rIndex = new Map();
|
||||||
|
this._rIndexInvalid = false;
|
||||||
|
this._pending = null;
|
||||||
|
this._flush = Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _batch<T>(fn: () => T): Promise<T> {
|
||||||
|
if (this._pending) {
|
||||||
|
console.error("Nested batch not ok");
|
||||||
|
}
|
||||||
|
|
||||||
|
this._pending = new Map();
|
||||||
|
|
||||||
|
let result: T;
|
||||||
|
try {
|
||||||
|
result = fn();
|
||||||
|
} catch (err) {
|
||||||
|
this._pending = null;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = this._pending;
|
||||||
|
this._pending = null;
|
||||||
|
|
||||||
|
for (const [inode, node] of pending) {
|
||||||
|
this._overlay.set(inode, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = Array.from(pending.entries());
|
||||||
|
const next = this._flush.then(() => this._metaStore.write(entries));
|
||||||
|
this._flush = next.catch(() => {});
|
||||||
|
await next;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _isWritable(): void {
|
||||||
|
if (this._readonly) throw Error(`The ${this._label} device under id - ${this._id} is marked readonly`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _buildReverseIndex(): Map<NodePointer, NodeEntry[]> {
|
||||||
|
const index: Map<NodePointer, NodeEntry[]> = new Map();
|
||||||
|
const stack: [number, number, number, string][] = [];
|
||||||
|
|
||||||
|
const root = this.getNode(0) as DirectoryNode;
|
||||||
|
for (const [name, inode] of root.children) {
|
||||||
|
if (name === "." || name === "..") continue;
|
||||||
|
stack.push([inode, 0, this._id, name]);
|
||||||
|
}
|
||||||
|
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const [inode, pinode, pdevice_id, name] = stack.pop()!;
|
||||||
|
const node = this.getNode(inode);
|
||||||
|
if (node === undefined) continue;
|
||||||
|
|
||||||
|
const key = NodePointer.of(this._id, inode);
|
||||||
|
const entry = {
|
||||||
|
pinode,
|
||||||
|
pdevice_id,
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
|
||||||
|
const arr = index.get(key);
|
||||||
|
if (arr) arr.push(entry);
|
||||||
|
else index.set(key, [entry]);
|
||||||
|
|
||||||
|
if (node.type === NodeType.Directory) {
|
||||||
|
for (const [name, cinode] of node.children) {
|
||||||
|
if (name === "." || name === "..") continue;
|
||||||
|
stack.push([cinode, inode, pdevice_id, name]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _putNode(inode: number, node: Node | null): void {
|
||||||
|
if (!this._pending)
|
||||||
|
throw new Error(
|
||||||
|
"_putNode called outside of batch. This is not a BUG. Every mutation must be wrapped in a _batch call",
|
||||||
|
);
|
||||||
|
|
||||||
|
this._pending.set(inode, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async open(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
|
||||||
|
const vdisk = new VDisk(config, data, meta);
|
||||||
|
await vdisk.loadOverlay();
|
||||||
|
vdisk._rIndex = vdisk._buildReverseIndex();
|
||||||
|
|
||||||
|
return vdisk;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getNode(inode: number): Node | undefined {
|
||||||
|
if (this._pending && this._pending.has(inode)) {
|
||||||
|
return this._pending.get(inode) ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const node = this._overlay.get(inode);
|
||||||
|
if (node) return node;
|
||||||
|
if (node === null) return undefined;
|
||||||
|
|
||||||
|
return this._base.get(inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async createNodeEntry(
|
||||||
|
pinode: number,
|
||||||
|
name: string,
|
||||||
|
data:
|
||||||
|
| {
|
||||||
|
type: NodeType.File;
|
||||||
|
mode: number;
|
||||||
|
owner: number;
|
||||||
|
group: number;
|
||||||
|
content: Blob | ReadableStream;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
| { type: NodeType.Directory; mode: number; owner: number; group: number }
|
||||||
|
| { type: NodeType.Symlink; mode: number; owner: number; group: number; target: string },
|
||||||
|
): Promise<number> {
|
||||||
|
return this._batch(async () => {
|
||||||
|
this._isWritable();
|
||||||
|
const index = ++this._iIndex;
|
||||||
|
const time = Date.now();
|
||||||
|
const link_count = data.type === NodeType.Directory ? 2 : 1;
|
||||||
|
|
||||||
|
const base = {
|
||||||
|
inode: index,
|
||||||
|
link_count,
|
||||||
|
type: data.type,
|
||||||
|
mode: data.mode,
|
||||||
|
owner: data.owner,
|
||||||
|
group: data.group,
|
||||||
|
mtime: time,
|
||||||
|
ctime: time,
|
||||||
|
atime: time,
|
||||||
|
};
|
||||||
|
|
||||||
|
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||||
|
const uuid = crypto.randomUUID();
|
||||||
|
|
||||||
|
let node: Node;
|
||||||
|
switch (data.type) {
|
||||||
|
case NodeType.File:
|
||||||
|
node = { ...base, type: NodeType.File, content: uuid, size: data.size };
|
||||||
|
this.writeContent(
|
||||||
|
uuid,
|
||||||
|
data.content instanceof ReadableStream ? await new Response(data.content).blob() : data.content,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case NodeType.Directory:
|
||||||
|
node = { ...base, type: NodeType.Directory, children: new Map() };
|
||||||
|
break;
|
||||||
|
case NodeType.Symlink:
|
||||||
|
node = { ...base, type: NodeType.Symlink, target: data.target };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const children = new Map(pnode.children);
|
||||||
|
children.set(name, index);
|
||||||
|
|
||||||
|
const parent = {
|
||||||
|
...pnode,
|
||||||
|
children,
|
||||||
|
link_count: pnode.link_count + (data.type === NodeType.Directory ? 1 : 0),
|
||||||
|
mtime: time,
|
||||||
|
ctime: time,
|
||||||
|
};
|
||||||
|
|
||||||
|
this._putNode(index, node);
|
||||||
|
this._putNode(pinode, parent);
|
||||||
|
this.invalidateRIndex();
|
||||||
|
|
||||||
|
return index;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public linkNodeEntry(pinode: number, name: string, tinode: number): Promise<void> {
|
||||||
|
return this._batch(() => {
|
||||||
|
this._isWritable();
|
||||||
|
|
||||||
|
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||||
|
const tnode = this.getNode(tinode) as Node;
|
||||||
|
const time = Date.now();
|
||||||
|
|
||||||
|
const children = new Map(pnode.children);
|
||||||
|
children.set(name, tnode.inode);
|
||||||
|
|
||||||
|
const parent = { ...pnode, children, mtime: time, ctime: time };
|
||||||
|
const target = { ...tnode, link_count: tnode.link_count + 1, ctime: time };
|
||||||
|
|
||||||
|
this._putNode(tinode, target);
|
||||||
|
this._putNode(pinode, parent);
|
||||||
|
this.invalidateRIndex();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public unlinkNodeEntry(inode: number, name: string): Promise<void> {
|
||||||
|
return this._batch(() => {
|
||||||
|
this._isWritable();
|
||||||
|
|
||||||
|
const pnode = this.getNode(inode) as DirectoryNode;
|
||||||
|
const tinode = pnode.children.get(name)!;
|
||||||
|
const tnode = this.getNode(tinode) as Node;
|
||||||
|
const time = Date.now();
|
||||||
|
|
||||||
|
const children = new Map(pnode.children);
|
||||||
|
children.delete(name);
|
||||||
|
const parent = { ...pnode, children, mtime: time, ctime: time };
|
||||||
|
|
||||||
|
const link_count = tnode.link_count - 1;
|
||||||
|
const wasLast = link_count === 0;
|
||||||
|
|
||||||
|
this._putNode(inode, parent);
|
||||||
|
this._putNode(tinode, wasLast ? null : { ...tnode, link_count, ctime: Date.now() });
|
||||||
|
this.invalidateRIndex();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public moveNodeEntry(pinode: number, dinode: number, tname: string, dname?: string): Promise<void> {
|
||||||
|
return this._batch(() => {
|
||||||
|
this._isWritable();
|
||||||
|
|
||||||
|
const pnode = this.getNode(pinode) as DirectoryNode;
|
||||||
|
const dnode = this.getNode(dinode) as DirectoryNode;
|
||||||
|
|
||||||
|
const tinode = pnode.children.get(tname)!;
|
||||||
|
const tnode = this.getNode(tinode)!;
|
||||||
|
|
||||||
|
const name = dname ?? tname;
|
||||||
|
const isDir = tnode.type === NodeType.Directory;
|
||||||
|
const time = Date.now();
|
||||||
|
|
||||||
|
if (pinode === dinode) {
|
||||||
|
const pchildren = new Map(pnode.children);
|
||||||
|
pchildren.delete(tname);
|
||||||
|
pchildren.set(name, tinode);
|
||||||
|
|
||||||
|
const parent = { ...pnode, children: pchildren, mtime: time, ctime: time };
|
||||||
|
const target = { ...tnode, ctime: time };
|
||||||
|
|
||||||
|
this._putNode(pinode, parent);
|
||||||
|
this._putNode(tinode, target);
|
||||||
|
this.invalidateRIndex();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pchildren = new Map(pnode.children);
|
||||||
|
pchildren.delete(tname);
|
||||||
|
|
||||||
|
const dchildren = new Map(dnode.children);
|
||||||
|
dchildren.set(name, tinode);
|
||||||
|
|
||||||
|
const parent = {
|
||||||
|
...pnode,
|
||||||
|
children: pchildren,
|
||||||
|
mtime: time,
|
||||||
|
ctime: time,
|
||||||
|
link_count: pnode.link_count - (isDir ? 1 : 0),
|
||||||
|
};
|
||||||
|
const target = { ...tnode, ctime: time };
|
||||||
|
const destination = {
|
||||||
|
...dnode,
|
||||||
|
children: dchildren,
|
||||||
|
mtime: time,
|
||||||
|
ctime: time,
|
||||||
|
link_count: dnode.link_count + (isDir ? 1 : 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
this._putNode(pinode, parent);
|
||||||
|
this._putNode(tinode, target);
|
||||||
|
this._putNode(dinode, destination);
|
||||||
|
this.invalidateRIndex();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public writeNodeEntry(inode: number, data: { mode?: number; owner?: number; group?: number }): Promise<void> {
|
||||||
|
return this._batch(() => {
|
||||||
|
this._isWritable();
|
||||||
|
|
||||||
|
const node = this.getNode(inode)!;
|
||||||
|
|
||||||
|
const newNode: Node = {
|
||||||
|
...node,
|
||||||
|
mode: data.mode ?? node.mode,
|
||||||
|
owner: data.owner ?? node.owner,
|
||||||
|
group: data.group ?? node.group,
|
||||||
|
ctime: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
this._putNode(inode, newNode);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public readContent(uuid: string): Promise<Uint8Array> {
|
||||||
|
return this._dataStore.read(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public streamContent(uuid: string): ReadableStream {
|
||||||
|
return this._dataStore.stream(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async writeContent(uuid: string, blob: Blob): Promise<void> {
|
||||||
|
this._isWritable();
|
||||||
|
await this._dataStore.put(uuid, blob);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteContent(uuid: string): Promise<void> {
|
||||||
|
this._isWritable();
|
||||||
|
await this._dataStore.delete(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public hasContent(uuid: string): Promise<boolean> {
|
||||||
|
return this._dataStore.has(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async loadOverlay(): Promise<void> {
|
||||||
|
const overlay = await this._metaStore.loadAll();
|
||||||
|
this._overlay = new Map(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
// public sweepOrphans(): Promise<void> {}
|
||||||
|
// public sweepDangling(): Promise<void> {}
|
||||||
|
|
||||||
|
public invalidateRIndex(): void {
|
||||||
|
this._rIndexInvalid = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getIndex(): ReadonlyMap<NodePointer, ReadonlyArray<NodeEntry>> {
|
||||||
|
if (this._rIndexInvalid) {
|
||||||
|
this._rIndex = this._buildReverseIndex();
|
||||||
|
this._rIndexInvalid = false;
|
||||||
|
}
|
||||||
|
return this._rIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get ID(): number {
|
||||||
|
return this._id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Label(): string {
|
||||||
|
return this._label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get IsReadonly(): boolean {
|
||||||
|
return this._readonly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get ByteSize(): number {
|
||||||
|
return this._totalSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
const HISTORY_MAX_CAPACITY = 255;
|
const HISTORY_MAX_CAPACITY = 255;
|
||||||
|
|
||||||
export type HistoryState = readonly string[];
|
export type HistoryState = readonly Uint8Array[];
|
||||||
|
|
||||||
export function addHistoryEntry(state: HistoryState, input: string): HistoryState {
|
export function addHistoryEntry(state: HistoryState, input: Uint8Array): HistoryState {
|
||||||
const entries: string[] = [...state];
|
const entries: Uint8Array[] = [...state];
|
||||||
|
|
||||||
if (entries.length === HISTORY_MAX_CAPACITY) {
|
if (entries.length === HISTORY_MAX_CAPACITY) {
|
||||||
entries.shift();
|
entries.shift();
|
||||||
@@ -12,11 +12,11 @@ export function addHistoryEntry(state: HistoryState, input: string): HistoryStat
|
|||||||
entries.push(input);
|
entries.push(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result: readonly string[] = entries;
|
const result: readonly Uint8Array[] = entries;
|
||||||
return Object.freeze(result);
|
return Object.freeze(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getHistoryEntry(state: HistoryState, index: number): string {
|
export function getHistoryEntry(state: HistoryState, index: number): Uint8Array {
|
||||||
const entry = state[index];
|
const entry = state[index];
|
||||||
if (entry === undefined) {
|
if (entry === undefined) {
|
||||||
// Add a custom error object later
|
// Add a custom error object later
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
import type { Signal } from "./signal";
|
|
||||||
|
|
||||||
export interface ProcessContext {
|
|
||||||
writeStdout(data: Uint8Array): void;
|
|
||||||
writeStderr(data: Uint8Array): void;
|
|
||||||
getSignal(): Promise<Signal>;
|
|
||||||
}
|
|
||||||
+4
-4
@@ -24,16 +24,16 @@ export function createErrorResult<E extends ShellError>(
|
|||||||
message: string,
|
message: string,
|
||||||
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
|
// Omit - includes all properties of E except the ones that are already inside ShellError - basically skipping duplicates and allowing this to be a one-liner
|
||||||
extraProps: Omit<E, keyof ShellError>,
|
extraProps: Omit<E, keyof ShellError>,
|
||||||
stdout: ImmutableBuffer,
|
|
||||||
stderr: ImmutableBuffer,
|
|
||||||
commandName?: string,
|
commandName?: string,
|
||||||
|
stdout?: ImmutableBuffer,
|
||||||
|
stderr?: ImmutableBuffer,
|
||||||
cause?: { name: string; message: string },
|
cause?: { name: string; message: string },
|
||||||
): ResultError<E> {
|
): ResultError<E> {
|
||||||
const error = createShellError<E>(errorType, message, extraProps, cause);
|
const error = createShellError<E>(errorType, message, extraProps, cause);
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
type: "error",
|
type: "error",
|
||||||
stdout,
|
stdout: stdout ?? createImmutableBuffer(new Uint8Array()),
|
||||||
stderr,
|
stderr: stderr ?? createImmutableBuffer(new Uint8Array()),
|
||||||
error,
|
error,
|
||||||
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
// commandName is either undefined or string but when undefined - has to be ommited - we achieve that with a condition wrapped in a spread
|
||||||
...(commandName !== undefined && { commandName }),
|
...(commandName !== undefined && { commandName }),
|
||||||
|
|||||||
@@ -1,21 +1,28 @@
|
|||||||
|
import type { NodePointer } from "./filesystem/node";
|
||||||
import { type HistoryState } from "./history_state";
|
import { type HistoryState } from "./history_state";
|
||||||
import { createShellState, type ShellState } from "./shell_state";
|
import { createShellState, type ShellState } from "./shell_state";
|
||||||
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
||||||
|
|
||||||
|
export interface GroupInfo {
|
||||||
|
readonly groupname: string;
|
||||||
|
readonly gid: number;
|
||||||
|
readonly members: number[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface UserInfo {
|
export interface UserInfo {
|
||||||
readonly username: string;
|
readonly username: string;
|
||||||
readonly uid: number;
|
readonly uid: number;
|
||||||
readonly gid: number;
|
readonly gid: number;
|
||||||
readonly group: readonly number[];
|
readonly group: readonly number[];
|
||||||
readonly home: number;
|
readonly home: NodePointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionState {
|
export interface SessionState {
|
||||||
readonly user: UserInfo;
|
readonly user: UserInfo;
|
||||||
readonly envVars: ReadonlyMap<string, string>;
|
readonly envVars: ReadonlyMap<string, string>;
|
||||||
readonly history: HistoryState;
|
readonly history: HistoryState;
|
||||||
readonly cwd: number;
|
readonly cwd: NodePointer;
|
||||||
readonly pwd: number;
|
readonly pwd: NodePointer;
|
||||||
readonly exitCode: number;
|
readonly exitCode: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +66,7 @@ export function login(
|
|||||||
|
|
||||||
const stack = [...state.sessionStack];
|
const stack = [...state.sessionStack];
|
||||||
stack.push(createInitialSessionState(user));
|
stack.push(createInitialSessionState(user));
|
||||||
return createShellState(state.filesystem, state.users, stack);
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logout(state: ShellState): ShellState {
|
export function logout(state: ShellState): ShellState {
|
||||||
@@ -67,7 +74,7 @@ export function logout(state: ShellState): ShellState {
|
|||||||
const stack = [...state.sessionStack];
|
const stack = [...state.sessionStack];
|
||||||
stack.pop();
|
stack.pop();
|
||||||
|
|
||||||
return createShellState(state.filesystem, state.users, stack);
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
||||||
}
|
}
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-4
@@ -1,46 +1,55 @@
|
|||||||
import type { FileSystem } from "./filesystem/filesystem";
|
import type { FileSystem } from "./filesystem/filesystem";
|
||||||
|
import type { NodePointer } from "./filesystem/node";
|
||||||
import { addHistoryEntry } from "./history_state";
|
import { addHistoryEntry } from "./history_state";
|
||||||
import type { UserInfo } from "./session_manager";
|
import type { GroupInfo, UserInfo } from "./session_manager";
|
||||||
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
|
import { createInitialSessionState, getCurrentSession, type SessionState } from "./session_manager";
|
||||||
|
|
||||||
export interface ShellState {
|
export interface ShellState {
|
||||||
readonly filesystem: FileSystem;
|
readonly filesystem: FileSystem;
|
||||||
readonly users: ReadonlyMap<number, UserInfo>;
|
readonly users: ReadonlyMap<number, UserInfo>;
|
||||||
|
readonly groups: ReadonlyMap<number, GroupInfo>;
|
||||||
readonly sessionStack: ReadonlyArray<SessionState>;
|
readonly sessionStack: ReadonlyArray<SessionState>;
|
||||||
|
//readonly commmandRegistry: CommandRegistry;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createInitialShellState(
|
export function createInitialShellState(
|
||||||
filesystem: FileSystem,
|
filesystem: FileSystem,
|
||||||
users: ReadonlyMap<number, UserInfo>,
|
users: ReadonlyMap<number, UserInfo>,
|
||||||
|
groups: ReadonlyMap<number, GroupInfo>,
|
||||||
user: UserInfo,
|
user: UserInfo,
|
||||||
|
//commandRegistry: CommandRegistry,
|
||||||
): ShellState {
|
): ShellState {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem,
|
filesystem,
|
||||||
users,
|
users,
|
||||||
|
groups,
|
||||||
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
||||||
|
//commandRegistry,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createShellState(
|
export function createShellState(
|
||||||
filesystem: FileSystem,
|
filesystem: FileSystem,
|
||||||
users: ReadonlyMap<number, UserInfo>,
|
users: ReadonlyMap<number, UserInfo>,
|
||||||
|
groups: ReadonlyMap<number, GroupInfo>,
|
||||||
sessionStack: ReadonlyArray<SessionState>,
|
sessionStack: ReadonlyArray<SessionState>,
|
||||||
): ShellState {
|
): ShellState {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem,
|
filesystem,
|
||||||
users,
|
users,
|
||||||
|
groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function withCwd(state: ShellState, inode: number): ShellState {
|
export function withCwd(state: ShellState, ptr: NodePointer): ShellState {
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
const newSession = Object.freeze({
|
const newSession = Object.freeze({
|
||||||
user: session.user,
|
user: session.user,
|
||||||
envVars: Object.freeze(session.envVars),
|
envVars: Object.freeze(session.envVars),
|
||||||
history: Object.freeze(session.history),
|
history: Object.freeze(session.history),
|
||||||
cwd: inode,
|
cwd: ptr,
|
||||||
pwd: session.cwd,
|
pwd: session.cwd,
|
||||||
exitCode: session.exitCode,
|
exitCode: session.exitCode,
|
||||||
} satisfies SessionState);
|
} satisfies SessionState);
|
||||||
@@ -52,11 +61,12 @@ export function withCwd(state: ShellState, inode: number): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function withHistory(state: ShellState, input: string): ShellState {
|
export function withHistory(state: ShellState, input: Uint8Array): ShellState {
|
||||||
const session = getCurrentSession(state);
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
const newSession = Object.freeze({
|
const newSession = Object.freeze({
|
||||||
@@ -75,6 +85,7 @@ export function withHistory(state: ShellState, input: string): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
@@ -101,6 +112,7 @@ export function withEnv(state: ShellState, key: string, value: string): ShellSta
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
@@ -124,6 +136,7 @@ export function withExitCode(state: ShellState, exitCode: number): ShellState {
|
|||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem: state.filesystem,
|
filesystem: state.filesystem,
|
||||||
users: state.users,
|
users: state.users,
|
||||||
|
groups: state.groups,
|
||||||
sessionStack: Object.freeze(sessionStack),
|
sessionStack: Object.freeze(sessionStack),
|
||||||
} satisfies ShellState);
|
} satisfies ShellState);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
export type Input = string;
|
|
||||||
|
|
||||||
//Payload optional because command that handles that signal
|
|
||||||
// is going to know what shape it is, therefore also able to cast it;
|
|
||||||
export type Signal = {
|
|
||||||
type: string;
|
|
||||||
payload?: unknown;
|
|
||||||
};
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { SIGNAL_MAP } from "@shell/shell";
|
||||||
|
|
||||||
export interface ShellError {
|
export interface ShellError {
|
||||||
readonly errorType: string;
|
readonly errorType: string;
|
||||||
readonly message: string;
|
readonly message: string;
|
||||||
@@ -18,7 +20,7 @@ export function createShellError<E extends ShellError>(
|
|||||||
let exitCode = EXIT_CODE_MAP[errorType] ?? 1;
|
let exitCode = EXIT_CODE_MAP[errorType] ?? 1;
|
||||||
|
|
||||||
// Special handling for signal termination
|
// Special handling for signal termination
|
||||||
if (errorType === "SIGNAL_TERMINATION") {
|
if (errorType === "SignalTermination") {
|
||||||
const signalError = extraProps as unknown as { signalNumber: number };
|
const signalError = extraProps as unknown as { signalNumber: number };
|
||||||
exitCode = 128 + signalError.signalNumber;
|
exitCode = 128 + signalError.signalNumber;
|
||||||
}
|
}
|
||||||
@@ -38,6 +40,7 @@ const EXIT_CODE_MAP: Record<string, number> = {
|
|||||||
GenericError: 1,
|
GenericError: 1,
|
||||||
InvalidArguments: 2,
|
InvalidArguments: 2,
|
||||||
|
|
||||||
|
ParseError: 62,
|
||||||
UsageError: 63,
|
UsageError: 63,
|
||||||
PathResolutionError: 64,
|
PathResolutionError: 64,
|
||||||
DataFormatError: 65,
|
DataFormatError: 65,
|
||||||
@@ -218,6 +221,5 @@ export interface ProtocolError extends ShellError {
|
|||||||
/** Process was killed by a signal (Exit = 128 + signalNumber) */
|
/** Process was killed by a signal (Exit = 128 + signalNumber) */
|
||||||
export interface SignalTerminationError extends ShellError {
|
export interface SignalTerminationError extends ShellError {
|
||||||
errorType: "SignalTermination";
|
errorType: "SignalTermination";
|
||||||
signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT)
|
signal: SIGNAL_MAP;
|
||||||
signalName: string; // e.g., "SIGTERM", "SIGKILL"
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export interface ImmutableBuffer {
|
|||||||
readonly length: number;
|
readonly length: number;
|
||||||
get(index: number): number;
|
get(index: number): number;
|
||||||
slice(start?: number, end?: number): ImmutableBuffer;
|
slice(start?: number, end?: number): ImmutableBuffer;
|
||||||
|
byteSize(): number;
|
||||||
toArray(): Uint8Array;
|
toArray(): Uint8Array;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,10 +23,15 @@ export function createImmutableBuffer(input: Uint8Array): ImmutableBuffer {
|
|||||||
return Uint8Array.from(buffer);
|
return Uint8Array.from(buffer);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const byteSize = (): number => {
|
||||||
|
return buffer.byteLength;
|
||||||
|
};
|
||||||
|
|
||||||
const result: ImmutableBuffer = {
|
const result: ImmutableBuffer = {
|
||||||
length: buffer.length,
|
length: buffer.length,
|
||||||
get,
|
get,
|
||||||
slice,
|
slice,
|
||||||
|
byteSize,
|
||||||
toArray,
|
toArray,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+2
-52
@@ -6,19 +6,14 @@ interface UnclosedQuoteError {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ParsedCommand {
|
export function tokenize(buff: Uint8Array): string[] {
|
||||||
command: string;
|
|
||||||
flags: string[];
|
|
||||||
args: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenize(input: string): string[] {
|
|
||||||
enum State {
|
enum State {
|
||||||
Normal,
|
Normal,
|
||||||
SingleQuote,
|
SingleQuote,
|
||||||
DoubleQuote,
|
DoubleQuote,
|
||||||
Escape,
|
Escape,
|
||||||
}
|
}
|
||||||
|
const input = new TextDecoder().decode(buff);
|
||||||
|
|
||||||
const tokens: string[] = [];
|
const tokens: string[] = [];
|
||||||
const buffer: string[] = [];
|
const buffer: string[] = [];
|
||||||
@@ -98,48 +93,3 @@ function tokenize(input: string): string[] {
|
|||||||
flushBuffer();
|
flushBuffer();
|
||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseCommand(input: string): ParsedCommand {
|
|
||||||
const tokens = tokenize(input);
|
|
||||||
const command = tokens[0] ?? "";
|
|
||||||
const flags: string[] = [];
|
|
||||||
const args: string[] = [];
|
|
||||||
|
|
||||||
let pastEndOfOptions = false;
|
|
||||||
|
|
||||||
for (let i = 1; i < tokens.length; i++) {
|
|
||||||
const token = tokens[i]!;
|
|
||||||
|
|
||||||
if (pastEndOfOptions) {
|
|
||||||
args.push(token);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (token === "--") {
|
|
||||||
pastEndOfOptions = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.startsWith("--")) {
|
|
||||||
flags.push(token.slice(2));
|
|
||||||
continue;
|
|
||||||
} else if (token.startsWith("-")) {
|
|
||||||
if (token.includes("=")) {
|
|
||||||
flags.push(token.slice(1));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (const char of token.slice(1)) {
|
|
||||||
flags.push(char);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
args.push(token);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
command,
|
|
||||||
flags,
|
|
||||||
args,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
+241
-45
@@ -1,73 +1,269 @@
|
|||||||
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
|
||||||
import type { FileSystem } from "../filesystem/filesystem";
|
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
|
||||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
|
||||||
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
export function resolvePath(state: ShellState, path: string): NodePointer {
|
||||||
|
let linkDepth = 0;
|
||||||
|
const maxDepth = state.filesystem.maxSymlinkDepth;
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
const isAbsolute = path.startsWith("/");
|
const isAbsolute = path.startsWith("/");
|
||||||
|
|
||||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
|
||||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
|
||||||
|
|
||||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
let currentDeviceId: number;
|
||||||
if (pathComponents.length === 0) return cwd;
|
let currentNode: Node;
|
||||||
|
|
||||||
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
|
if (isAbsolute) {
|
||||||
if (!currentNode) {
|
currentDeviceId = 0;
|
||||||
throw {
|
currentNode = state.filesystem.getRoot();
|
||||||
type: "NodeNotFound",
|
} else if (!isAbsolute && pathComponents[0] === "~") {
|
||||||
message: `CWD node under inode ${cwd} not found`,
|
const home = session.user.home;
|
||||||
timestamp: Date.now(),
|
currentDeviceId = home.device;
|
||||||
inode: cwd,
|
currentNode = state.filesystem.getNode(session.user.home)!;
|
||||||
} satisfies NodeNotFoundError;
|
if (!currentNode) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `[Panic] ${session.user.username}'s home directory does not exist!`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: session.user.home,
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
|
pathComponents.shift();
|
||||||
|
|
||||||
|
if (currentNode.type === NodeType.Symlink) {
|
||||||
|
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||||
|
const target = currentNode.target;
|
||||||
|
if (target.startsWith("/")) {
|
||||||
|
currentDeviceId = 0;
|
||||||
|
currentNode = state.filesystem.getRoot();
|
||||||
|
} else {
|
||||||
|
const entries = state.filesystem.getNodeEntries(session.user.home);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentDeviceId = session.cwd.device;
|
||||||
|
currentNode = state.filesystem.getNode(session.cwd)!;
|
||||||
|
if (!currentNode) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: "[Panic] Current working directory does not exist!",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: session.cwd,
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const name of pathComponents) {
|
while (pathComponents.length > 0) {
|
||||||
if (name === ".") continue;
|
const name = pathComponents.shift()!;
|
||||||
|
|
||||||
|
if (name === ".") continue;
|
||||||
if (name === "..") {
|
if (name === "..") {
|
||||||
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
|
if (state.filesystem.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
|
||||||
|
const mount = state.filesystem.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||||
|
if (!mount) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Mount registry entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = state.filesystem.getNodeEntries(mount);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (currentNode.inode === 0) continue;
|
||||||
|
|
||||||
|
const entries = state.filesystem.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||||
|
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const inode = currentNode.children[name];
|
if (currentNode.type !== NodeType.Directory) {
|
||||||
|
|
||||||
if (!inode)
|
|
||||||
throw {
|
|
||||||
type: "NodeNotFound",
|
|
||||||
message: `Child node in ${currentNode.name} under name ${name} not found`,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
inode: currentNode.inode,
|
|
||||||
} satisfies NodeNotFoundError;
|
|
||||||
if (fs.isFile(inode))
|
|
||||||
throw {
|
throw {
|
||||||
type: "NotADirectory",
|
type: "NotADirectory",
|
||||||
message: `Child node ${name} is not a directory`,
|
message: "Not a directory",
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: inode,
|
inode: currentNode.inode,
|
||||||
nodeType: TreeNodeType.File,
|
nodeType: currentNode.type,
|
||||||
} satisfies NotADirectoryError;
|
} satisfies NotADirectoryError;
|
||||||
|
}
|
||||||
|
|
||||||
currentNode = fs.getNode(inode) as DirectoryNode;
|
const childInode = currentNode.children.get(name);
|
||||||
|
if (childInode === undefined) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `${name} not found`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
|
|
||||||
|
let childPtr = NodePointer.of(currentDeviceId, childInode);
|
||||||
|
|
||||||
|
if (state.filesystem.isMountPoint(childPtr)) {
|
||||||
|
const mount = state.filesystem.getMountTarget(childPtr)!;
|
||||||
|
childPtr = mount;
|
||||||
|
currentDeviceId = mount.device;
|
||||||
|
}
|
||||||
|
|
||||||
|
let child = state.filesystem.getNode(childPtr);
|
||||||
|
if (!child) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `Node under ${childPtr} not found (probable dangling orphan)`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: childPtr,
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (child.type === NodeType.Symlink) {
|
||||||
|
// Change to typed error later on
|
||||||
|
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||||
|
const target = child.target;
|
||||||
|
if (target.startsWith("/")) {
|
||||||
|
currentDeviceId = 0;
|
||||||
|
currentNode = state.filesystem.getRoot();
|
||||||
|
} else {
|
||||||
|
const entries = state.filesystem.getNodeEntries(childPtr);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = state.filesystem.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = child;
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentNode.inode;
|
return NodePointer.of(currentDeviceId, currentNode.inode);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveInode(fs: FileSystem, inode: number): string {
|
export function resolvePointer(state: ShellState, pointer: NodePointer): string {
|
||||||
const node = fs.getNode(inode);
|
const node = state.filesystem.getNode(pointer);
|
||||||
const components: string[] = [];
|
const components: string[] = [];
|
||||||
|
|
||||||
if (node === undefined) return "";
|
if (node === undefined) return "";
|
||||||
|
|
||||||
let currentInode = inode;
|
let ptr = pointer;
|
||||||
while (currentInode !== 0) {
|
// TODO: Change while statements condition to not be hardcoded
|
||||||
const node = fs.getNode(currentInode) as TreeNode;
|
while (!ptr.equals(NodePointer.of(0, 0))) {
|
||||||
if (!node) break;
|
if (state.filesystem.isMountTarget(ptr)) {
|
||||||
|
const mount = state.filesystem.getMountPoint(ptr);
|
||||||
|
if (!mount) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Mount registry entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
components.push(node.name);
|
const entries = state.filesystem.getNodeEntries(mount);
|
||||||
currentInode = node.parent;
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
components.push(entries[0].name);
|
||||||
|
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = state.filesystem.getNodeEntries(ptr);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
components.push(entries[0].name);
|
||||||
|
ptr = NodePointer.of(entries[0].pdevice_id, entries[0].pinode);
|
||||||
}
|
}
|
||||||
components.reverse();
|
if (components.length === 0) {
|
||||||
components.unshift("");
|
components.push("/");
|
||||||
return components.join("/");
|
return components.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
components.reverse().unshift("");
|
||||||
|
let result = components.join("/");
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePointerToHome(state: ShellState, ptr: NodePointer): string {
|
||||||
|
const home = resolvePointer(state, getCurrentSession(state).user.home);
|
||||||
|
let result = resolvePointer(state, ptr);
|
||||||
|
|
||||||
|
if (result.startsWith(home)) {
|
||||||
|
result = `~${result.slice(home.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePointerToCwd(state: ShellState, ptr: NodePointer): string {
|
||||||
|
const cwd = resolvePointer(state, getCurrentSession(state).cwd);
|
||||||
|
let result = resolvePointer(state, ptr);
|
||||||
|
|
||||||
|
if (result.startsWith(cwd)) {
|
||||||
|
result = `.${result.slice(cwd.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePointerRelative(state: ShellState, ptr: NodePointer, relative: NodePointer): string {
|
||||||
|
const rel = resolvePointer(state, relative);
|
||||||
|
let result = resolvePointer(state, ptr);
|
||||||
|
|
||||||
|
if (result.startsWith(rel)) {
|
||||||
|
result = `.${result.slice(rel.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { FileNode, NodePointer } from "@core/filesystem/node";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import { Posix } from "@termos/util/posix";
|
||||||
|
|
||||||
|
export enum SortNodeBy {
|
||||||
|
NAME = "name",
|
||||||
|
INODE = "inode",
|
||||||
|
SIZE = "size",
|
||||||
|
EXTENSION = "extension",
|
||||||
|
TYPE = "type",
|
||||||
|
MTIME = "mtime",
|
||||||
|
ATIME = "atime",
|
||||||
|
CTIME = "ctime",
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortNodes<T extends { name: string; ptr: NodePointer }>(
|
||||||
|
state: ShellState,
|
||||||
|
arr: T[],
|
||||||
|
r: boolean = false,
|
||||||
|
by: SortNodeBy = SortNodeBy.NAME,
|
||||||
|
): T[] {
|
||||||
|
if (arr.length === 0) return [];
|
||||||
|
|
||||||
|
nodeQS(arr, r, by, 0, arr.length - 1, state);
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeQS(
|
||||||
|
arr: { name: string; ptr: NodePointer }[],
|
||||||
|
r: boolean,
|
||||||
|
by: SortNodeBy,
|
||||||
|
start: number,
|
||||||
|
end: number,
|
||||||
|
state: ShellState,
|
||||||
|
): void {
|
||||||
|
if (end <= start) return;
|
||||||
|
|
||||||
|
const pivot = partitionNodeArray(arr, r, by, start, end, state);
|
||||||
|
nodeQS(arr, r, by, start, pivot - 1, state);
|
||||||
|
nodeQS(arr, r, by, pivot + 1, end, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
function partitionNodeArray(
|
||||||
|
part: { name: string; ptr: NodePointer }[],
|
||||||
|
r: boolean,
|
||||||
|
by: SortNodeBy,
|
||||||
|
start: number,
|
||||||
|
end: number,
|
||||||
|
state: ShellState,
|
||||||
|
): number {
|
||||||
|
const pivot = part[end];
|
||||||
|
let i = start - 1;
|
||||||
|
|
||||||
|
for (let j = start; j <= end; j++) {
|
||||||
|
if (compareNode(part[j]!, pivot!, by, r, state) < 0) {
|
||||||
|
i++;
|
||||||
|
const temp = part[i]!;
|
||||||
|
part[i] = part[j]!;
|
||||||
|
part[j] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
i++;
|
||||||
|
const temp = part[i]!;
|
||||||
|
part[i] = part[end]!;
|
||||||
|
part[end] = temp;
|
||||||
|
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareNode(
|
||||||
|
a: { name: string; ptr: NodePointer },
|
||||||
|
b: { name: string; ptr: NodePointer },
|
||||||
|
by: SortNodeBy,
|
||||||
|
r: boolean,
|
||||||
|
state: ShellState,
|
||||||
|
): number {
|
||||||
|
switch (by) {
|
||||||
|
case SortNodeBy.NAME: {
|
||||||
|
const A: string = a.name;
|
||||||
|
const B: string = b.name;
|
||||||
|
const min = Math.min(A.length, B.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < min; i++) {
|
||||||
|
const charA = Posix.GetCharWeight(A.charAt(i));
|
||||||
|
const charB = Posix.GetCharWeight(B.charAt(i));
|
||||||
|
|
||||||
|
if (charA !== charB) {
|
||||||
|
return r ? charB - charA : charA - charB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return r ? B.length - A.length : A.length - B.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortNodeBy.MTIME:
|
||||||
|
case SortNodeBy.ATIME:
|
||||||
|
case SortNodeBy.CTIME: {
|
||||||
|
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||||
|
const nodeB = state.filesystem.getNode(b.ptr)!;
|
||||||
|
const A: number = nodeA[by];
|
||||||
|
const B: number = nodeB[by];
|
||||||
|
|
||||||
|
return r ? A - B : B - A;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortNodeBy.SIZE: {
|
||||||
|
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||||
|
const nodeB = state.filesystem.getNode(b.ptr)!;
|
||||||
|
const A: number = (nodeA as FileNode).size;
|
||||||
|
const B: number = (nodeB as FileNode).size;
|
||||||
|
|
||||||
|
return r ? A - B : B - A;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortNodeBy.EXTENSION: {
|
||||||
|
const A: string = a.name.split(".").pop() ?? "";
|
||||||
|
const B: string = b.name.split(".").pop() ?? "";
|
||||||
|
const min = Math.min(A.length, B.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < min; i++) {
|
||||||
|
const charA = Posix.GetCharWeight(A.charAt(i));
|
||||||
|
const charB = Posix.GetCharWeight(B.charAt(i));
|
||||||
|
|
||||||
|
if (charA !== charB) {
|
||||||
|
return r ? charB - charA : charA - charB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return r ? B.length - A.length : A.length - B.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortNodeBy.INODE: {
|
||||||
|
return r ? b.ptr.inode - a.ptr.inode : a.ptr.inode - b.ptr.inode;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortNodeBy.TYPE: {
|
||||||
|
const nodeA = state.filesystem.getNode(a.ptr)!;
|
||||||
|
const nodeB = state.filesystem.getNode(a.ptr)!;
|
||||||
|
return r ? nodeB.type - nodeA.type : nodeA.type - nodeB.type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import type { Node } from "@core/filesystem/node";
|
||||||
|
import type { IDataStore, IMetaStore } from "@core/filesystem/vdisk";
|
||||||
|
|
||||||
|
export class MemMetaStore implements IMetaStore {
|
||||||
|
private _data: Map<number, Node | null> = new Map();
|
||||||
|
|
||||||
|
public loadAll(): Promise<Map<number, Node | null>> {
|
||||||
|
return Promise.resolve(this._data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public write(entries: Array<[number, Node | null]>): Promise<void> {
|
||||||
|
for (const [inode, node] of entries) {
|
||||||
|
this._data.set(inode, node);
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
public delete(entries: number[]): Promise<void> {
|
||||||
|
for (const inode of entries) {
|
||||||
|
this._data.delete(inode);
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MemDataStore implements IDataStore {
|
||||||
|
private _data: Map<string, Blob> = new Map();
|
||||||
|
|
||||||
|
public async read(uuid: string): Promise<Uint8Array> {
|
||||||
|
const blob = this._data.get(uuid);
|
||||||
|
if (!blob) throw new Error("Content missing - " + uuid);
|
||||||
|
const buff = await blob.arrayBuffer();
|
||||||
|
return new Uint8Array(buff);
|
||||||
|
}
|
||||||
|
|
||||||
|
public stream(uuid: string): ReadableStream {
|
||||||
|
const blob = this._data.get(uuid);
|
||||||
|
if (!blob) throw new Error("Content missing - " + uuid);
|
||||||
|
|
||||||
|
return blob.stream();
|
||||||
|
}
|
||||||
|
|
||||||
|
public put(uuid: string, blob: Blob): Promise<void> {
|
||||||
|
this._data.set(uuid, blob);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
public delete(uuid: string): Promise<void> {
|
||||||
|
this._data.delete(uuid);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
public has(uuid: string): Promise<boolean> {
|
||||||
|
return Promise.resolve(this._data.has(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
public list(): Promise<string[]> {
|
||||||
|
return Promise.resolve(Array.from(this._data.keys()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,41 +1,44 @@
|
|||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType, type TreeNode } from "@core/filesystem/treenode";
|
import { NodePointer, NodeType, type NodeEntry } from "@core/filesystem/node";
|
||||||
|
|
||||||
export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
export function dnTraverseTree(fs: FileSystem, root: NodePointer): NodePointer[] {
|
||||||
if (fs.getNode(root) === undefined) return [];
|
if (fs.getNode(root) === undefined) return [];
|
||||||
|
|
||||||
const result: number[] = [];
|
const result: NodePointer[] = [];
|
||||||
const stack: number[] = [];
|
const stack: NodePointer[] = [];
|
||||||
stack.push(root);
|
stack.push(root);
|
||||||
while (stack.length > 0) {
|
while (stack.length > 0) {
|
||||||
const node = fs.getNode(stack.pop() as number);
|
const ptr = stack.pop()!;
|
||||||
if (node === undefined) continue;
|
const node = fs.getNode(ptr);
|
||||||
|
if (!node) continue;
|
||||||
|
|
||||||
result.push(node.inode);
|
result.push(ptr);
|
||||||
|
|
||||||
if (node.type === TreeNodeType.Directory) {
|
if (node.type === NodeType.Directory) {
|
||||||
for (const value of Object.values(node.children)) {
|
const children = Array.from(node.children.values());
|
||||||
stack.push(value);
|
for (let i = children.length - 1; i >= 0; i--) {
|
||||||
|
const child = children[i]!;
|
||||||
|
const pointer = NodePointer.of(ptr.device, child);
|
||||||
|
stack.push(pointer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function upTraverseTree(fs: FileSystem, inode: number): number[] {
|
export function upTraverseTree(fs: FileSystem, ptr: NodePointer): NodePointer[] {
|
||||||
if (fs.getNode(inode) === undefined) return [];
|
if (fs.getNode(ptr) === undefined) return [];
|
||||||
|
|
||||||
const result: number[] = [];
|
const result: NodePointer[] = [ptr];
|
||||||
result.push(inode);
|
let currentPtr = ptr;
|
||||||
|
|
||||||
let currentInode = inode;
|
while (currentPtr.inode !== 0) {
|
||||||
while (currentInode !== 0) {
|
const entries = fs.getNodeEntries(currentPtr);
|
||||||
const node = fs.getNode(currentInode) as TreeNode;
|
if (!entries || entries.length === 0) throw new Error(`No reverse-index entry found for ${currentPtr}`);
|
||||||
if (!node) break;
|
|
||||||
|
|
||||||
result.push(node.parent);
|
const parent = entries[0] as NodeEntry;
|
||||||
currentInode = node.parent;
|
currentPtr = NodePointer.of(parent.pdevice_id, parent.pinode);
|
||||||
|
result.push(currentPtr);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { IDataStore, IMetaStore, VDisk, VDiskConfig } from "@core/filesystem/vdisk";
|
||||||
|
|
||||||
|
export class VDiskManager {
|
||||||
|
private _disks: Map<number, VDisk>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._disks = new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async registerDisk(config: VDiskConfig, data: IDataStore, meta: IMetaStore): Promise<VDisk> {
|
||||||
|
if (this._disks.has(config.id)) {
|
||||||
|
throw new Error("Disk of this id already exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
const vd = await VDisk.open(config, data, meta);
|
||||||
|
this._disks.set(config.id, vd);
|
||||||
|
|
||||||
|
return vd;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getDisk(id: number): VDisk | undefined {
|
||||||
|
const vd = this._disks.get(id);
|
||||||
|
return vd;
|
||||||
|
}
|
||||||
|
|
||||||
|
public hasDisk(id: number): boolean {
|
||||||
|
return this._disks.has(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public listDisk(): VDisk[] {
|
||||||
|
return Array.from(this._disks.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public listID(): number[] {
|
||||||
|
return Array.from(this._disks.keys());
|
||||||
|
}
|
||||||
|
|
||||||
|
public unregisterDisk(id: number): void {
|
||||||
|
if (!this._disks.has(id)) {
|
||||||
|
throw new Error("Disk of this id doesnt exist");
|
||||||
|
}
|
||||||
|
|
||||||
|
this._disks.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
File diff suppressed because one or more lines are too long
+188
@@ -0,0 +1,188 @@
|
|||||||
|
import type { FileSystemCorruptionError, NodeNotFoundError, NotADirectoryError } from "@core/filesystem/errors";
|
||||||
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
|
import { NodePointer, NodeType, type Node } from "@core/filesystem/node";
|
||||||
|
import type { GroupInfo, UserInfo } from "@core/session_manager";
|
||||||
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
|
import { deserializeFileSystem } from "@shell/serializer";
|
||||||
|
import { Shell } from "@shell/shell";
|
||||||
|
import type { TermosConfig } from "./config";
|
||||||
|
|
||||||
|
async function getShell(config: TermosConfig): Promise<Shell> {
|
||||||
|
// TODO: Validate json schema
|
||||||
|
const devices = deserializeFileSystem(config.filesystem.json);
|
||||||
|
|
||||||
|
const fs = await FileSystem.init(devices);
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const groups: Map<number, GroupInfo> = new Map();
|
||||||
|
const reverseGroups: Map<string, number> = new Map();
|
||||||
|
const reverseUsers: Map<string, number> = new Map();
|
||||||
|
|
||||||
|
if (config.users.length === 0) throw new Error("System needs to have at least one user");
|
||||||
|
if (config.groups.length === 0) throw new Error("System needs to have at least one user group");
|
||||||
|
for (let i = 1000; i < config.groups.length + 1000; i++) {
|
||||||
|
const group = config.groups[i - 1000]!;
|
||||||
|
reverseGroups.set(group, i);
|
||||||
|
|
||||||
|
const members: number[] = [];
|
||||||
|
for (let i = 1000; i < config.users.length + 1000; i++) {
|
||||||
|
const user = config.users[i - 1000]!;
|
||||||
|
if (user.groups.some(g => g === group)) {
|
||||||
|
members.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groups.set(i, { groupname: group, gid: i, members });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 1000; i < config.users.length + 1000; i++) {
|
||||||
|
const user = config.users[i - 1000]!;
|
||||||
|
if (user.groups.length === 0) throw new Error("User must belong to at least one user group");
|
||||||
|
|
||||||
|
const gid = reverseGroups.get(user.groups[0]!);
|
||||||
|
if (!gid) throw new Error("User is a member of an undefined group");
|
||||||
|
|
||||||
|
const groups: number[] = [];
|
||||||
|
|
||||||
|
for (const group of user.groups) {
|
||||||
|
if (group === "sudoers") continue;
|
||||||
|
const gid = reverseGroups.get(group);
|
||||||
|
if (!gid) throw new Error("User is a member of an undefined group");
|
||||||
|
groups.push(gid);
|
||||||
|
}
|
||||||
|
|
||||||
|
reverseUsers.set(user.username, i);
|
||||||
|
users.set(i, { username: user.username, uid: i, gid, group: groups, home: resPath(user.home) });
|
||||||
|
}
|
||||||
|
const uid = reverseUsers.get(config.general.user);
|
||||||
|
if (!uid) throw new Error("Tried to initialize termos with an undefined user");
|
||||||
|
|
||||||
|
const user = users.get(uid)!;
|
||||||
|
|
||||||
|
const state: ShellState = createInitialShellState(fs, users, groups, user);
|
||||||
|
return new Shell(state);
|
||||||
|
|
||||||
|
function resPath(path: string) {
|
||||||
|
let linkDepth = 0;
|
||||||
|
const maxDepth = fs.maxSymlinkDepth;
|
||||||
|
|
||||||
|
const pathComponents: string[] = path.split("/").filter(c => c.length > 0);
|
||||||
|
|
||||||
|
let currentDeviceId: number = 0;
|
||||||
|
let currentNode: Node = fs.getRoot();
|
||||||
|
|
||||||
|
while (pathComponents.length > 0) {
|
||||||
|
const name = pathComponents.shift()!;
|
||||||
|
|
||||||
|
if (name === ".") continue;
|
||||||
|
if (name === "..") {
|
||||||
|
if (fs.isMountTarget(NodePointer.of(currentDeviceId, currentNode.inode))) {
|
||||||
|
const mount = fs.getMountPoint(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||||
|
if (!mount) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Mount registry entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = fs.getNodeEntries(mount);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (currentNode.inode === 0) continue;
|
||||||
|
|
||||||
|
const entries = fs.getNodeEntries(NodePointer.of(currentDeviceId, currentNode.inode));
|
||||||
|
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentNode.type !== NodeType.Directory) {
|
||||||
|
throw {
|
||||||
|
type: "NotADirectory",
|
||||||
|
message: "Not a directory",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
inode: currentNode.inode,
|
||||||
|
nodeType: currentNode.type,
|
||||||
|
} satisfies NotADirectoryError;
|
||||||
|
}
|
||||||
|
|
||||||
|
const childInode = currentNode.children.get(name);
|
||||||
|
if (childInode === undefined) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `${name} not found`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: NodePointer.of(currentDeviceId, currentNode.inode),
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
|
|
||||||
|
let childPtr = NodePointer.of(currentDeviceId, childInode);
|
||||||
|
|
||||||
|
if (fs.isMountPoint(childPtr)) {
|
||||||
|
const mount = fs.getMountTarget(childPtr)!;
|
||||||
|
childPtr = mount;
|
||||||
|
currentDeviceId = mount.device;
|
||||||
|
}
|
||||||
|
|
||||||
|
let child = fs.getNode(childPtr);
|
||||||
|
if (!child) {
|
||||||
|
throw {
|
||||||
|
type: "NodeNotFound",
|
||||||
|
message: `Node under ${childPtr} not found (probable dangling orphan)`,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
pointer: childPtr,
|
||||||
|
} satisfies NodeNotFoundError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (child.type === NodeType.Symlink) {
|
||||||
|
if (++linkDepth > maxDepth) throw new Error("Symlink max depth - aborting!");
|
||||||
|
const target = child.target;
|
||||||
|
if (target.startsWith("/")) {
|
||||||
|
currentDeviceId = 0;
|
||||||
|
currentNode = fs.getRoot();
|
||||||
|
} else {
|
||||||
|
const entries = fs.getNodeEntries(childPtr);
|
||||||
|
if (!entries?.[0]) {
|
||||||
|
throw {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: "Reverse index entry missing, FileSystem corrupted",
|
||||||
|
timestamp: Date.now(),
|
||||||
|
} satisfies FileSystemCorruptionError;
|
||||||
|
}
|
||||||
|
currentDeviceId = entries[0].pdevice_id;
|
||||||
|
currentNode = fs.getNode(NodePointer.of(entries[0].pdevice_id, entries[0].pinode))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
pathComponents.unshift(...target.split("/").filter(c => c.length > 0));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = child;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NodePointer.of(currentDeviceId, currentNode.inode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Termos = {
|
||||||
|
getShell,
|
||||||
|
};
|
||||||
+8
-15
@@ -1,15 +1,8 @@
|
|||||||
import { defaultConfig, TermosConfig } from "./config";
|
export {
|
||||||
|
resolvePointer,
|
||||||
let config: TermosConfig = { ...defaultConfig };
|
resolvePointerRelative,
|
||||||
|
resolvePointerToCwd,
|
||||||
namespace Termos {
|
resolvePointerToHome,
|
||||||
export function init(config: Partial<TermosConfig>) {
|
} from "@core/util/path_resolver";
|
||||||
config = { ...defaultConfig, ...config};
|
export { Termos } from "./entry";
|
||||||
console.log("termos initialized");
|
export { type Shell } from "./shell/index";
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const message: string = "Hello, World!";
|
|
||||||
console.log(message);
|
|
||||||
|
|
||||||
export { Termos };
|
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
/*
|
|
||||||
Create an interface for the rest of the library to use to fetch nessesary data.
|
|
||||||
To do that, implement a termos config that will contain the table and db names, aswell as other relevant information -
|
|
||||||
maybe a flag for headless mode (uses the built-in console frontend module - need to evaluate this idea more)
|
|
||||||
*/
|
|
||||||
|
|
||||||
export async fetchFileSystem(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export async fetchUserGroups(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export async fetchUsers(): Promise<JSON> {
|
|
||||||
|
|
||||||
}
|
|
||||||
+15
-13
@@ -1,26 +1,28 @@
|
|||||||
|
type Listener = (payload: unknown) => void;
|
||||||
|
|
||||||
export class EventEmitter<TEvents> {
|
export class EventEmitter<TEvents> {
|
||||||
private handlers: Map<keyof TEvents, Set<Function>> = new Map();
|
private Handlers: Map<keyof TEvents, Set<Listener>> = new Map();
|
||||||
|
|
||||||
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||||
const listeners = this.handlers.get(type);
|
const listeners = this.Handlers.get(type);
|
||||||
|
|
||||||
if (listeners) {
|
if (listeners) {
|
||||||
listeners.add(handler);
|
listeners.add(handler as Listener);
|
||||||
} else {
|
} else {
|
||||||
const set: Set<Function> = new Set();
|
const set: Set<Listener> = new Set();
|
||||||
set.add(handler);
|
set.add(handler as Listener);
|
||||||
this.handlers.set(type, set);
|
this.Handlers.set(type, set);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (): void => this.off(type, handler);
|
return (): void => this.off(type, handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
||||||
this.handlers.get(type)?.delete(handler);
|
this.Handlers.get(type)?.delete(handler as Listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||||
const listeners = this.handlers.get(type);
|
const listeners = this.Handlers.get(type);
|
||||||
|
|
||||||
const wrapper = (payload: TEvents[K]) => {
|
const wrapper = (payload: TEvents[K]) => {
|
||||||
handler(payload);
|
handler(payload);
|
||||||
@@ -28,18 +30,18 @@ export class EventEmitter<TEvents> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (listeners) {
|
if (listeners) {
|
||||||
listeners.add(wrapper);
|
listeners.add(wrapper as Listener);
|
||||||
} else {
|
} else {
|
||||||
const set: Set<Function> = new Set();
|
const set: Set<Listener> = new Set();
|
||||||
set.add(wrapper);
|
set.add(wrapper as Listener);
|
||||||
this.handlers.set(type, set);
|
this.Handlers.set(type, set);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (): void => this.off(type, wrapper);
|
return (): void => this.off(type, wrapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void {
|
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void {
|
||||||
const listeners = this.handlers.get(type);
|
const listeners = this.Handlers.get(type);
|
||||||
|
|
||||||
if (listeners) {
|
if (listeners) {
|
||||||
for (const listener of [...listeners]) {
|
for (const listener of [...listeners]) {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { type Shell } from "./shell";
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import type { CommandDescriptor } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { ShellError, SignalTerminationError } from "@core/util/errors";
|
||||||
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
|
import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { ShellEventMap, SIGNAL_MAP, type Input } from "./shell";
|
||||||
|
|
||||||
|
export class Process {
|
||||||
|
private _InputQueue: Input[] = [];
|
||||||
|
private _InputHandler: ((signal: Input) => void) | null = null;
|
||||||
|
private _StdoutChunks: Uint8Array[] = [];
|
||||||
|
private _StderrChunks: Uint8Array[] = [];
|
||||||
|
private _Settled: boolean = false;
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap>;
|
||||||
|
private readonly _MaxChunkByteSize: number;
|
||||||
|
|
||||||
|
readonly PID: number;
|
||||||
|
readonly Name: string;
|
||||||
|
readonly CommandDescriptor: CommandDescriptor;
|
||||||
|
readonly State: ShellState;
|
||||||
|
readonly Args: string[];
|
||||||
|
|
||||||
|
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, args: string[]) {
|
||||||
|
this.PID = pid;
|
||||||
|
this.State = state;
|
||||||
|
this.Name = descriptor.name;
|
||||||
|
this.CommandDescriptor = descriptor;
|
||||||
|
this.Args = args;
|
||||||
|
// Check if positive later and throw an error if so
|
||||||
|
this._MaxChunkByteSize = 1024;
|
||||||
|
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// WARNING, CHUNKING OUTPUT BREAKS FORMATING
|
||||||
|
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
||||||
|
if (this._Settled) return;
|
||||||
|
|
||||||
|
if (data.length <= this._MaxChunkByteSize) {
|
||||||
|
chunks.push(data);
|
||||||
|
this._EventEmitter.emit(eventType, { pid: this.PID, data });
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
const arr = splitUint8Array(data, this._MaxChunkByteSize);
|
||||||
|
for (const ent of arr) {
|
||||||
|
chunks.push(ent);
|
||||||
|
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public execute(): void {
|
||||||
|
const io: CommandIO = {
|
||||||
|
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
|
||||||
|
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
|
||||||
|
onInput: () => {
|
||||||
|
const signal: Input | undefined = this._InputQueue.shift();
|
||||||
|
if (signal !== undefined) return Promise.resolve(signal);
|
||||||
|
|
||||||
|
const promise = new Promise<Input>(resolve => {
|
||||||
|
this._InputHandler = resolve;
|
||||||
|
});
|
||||||
|
return promise;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const promise = this.CommandDescriptor.fn(io, this.State, this.Args);
|
||||||
|
|
||||||
|
promise
|
||||||
|
.then(output => {
|
||||||
|
if (this._Settled) return;
|
||||||
|
|
||||||
|
let result: ResultSuccess | ResultError<ShellError>;
|
||||||
|
const stdout: Uint8Array = concatUint8Arrays(this._StdoutChunks);
|
||||||
|
const stderr: Uint8Array = concatUint8Arrays(this._StderrChunks);
|
||||||
|
|
||||||
|
if (output.result.type === "success") {
|
||||||
|
result = createSuccessResult(
|
||||||
|
this.CommandDescriptor.name,
|
||||||
|
0,
|
||||||
|
createImmutableBuffer(stdout),
|
||||||
|
createImmutableBuffer(stderr),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
result = {
|
||||||
|
...output.result,
|
||||||
|
stdout: createImmutableBuffer(stdout),
|
||||||
|
stderr: createImmutableBuffer(stderr),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
|
||||||
|
this._Settled = true;
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
if (this._Settled) return;
|
||||||
|
|
||||||
|
const result: ResultError<ShellError> = createErrorResult(
|
||||||
|
"GenericError",
|
||||||
|
"Promised output from command function rejected",
|
||||||
|
{},
|
||||||
|
this.CommandDescriptor.name,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
|
name: "Caught error",
|
||||||
|
message: String(error),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public sendInput(input: Input): void {
|
||||||
|
if (this._Settled) return;
|
||||||
|
|
||||||
|
if (this._InputHandler !== null) {
|
||||||
|
this._InputHandler(input);
|
||||||
|
this._InputHandler = null;
|
||||||
|
} else {
|
||||||
|
this._InputQueue.push(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sendSignal(signal: SIGNAL_MAP): void {
|
||||||
|
if (this._Settled) return;
|
||||||
|
|
||||||
|
const result: ResultError<SignalTerminationError> = createErrorResult(
|
||||||
|
"SignalTermination",
|
||||||
|
`Process ${this.Name} PID: ${this.PID} killed by a ${SIGNAL_MAP[signal]}`,
|
||||||
|
{ signal },
|
||||||
|
this.CommandDescriptor.name,
|
||||||
|
);
|
||||||
|
|
||||||
|
switch (signal) {
|
||||||
|
case SIGNAL_MAP.SIGINT:
|
||||||
|
this._Settled = true;
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import type { CommandDescriptor } from "@core/command";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { Process } from "./process";
|
||||||
|
import { Input, ShellEventMap, SIGNAL_MAP } from "./shell";
|
||||||
|
|
||||||
|
export class ProcessManager {
|
||||||
|
private _Processes: Map<number, Process> = new Map();
|
||||||
|
private _PIDIndex: number = 0;
|
||||||
|
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
|
||||||
|
public createProcess(state: ShellState, descriptor: CommandDescriptor, args: string[]): number {
|
||||||
|
const pid = ++this._PIDIndex;
|
||||||
|
const process = new Process(pid, state, descriptor, args);
|
||||||
|
this._Processes.set(pid, process);
|
||||||
|
|
||||||
|
process.on("signal", payload => this._EventEmitter.emit("signal", payload));
|
||||||
|
process.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
|
process.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||||
|
process.on("result", payload => {
|
||||||
|
this._Processes.delete(payload.pid);
|
||||||
|
this._EventEmitter.emit("result", payload);
|
||||||
|
});
|
||||||
|
|
||||||
|
this._EventEmitter.emit("process", { pid, name: descriptor.name });
|
||||||
|
process.execute();
|
||||||
|
|
||||||
|
return pid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sendSignal(pid: number, signal: SIGNAL_MAP): void {
|
||||||
|
const process = this._Processes.get(pid);
|
||||||
|
|
||||||
|
if (!process) {
|
||||||
|
//Implement a proper error object later to return to shell
|
||||||
|
console.error("PID not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.sendSignal(signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sendInput(pid: number, input: Input): void {
|
||||||
|
const process = this._Processes.get(pid);
|
||||||
|
if (!process) {
|
||||||
|
//Implement a proper error object later to return to shell
|
||||||
|
console.error("PID not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
process.sendInput(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public kill(pid: number): void {
|
||||||
|
const process = this._Processes.get(pid);
|
||||||
|
|
||||||
|
if (!process) {
|
||||||
|
//Implement a proper error object later to return to shell
|
||||||
|
console.error("PID not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Make global signals an enum later
|
||||||
|
process.sendSignal(SIGNAL_MAP.SIGINT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
+125
-74
@@ -1,88 +1,139 @@
|
|||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import type { IDataStore, IMetaStore, VDiskConfig } from "@core/filesystem/vdisk";
|
||||||
import { z } from "zod";
|
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "../core/filesystem/treenode";
|
import { NodeType, type DirectoryNode, type FileNode, type Node, type SymlinkNode } from "../core/filesystem/node";
|
||||||
|
|
||||||
const FileNodeSchema = z.object({
|
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
|
||||||
inode: z.number(),
|
|
||||||
name: z.string(),
|
|
||||||
mode: z.number(),
|
|
||||||
parent: z.number(),
|
|
||||||
owner: z.number(),
|
|
||||||
group: z.number(),
|
|
||||||
mtime: z.number(),
|
|
||||||
ctime: z.number(),
|
|
||||||
atime: z.number(),
|
|
||||||
type: z.literal("regular"),
|
|
||||||
content: z.array(z.number()),
|
|
||||||
});
|
|
||||||
|
|
||||||
const DirectoryNodeSchema = z.object({
|
} */
|
||||||
inode: z.number(),
|
|
||||||
name: z.string(),
|
|
||||||
mode: z.number(),
|
|
||||||
parent: z.number(),
|
|
||||||
owner: z.number(),
|
|
||||||
group: z.number(),
|
|
||||||
mtime: z.number(),
|
|
||||||
ctime: z.number(),
|
|
||||||
atime: z.number(),
|
|
||||||
type: z.literal("directory"),
|
|
||||||
children: z.array(z.lazy((): any => TreeNodeSchema)),
|
|
||||||
});
|
|
||||||
|
|
||||||
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
|
export function deserializeFileSystem(json: string): { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] {
|
||||||
|
|
||||||
export function serializeFileSystem() {}
|
|
||||||
|
|
||||||
export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNode> {
|
|
||||||
const raw = JSON.parse(json);
|
const raw = JSON.parse(json);
|
||||||
const validated = TreeNodeSchema.parse(raw);
|
let index = 0;
|
||||||
|
|
||||||
const map = new Map<number, TreeNode>();
|
// prettier-ignore
|
||||||
|
function parseNode(tree: any, parent: number, store: MemDataStore, map: Map<number, Node>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
|
if(tree === null || tree.type === undefined) {
|
||||||
|
const time = Date.now();
|
||||||
|
const defaultNode: DirectoryNode = {
|
||||||
|
type: NodeType.Directory,
|
||||||
|
inode: 0,
|
||||||
|
link_count: 2,
|
||||||
|
mode: 0o0555,
|
||||||
|
owner: 0,
|
||||||
|
group: 0,
|
||||||
|
mtime: time,
|
||||||
|
ctime: time,
|
||||||
|
atime: time,
|
||||||
|
children: new Map(),
|
||||||
|
};
|
||||||
|
map.set(0, Object.freeze(defaultNode));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
function parseNode(tree: any, parent: number): void {
|
if(tree.inode > index) index = tree.inode;
|
||||||
if (tree.type === "directory") {
|
|
||||||
const children: Record<string, number> = {};
|
|
||||||
|
|
||||||
for (const child of tree.children) {
|
switch(tree.type) {
|
||||||
parseNode(child, tree.inode);
|
case "directory": {
|
||||||
children[child.name] = child.inode;
|
const children: Map<string, number> = new Map();
|
||||||
|
|
||||||
|
for (const child of tree.children) {
|
||||||
|
parseNode(child, tree.inode, store, map);
|
||||||
|
children.set(child.name, child.inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
const directoryNode: DirectoryNode = {
|
||||||
|
type: NodeType.Directory,
|
||||||
|
inode: tree.inode,
|
||||||
|
link_count: tree.link_count,
|
||||||
|
mode: tree.mode,
|
||||||
|
owner: tree.owner,
|
||||||
|
group: tree.group,
|
||||||
|
mtime: tree.mtime,
|
||||||
|
ctime: tree.ctime,
|
||||||
|
atime: tree.atime,
|
||||||
|
children,
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
if(Object.values(directoryNode).some(e => e === undefined))
|
||||||
|
throw new Error(`Serialization failed, object contains undefined fields - ${directoryNode}`);
|
||||||
|
|
||||||
|
children.set('..', parent);
|
||||||
|
children.set('.', tree.inode);
|
||||||
|
map.set(tree.inode, Object.freeze(directoryNode));
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
case "regular": {
|
||||||
|
const uuid = crypto.randomUUID();
|
||||||
|
const fileNode: FileNode = {
|
||||||
|
type: NodeType.File,
|
||||||
|
inode: tree.inode,
|
||||||
|
mode: tree.mode,
|
||||||
|
link_count: tree.link_count,
|
||||||
|
owner: tree.owner,
|
||||||
|
group: tree.group,
|
||||||
|
mtime: tree.mtime,
|
||||||
|
ctime: tree.ctime,
|
||||||
|
atime: tree.atime,
|
||||||
|
content: uuid,
|
||||||
|
size: tree.size,
|
||||||
|
};
|
||||||
|
|
||||||
const directoryNode: DirectoryNode = {
|
if(Object.values(fileNode).some(e => e === undefined))
|
||||||
type: TreeNodeType.Directory,
|
throw new Error(`Serialization failed, object contains undefined fields - ${fileNode}`);
|
||||||
inode: tree.inode,
|
|
||||||
name: tree.name,
|
const buff: Uint8Array<ArrayBuffer> = Uint8Array.from(tree.content);
|
||||||
parent,
|
store.put(uuid, new Blob([buff]));
|
||||||
mode: tree.mode,
|
map.set(tree.inode, Object.freeze(fileNode));
|
||||||
owner: tree.owner,
|
break;
|
||||||
group: tree.group,
|
}
|
||||||
mtime: tree.mtime,
|
case "symlink": {
|
||||||
ctime: tree.ctime,
|
const symlinkNode: SymlinkNode = {
|
||||||
atime: tree.atime,
|
type: NodeType.Symlink,
|
||||||
children,
|
inode: tree.inode,
|
||||||
};
|
mode: tree.mode,
|
||||||
map.set(tree.inode, Object.freeze(directoryNode));
|
link_count: tree.link_count,
|
||||||
} else {
|
owner: tree.owner,
|
||||||
const fileNode: FileNode = {
|
group: tree.group,
|
||||||
type: TreeNodeType.File,
|
mtime: tree.mtime,
|
||||||
inode: tree.inode,
|
ctime: tree.ctime,
|
||||||
name: tree.name,
|
atime: tree.atime,
|
||||||
parent,
|
target: tree.target,
|
||||||
mode: tree.mode,
|
};
|
||||||
owner: tree.owner,
|
|
||||||
group: tree.group,
|
if(Object.values(symlinkNode).some(e => e === undefined))
|
||||||
mtime: tree.mtime,
|
throw new Error(`Serialization failed, object contains undefined fields - ${symlinkNode}`);
|
||||||
ctime: tree.ctime,
|
|
||||||
atime: tree.atime,
|
map.set(tree.inode, Object.freeze(symlinkNode));
|
||||||
content: createImmutableBuffer(new Uint8Array()),
|
break;
|
||||||
};
|
}
|
||||||
map.set(tree.inode, Object.freeze(fileNode));
|
default:
|
||||||
|
throw new Error(`Unknown node type in JSON ${tree.type}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
parseNode(validated, validated.inode);
|
const result: { dstore: IDataStore; mstore: IMetaStore; config: VDiskConfig }[] = [];
|
||||||
const base: ReadonlyMap<number, TreeNode> = map;
|
for (const dev of raw.dev) {
|
||||||
|
const map = new Map();
|
||||||
|
const data = new MemDataStore();
|
||||||
|
const meta = new MemMetaStore();
|
||||||
|
parseNode(dev.tree, dev.tree.inode, data, map);
|
||||||
|
|
||||||
return base;
|
const config: VDiskConfig = {
|
||||||
|
id: dev.id,
|
||||||
|
label: `disk-${dev.id}`,
|
||||||
|
index,
|
||||||
|
readonly: false,
|
||||||
|
size: 1024 * 1024 * 1024 * 8, //8 GiB
|
||||||
|
base: map,
|
||||||
|
dataC: {
|
||||||
|
chunkSize: 1024 * 8, //8 KiB
|
||||||
|
cacheSize: 1024 * 1024 * 64, //64 MiB
|
||||||
|
cacheTTL: 1000 * 60, // 1 min
|
||||||
|
},
|
||||||
|
};
|
||||||
|
result.push({ dstore: data, mstore: meta, config });
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
+135
-80
@@ -1,110 +1,164 @@
|
|||||||
import { COMMAND_REGISTRY } from "@core/command_registry";
|
import { COMMAND_REGISTRY } from "@core/command_registry";
|
||||||
import { createErrorResult, createSuccessResult, type Result, type ResultError } from "@core/result";
|
import { createErrorResult, type Result } from "@core/result";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession, type SessionState } from "@core/session_manager";
|
||||||
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
||||||
import type { CommandNotFoundError, ParseError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
import type { ShellError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
import { parseCommand } from "@core/util/parser";
|
import { tokenize } from "@core/util/parser";
|
||||||
|
import { concatUint8Arrays } from "@termos/util/concat";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { ProcessManager } from "./process_manager";
|
||||||
|
|
||||||
|
export interface TTYState {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum SIGNAL_MAP {
|
||||||
|
CLR = 0,
|
||||||
|
SIGINT = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Input {
|
||||||
|
sequence: string;
|
||||||
|
name: string;
|
||||||
|
ctrl: boolean;
|
||||||
|
meta: boolean;
|
||||||
|
shift: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export class Shell {
|
export class Shell {
|
||||||
static #instance: Shell;
|
private _State: Readonly<ShellState>;
|
||||||
static #promise: Promise<Shell> | null = null;
|
private _Session: SessionState;
|
||||||
private _state: Readonly<ShellState>;
|
private _ProcessManager: ProcessManager = new ProcessManager();
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
private _SignalMap: ReadonlyMap<string, SIGNAL_MAP> = new Map([
|
||||||
|
["\f", SIGNAL_MAP.CLR],
|
||||||
|
["\x03", SIGNAL_MAP.SIGINT],
|
||||||
|
]);
|
||||||
|
private readonly E: TextEncoder = new TextEncoder();
|
||||||
|
private readonly D: TextDecoder = new TextDecoder();
|
||||||
|
|
||||||
private constructor(state: ShellState) {
|
private _Stdin: Uint8Array = new Uint8Array();
|
||||||
this._state = Object.freeze(state);
|
|
||||||
|
public BoundPID: number | null = null;
|
||||||
|
|
||||||
|
constructor(state: ShellState) {
|
||||||
|
this._State = Object.freeze(state);
|
||||||
|
this._Session = state.sessionStack[state.sessionStack.length - 1]!;
|
||||||
|
|
||||||
|
this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload));
|
||||||
|
this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload));
|
||||||
|
this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload));
|
||||||
|
this._ProcessManager.on("result", payload => {
|
||||||
|
this._State = payload.state;
|
||||||
|
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
|
||||||
|
this._State = withExitCode(
|
||||||
|
this._State,
|
||||||
|
payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (this.BoundPID === payload.pid) this.BoundPID = null;
|
||||||
|
this._EventEmitter.emit("result", payload);
|
||||||
|
});
|
||||||
|
this._ProcessManager.on("signal", payload => this._EventEmitter.emit("signal", payload));
|
||||||
}
|
}
|
||||||
|
|
||||||
static async init(initialState: ShellState): Promise<Shell> {
|
public async input(key: {
|
||||||
if (Shell.#instance) {
|
sequence: string;
|
||||||
console.warn("Shell already initialized");
|
name: string;
|
||||||
return this.#instance;
|
ctrl: boolean;
|
||||||
|
meta: boolean;
|
||||||
|
shift: boolean;
|
||||||
|
}): Promise<void> {
|
||||||
|
const stdin = Uint8Array.from(this._Stdin);
|
||||||
|
switch (key.sequence) {
|
||||||
|
case "\x03":
|
||||||
|
if (!this.BoundPID) break;
|
||||||
|
const sig = this._SignalMap.get(key.sequence)!;
|
||||||
|
this._ProcessManager.sendSignal(this.BoundPID, sig);
|
||||||
|
break;
|
||||||
|
case "\r":
|
||||||
|
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
|
||||||
|
this._Stdin = new Uint8Array();
|
||||||
|
this._execute(stdin);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key);
|
||||||
|
const buffer = this.E.encode(key.sequence);
|
||||||
|
this._Stdin = concatUint8Arrays([stdin, buffer]);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Shell.#promise) return Shell.#promise;
|
|
||||||
|
|
||||||
Shell.#promise = (async () => {
|
|
||||||
try {
|
|
||||||
Shell.#instance = new Shell(initialState);
|
|
||||||
return Shell.#instance;
|
|
||||||
} finally {
|
|
||||||
Shell.#promise = null;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
return Shell.#promise;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Execute(input: string): Promise<Result<ShellError>> {
|
private async _execute(input: Uint8Array): Promise<void> {
|
||||||
let parsed;
|
const parsed = tokenize(input);
|
||||||
try {
|
|
||||||
parsed = parseCommand(input);
|
|
||||||
} catch {
|
|
||||||
return createErrorResult(
|
|
||||||
"ParseError",
|
|
||||||
`Parsing error - ${input}`,
|
|
||||||
{},
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
"",
|
|
||||||
) satisfies ResultError<ParseError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsed.command === "") {
|
if (!parsed[0]) return;
|
||||||
return createSuccessResult(
|
|
||||||
"",
|
this._State = withHistory(this._State, input);
|
||||||
0,
|
const command = COMMAND_REGISTRY.get(parsed[0]);
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
|
if (!command) {
|
||||||
|
const encoded = new TextEncoder().encode(`Command ${parsed[0]} not found`);
|
||||||
|
|
||||||
|
const result = createErrorResult(
|
||||||
|
"CommandNotFound",
|
||||||
|
`Command ${parsed[0]} not found`,
|
||||||
|
{ command: parsed[0] },
|
||||||
|
parsed[0],
|
||||||
|
createImmutableBuffer(encoded),
|
||||||
createImmutableBuffer(new Uint8Array()),
|
createImmutableBuffer(new Uint8Array()),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._state = withHistory(this._state, input);
|
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
|
||||||
const command = COMMAND_REGISTRY.get(parsed.command);
|
const result = createErrorResult(
|
||||||
|
|
||||||
if (!command)
|
|
||||||
return createErrorResult(
|
|
||||||
"CommandNotFound",
|
|
||||||
`Command ${parsed.command} not found`,
|
|
||||||
{ command: parsed.command },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
parsed.command,
|
|
||||||
) satisfies ResultError<CommandNotFoundError>;
|
|
||||||
|
|
||||||
if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) {
|
|
||||||
return createErrorResult(
|
|
||||||
"PermissionDenied",
|
"PermissionDenied",
|
||||||
`Permission Denied`,
|
`Permission Denied`,
|
||||||
{ resource: `Execution of the ${command.name} command` },
|
{ resource: `Execution of the ${command.name} command` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
parsed[0],
|
||||||
createImmutableBuffer(new Uint8Array()),
|
);
|
||||||
parsed.command,
|
|
||||||
) satisfies ResultError<PermissionDeniedError>;
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._Session = this._State.sessionStack[this._State.sessionStack.length - 1]!;
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const out = command.fn(this._state, parsed.flags, parsed.args);
|
parsed.shift();
|
||||||
this._state = out.state;
|
|
||||||
|
|
||||||
if (out.result.type === "error") {
|
const pid = this._ProcessManager.createProcess(this._State, command, parsed);
|
||||||
this._state = withExitCode(this._state, out.result.error.exitCode);
|
this.BoundPID = pid;
|
||||||
} else {
|
}
|
||||||
this._state = withExitCode(this._state, out.result.exitCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
return out.result;
|
public getHistoryIndex(i: number): Uint8Array | undefined {
|
||||||
|
return this._Session.history[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
public get State(): Readonly<ShellState> {
|
public get State(): Readonly<ShellState> {
|
||||||
return this._state;
|
return this._State;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static get Instance(): Shell | undefined {
|
public get Session(): Readonly<SessionState> {
|
||||||
if (!Shell.#instance) {
|
return this._Session;
|
||||||
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
}
|
||||||
return;
|
|
||||||
}
|
public on<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
return Shell.#instance;
|
return this._EventEmitter.on(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public once<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): () => void {
|
||||||
|
return this._EventEmitter.once(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public off<K extends keyof ShellEventMap>(type: K, handler: (payload: ShellEventMap[K]) => void): void {
|
||||||
|
this._EventEmitter.off(type, handler);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,5 +166,6 @@ export interface ShellEventMap {
|
|||||||
process: { pid: number; name: string };
|
process: { pid: number; name: string };
|
||||||
stdout: { pid: number; data: Uint8Array };
|
stdout: { pid: number; data: Uint8Array };
|
||||||
stderr: { pid: number; data: Uint8Array };
|
stderr: { pid: number; data: Uint8Array };
|
||||||
result: { pid: number; result: Result<ShellError> };
|
result: { pid: number; result: Result<ShellError>; state: ShellState };
|
||||||
|
signal: { pid: number; sig: SIGNAL_MAP };
|
||||||
}
|
}
|
||||||
|
|||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
import { stdin as input, stdout as output } from "node:process";
|
||||||
|
import readline from "node:readline";
|
||||||
|
|
||||||
|
process.stdin.setRawMode(true);
|
||||||
|
readline.emitKeypressEvents(process.stdin);
|
||||||
|
|
||||||
|
const rl = readline.createInterface({ input, output });
|
||||||
|
|
||||||
|
const d = new TextDecoder();
|
||||||
|
|
||||||
|
//@ts-ignore
|
||||||
|
rl.on("line", input => {
|
||||||
|
console.log(`Received: ${input}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.stdin.on("keypress", async (str, key) => {
|
||||||
|
console.log(str, key);
|
||||||
|
});
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import { MD5 } from "./hash";
|
|
||||||
|
|
||||||
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
|
||||||
|
|
||||||
//TODO: load IDB db name from config;
|
|
||||||
|
|
||||||
export async function initializeIDB() {
|
|
||||||
const request = indexedDB.open("cache");
|
|
||||||
request.onerror = e => {
|
|
||||||
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
request.onsuccess = e => {
|
|
||||||
const DB = request.result;
|
|
||||||
const STORE = DB.createObjectStore("fs", { autoIncrement: true });
|
|
||||||
|
|
||||||
STORE.createIndex("json", "json");
|
|
||||||
STORE.createIndex("checksum", "checksum");
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function writeFileSystemCache(cache: string, checksum: string) {
|
|
||||||
if (cache.length === 0 || checksum.length === 0) {
|
|
||||||
throw new Error(`Cache value or the checksum value cannot be empty!`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isChecksumMatching(cache, checksum))
|
|
||||||
throw new Error("The cache value checksum does not match the provided checksum");
|
|
||||||
|
|
||||||
const request = indexedDB.open("cache");
|
|
||||||
request.onerror = e => {
|
|
||||||
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
request.onsuccess = e => {
|
|
||||||
const DB = request.result;
|
|
||||||
const T = DB.transaction(["cache"], "readwrite");
|
|
||||||
const STOREFS = T.objectStore("fs");
|
|
||||||
const STORECK = T.objectStore("fs");
|
|
||||||
|
|
||||||
const RFS = STOREFS.add(cache);
|
|
||||||
//const CFS =
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchFileSystemCache(): Promise<{ cache: string; checksum: string }> {
|
|
||||||
const request = indexedDB.open("cache");
|
|
||||||
|
|
||||||
request.onerror = e => {
|
|
||||||
throw new Error(`Failed to open the IDB - ${request.error}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
request.onsuccess = e => {
|
|
||||||
const DB = request.result;
|
|
||||||
const T = DB.transaction(["cache"], "readonly");
|
|
||||||
const STORE = T.objectStore("fs");
|
|
||||||
|
|
||||||
const R = STORE.get("1");
|
|
||||||
|
|
||||||
R.onerror = e => {
|
|
||||||
throw new Error(`Some IDB error - ${R.error}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
R.onsuccess = e => {
|
|
||||||
console.log(R.result.json, R.result.checksum);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function isChecksumMatching(json: string, checksum: string): boolean {
|
|
||||||
const resourceChksm = MD5.hash(json);
|
|
||||||
return resourceChksm === checksum;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
|
||||||
|
const size = arrays.reduce((sum, arr) => sum + arr.length, 0);
|
||||||
|
const array = new Uint8Array(size);
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
for (const arr of arrays) {
|
||||||
|
array.set(arr, offset);
|
||||||
|
offset += arr.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function splitUint8Array(data: Uint8Array, size: number): Uint8Array[] {
|
||||||
|
const nChunks: number = Math.ceil(data.length / size);
|
||||||
|
const chunks: Uint8Array[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < nChunks; i++) {
|
||||||
|
const start = size * i;
|
||||||
|
const end = size * (i + 1);
|
||||||
|
|
||||||
|
chunks.push(data.subarray(start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export function convertToUnit(bytes: number, decimalPoint?: number, pow: 1024 | 1000 = 1024): string {
|
||||||
|
if (!+bytes) return "0";
|
||||||
|
|
||||||
|
const k: number = pow;
|
||||||
|
const dp: number = decimalPoint ? (decimalPoint < 0 ? 0 : decimalPoint) : 1;
|
||||||
|
const units: string[] = ["", "K", "M", "G", "T", "P"];
|
||||||
|
|
||||||
|
const i: number = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
|
||||||
|
return `${(bytes / Math.pow(k, i)).toFixed(dp)}${units[i]}`;
|
||||||
|
}
|
||||||
+3
-3
@@ -52,7 +52,7 @@ export class MD5 {
|
|||||||
return (b & d) | (c & ~d);
|
return (b & d) | (c & ~d);
|
||||||
}
|
}
|
||||||
|
|
||||||
let AA = A,
|
const AA = A,
|
||||||
BB = B,
|
BB = B,
|
||||||
CC = C,
|
CC = C,
|
||||||
DD = D;
|
DD = D;
|
||||||
@@ -129,7 +129,7 @@ export class MD5 {
|
|||||||
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static sliceToBlocks(input: Uint8Array): number[][] {
|
/* private static sliceToBlocks(input: Uint8Array): number[][] {
|
||||||
const blocks: number[][] = [];
|
const blocks: number[][] = [];
|
||||||
|
|
||||||
for (let i = 0; i < input.length; i += 64) {
|
for (let i = 0; i < input.length; i += 64) {
|
||||||
@@ -138,7 +138,7 @@ export class MD5 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return blocks;
|
return blocks;
|
||||||
}
|
} */
|
||||||
|
|
||||||
private static sliceToWords(block: Uint8Array): number[] {
|
private static sliceToWords(block: Uint8Array): number[] {
|
||||||
const words: number[] = new Array<number>(16);
|
const words: number[] = new Array<number>(16);
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
export class Posix {
|
||||||
|
private static readonly CharTable = {
|
||||||
|
// Space and punctuation (32-47)
|
||||||
|
" ": 32,
|
||||||
|
"!": 33,
|
||||||
|
'"': 34,
|
||||||
|
"#": 35,
|
||||||
|
$: 36,
|
||||||
|
"%": 37,
|
||||||
|
"&": 38,
|
||||||
|
"'": 39,
|
||||||
|
"(": 40,
|
||||||
|
")": 41,
|
||||||
|
"*": 42,
|
||||||
|
"+": 43,
|
||||||
|
",": 44,
|
||||||
|
"-": 45,
|
||||||
|
".": 46,
|
||||||
|
"/": 47,
|
||||||
|
|
||||||
|
// Numbers 0-9 (48-57)
|
||||||
|
"0": 48,
|
||||||
|
"1": 49,
|
||||||
|
"2": 50,
|
||||||
|
"3": 51,
|
||||||
|
"4": 52,
|
||||||
|
"5": 53,
|
||||||
|
"6": 54,
|
||||||
|
"7": 55,
|
||||||
|
"8": 56,
|
||||||
|
"9": 57,
|
||||||
|
|
||||||
|
// More punctuation (58-64)
|
||||||
|
":": 58,
|
||||||
|
";": 59,
|
||||||
|
"<": 60,
|
||||||
|
"=": 61,
|
||||||
|
">": 62,
|
||||||
|
"?": 63,
|
||||||
|
"@": 64,
|
||||||
|
|
||||||
|
// LETTERS - INTERLEAVED AaBbCc... (65-116)
|
||||||
|
A: 65,
|
||||||
|
a: 66,
|
||||||
|
B: 67,
|
||||||
|
b: 68,
|
||||||
|
C: 69,
|
||||||
|
c: 70,
|
||||||
|
D: 71,
|
||||||
|
d: 72,
|
||||||
|
E: 73,
|
||||||
|
e: 74,
|
||||||
|
F: 75,
|
||||||
|
f: 76,
|
||||||
|
G: 77,
|
||||||
|
g: 78,
|
||||||
|
H: 79,
|
||||||
|
h: 80,
|
||||||
|
I: 81,
|
||||||
|
i: 82,
|
||||||
|
J: 83,
|
||||||
|
j: 84,
|
||||||
|
K: 85,
|
||||||
|
k: 86,
|
||||||
|
L: 87,
|
||||||
|
l: 88,
|
||||||
|
M: 89,
|
||||||
|
m: 90,
|
||||||
|
N: 91,
|
||||||
|
n: 92,
|
||||||
|
O: 93,
|
||||||
|
o: 94,
|
||||||
|
P: 95,
|
||||||
|
p: 96,
|
||||||
|
Q: 97,
|
||||||
|
q: 98,
|
||||||
|
R: 99,
|
||||||
|
r: 100,
|
||||||
|
S: 101,
|
||||||
|
s: 102,
|
||||||
|
T: 103,
|
||||||
|
t: 104,
|
||||||
|
U: 105,
|
||||||
|
u: 106,
|
||||||
|
V: 107,
|
||||||
|
v: 108,
|
||||||
|
W: 109,
|
||||||
|
w: 110,
|
||||||
|
X: 111,
|
||||||
|
x: 112,
|
||||||
|
Y: 113,
|
||||||
|
y: 114,
|
||||||
|
Z: 115,
|
||||||
|
z: 116,
|
||||||
|
|
||||||
|
// Specials after letters (now 117-126)
|
||||||
|
"[": 117,
|
||||||
|
"\\": 118,
|
||||||
|
"]": 119,
|
||||||
|
"^": 120,
|
||||||
|
_: 121,
|
||||||
|
"`": 122,
|
||||||
|
"{": 123,
|
||||||
|
"|": 124,
|
||||||
|
"}": 125,
|
||||||
|
"~": 126,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
public static GetCharWeight(char: string): number {
|
||||||
|
return this.CharTable[char as keyof typeof this.CharTable];
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
-33
@@ -1,61 +1,104 @@
|
|||||||
import type { FileSystem } from "@core/filesystem/filesystem";
|
import type { FileSystem } from "@core/filesystem/filesystem";
|
||||||
import { TreeNodeType } from "@core/filesystem/treenode";
|
import { NodePointer, NodeType, type SymlinkNode } from "@core/filesystem/node";
|
||||||
|
|
||||||
export function printTree(fs: FileSystem, root: number): string {
|
type Frame = {
|
||||||
|
ptr: NodePointer;
|
||||||
|
name: string;
|
||||||
|
prefix: string;
|
||||||
|
isLast: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getSortedChildren(fs: FileSystem, ptr: NodePointer): Array<{ name: string; ptr: NodePointer }> {
|
||||||
|
const node = fs.getNode(ptr);
|
||||||
|
if (!node || node.type !== NodeType.Directory) return [];
|
||||||
|
|
||||||
|
const entries = Array.from(node.children.entries());
|
||||||
|
entries.sort(([a], [b]) => a.localeCompare(b));
|
||||||
|
|
||||||
|
return entries.map(([name, inode]) => ({
|
||||||
|
name,
|
||||||
|
ptr: NodePointer.of(ptr.device, inode),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountSuffix(fs: FileSystem, ptr: NodePointer): string {
|
||||||
|
if (!fs.isMountPoint(ptr)) return "";
|
||||||
|
const target = fs.getMountPoint(ptr);
|
||||||
|
if (!target) return " -> [mount: target missing]";
|
||||||
|
return ` -> ${target.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function symlinkSuffix(node: { type: NodeType; target?: string }): string {
|
||||||
|
return node.type === NodeType.Symlink ? ` -> ${(node as SymlinkNode).target}` : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printTree(fs: FileSystem, root: NodePointer, rootLabel = "/"): string {
|
||||||
const rootNode = fs.getNode(root);
|
const rootNode = fs.getNode(root);
|
||||||
if (rootNode === undefined) return "";
|
if (rootNode === undefined) return "";
|
||||||
|
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
const rootSuffix = mountSuffix(fs, root) + symlinkSuffix(rootNode);
|
||||||
lines.push(rootNode.name);
|
lines.push(`${rootLabel} ${root.toString()}${rootSuffix}`);
|
||||||
|
|
||||||
type Frame = {
|
|
||||||
inode: number;
|
|
||||||
prefix: string;
|
|
||||||
isLast: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
const stack: Frame[] = [];
|
const stack: Frame[] = [];
|
||||||
|
const rootChildren = getSortedChildren(fs, root);
|
||||||
const getSorterChildren = (inode: number): number[] => {
|
|
||||||
const node = fs.getNode(inode);
|
|
||||||
if (!node || node.type !== TreeNodeType.Directory) return [];
|
|
||||||
|
|
||||||
const entries = Object.entries(node.children);
|
|
||||||
entries.sort(([a], [b]) => a.localeCompare(b));
|
|
||||||
return entries.map(([, childInode]) => childInode) as number[];
|
|
||||||
};
|
|
||||||
|
|
||||||
const rootChildren = getSorterChildren(root);
|
|
||||||
|
|
||||||
for (let i = rootChildren.length - 1; i >= 0; i--) {
|
for (let i = rootChildren.length - 1; i >= 0; i--) {
|
||||||
const childInode: number = rootChildren[i] as number;
|
const child = rootChildren[i]!;
|
||||||
|
if (child.name.startsWith(".")) continue;
|
||||||
const isLast = i === rootChildren.length - 1;
|
const isLast = i === rootChildren.length - 1;
|
||||||
|
stack.push({ ptr: child.ptr, name: child.name, prefix: "", isLast });
|
||||||
stack.push({ inode: childInode, prefix: "", isLast });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
while (stack.length > 0) {
|
while (stack.length > 0) {
|
||||||
const frame = stack.pop()!;
|
const frame = stack.pop()!;
|
||||||
const node = fs.getNode(frame.inode);
|
const node = fs.getNode(frame.ptr);
|
||||||
if (!node) continue;
|
if (!node) continue;
|
||||||
|
|
||||||
const name = node.name;
|
|
||||||
const connector = frame.isLast ? "└── " : "├── ";
|
const connector = frame.isLast ? "└── " : "├── ";
|
||||||
lines.push(frame.prefix + connector + name);
|
const suffix = mountSuffix(fs, frame.ptr) + symlinkSuffix(node);
|
||||||
|
lines.push(`${frame.prefix}${connector}${frame.name} ${frame.ptr.toString()}${suffix}`);
|
||||||
|
|
||||||
if (node.type === TreeNodeType.Directory) {
|
if (node.type === NodeType.Directory && !fs.isMountPoint(frame.ptr)) {
|
||||||
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
|
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
|
||||||
const children = getSorterChildren(frame.inode);
|
const children = getSortedChildren(fs, frame.ptr);
|
||||||
|
|
||||||
for (let i = children.length - 1; i >= 0; i--) {
|
for (let i = children.length - 1; i >= 0; i--) {
|
||||||
const childInode = children[i] as number;
|
const child = children[i]!;
|
||||||
|
if (child.name.startsWith(".")) continue;
|
||||||
const childIsLast = i === children.length - 1;
|
const childIsLast = i === children.length - 1;
|
||||||
|
stack.push({
|
||||||
stack.push({ inode: childInode, prefix: childPrefix, isLast: childIsLast });
|
ptr: child.ptr,
|
||||||
|
name: child.name,
|
||||||
|
prefix: childPrefix,
|
||||||
|
isLast: childIsLast,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return lines.join("\n");
|
return lines.join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function printDeviceTree(fs: FileSystem, deviceId: number, rootLabel?: string): string {
|
||||||
|
return printTree(fs, NodePointer.of(deviceId, 0), rootLabel ?? `disk-${deviceId}:/`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printAllDeviceTrees(fs: FileSystem, deviceIds?: number[]): string {
|
||||||
|
const ids =
|
||||||
|
deviceIds ??
|
||||||
|
(() => {
|
||||||
|
const mgr = (fs as unknown as { _VDiskManager?: { listID(): number[] } })._VDiskManager;
|
||||||
|
if (!mgr) {
|
||||||
|
throw new Error(
|
||||||
|
"printAllDeviceTrees: FileSystem has no public device list — pass deviceIds explicitly",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return mgr.listID();
|
||||||
|
})();
|
||||||
|
|
||||||
|
return ids
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => a - b)
|
||||||
|
.map(id => printDeviceTree(fs, id))
|
||||||
|
.join("\n\n");
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,113 +0,0 @@
|
|||||||
import { descriptor as cd } from "@core/commands/cd";
|
|
||||||
import type { ResultError, ResultSuccess } from "@core/result";
|
|
||||||
import type { UserInfo } from "@core/session_manager";
|
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
|
||||||
import { createInitialShellState, withCwd, type ShellState } from "@core/shell_state";
|
|
||||||
import type { PathResolutionError } from "@core/util/errors";
|
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { expect, test } from "vitest";
|
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 1,
|
|
||||||
name: "hello.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye World!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 2,
|
|
||||||
name: "sub",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 3,
|
|
||||||
name: "world.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 4,
|
|
||||||
name: "bye",
|
|
||||||
type: "Dir",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
|
||||||
const user: UserInfo = {
|
|
||||||
username: "root",
|
|
||||||
uid: 0,
|
|
||||||
gid: 0,
|
|
||||||
group: [0],
|
|
||||||
home: 0,
|
|
||||||
};
|
|
||||||
users.set(0, user);
|
|
||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
|
||||||
|
|
||||||
test("changes cwd to home", () => {
|
|
||||||
let newState = withCwd(state, 2);
|
|
||||||
const output = cd.fn(newState, [], []);
|
|
||||||
newState = output.state;
|
|
||||||
const result = output.result;
|
|
||||||
const session = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
|
||||||
expect(session.cwd).toBe(0);
|
|
||||||
expect(session.pwd).toBe(2);
|
|
||||||
});
|
|
||||||
test("changes cwd to pwd", () => {
|
|
||||||
let newState = withCwd(state, 2);
|
|
||||||
|
|
||||||
const output = cd.fn(newState, [], ["-"]);
|
|
||||||
newState = output.state;
|
|
||||||
const result = output.result;
|
|
||||||
const session = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
|
||||||
expect(session.cwd).toBe(0);
|
|
||||||
expect(session.pwd).toBe(2);
|
|
||||||
});
|
|
||||||
test("changes cwd to 4", () => {
|
|
||||||
const output = cd.fn(state, [], ["/sub/bye"]);
|
|
||||||
const newState = output.state;
|
|
||||||
const result = output.result;
|
|
||||||
const session = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect((result as ResultSuccess).exitCode).toBe(0);
|
|
||||||
expect(session.cwd).toBe(4);
|
|
||||||
expect(session.pwd).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns an error result (tried to enter a non existent location)", () => {
|
|
||||||
const output = cd.fn(state, [], ["/not/real"]);
|
|
||||||
const newState = output.state;
|
|
||||||
const result = output.result;
|
|
||||||
const session = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
|
|
||||||
expect(session.cwd).toBe(0);
|
|
||||||
expect(session.pwd).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns an error result (tried to enter a file)", () => {
|
|
||||||
const output = cd.fn(state, [], ["/hello.txt"]);
|
|
||||||
const newState = output.state;
|
|
||||||
const result = output.result;
|
|
||||||
const session = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect((result as ResultError<PathResolutionError>).error.exitCode).toBe(64);
|
|
||||||
expect(session.cwd).toBe(0);
|
|
||||||
expect(session.pwd).toBe(0);
|
|
||||||
});
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
import { descriptor as echo } from "@core/commands/echo";
|
|
||||||
import type { ResultSuccess } from "@core/result";
|
|
||||||
import type { UserInfo } from "@core/session_manager";
|
|
||||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { expect, test } from "vitest";
|
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 1,
|
|
||||||
name: "hello.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye World!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 2,
|
|
||||||
name: "sub",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 3,
|
|
||||||
name: "world.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 4,
|
|
||||||
name: "bye",
|
|
||||||
type: "Dir",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
|
||||||
const user: UserInfo = {
|
|
||||||
username: "root",
|
|
||||||
uid: 0,
|
|
||||||
gid: 0,
|
|
||||||
group: [0],
|
|
||||||
home: 0,
|
|
||||||
};
|
|
||||||
users.set(0, user);
|
|
||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
|
||||||
|
|
||||||
test("returns a Result of type success", () => {
|
|
||||||
const output = echo.fn(state, [], ["hello", "world"]);
|
|
||||||
const string = new TextDecoder().decode(output.result.stdout.toArray());
|
|
||||||
|
|
||||||
expect(output.result.type).toBe("success");
|
|
||||||
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
|
||||||
expect(string).toBe("hello world");
|
|
||||||
});
|
|
||||||
+1199
-351
File diff suppressed because it is too large
Load Diff
+628
-59
@@ -1,73 +1,642 @@
|
|||||||
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
// @tests/core/util/path_resolver.test.ts (adjust)
|
||||||
|
import { NodePointer } from "@core/filesystem/node";
|
||||||
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
|
import { expectNodeNotFoundError, expectNotADirectoryError } from "@tests/helpers/error_matchers";
|
||||||
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
|
import { makeFS, makeShellState, makeTree, makeUser } from "@tests/helpers/filesystems_fixture";
|
||||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
import { describe, expect, it } from "vitest";
|
||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
const fs = buildTestFS(depth7Tree);
|
// ============================================================================
|
||||||
|
// Path normalization
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
describe("resolvePath", () => {
|
describe("resolvePath — path normalization", () => {
|
||||||
test("returns an inode from an absolute path", () => {
|
/**
|
||||||
const path = "/d1/d2/d3/d4/";
|
* `/` is the root of device 0; no traversal is needed.
|
||||||
const result = resolvePath(fs, 1, path);
|
*/
|
||||||
|
it("resolves '/' to the root of device 0", async () => {
|
||||||
expect(result).toBeDefined();
|
const fs = await makeFS([makeTree().build()]);
|
||||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
expect(resolvePath(makeShellState(fs), "/")).toEqual({ device_id: 0, inode: 0 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an inode from a relative path", () => {
|
/**
|
||||||
const path = "./d2/d3/d4/";
|
* Redundant leading slashes are stripped by the normalizer.
|
||||||
const result = resolvePath(fs, 1, path);
|
*/
|
||||||
|
it("resolves '/', '//', and '///' identically", async () => {
|
||||||
expect(result).toBeDefined();
|
const fs = await makeFS([makeTree().build()]);
|
||||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
const state = makeShellState(fs);
|
||||||
|
for (const p of ["/", "//", "///"]) {
|
||||||
|
expect(resolvePath(state, p)).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an inode from a relative parent path", () => {
|
/**
|
||||||
const path = "../d1/d2/d3/d4/";
|
* Empty path returns the current working directory without traversal.
|
||||||
const result = resolvePath(fs, 1, path);
|
*/
|
||||||
|
it("resolves an empty string to the current working directory", async () => {
|
||||||
expect(result).toBeDefined();
|
const t = makeTree();
|
||||||
expect(fs.getNode(result as number)!.name).toBe("d4");
|
const work = t.addDir(0, "work");
|
||||||
});
|
const fs = await makeFS([t.build()]);
|
||||||
|
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
|
||||||
test("returns inode 0", () => {
|
expect(resolvePath(state, "")).toEqual({ device_id: 0, inode: work });
|
||||||
const path = "/";
|
|
||||||
const result = resolvePath(fs, 1, path);
|
|
||||||
|
|
||||||
expect(result).toBeDefined();
|
|
||||||
expect(result).toBe(0);
|
|
||||||
expect(fs.getNode(result as number)!.name).toBe("root");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns inode 1 (cwd)", () => {
|
|
||||||
const path = "";
|
|
||||||
const result = resolvePath(fs, 1, path);
|
|
||||||
|
|
||||||
expect(result).toBeDefined();
|
|
||||||
expect(result).toBe(1);
|
|
||||||
expect(fs.getNode(result as number)!.name).toBe("d1");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("throws because of a nonexistent path", () => {
|
|
||||||
expectNodeNotFoundError(() => resolvePath(fs, 1, "/d3"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("throws because of file path component", () => {
|
|
||||||
expectNotADirectoryError(() => resolvePath(fs, 6, "./deep_file.txt/d8"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("throws because of a nonexistent cwd inode (technicaly should never happen)", () => {
|
|
||||||
expectNodeNotFoundError(() => resolvePath(fs, 69, "/d3"));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("resolveInode", () => {
|
// ============================================================================
|
||||||
test("returns an the path from the d4 node", () => {
|
// Absolute paths
|
||||||
expect(resolveInode(fs, 4)).toBe("/d1/d2/d3/d4");
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — absolute paths", () => {
|
||||||
|
/**
|
||||||
|
* Single-component absolute path resolves to the child's pointer.
|
||||||
|
*/
|
||||||
|
it("resolves '/name' to the child node of root", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const foo = t.addFile(0, "foo");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
expect(resolvePath(makeShellState(fs), "/foo")).toEqual({ device_id: 0, inode: foo });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an empty string from a non existent inode", () => {
|
/**
|
||||||
expect(resolveInode(fs, 999)).toBe("");
|
* Nested paths traverse each directory in turn.
|
||||||
|
*/
|
||||||
|
it("resolves a nested path '/a/b' to the final child", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const a = t.addDir(0, "a");
|
||||||
|
const b = t.addFile(a, "b");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 0, inode: b });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deeper paths traverse more levels.
|
||||||
|
*/
|
||||||
|
it("resolves a deep path '/a/b/c/d' to the final child", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const a = t.addDir(0, "a");
|
||||||
|
const b = t.addDir(a, "b");
|
||||||
|
const c = t.addDir(b, "c");
|
||||||
|
const d = t.addFile(c, "d");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
expect(resolvePath(makeShellState(fs), "/a/b/c/d")).toEqual({ device_id: 0, inode: d });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trailing slash is stripped and resolves the same as without it.
|
||||||
|
*/
|
||||||
|
it("resolves '/a/b/' to the same pointer as '/a/b'", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const a = t.addDir(0, "a");
|
||||||
|
t.addFile(a, "b");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
const state = makeShellState(fs);
|
||||||
|
expect(resolvePath(state, "/a/b/")).toEqual(resolvePath(state, "/a/b"));
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Missing top-level component raises a typed NodeNotFound.
|
||||||
|
*/
|
||||||
|
it("throws NodeNotFound when the first component does not exist", async () => {
|
||||||
|
const fs = await makeFS([makeTree().build()]);
|
||||||
|
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/missing"));
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Missing intermediate component raises a typed NodeNotFound.
|
||||||
|
*/
|
||||||
|
it("throws NodeNotFound when an intermediate component does not exist", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
t.addDir(0, "a");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "/a/missing/b"));
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Descending through a file at a non-final position is rejected with
|
||||||
|
* NotADirectory (this one works — the isFile check fires because `a` is
|
||||||
|
* not the last component).
|
||||||
|
*/
|
||||||
|
it("throws NotADirectory when traversing through a file at a non-final position", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
t.addFile(0, "a");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b/c"));
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: descending through a file at the final position should
|
||||||
|
* also throw NotADirectory. Current implementation skips the isFile check
|
||||||
|
* on the last iteration and then crashes on `(file as Directory).children`.
|
||||||
|
*/
|
||||||
|
it("should throw NotADirectory when descending through a file at the final position", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
t.addFile(0, "a");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
await expectNotADirectoryError(() => resolvePath(makeShellState(fs), "/a/b"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Relative paths
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — relative paths", () => {
|
||||||
|
/**
|
||||||
|
* A single relative component resolves against cwd.
|
||||||
|
*/
|
||||||
|
it("resolves a relative path from a device-0 cwd", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const work = t.addDir(0, "work");
|
||||||
|
const file = t.addFile(work, "file");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
|
||||||
|
expect(resolvePath(state, "file")).toEqual({ device_id: 0, inode: file });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multi-component relative paths traverse from cwd.
|
||||||
|
*/
|
||||||
|
it("resolves a multi-component relative path from cwd", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const work = t.addDir(0, "work");
|
||||||
|
const sub = t.addDir(work, "sub");
|
||||||
|
const leaf = t.addFile(sub, "leaf");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
const state = makeShellState(fs, { cwd: NodePointer.of(0, work) });
|
||||||
|
expect(resolvePath(state, "sub/leaf")).toEqual({ device_id: 0, inode: leaf });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Missing relative component raises a typed NodeNotFound.
|
||||||
|
*/
|
||||||
|
it("throws NodeNotFound for a missing relative component", async () => {
|
||||||
|
const fs = await makeFS([makeTree().build()]);
|
||||||
|
await expectNodeNotFoundError(() => resolvePath(makeShellState(fs), "nope"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// ~ expansion
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — '~' expansion", () => {
|
||||||
|
/**
|
||||||
|
* `~` expands to the user's home directory (home on device 0).
|
||||||
|
*/
|
||||||
|
it("expands '~' to the user's home directory", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const home = t.addDir(0, "home");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
const user = makeUser(NodePointer.of(0, home));
|
||||||
|
const state = makeShellState(fs, { user });
|
||||||
|
expect(resolvePath(state, "~")).toEqual({ device_id: 0, inode: home });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `~/name` expands home first, then resolves `name` beneath it.
|
||||||
|
*/
|
||||||
|
it("expands '~/name' to a child of home", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const home = t.addDir(0, "home");
|
||||||
|
const file = t.addFile(home, "file");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
const user = makeUser(NodePointer.of(0, home));
|
||||||
|
const state = makeShellState(fs, { user });
|
||||||
|
expect(resolvePath(state, "~/file")).toEqual({ device_id: 0, inode: file });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: `~` expansion never touches `currentVD`, so a home on
|
||||||
|
* device 1 resolves the first component but then reads subsequent children
|
||||||
|
* from device 0 — usually crashing on a missing inode.
|
||||||
|
*/
|
||||||
|
it("should resolve '~/file' when home lives on device 1", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const t1 = makeTree();
|
||||||
|
const home = t1.addDir(0, "home");
|
||||||
|
const file = t1.addFile(home, "file");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
const user = makeUser(NodePointer.of(1, home));
|
||||||
|
const state = makeShellState(fs, { user });
|
||||||
|
expect(resolvePath(state, "~/file")).toEqual({ device_id: 1, inode: file });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Symlink resolution
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — symlink resolution", () => {
|
||||||
|
/**
|
||||||
|
* Absolute symlink targets resolve from device 0's root.
|
||||||
|
*/
|
||||||
|
it("follows an absolute symlink target", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const real = t.addDir(0, "real");
|
||||||
|
const leaf = t.addFile(real, "leaf");
|
||||||
|
t.addSymlink(0, "link", "/real/leaf");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 0, inode: leaf });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Mount points
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — mount points", () => {
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: mount redirect must fire on the child before descent.
|
||||||
|
* `/mnt` alone should return the mounted device's root, not the mountpoint
|
||||||
|
* directory on the parent device.
|
||||||
|
*/
|
||||||
|
it("should resolve '/mnt' to the mounted device's root", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
expect(resolvePath(makeShellState(fs), "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: `/mnt/file` should descend through the mount and land
|
||||||
|
* on `/file` on device 1 — the trailing component must not be consumed by
|
||||||
|
* the redirect.
|
||||||
|
*/
|
||||||
|
it("should resolve '/mnt/file' to '/file' on the mounted device", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const file = t1.addFile(0, "file");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
expect(resolvePath(makeShellState(fs), "/mnt/file")).toEqual({ device_id: 1, inode: file });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: deep paths through a mount must traverse the mounted
|
||||||
|
* device for every subsequent component.
|
||||||
|
*/
|
||||||
|
it("should resolve '/mnt/sub/leaf' to '/sub/leaf' on the mounted device", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const leaf = t1.addFile(sub, "leaf");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A non-mountpoint directory resolves to itself on the parent device —
|
||||||
|
* `/a` is not a mount, so no redirect.
|
||||||
|
*/
|
||||||
|
it("resolves a non-mountpoint directory to itself on the parent device", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const a = t0.addDir(0, "a"); // /a = device 0:1 (not a mountpoint)
|
||||||
|
const mnt = t0.addDir(0, "mnt"); // /mnt = device 0:2 (the mountpoint)
|
||||||
|
const t1 = makeTree();
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(
|
||||||
|
NodePointer.of(0, mnt), // "0:2" — the mountpoint
|
||||||
|
NodePointer.of(1, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
const state = makeShellState(fs);
|
||||||
|
|
||||||
|
// /a is not a mountpoint → resolves to itself on device 0
|
||||||
|
expect(resolvePath(state, "/a")).toEqual({ device_id: 0, inode: a });
|
||||||
|
|
||||||
|
// /mnt IS a mountpoint → redirects to device 1's root
|
||||||
|
// (this is already covered by the /mnt tests; include for contrast or drop)
|
||||||
|
expect(resolvePath(state, "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: nested mount at `/a/b` should redirect to dev1's sub.
|
||||||
|
*/
|
||||||
|
it("should resolve '/a/b' (nested mount) to the mounted device's sub", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const a = t0.addDir(0, "a");
|
||||||
|
const b = t0.addDir(a, "b");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
|
||||||
|
expect(resolvePath(makeShellState(fs), "/a/b")).toEqual({ device_id: 1, inode: sub });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: continuation of the nested case — `/a/b/leaf` should
|
||||||
|
* land on dev1's leaf through the mounted sub.
|
||||||
|
*/
|
||||||
|
it("should resolve '/a/b/leaf' through a nested mount", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const a = t0.addDir(0, "a");
|
||||||
|
const b = t0.addDir(a, "b");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const leaf = t1.addFile(sub, "leaf");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, b), NodePointer.of(1, sub));
|
||||||
|
expect(resolvePath(makeShellState(fs), "/a/b/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: two independent mounts must redirect independently.
|
||||||
|
*/
|
||||||
|
it("should resolve multiple independent mounts", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const other = t0.addDir(0, "other");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const file = t1.addFile(0, "file");
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const leaf = t1.addFile(sub, "leaf");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
fs.mount(NodePointer.of(0, other), NodePointer.of(1, sub));
|
||||||
|
|
||||||
|
const state = makeShellState(fs);
|
||||||
|
expect(resolvePath(state, "/mnt/file")).toEqual({ device_id: 1, inode: file });
|
||||||
|
expect(resolvePath(state, "/other/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Symlinks across mount points
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — symlinks across mount points", () => {
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: symlink whose target lands on another device must
|
||||||
|
* return the target's device id in the result. Without threading, the loop
|
||||||
|
* terminates with currentNode from dev1 but currentVD still 0.
|
||||||
|
*/
|
||||||
|
it("should thread the target's device into currentVD after a symlink→mount hop", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
t0.addSymlink(0, "link", "/mnt");
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
expect(resolvePath(makeShellState(fs), "/link")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXPECTED-TO-FAIL: full traversal through the symlink and across the
|
||||||
|
* mount. Verifies not only the final pointer is right, but that the loop
|
||||||
|
* can continue descending on the mounted device.
|
||||||
|
*/
|
||||||
|
it("should resolve through a symlink→mount hop and continue on the mounted device", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
t0.addSymlink(0, "link", "/mnt");
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const file = t1.addFile(0, "file");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
expect(resolvePath(makeShellState(fs), "/link/file")).toEqual({ device_id: 1, inode: file });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Integration
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — integration", () => {
|
||||||
|
/**
|
||||||
|
* Full traversal across multiple levels with a file terminus.
|
||||||
|
*/
|
||||||
|
it("resolves a multi-level path through directories to a file", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const varInode = t.addDir(0, "var");
|
||||||
|
const logInode = t.addDir(varInode, "log");
|
||||||
|
const appLog = t.addFile(logInode, "app.log");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
expect(resolvePath(makeShellState(fs), "/var/log/app.log")).toEqual({ device_id: 0, inode: appLog });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Known bugs — each test asserts *current* behavior and goes red on the fix.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
describe("resolvePath — known bugs", () => {
|
||||||
|
/**
|
||||||
|
* BUG: symlink depth overflow throws a raw `Error`, not a typed error.
|
||||||
|
* Same setup as above; asserts the thrown object isn't a discriminated
|
||||||
|
* union member (no `type` field).
|
||||||
|
*
|
||||||
|
* Fix: throw a typed `SymlinkLoopError` (or similar) from `errors.ts`.
|
||||||
|
*/
|
||||||
|
it("BUG: symlink depth overflow throws a raw Error, not a typed one", async () => {
|
||||||
|
const t = makeTree();
|
||||||
|
const sNames = Array.from({ length: 41 }, (_, i) => `s${i + 1}`);
|
||||||
|
t.addFile(0, "target");
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
t.addSymlink(0, sNames[i]!, `/${sNames[i + 1]}`);
|
||||||
|
}
|
||||||
|
t.addSymlink(0, sNames[40]!, "/target");
|
||||||
|
const fs = await makeFS([t.build()]);
|
||||||
|
|
||||||
|
let thrown: unknown = undefined;
|
||||||
|
try {
|
||||||
|
resolvePath(makeShellState(fs), "/s1");
|
||||||
|
} catch (e) {
|
||||||
|
thrown = e;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(Error);
|
||||||
|
expect(thrown).not.toHaveProperty("type");
|
||||||
|
// ^ BUG: no `type` discriminant. Correct: typed (e.g. SymlinkLoop).
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolvePath — '..' across mount boundaries", () => {
|
||||||
|
/**
|
||||||
|
* BASIC CASE. Mount `/mnt` (device 0) → device 1's root. From inside the
|
||||||
|
* mount (at `1:0`), `..` must exit through the reverse mount index to
|
||||||
|
* `/mnt`'s parent (`/`) — not stay put via the `inode === 0` shortcut.
|
||||||
|
*
|
||||||
|
* This is the direct fix target: the `..` branch must check
|
||||||
|
* `getMountSource(currentPtr)` *before* the `inode === 0` shortcut.
|
||||||
|
*/
|
||||||
|
it("'..' from a mount root returns to the mountpoint's parent", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* NON-ROOT MOUNTPOINT. Mount `/home/user/mnt` → device 1's root. `..` from
|
||||||
|
* the mounted root must land on `/home/user` (device 0), *not* `/`.
|
||||||
|
* Catches a fix that hardcodes "go to root on mount exit".
|
||||||
|
*/
|
||||||
|
it("'..' from a non-root mount returns to the mountpoint's immediate parent", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const home = t0.addDir(0, "home");
|
||||||
|
const user = t0.addDir(home, "user");
|
||||||
|
const mnt = t0.addDir(user, "mnt");
|
||||||
|
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: user });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* INSIDE-MOUNT `..`. A subdirectory of the mounted device is *not* the
|
||||||
|
* mount root, so `..` from `1:sub` must stay inside device 1 (regular
|
||||||
|
* reverse-index walk), not exit the mount. Catches a fix that exits the
|
||||||
|
* mount on every `..` inside the mounted device instead of only at its
|
||||||
|
* root.
|
||||||
|
*/
|
||||||
|
it("'..' from inside a mount (not at its root) stays inside the mount", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
|
||||||
|
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MULTI-STEP `..`. From `/mnt/sub/leaf`, three consecutive `..` should
|
||||||
|
* produce `/mnt/sub` → `/mnt` → `/`. Exercises both the in-mount walk and
|
||||||
|
* the final mount exit in one flow. Catches a fix that only handles the
|
||||||
|
* "already at mount root" case but breaks when coming from deeper.
|
||||||
|
*/
|
||||||
|
it("multi-step '..' walks from deep inside a mount out to the parent device", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const t1 = makeTree();
|
||||||
|
const sub = t1.addDir(0, "sub");
|
||||||
|
const leaf = t1.addFile(sub, "leaf");
|
||||||
|
const fs = await makeFS([t0.build(), t1.build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
// Sanity: full descent lands at `1:leaf`
|
||||||
|
expect(resolvePath(makeShellState(fs), "/mnt/sub/leaf")).toEqual({ device_id: 1, inode: leaf });
|
||||||
|
|
||||||
|
// One `..` up: /mnt/sub
|
||||||
|
const atLeaf = makeShellState(fs, { cwd: NodePointer.of(1, leaf) });
|
||||||
|
expect(resolvePath(atLeaf, "..")).toEqual({ device_id: 1, inode: sub });
|
||||||
|
|
||||||
|
// Another `..`: /mnt's content = dev1 root
|
||||||
|
const atSub = makeShellState(fs, { cwd: NodePointer.of(1, sub) });
|
||||||
|
expect(resolvePath(atSub, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
|
||||||
|
// Final `..`: exit the mount → /
|
||||||
|
const atMountedRoot = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atMountedRoot, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* INDEPENDENT MOUNTS AT DIFFERENT DEPTHS. Mount A at `/a` (dev0 → dev1)
|
||||||
|
* and Mount B at `/b/nested` (dev0 → dev2). `..` from dev1's root must go
|
||||||
|
* to `/` (parent of `/a`), while `..` from dev2's root must go to `/b`
|
||||||
|
* (parent of `/b/nested`).
|
||||||
|
*
|
||||||
|
* Catches a fix that collapses the reverse index to a single entry — e.g.,
|
||||||
|
* if `getMountSource` returns the *first* mount's mountpoint for any
|
||||||
|
* target, or if `mount()` overwrites the wrong entry.
|
||||||
|
*/
|
||||||
|
it("'..' from different mounts returns to each mountpoint's own parent", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const a = t0.addDir(0, "a");
|
||||||
|
const b = t0.addDir(0, "b");
|
||||||
|
const nested = t0.addDir(b, "nested");
|
||||||
|
|
||||||
|
const fs = await makeFS([t0.build(), makeTree().build(), makeTree().build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, a), NodePointer.of(1, 0)); // /a → dev1
|
||||||
|
await fs.mount(NodePointer.of(0, nested), NodePointer.of(2, 0)); // /b/nested → dev2
|
||||||
|
|
||||||
|
// `..` from dev1's root → parent of `/a` = `/`
|
||||||
|
const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
|
||||||
|
// `..` from dev2's root → parent of `/b/nested` = `/b`
|
||||||
|
const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
|
||||||
|
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 0, inode: b });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MOUNT NESTED IN A MOUNTED DEVICE'S TREE. The most realistic cross-device
|
||||||
|
* scenario:
|
||||||
|
*
|
||||||
|
* dev0: /mnt (0:1)
|
||||||
|
* dev1: / (1:0)
|
||||||
|
* /b (1:2) ← mountpoint of B
|
||||||
|
* dev2: / (2:0)
|
||||||
|
*
|
||||||
|
* Mount A: 0:1 → 1:0 (/mnt shows dev1)
|
||||||
|
* Mount B: 1:2 → 2:0 (/mnt/b shows dev2)
|
||||||
|
*
|
||||||
|
* From `/mnt/b` (dev2 root), `..` must exit B's mount to `/mnt/b`'s parent
|
||||||
|
* in the *mounted* device 1 (`1:0`), not skip straight to device 0. A
|
||||||
|
* second `..` then exits A's mount to `/`.
|
||||||
|
*
|
||||||
|
* This is the true "chained mount exit" case. Each `..` handles exactly
|
||||||
|
* one mount; the reverse index for `1:2` (B's mountpoint) lands on `1:0`
|
||||||
|
* (dev1 root), which is itself a mount target of A. The second `..` then
|
||||||
|
* exits A. Both steps go through the same `getMountSource` branch.
|
||||||
|
*/
|
||||||
|
it("'..' walks out of a mount nested inside another mount's device tree", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
|
||||||
|
const t1 = makeTree();
|
||||||
|
const b = t1.addDir(0, "b");
|
||||||
|
|
||||||
|
const fs = await makeFS([t0.build(), t1.build(), makeTree().build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0)); // /mnt → dev1
|
||||||
|
await fs.mount(NodePointer.of(1, b), NodePointer.of(2, 0)); // /mnt/b → dev2
|
||||||
|
|
||||||
|
// Sanity: /mnt/b resolves to dev2 root
|
||||||
|
expect(resolvePath(makeShellState(fs), "/mnt/b")).toEqual({ device_id: 2, inode: 0 });
|
||||||
|
|
||||||
|
// `..` from dev2 root → exit B's mount → parent of `1:b` = `1:0` (dev1 root)
|
||||||
|
const atDev2Root = makeShellState(fs, { cwd: NodePointer.of(2, 0) });
|
||||||
|
expect(resolvePath(atDev2Root, "..")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
|
||||||
|
// `..` from dev1 root → exit A's mount → parent of `0:mnt` = `/`
|
||||||
|
const atDev1Root = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atDev1Root, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ROUND TRIP. `cd /mnt`, `cd ..`, `cd mnt` should land back at `{1:0}`.
|
||||||
|
* Catches a fix that mutates mount state (e.g., a stale `currentDeviceId`
|
||||||
|
* that leaks across calls) or that resolves `/mnt` differently after a
|
||||||
|
* `..` exit.
|
||||||
|
*/
|
||||||
|
it("entering and exiting a mount via resolvePath round-trips", async () => {
|
||||||
|
const t0 = makeTree();
|
||||||
|
const mnt = t0.addDir(0, "mnt");
|
||||||
|
const fs = await makeFS([t0.build(), makeTree().build()]);
|
||||||
|
await fs.mount(NodePointer.of(0, mnt), NodePointer.of(1, 0));
|
||||||
|
|
||||||
|
// Start at /, enter /mnt
|
||||||
|
const fromRoot = makeShellState(fs);
|
||||||
|
expect(resolvePath(fromRoot, "/mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||||
|
|
||||||
|
// `..` from mounted root → /
|
||||||
|
const atMnt = makeShellState(fs, { cwd: NodePointer.of(1, 0) });
|
||||||
|
expect(resolvePath(atMnt, "..")).toEqual({ device_id: 0, inode: 0 });
|
||||||
|
|
||||||
|
// `mnt` again from / → back to mounted root
|
||||||
|
const atRoot = makeShellState(fs, { cwd: NodePointer.of(0, 0) });
|
||||||
|
expect(resolvePath(atRoot, "mnt")).toEqual({ device_id: 1, inode: 0 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
import type { UserInfo } from "@core/session_manager";
|
|
||||||
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
|
|
||||||
import { createInitialShellState } from "@core/shell_state";
|
|
||||||
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
|
||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
const root: UserInfo = {
|
|
||||||
username: "root",
|
|
||||||
uid: 0,
|
|
||||||
gid: 0,
|
|
||||||
group: [0],
|
|
||||||
home: 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
const testU: UserInfo = {
|
|
||||||
username: "test",
|
|
||||||
uid: 1,
|
|
||||||
gid: 1,
|
|
||||||
group: [1],
|
|
||||||
home: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
const fs = buildTestFS(depth7Tree);
|
|
||||||
const users = new Map();
|
|
||||||
users.set(0, root);
|
|
||||||
users.set(1, testU);
|
|
||||||
const state = createInitialShellState(fs, users, root);
|
|
||||||
|
|
||||||
const passMap = new Map();
|
|
||||||
passMap.set(0, "123");
|
|
||||||
passMap.set(1, "321");
|
|
||||||
|
|
||||||
test("createInitialSessionState - successfully creates a new session state", () => {
|
|
||||||
const state = createInitialSessionState(root);
|
|
||||||
|
|
||||||
expect(state.cwd).toEqual(root.home);
|
|
||||||
expect(state.pwd).toEqual(root.home);
|
|
||||||
expect(state.exitCode).toEqual(0);
|
|
||||||
expect(state.user).toBe(root);
|
|
||||||
expect(Object.isFrozen(state)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("login", () => {
|
|
||||||
test("it successfully starts a new session under the user test", () => {
|
|
||||||
const newState = login(state, "test", "321", passMap);
|
|
||||||
const pop = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect(pop.user).toEqual(testU);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fails to start a new session. Cause: no password mapped to the uid", () => {
|
|
||||||
const nopass: UserInfo = {
|
|
||||||
username: "no pass",
|
|
||||||
uid: 2,
|
|
||||||
gid: 1,
|
|
||||||
group: [1],
|
|
||||||
home: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
users.set(2, nopass);
|
|
||||||
|
|
||||||
//TODO: Fix to expect the correct object;
|
|
||||||
expect(() => login(state, "no pass", "321", passMap)).toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fails to start a new session. Cause: Incorrect password", () => {
|
|
||||||
//TODO: Fix to expect the correct object;
|
|
||||||
expect(() => login(state, "no pass", "333", passMap)).toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fails to start a new session. Cause: Specified user does not exist", () => {
|
|
||||||
//TODO: Fix to expect the correct object;
|
|
||||||
expect(() => login(state, "no user", "321", passMap)).toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("logout", () => {
|
|
||||||
test("returns the state with the current user poped from the stack", () => {
|
|
||||||
const newState = login(state, "test", "321", passMap);
|
|
||||||
const newPop = getCurrentSession(newState);
|
|
||||||
|
|
||||||
expect(newPop.user).toEqual(testU);
|
|
||||||
|
|
||||||
const newNewState = logout(state);
|
|
||||||
const pop = getCurrentSession(newNewState);
|
|
||||||
|
|
||||||
expect(pop.user).toEqual(root);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import { FileSystem } from "@core/filesystem/filesystem";
|
|
||||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
|
|
||||||
import type { UserInfo } from "@core/session_manager";
|
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
|
||||||
import { createInitialShellState, withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
|
|
||||||
import { expect, test } from "vitest";
|
|
||||||
|
|
||||||
const map: Map<number, TreeNode> = new Map();
|
|
||||||
const time = Date.now();
|
|
||||||
|
|
||||||
const root: DirectoryNode = {
|
|
||||||
type: TreeNodeType.Directory,
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
parent: 0,
|
|
||||||
mode: 0o555,
|
|
||||||
owner: 0,
|
|
||||||
group: 0,
|
|
||||||
mtime: time,
|
|
||||||
atime: time,
|
|
||||||
ctime: time,
|
|
||||||
children: {},
|
|
||||||
};
|
|
||||||
map.set(0, root);
|
|
||||||
|
|
||||||
const base: ReadonlyMap<number, TreeNode> = map;
|
|
||||||
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
|
||||||
const fs = FileSystem.init(base, overlay, 0);
|
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
|
||||||
const user: UserInfo = {
|
|
||||||
username: "root",
|
|
||||||
uid: 0,
|
|
||||||
gid: 0,
|
|
||||||
group: [0],
|
|
||||||
home: 0,
|
|
||||||
};
|
|
||||||
users.set(0, user);
|
|
||||||
|
|
||||||
const state = createInitialShellState(fs, users, user);
|
|
||||||
|
|
||||||
test("createInitialShellState - initializes successfully", () => {
|
|
||||||
expect(state.sessionStack.at(0)).toBeDefined();
|
|
||||||
|
|
||||||
expect(state.users.get(user.uid)).toEqual(user);
|
|
||||||
expect(Object.isFrozen(state)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fails - tries to mutate a frozen immutable object", () => {
|
|
||||||
expect(() => {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
(state as any).sessionStack = [];
|
|
||||||
}).toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("getCurrentSession - successfully returns the current (top most) session from the stack", () => {
|
|
||||||
const session = getCurrentSession(state);
|
|
||||||
|
|
||||||
expect(session.cwd).toBe(0);
|
|
||||||
expect(session.pwd).toBe(0);
|
|
||||||
expect(session.exitCode).toBe(0);
|
|
||||||
expect(session.history).toEqual([]);
|
|
||||||
expect(session.envVars.size).toBe(0);
|
|
||||||
expect(session.user).toBe(user);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("withCwd", () => {
|
|
||||||
const nstate = withCwd(state, 1);
|
|
||||||
const result = getCurrentSession(nstate);
|
|
||||||
expect(result.cwd).toBe(1);
|
|
||||||
expect(result.pwd).toBe(0);
|
|
||||||
expect(nstate.filesystem).toBe(state.filesystem);
|
|
||||||
expect(getCurrentSession(state).cwd).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("withEnv", () => {
|
|
||||||
const nstate = withEnv(state, "foo", "Hello World!");
|
|
||||||
const result = getCurrentSession(nstate);
|
|
||||||
expect(result.envVars.get("foo")).toBe("Hello World!");
|
|
||||||
expect(nstate.filesystem).toBe(state.filesystem);
|
|
||||||
expect(getCurrentSession(state).envVars.get("foo")).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("withHistory", () => {
|
|
||||||
const nstate = withHistory(state, 'echo "Hi!"');
|
|
||||||
const result = getCurrentSession(nstate);
|
|
||||||
expect(result.history).toContain('echo "Hi!"');
|
|
||||||
expect(nstate.filesystem).toBe(state.filesystem);
|
|
||||||
expect(getCurrentSession(state).history).not.toContain('echo "Hi!"');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("withExitCode", () => {
|
|
||||||
const nstate = withExitCode(state, 10);
|
|
||||||
const result = getCurrentSession(nstate);
|
|
||||||
expect(result.exitCode).toEqual(10);
|
|
||||||
expect(nstate.filesystem).toBe(state.filesystem);
|
|
||||||
expect(getCurrentSession(state).exitCode).toEqual(0);
|
|
||||||
});
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
import { parseCommand } from "@core/util/parser";
|
|
||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
describe("parseCommand", () => {
|
|
||||||
test("returns an empty ParsedCommand object", () => {
|
|
||||||
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
|
|
||||||
});
|
|
||||||
test("returns an empty ParsedCommand object", () => {
|
|
||||||
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
|
|
||||||
});
|
|
||||||
test("returns an empty ParsedCommand object", () => {
|
|
||||||
expect(parseCommand("")).toEqual({ command: "", flags: [], args: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed ls command without any args", () => {
|
|
||||||
expect(parseCommand("ls")).toEqual({ command: "ls", flags: [], args: [] });
|
|
||||||
});
|
|
||||||
test("returns a parsed ls command with arg /tmp", () => {
|
|
||||||
expect(parseCommand("ls /tmp")).toEqual({ command: "ls", flags: [], args: ["/tmp"] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed ls command with flags l and no args", () => {
|
|
||||||
expect(parseCommand("ls -l")).toEqual({ command: "ls", flags: ["l"], args: [] });
|
|
||||||
});
|
|
||||||
test("returns a parsed command with flags l,a and no args", () => {
|
|
||||||
expect(parseCommand("ls -la")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
|
|
||||||
});
|
|
||||||
test("returns a parsed command with flags l,a and no args", () => {
|
|
||||||
expect(parseCommand("ls -l -a")).toEqual({ command: "ls", flags: ["l", "a"], args: [] });
|
|
||||||
});
|
|
||||||
test("returns a parsed command with flags l,a and a /tmp arg", () => {
|
|
||||||
expect(parseCommand("ls -la /tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["/tmp"] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed grep command with a valued color flag", () => {
|
|
||||||
expect(parseCommand("grep --color=auto")).toEqual({ command: "grep", flags: ["color=auto"], args: [] });
|
|
||||||
});
|
|
||||||
test("returns a parsed grep command with a valued color and r flags", () => {
|
|
||||||
expect(parseCommand("grep --color=auto -r")).toEqual({
|
|
||||||
command: "grep",
|
|
||||||
flags: ["color=auto", "r"],
|
|
||||||
args: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed grep command with a valued color in short form and r flags", () => {
|
|
||||||
expect(parseCommand("grep -color=auto -r")).toEqual({
|
|
||||||
command: "grep",
|
|
||||||
flags: ["color=auto", "r"],
|
|
||||||
args: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed grep command with a valued w in short form and r flags", () => {
|
|
||||||
expect(parseCommand("grep -w=auto -r")).toEqual({
|
|
||||||
command: "grep",
|
|
||||||
flags: ["w=auto", "r"],
|
|
||||||
args: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed echo command with a --version arg", () => {
|
|
||||||
expect(parseCommand("echo -- --version")).toEqual({ command: "echo", flags: [], args: ["--version"] });
|
|
||||||
});
|
|
||||||
test("returns a parsed echo command with a -f arg", () => {
|
|
||||||
expect(parseCommand("echo -- -f")).toEqual({ command: "echo", flags: [], args: ["-f"] });
|
|
||||||
});
|
|
||||||
test("returns a parsed echo command without any args", () => {
|
|
||||||
expect(parseCommand("echo --")).toEqual({ command: "echo", flags: [], args: [] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns a parsed ls command with flags l,a and a --tmp arg", () => {
|
|
||||||
expect(parseCommand("ls -la -- --tmp")).toEqual({ command: "ls", flags: ["l", "a"], args: ["--tmp"] });
|
|
||||||
});
|
|
||||||
test("returns a parsed rm command with flags r,f,no-preserve-root and a / arg", () => {
|
|
||||||
expect(parseCommand("rm -rf --no-preserve-root /")).toEqual({
|
|
||||||
command: "rm",
|
|
||||||
flags: ["r", "f", "no-preserve-root"],
|
|
||||||
args: ["/"],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("throws an UnclosedQuote error", () => {
|
|
||||||
expect(() => parseCommand('echo "hello')).toThrow(expect.objectContaining({ type: "UnclosedQuote" }));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
import { dnTraverseTree, upTraverseTree } from "@core/util/tree_traversal";
|
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
|
||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 1,
|
|
||||||
name: "hello.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Hello, world!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 2,
|
|
||||||
name: "sub",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 3,
|
|
||||||
name: "world.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
|
||||||
const fsTwo = buildTestFS(depth7Tree);
|
|
||||||
|
|
||||||
describe("dnTraverseTree", () => {
|
|
||||||
test("successfully traverses down the tree in depth-first pre-order", () => {
|
|
||||||
const result = dnTraverseTree(fs, 0);
|
|
||||||
expect(result, `Checking the result ${result} to be [0, 1, 2, 3]`).toEqual([0, 2, 3, 1]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns empty array for a non existent root inode", () => {
|
|
||||||
expect(dnTraverseTree(fs, 999)).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("upTraverseTree", () => {
|
|
||||||
test("successfully traverses up the tree", () => {
|
|
||||||
const result = upTraverseTree(fsTwo, 7);
|
|
||||||
expect(result, `Checking the result ${result} to be [7, 6, 5, 4, 3, 2, 1, 0]`).toEqual([
|
|
||||||
7, 6, 5, 4, 3, 2, 1, 0,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns empty array for a non existent inode", () => {
|
|
||||||
expect(dnTraverseTree(fs, 999)).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,17 +1,23 @@
|
|||||||
|
// @core/filesystem/errors.test-util.ts (adjust path to match yours)
|
||||||
import type {
|
import type {
|
||||||
AlreadyExistsError,
|
AlreadyExistsError,
|
||||||
|
DeviceNotFoundError,
|
||||||
DirectoryLoopError,
|
DirectoryLoopError,
|
||||||
|
FileSystemCorruptionError,
|
||||||
|
FileSystemInitializationError,
|
||||||
IllegalMutationError,
|
IllegalMutationError,
|
||||||
|
InvalidNodeNameError,
|
||||||
NodeNotFoundError,
|
NodeNotFoundError,
|
||||||
NotADirectoryError,
|
NotADirectoryError,
|
||||||
|
NotAFileError,
|
||||||
} from "@core/filesystem/errors";
|
} from "@core/filesystem/errors";
|
||||||
import type { TreeNodeType } from "@core/filesystem/treenode";
|
import type { NodeType } from "@core/filesystem/node";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
export function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
export async function expectThrows(fn: () => unknown, expectedShape: Record<string, unknown>) {
|
||||||
let thrown: unknown;
|
let thrown: unknown;
|
||||||
try {
|
try {
|
||||||
fn();
|
await fn();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
thrown = e;
|
thrown = e;
|
||||||
}
|
}
|
||||||
@@ -20,19 +26,19 @@ export function expectThrows(fn: () => unknown, expectedShape: Record<string, un
|
|||||||
expect(thrown).toMatchObject(expectedShape);
|
expect(thrown).toMatchObject(expectedShape);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
|
export async function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<NotADirectoryError>) {
|
||||||
expectThrows(fn, {
|
return await expectThrows(fn, {
|
||||||
type: "NotADirectory",
|
type: "NotADirectory",
|
||||||
inode: expect.any(Number) as number,
|
inode: expect.any(Number) as number,
|
||||||
message: expect.any(String) as string,
|
message: expect.any(String) as string,
|
||||||
timestamp: expect.any(Number) as number,
|
timestamp: expect.any(Number) as number,
|
||||||
nodeType: expect.any(String) as TreeNodeType,
|
nodeType: expect.any(Number) as NodeType,
|
||||||
...overrides,
|
...overrides,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
|
export async function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<AlreadyExistsError>) {
|
||||||
expectThrows(fn, {
|
return await expectThrows(fn, {
|
||||||
type: "AlreadyExists",
|
type: "AlreadyExists",
|
||||||
parentInode: expect.any(Number) as number,
|
parentInode: expect.any(Number) as number,
|
||||||
name: expect.any(String) as string,
|
name: expect.any(String) as string,
|
||||||
@@ -42,18 +48,23 @@ export function expectAlreadyExistsError(fn: () => unknown, overrides?: Partial<
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
|
/**
|
||||||
expectThrows(fn, {
|
* FIXED: `NodeNotFoundError` has `pointer: NodePointer` (a string), not `inode: number`.
|
||||||
|
* The previous version asserted `inode: expect.any(Number)` and would have failed
|
||||||
|
* against every real thrown `NodeNotFoundError`.
|
||||||
|
*/
|
||||||
|
export async function expectNodeNotFoundError(fn: () => unknown, overrides?: Partial<NodeNotFoundError>) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
type: "NodeNotFound",
|
type: "NodeNotFound",
|
||||||
inode: expect.any(Number) as number,
|
pointer: expect.any(String) as string,
|
||||||
message: expect.any(String) as string,
|
message: expect.any(String) as string,
|
||||||
timestamp: expect.any(Number) as number,
|
timestamp: expect.any(Number) as number,
|
||||||
...overrides,
|
...overrides,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
|
export async function expectIllegalMutationError(fn: () => unknown, overrides?: Partial<IllegalMutationError>) {
|
||||||
expectThrows(fn, {
|
return await expectThrows(fn, {
|
||||||
type: "IllegalMutation",
|
type: "IllegalMutation",
|
||||||
message: expect.any(String) as string,
|
message: expect.any(String) as string,
|
||||||
timestamp: expect.any(Number) as number,
|
timestamp: expect.any(Number) as number,
|
||||||
@@ -61,8 +72,8 @@ export function expectIllegalMutationError(fn: () => unknown, overrides?: Partia
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
|
export async function expectDirectoryLoopError(fn: () => void, overrides?: Partial<DirectoryLoopError>) {
|
||||||
expectThrows(fn, {
|
return await expectThrows(fn, {
|
||||||
type: "DirectoryLoop",
|
type: "DirectoryLoop",
|
||||||
descendantInode: expect.any(Number) as number,
|
descendantInode: expect.any(Number) as number,
|
||||||
ancestorInode: expect.any(Number) as number,
|
ancestorInode: expect.any(Number) as number,
|
||||||
@@ -71,3 +82,61 @@ export function expectDirectoryLoopError(fn: () => void, overrides?: Partial<Dir
|
|||||||
...overrides,
|
...overrides,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- NEW helpers below ----
|
||||||
|
|
||||||
|
export async function expectDeviceNotFoundError(fn: () => unknown, overrides?: Partial<DeviceNotFoundError>) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
|
type: "DeviceNotFound",
|
||||||
|
device_id: expect.any(Number) as number,
|
||||||
|
message: expect.any(String) as string,
|
||||||
|
timestamp: expect.any(Number) as number,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectNotAFileError(fn: () => unknown, overrides?: Partial<NotAFileError>) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
|
type: "NotAFile",
|
||||||
|
inode: expect.any(Number) as number,
|
||||||
|
message: expect.any(String) as string,
|
||||||
|
timestamp: expect.any(Number) as number,
|
||||||
|
nodeType: expect.any(Number) as NodeType,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectFileSystemInitializationError(
|
||||||
|
fn: () => unknown,
|
||||||
|
overrides?: Partial<FileSystemInitializationError>,
|
||||||
|
) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
|
type: "FileSystemInitializationError",
|
||||||
|
message: expect.any(String) as string,
|
||||||
|
timestamp: expect.any(Number) as number,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectInvalidNodeNameError(fn: () => unknown, overrides?: Partial<InvalidNodeNameError>) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
|
type: "InvalidNodeName",
|
||||||
|
pointer: expect.any(String) as string,
|
||||||
|
attemptedName: expect.any(String) as string,
|
||||||
|
message: expect.any(String) as string,
|
||||||
|
timestamp: expect.any(Number) as number,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectFileSystemCorruptionError(
|
||||||
|
fn: () => unknown,
|
||||||
|
overrides?: Partial<FileSystemCorruptionError>,
|
||||||
|
) {
|
||||||
|
return await expectThrows(fn, {
|
||||||
|
type: "FileSystemCorruption",
|
||||||
|
message: expect.any(String) as string,
|
||||||
|
timestamp: expect.any(Number) as number,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,71 +1,181 @@
|
|||||||
import { FileSystem } from "@core/filesystem/filesystem";
|
// ============================================================================
|
||||||
import { TreeNodeType, type DirectoryNode, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
// Node fixtures
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
// ============================================================================
|
||||||
|
|
||||||
export interface FixtureNode {
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
inode: number;
|
import {
|
||||||
name: string;
|
NodePointer,
|
||||||
type: "File" | "Dir";
|
NodeType,
|
||||||
children: FixtureNode[];
|
type DirectoryNode,
|
||||||
content?: string;
|
type FileNode,
|
||||||
mode?: number;
|
type Node,
|
||||||
owner?: number;
|
type SymlinkNode,
|
||||||
group?: number;
|
} from "@core/filesystem/node";
|
||||||
mtime?: number;
|
import { DefaultVDiskConfig } from "@core/filesystem/vdisk";
|
||||||
ctime?: number;
|
import type { SessionState, UserInfo } from "@core/session_manager";
|
||||||
atime?: number;
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import { MemDataStore, MemMetaStore } from "@core/util/temp_mem_stores";
|
||||||
|
|
||||||
|
export function makeDir(inode: number, children: Record<string, number> = {}): DirectoryNode {
|
||||||
|
return {
|
||||||
|
type: NodeType.Directory,
|
||||||
|
inode,
|
||||||
|
link_count: 2,
|
||||||
|
mode: 0o755,
|
||||||
|
owner: 0,
|
||||||
|
group: 0,
|
||||||
|
mtime: 0,
|
||||||
|
ctime: 0,
|
||||||
|
atime: 0,
|
||||||
|
children: new Map(Object.entries(children)),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildTestFS(tree: FixtureNode): FileSystem {
|
export function makeFile(inode: number): FileNode {
|
||||||
const map = new Map<number, TreeNode>();
|
return {
|
||||||
|
type: NodeType.File,
|
||||||
|
inode,
|
||||||
|
link_count: 1,
|
||||||
|
mode: 0o644,
|
||||||
|
owner: 0,
|
||||||
|
group: 0,
|
||||||
|
mtime: 0,
|
||||||
|
ctime: 0,
|
||||||
|
atime: 0,
|
||||||
|
content: `uuid-${inode}`,
|
||||||
|
size: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function parse(node: FixtureNode, parent: number): void {
|
export function makeSymlink(inode: number, target: string): SymlinkNode {
|
||||||
if (node.type === "Dir") {
|
return {
|
||||||
for (const child of node.children) {
|
type: NodeType.Symlink,
|
||||||
parse(child, node.inode);
|
inode,
|
||||||
}
|
link_count: 1,
|
||||||
|
mode: 0o777,
|
||||||
|
owner: 0,
|
||||||
|
group: 0,
|
||||||
|
mtime: 0,
|
||||||
|
ctime: 0,
|
||||||
|
atime: 0,
|
||||||
|
target,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const children: Record<string, number> = {};
|
export function makeUser(home: NodePointer = NodePointer.of(0, 0)): UserInfo {
|
||||||
for (const child of node.children) {
|
return {
|
||||||
children[child.name] = child.inode;
|
username: "test",
|
||||||
}
|
uid: 1000,
|
||||||
|
gid: 1000,
|
||||||
|
group: [],
|
||||||
|
home,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const directoryNode: DirectoryNode = {
|
// ============================================================================
|
||||||
type: TreeNodeType.Directory,
|
// Tree builder — auto-assigns inodes, validates before use
|
||||||
inode: node.inode,
|
// ============================================================================
|
||||||
name: node.name,
|
|
||||||
parent: parent,
|
export interface TreeBuilder {
|
||||||
mode: node.mode ?? 0o777,
|
addDir(parentInode: number, name: string): number;
|
||||||
owner: node.owner ?? 0,
|
addFile(parentInode: number, name: string): number;
|
||||||
group: node.group ?? 0,
|
addSymlink(parentInode: number, name: string, target: string): number;
|
||||||
mtime: node.mtime ?? Date.now(),
|
build(): Map<number, Node>;
|
||||||
ctime: node.ctime ?? Date.now(),
|
}
|
||||||
atime: node.atime ?? Date.now(),
|
|
||||||
children: children,
|
export function makeTree(): TreeBuilder {
|
||||||
};
|
const nodes = new Map<number, Node>([[0, makeDir(0)]]);
|
||||||
map.set(node.inode, Object.freeze(directoryNode));
|
let nextInode = 1;
|
||||||
} else {
|
|
||||||
const fileNode: FileNode = {
|
function attach(parentInode: number, name: string, childInode: number): void {
|
||||||
type: TreeNodeType.File,
|
const parent = nodes.get(parentInode);
|
||||||
inode: node.inode,
|
if (!parent || parent.type !== NodeType.Directory) {
|
||||||
name: node.name,
|
throw new Error(`Parent inode ${parentInode} is not a directory`);
|
||||||
parent: parent,
|
|
||||||
mode: node.mode ?? 0o777,
|
|
||||||
owner: node.owner ?? 0,
|
|
||||||
group: node.group ?? 0,
|
|
||||||
mtime: node.mtime ?? Date.now(),
|
|
||||||
ctime: node.ctime ?? Date.now(),
|
|
||||||
atime: node.atime ?? Date.now(),
|
|
||||||
content: createImmutableBuffer(new TextEncoder().encode(node.content)),
|
|
||||||
};
|
|
||||||
map.set(node.inode, Object.freeze(fileNode));
|
|
||||||
}
|
}
|
||||||
|
const children = new Map(parent.children);
|
||||||
|
children.set(name, childInode);
|
||||||
|
nodes.set(parentInode, { ...parent, children });
|
||||||
}
|
}
|
||||||
|
|
||||||
parse(tree, 0);
|
function add(node: Node, parentInode: number, name: string): number {
|
||||||
|
attach(parentInode, name, node.inode);
|
||||||
|
nodes.set(node.inode, node);
|
||||||
|
return node.inode;
|
||||||
|
}
|
||||||
|
|
||||||
const base: ReadonlyMap<number, TreeNode> = map;
|
return {
|
||||||
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
addDir(parentInode, name) {
|
||||||
|
return add(makeDir(nextInode++), parentInode, name);
|
||||||
|
},
|
||||||
|
addFile(parentInode, name) {
|
||||||
|
return add(makeFile(nextInode++), parentInode, name);
|
||||||
|
},
|
||||||
|
addSymlink(parentInode, name, target) {
|
||||||
|
return add(makeSymlink(nextInode++, target), parentInode, name);
|
||||||
|
},
|
||||||
|
build() {
|
||||||
|
for (const [key, node] of nodes) {
|
||||||
|
if (node.inode !== key) {
|
||||||
|
throw new Error(`inode mismatch: key=${key}, node.inode=${node.inode}`);
|
||||||
|
}
|
||||||
|
if (node.type === NodeType.Directory) {
|
||||||
|
for (const [cname, cinode] of node.children) {
|
||||||
|
if (!nodes.has(cinode)) {
|
||||||
|
throw new Error(`dangling child '${cname}' → inode ${cinode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return FileSystem.init(base, overlay, base.size - 1);
|
// ============================================================================
|
||||||
|
// FileSystem builder — real VDisk stack, one device per base map
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export async function makeFS(bases: Map<number, Node>[]): Promise<FileSystem> {
|
||||||
|
const devices = bases.map((base, id) => ({
|
||||||
|
dstore: new MemDataStore(),
|
||||||
|
mstore: new MemMetaStore(),
|
||||||
|
config: {
|
||||||
|
...DefaultVDiskConfig(id),
|
||||||
|
base,
|
||||||
|
index: Math.max(0, ...base.keys()),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const fs = FileSystem.init(devices);
|
||||||
|
// `FileSystem.init` does not await `registerDisk` (see the init suite BUG);
|
||||||
|
// flush a macrotask so every disk is registered before the first resolve.
|
||||||
|
await new Promise(r => setImmediate(r));
|
||||||
|
return fs;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Shell state fixture
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export function makeShellState(
|
||||||
|
fs: FileSystem,
|
||||||
|
opts: { cwd?: NodePointer; home?: NodePointer; user?: UserInfo } = {},
|
||||||
|
): ShellState {
|
||||||
|
const cwd = opts.cwd ?? NodePointer.of(0, 0);
|
||||||
|
const user = opts.user ?? makeUser(opts.home);
|
||||||
|
const session = {
|
||||||
|
user,
|
||||||
|
envVars: new Map<string, string>(),
|
||||||
|
history: [],
|
||||||
|
cwd,
|
||||||
|
pwd: cwd,
|
||||||
|
exitCode: 0,
|
||||||
|
} as unknown as SessionState;
|
||||||
|
|
||||||
|
return {
|
||||||
|
filesystem: fs,
|
||||||
|
users: new Map(),
|
||||||
|
groups: new Map(),
|
||||||
|
sessionStack: [session],
|
||||||
|
} as unknown as ShellState;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
import type { FixtureNode } from "./filesystems_fixture";
|
|
||||||
|
|
||||||
export const depth7Tree: FixtureNode = {
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 1,
|
|
||||||
name: "d1",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 2,
|
|
||||||
name: "d2",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 3,
|
|
||||||
name: "d3",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 4,
|
|
||||||
name: "d4",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 5,
|
|
||||||
name: "d5",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 6,
|
|
||||||
name: "d6",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 7,
|
|
||||||
name: "deep_file.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Deepest node at depth 7",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { deserializeFileSystem } from "@shell/serializer";
|
|
||||||
import { test } from "vitest";
|
|
||||||
|
|
||||||
const rawJson = `{"atime": 1786341244,"children": [{"atime": 1786341264,"children": [{"atime": 1786341330,"children": [],"content": null,"ctime": 1786341330,"group": 1000,"inode": 2,"mode": 493,"mtime": 1786341330,"name": "subdir1","owner": 1000,"parent": 1,"type": "directory"}],"content": null,"ctime": 1786341330,"group": 1000,"inode": 1,"mode": 493,"mtime": 1786341330,"name": "folder1","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341269,"children": [{"atime": 1786341344,"children": [],"content": null,"ctime": 1786341344,"group": 1000,"inode": 4,"mode": 493,"mtime": 1786341344,"name": "subdir2","owner": 1000,"parent": 3,"type": "directory"},{"atime": 1786341345,"children": [{"atime": 1786341356,"children": [],"content": [],"ctime": 1786341356,"group": 1000,"inode": 6,"mode": 420,"mtime": 1786341356,"name": "empty-foo","owner": 1000,"parent": 5,"type": "regular"}],"content": null,"ctime": 1786341356,"group": 1000,"inode": 5,"mode": 493,"mtime": 1786341356,"name": "subdir3","owner": 1000,"parent": 3,"type": "directory"}],"content": null,"ctime": 1786341345,"group": 1000,"inode": 3,"mode": 493,"mtime": 1786341345,"name": "folder2","owner": 1000,"parent": 0,"type": "directory"},{"atime": 1786341312,"children": [],"content": [72,101,108,108,111,44,32,87,111,114,108,100,33,10],"ctime": 1786341312,"group": 1000,"inode": 7,"mode": 420,"mtime": 1786341312,"name": "some-file","owner": 1000,"parent": 0,"type": "regular"}],"content": null,"ctime": 1786341312,"group": 1000,"inode": 0,"mode": 493,"mtime": 1786341312,"name": "root","owner": 1000,"parent": 0,"type": "directory"}`;
|
|
||||||
|
|
||||||
test("deserialize json into the correct tree structure", () => {
|
|
||||||
const base = deserializeFileSystem(rawJson);
|
|
||||||
console.log(base);
|
|
||||||
});
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { getCurrentSession, type UserInfo } from "@core/session_manager";
|
|
||||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
|
||||||
import { Shell } from "@shell/shell";
|
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
|
||||||
inode: 0,
|
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 1,
|
|
||||||
name: "hello.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye World!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 2,
|
|
||||||
name: "sub",
|
|
||||||
type: "Dir",
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
inode: 3,
|
|
||||||
name: "world.txt",
|
|
||||||
type: "File",
|
|
||||||
content: "Goodbye!",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
inode: 4,
|
|
||||||
name: "bye",
|
|
||||||
type: "Dir",
|
|
||||||
children: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const fs = buildTestFS(testTree);
|
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
|
||||||
const user: UserInfo = {
|
|
||||||
username: "root",
|
|
||||||
uid: 0,
|
|
||||||
gid: 0,
|
|
||||||
group: [0],
|
|
||||||
home: 0,
|
|
||||||
};
|
|
||||||
users.set(0, user);
|
|
||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
|
||||||
|
|
||||||
describe("Shell tests", () => {
|
|
||||||
test("Successfully executes the cd command", async () => {
|
|
||||||
await Shell.init(state);
|
|
||||||
const result = await Shell.Instance?.Execute("cd /sub");
|
|
||||||
const statee = Shell.Instance?.State;
|
|
||||||
|
|
||||||
expect(result?.type).toEqual("success");
|
|
||||||
expect(getCurrentSession(statee!).history.length).toBe(1);
|
|
||||||
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
|
|
||||||
expect(getCurrentSession(statee!).cwd).toBe(2);
|
|
||||||
expect(getCurrentSession(statee!).exitCode).toBe(0);
|
|
||||||
});
|
|
||||||
test("Returns a proper command error from cd", () => {});
|
|
||||||
test("Returns an empty success result as per parsing a whitespace character or inputing nothing", () => {});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { splitUint8Array } from "@termos/util/concat";
|
||||||
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
|
test("divide to chunks", () => {
|
||||||
|
const data: Uint8Array = new Uint8Array(2048);
|
||||||
|
const result = splitUint8Array(data, 1024);
|
||||||
|
expect(result.length).toEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("divide to chunks", () => {
|
||||||
|
const data: Uint8Array = new Uint8Array(2049);
|
||||||
|
const result = splitUint8Array(data, 1024);
|
||||||
|
expect(result.length).toEqual(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("divide to chunks", () => {
|
||||||
|
const data: Uint8Array = new Uint8Array(2048);
|
||||||
|
const result = splitUint8Array(data, 53);
|
||||||
|
expect(result.length).toEqual(Math.ceil(2048 / 53));
|
||||||
|
});
|
||||||
@@ -23,6 +23,7 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"ignoreDeprecations": "6.0",
|
"ignoreDeprecations": "6.0",
|
||||||
"baseUrl": "./",
|
"baseUrl": "./",
|
||||||
|
"types": ["node"],
|
||||||
"paths": {
|
"paths": {
|
||||||
"@tests/*": ["test/*"],
|
"@tests/*": ["test/*"],
|
||||||
"@shell/*": ["src/shell/*"],
|
"@shell/*": ["src/shell/*"],
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from "tsup";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
entry: ["src/index.ts", "!src/dev.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
|
||||||
|
format: ["esm"],
|
||||||
|
dts: true,
|
||||||
|
clean: true,
|
||||||
|
sourcemap: true,
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user