Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e9227f6d8 | ||
|
|
8e054a220d | ||
|
|
4776232377 | ||
|
|
d0f8376244 | ||
|
|
f1b69bb282 | ||
|
|
1b3314ab87 | ||
|
|
96e15a87f2 | ||
|
|
55b5d3a873 | ||
|
|
1ee2a2fe7a | ||
|
|
310218663d | ||
|
|
20718604e4 | ||
|
|
dad18cd4cc | ||
|
|
48aac3c883 | ||
|
|
268729bb62 | ||
|
|
e313aa5b9d | ||
|
|
16a1805f25 |
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"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,3 +1,41 @@
|
|||||||
# 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 26.2.0 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.
|
||||||
|
|
||||||
|
[ref1]: https://nodejs.org/en/download
|
||||||
|
|
||||||
|
```bash
|
||||||
|
wget https://git.gornodox.dev/ChaosMaker/termos/archive/unstable-async.zip
|
||||||
|
unzip -d termos unstable-async.zip
|
||||||
|
cd termos
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the test suite
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run test
|
||||||
|
```
|
||||||
+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
+4
-4
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"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",
|
||||||
@@ -1084,9 +1084,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "26.1.0",
|
"version": "26.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
|
||||||
"integrity": "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw==",
|
"integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+5
-4
@@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "termos",
|
"name": "termos",
|
||||||
"version": "1.0.0",
|
"version": "0.0.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",
|
"main": "index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "eslint . && vitest"
|
"test": "eslint . && vitest",
|
||||||
|
"dev": "npx tsx src/index.ts"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -16,7 +17,7 @@
|
|||||||
"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",
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
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 echo } from "./commands/echo";
|
import { descriptor as echo } from "./commands/echo";
|
||||||
|
import { descriptor as ls } from "./commands/ls";
|
||||||
|
import { descriptor as testasync } from "./commands/testasync";
|
||||||
|
|
||||||
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);
|
||||||
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,27 @@
|
|||||||
|
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 = "";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
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,72 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType, type FileNode, type TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import { createErrorResult, createSuccessResult, type ResultSuccess } from "@core/result";
|
||||||
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { PathResolutionError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
||||||
|
import { resolvePath } from "@core/util/path_resolver";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "cat";
|
||||||
|
|
||||||
|
//Need to implement escape sequences
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
for (const arg of args) {
|
||||||
|
const inode = resolvePath(state, arg);
|
||||||
|
if (inode === -1) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
"No such file or directory",
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casting to TreeNode because the resolvePath already ensures the inode is correct;
|
||||||
|
const node = state.filesystem.getNode(inode) as TreeNode;
|
||||||
|
|
||||||
|
if (node.type != TreeNodeType.File) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
`${node.name} is a directory`,
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
} satisfies CommandOutput<PathResolutionError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
if (!state.filesystem.canRead(inode, session.user)) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("PermissionDenied", "Permission denied", { resource: arg }, COMMAND_NAME),
|
||||||
|
} satisfies CommandOutput<PermissionDeniedError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
node as FileNode;
|
||||||
|
io.writeStdout(node.content.toArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
+12
-39
@@ -1,5 +1,5 @@
|
|||||||
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 { 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 +9,16 @@ 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,
|
||||||
|
__flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
@@ -22,8 +26,6 @@ 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>;
|
||||||
@@ -37,48 +39,31 @@ function main(state: ShellState, __flags: string[], args: string[]): CommandOutp
|
|||||||
} else if (args[0] === "-") {
|
} else if (args[0] === "-") {
|
||||||
inode = session.pwd;
|
inode = session.pwd;
|
||||||
} else {
|
} else {
|
||||||
const result = safeResolvePath(state.filesystem, session.cwd, args[0]);
|
inode = resolvePath(state, args[0]);
|
||||||
if (result.type === "error") {
|
if (inode === -1) {
|
||||||
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(inode)) {
|
||||||
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(inode, 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>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,18 +73,6 @@ function main(state: ShellState, __flags: string[], args: string[]): CommandOutp
|
|||||||
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 = {
|
||||||
|
|||||||
+11
-12
@@ -1,25 +1,24 @@
|
|||||||
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,
|
||||||
|
__flags: string[],
|
||||||
|
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,312 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType, type DirectoryNode, type TreeNode } from "@core/filesystem/treenode";
|
||||||
|
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 { SortTreeNodeBy, sortTreeNodes } from "@core/util/sort";
|
||||||
|
import { convertToUnit } from "@termos/util/format_unit";
|
||||||
|
|
||||||
|
export const COMMAND_NAME = "ls";
|
||||||
|
|
||||||
|
async function main(
|
||||||
|
io: CommandIO,
|
||||||
|
state: ShellState,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
const entries: { inode: number; path: string }[] = [];
|
||||||
|
const e = new TextEncoder();
|
||||||
|
const vars = flags.filter(
|
||||||
|
// Match at least 1 character between each side of a singular = character
|
||||||
|
f =>
|
||||||
|
f.match(/\w+[=]{1}\w+/g) &&
|
||||||
|
// Check if descriptors flags array contains an object with the name as the flags key and has takesValue set to true
|
||||||
|
descriptor.flags?.some(flag => flag.name === f.split("=")[0] && flag.takesValue === true),
|
||||||
|
);
|
||||||
|
|
||||||
|
const fSet = new Set(flags.filter(f => descriptor.flags?.some(flag => flag.name === f) && !vars.includes(f)));
|
||||||
|
|
||||||
|
if (fSet.size + vars.length < flags.length) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult("UsageError", `Invalid options`, {}, COMMAND_NAME),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
const timeVar = vars.find(f => f.startsWith("time"))?.split("=")[1];
|
||||||
|
const sortVar = vars.find(f => f.startsWith("sort"))?.split("=")[1];
|
||||||
|
|
||||||
|
let sortBy: SortTreeNodeBy = sortVar && isValidSortMethod(sortVar) ? sortVar : SortTreeNodeBy.NAME;
|
||||||
|
let timestamp: SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME =
|
||||||
|
timeVar && isValidTimestamp(timeVar) ? timeVar : SortTreeNodeBy.ATIME;
|
||||||
|
|
||||||
|
if (args.length === 0) {
|
||||||
|
entries.push({ inode: session.cwd, path: "." });
|
||||||
|
} else {
|
||||||
|
for (const arg of args) {
|
||||||
|
const inode = resolvePath(state, arg);
|
||||||
|
if (inode === -1) {
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createErrorResult(
|
||||||
|
"PathResolutionError",
|
||||||
|
`No such file or directory`,
|
||||||
|
{ path: arg },
|
||||||
|
COMMAND_NAME,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
entries.push({ inode: inode, path: arg });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
|
||||||
|
for (const entry of entries) {
|
||||||
|
listDirEntries(entry);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const entry of entries) {
|
||||||
|
//shortDirEntries(entry);
|
||||||
|
}
|
||||||
|
io.writeStdout(e.encode(`No support for short format yet\n`));
|
||||||
|
}
|
||||||
|
io.writeStdout(e.encode("\n"));
|
||||||
|
|
||||||
|
return {
|
||||||
|
state,
|
||||||
|
result: createSuccessResult(COMMAND_NAME),
|
||||||
|
};
|
||||||
|
|
||||||
|
function listDirEntries(entry: { inode: number; path: string }): void {
|
||||||
|
const node = state.filesystem.getNode(entry.inode) as DirectoryNode;
|
||||||
|
|
||||||
|
// This method of evaluating flags is faulty, it doesnt respect order;
|
||||||
|
if (fSet.has("t")) sortBy = timestamp;
|
||||||
|
if (fSet.has("S")) sortBy = SortTreeNodeBy.SIZE;
|
||||||
|
if (fSet.has("X")) sortBy = SortTreeNodeBy.EXTENSION;
|
||||||
|
|
||||||
|
if (fSet.has("R") || fSet.has("recursive")) io.writeStdout(e.encode(`${entry.path}:\n`));
|
||||||
|
io.writeStdout(e.encode(`total ${Object.entries(node.children).length}\n`));
|
||||||
|
|
||||||
|
let children: TreeNode[] = Object.entries(node.children).map(c => state.filesystem.getNode(c[1])!);
|
||||||
|
if (!fSet.has("f") || !fSet.has("U"))
|
||||||
|
children = sortTreeNodes(state, children, fSet.has("r") || fSet.has("reverse"), sortBy);
|
||||||
|
|
||||||
|
if (fSet.has("a") || fSet.has("A") || fSet.has("all") || fSet.has("almost-all") || fSet.has("f"))
|
||||||
|
children = children.filter(c => !c.name.startsWith("."));
|
||||||
|
|
||||||
|
if (fSet.has("l") || fSet.has("g") || fSet.has("o")) {
|
||||||
|
longMode(io, state, children, fSet);
|
||||||
|
io.writeStdout(e.encode("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fSet.has("R") || fSet.has("recursive")) {
|
||||||
|
for (const child of children) {
|
||||||
|
if (child.type === TreeNodeType.Directory) {
|
||||||
|
let path;
|
||||||
|
if (entry.path === "/") {
|
||||||
|
path = "/" + child.name;
|
||||||
|
} else if (entry.path.endsWith("/")) {
|
||||||
|
path = entry.path + child.name;
|
||||||
|
} else path = entry.path + "/" + child.name;
|
||||||
|
listDirEntries({ inode: child.inode, path });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//function normalMode(io: CommandIO, state: ShellState, flags: string[], args: string[]): void {}
|
||||||
|
|
||||||
|
function longMode(io: CommandIO, state: ShellState, nodes: TreeNode[], flags: Set<string>): void {
|
||||||
|
const e = new TextEncoder();
|
||||||
|
|
||||||
|
if (flags.has("a") || flags.has("all") || flags.has("f")) {
|
||||||
|
const cwdNode = state.filesystem.getNode(nodes[0]!.parent)!;
|
||||||
|
const parentNode = state.filesystem.getNode(cwdNode.parent)!;
|
||||||
|
|
||||||
|
const parent: TreeNode = { ...parentNode, name: ".." };
|
||||||
|
nodes.unshift(parent);
|
||||||
|
|
||||||
|
const cwd: TreeNode = { ...cwdNode, name: "." };
|
||||||
|
nodes.unshift(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate the string size of the biggerst node in the array;
|
||||||
|
// Sets 4 length for directories because the arbitrary size is 4096 later in the code
|
||||||
|
const maxInodeWidth = Math.max(...nodes.map(c => c.inode.toString().length));
|
||||||
|
|
||||||
|
const maxSizeWidth = Math.max(
|
||||||
|
...nodes.map(c => (c.type === TreeNodeType.File ? c.content.byteSize().toString().length : 4)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const maxChildrenWidth = Math.max(
|
||||||
|
...nodes.map(c =>
|
||||||
|
c.type === TreeNodeType.Directory ? Object.entries(c.children).length.toString().length : 2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (flags.has("i") || flags.has("inode")) {
|
||||||
|
const inode = node.inode.toString().padStart(maxInodeWidth, " ");
|
||||||
|
io.writeStdout(e.encode(inode + " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode: string = parseMode(node.mode);
|
||||||
|
|
||||||
|
switch (node.type) {
|
||||||
|
case TreeNodeType.Directory:
|
||||||
|
io.writeStdout(e.encode("d" + mode + " "));
|
||||||
|
break;
|
||||||
|
case TreeNodeType.File:
|
||||||
|
io.writeStdout(e.encode("-" + mode + " "));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const childAmnt =
|
||||||
|
node.type === TreeNodeType.Directory
|
||||||
|
? `${Object.entries(node.children).length.toString().padStart(maxChildrenWidth, " ")} `
|
||||||
|
: `${"10".padStart(maxChildrenWidth, " ")} `;
|
||||||
|
|
||||||
|
io.writeStdout(e.encode(childAmnt));
|
||||||
|
|
||||||
|
if (flags.has("o") || flags.has("G") || flags.has("no-group")) {
|
||||||
|
io.writeStdout(e.encode(`${state.users.get(node.owner)?.username} `));
|
||||||
|
} else if (flags.has("g")) {
|
||||||
|
io.writeStdout(e.encode(`${state.groups.get(node.group)?.groupname} `));
|
||||||
|
} else if (flags.has("n") || flags.has("numeric-uid-gid")) {
|
||||||
|
io.writeStdout(e.encode(`${node.owner} ${node.group} `));
|
||||||
|
} else {
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(`${state.users.get(node.owner)?.username} ${state.groups.get(node.group)?.groupname} `),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Holy abomination, pad the stringified bytesize number with whitespaces so the actual length of the string matches across all rows
|
||||||
|
// Sets the folder size to an arbitrary 4096, could change it later to smth else
|
||||||
|
let size;
|
||||||
|
if (flags.has("h") || flags.has("human-readable")) {
|
||||||
|
const bytes = node.type === TreeNodeType.File ? node.content.byteSize() : 4096;
|
||||||
|
size = convertToUnit(bytes, 1, flags.has("si") ? 1000 : 1024);
|
||||||
|
} else {
|
||||||
|
size =
|
||||||
|
node.type === TreeNodeType.File
|
||||||
|
? `${node.content.byteSize().toString().padStart(maxSizeWidth, " ")} `
|
||||||
|
: `${"4096".padStart(maxSizeWidth, " ")} `;
|
||||||
|
}
|
||||||
|
|
||||||
|
io.writeStdout(e.encode(size));
|
||||||
|
|
||||||
|
// for now only mtime, need a helper function for all the formatting later on
|
||||||
|
const mtime = new Date(node.mtime);
|
||||||
|
if (flags.has("full-time")) {
|
||||||
|
io.writeStdout(
|
||||||
|
// Month + 1 because January is 0
|
||||||
|
e.encode(
|
||||||
|
`${mtime.getFullYear()}-${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
io.writeStdout(
|
||||||
|
// Month + 1 because January is 0
|
||||||
|
e.encode(`${mtime.getMonth() + 1}-${mtime.getDate()} ${mtime.getHours()}:${mtime.getMinutes()} `),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const appendSlash = flags.has("p");
|
||||||
|
if (flags.has("Q") || flags.has("quote-name")) {
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(
|
||||||
|
`"${node.type === TreeNodeType.Directory ? node.name + '"' + (appendSlash ? "/" : "") : node.name + '"'}\n`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else if (!flags.has("N") || !flags.has("literal")) {
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(
|
||||||
|
`${node.type === TreeNodeType.Directory ? node.name + (appendSlash ? "/" : "") : node.name}\n`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const name = `${node.name.includes(" ") ? "'" + node.name + "'" : node.name}`;
|
||||||
|
io.writeStdout(
|
||||||
|
e.encode(`${node.type === TreeNodeType.Directory ? name + (appendSlash ? "/" : "") : name}\n`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 SortTreeNodeBy {
|
||||||
|
return Object.values(SortTreeNodeBy).includes(value as SortTreeNodeBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidTimestamp(value: string): value is SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME {
|
||||||
|
return Object.values(SortTreeNodeBy).includes(
|
||||||
|
value as SortTreeNodeBy.ATIME | SortTreeNodeBy.MTIME | SortTreeNodeBy.CTIME,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
flags: [
|
||||||
|
{ name: "l" }, // 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,45 @@
|
|||||||
|
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 { SIGNAL_MAP } from "@core/signal";
|
||||||
|
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,
|
||||||
|
__flags: string[],
|
||||||
|
__args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
while (true) {
|
||||||
|
const out = await io.getSignal();
|
||||||
|
|
||||||
|
if (out.type === SIGNAL_MAP.INPUT) {
|
||||||
|
const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string);
|
||||||
|
io.writeStdout(encoded);
|
||||||
|
|
||||||
|
if (out.payload === "x") {
|
||||||
|
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,59 @@
|
|||||||
|
import type { CommandDescriptor, CommandOutput } from "@core/command";
|
||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
|
import { TreeNodeType } from "@core/filesystem/treenode";
|
||||||
|
import { 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,
|
||||||
|
flags: string[],
|
||||||
|
args: string[],
|
||||||
|
): Promise<CommandOutput<ShellError>> {
|
||||||
|
for (const arg of args) {
|
||||||
|
const inode = resolvePath(state, arg);
|
||||||
|
const session = getCurrentSession(state);
|
||||||
|
|
||||||
|
let newState;
|
||||||
|
|
||||||
|
if (inode === -1) {
|
||||||
|
const index = arg.lastIndexOf("/");
|
||||||
|
let parentPath;
|
||||||
|
if (index === -1) {
|
||||||
|
parentPath = "./";
|
||||||
|
} else {
|
||||||
|
parentPath = arg.slice(0, index);
|
||||||
|
}
|
||||||
|
const fileName = arg.slice(index + 1);
|
||||||
|
const parent = resolvePath(state, parentPath);
|
||||||
|
|
||||||
|
newState = state.filesystem.createNode(
|
||||||
|
parent,
|
||||||
|
fileName,
|
||||||
|
TreeNodeType.File,
|
||||||
|
0o644,
|
||||||
|
session.user.uid,
|
||||||
|
session.user.gid,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ResultSuccess = createSuccessResult(COMMAND_NAME);
|
||||||
|
|
||||||
|
return {
|
||||||
|
state: state,
|
||||||
|
result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const descriptor: CommandDescriptor = {
|
||||||
|
fn: main,
|
||||||
|
name: COMMAND_NAME,
|
||||||
|
};
|
||||||
@@ -45,7 +45,7 @@ export interface DirectoryNode {
|
|||||||
} */
|
} */
|
||||||
|
|
||||||
export enum TreeNodeType {
|
export enum TreeNodeType {
|
||||||
File = "0",
|
File = 0,
|
||||||
Directory = "1",
|
Directory = 1,
|
||||||
//Symlink = "2",
|
//Symlink = 2,
|
||||||
}
|
}
|
||||||
|
|||||||
+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 }),
|
||||||
|
|||||||
@@ -2,6 +2,12 @@ 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;
|
||||||
@@ -59,7 +65,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 +73,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;
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-1
@@ -1,22 +1,25 @@
|
|||||||
import type { FileSystem } from "./filesystem/filesystem";
|
import type { FileSystem } from "./filesystem/filesystem";
|
||||||
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>;
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
||||||
): ShellState {
|
): ShellState {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
filesystem,
|
filesystem,
|
||||||
users,
|
users,
|
||||||
|
groups,
|
||||||
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
sessionStack: Object.freeze([createInitialSessionState(user)]),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -24,11 +27,13 @@ export function createInitialShellState(
|
|||||||
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),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -52,6 +57,7 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -75,6 +81,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 +108,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 +132,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);
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-3
@@ -1,8 +1,13 @@
|
|||||||
export type Input = string;
|
|
||||||
|
|
||||||
//Payload optional because command that handles that signal
|
//Payload optional because command that handles that signal
|
||||||
// is going to know what shape it is, therefore also able to cast it;
|
// is going to know what shape it is, therefore also able to cast it;
|
||||||
export type Signal = {
|
export type Signal = {
|
||||||
type: string;
|
type: SIGNAL_MAP;
|
||||||
payload?: unknown;
|
payload?: unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export enum SIGNAL_MAP {
|
||||||
|
SIGINT = 2,
|
||||||
|
SIGTERM = 3,
|
||||||
|
SIGKILL = 9,
|
||||||
|
INPUT = 10,
|
||||||
|
}
|
||||||
|
|||||||
@@ -38,6 +38,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,
|
||||||
|
|||||||
@@ -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,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,30 @@
|
|||||||
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
import type { NodeNotFoundError, NotADirectoryError } from "../filesystem/errors";
|
||||||
import type { FileSystem } from "../filesystem/filesystem";
|
|
||||||
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
import { TreeNodeType, type DirectoryNode, type TreeNode } from "../filesystem/treenode";
|
||||||
|
|
||||||
export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
export function resolvePath(state: ShellState, path: string): number {
|
||||||
|
const session = getCurrentSession(state);
|
||||||
const isAbsolute = path.startsWith("/");
|
const isAbsolute = path.startsWith("/");
|
||||||
|
|
||||||
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
const normalizedPath: string = path.replace(/^\/+|\/+$/g, "");
|
||||||
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
const pathComponents: string[] = normalizedPath.split("/").filter(name => name.length > 0);
|
||||||
|
|
||||||
if (pathComponents.length === 0 && isAbsolute) return 0;
|
if (pathComponents.length === 0 && isAbsolute) return 0;
|
||||||
if (pathComponents.length === 0) return cwd;
|
if (pathComponents.length === 0) return session.cwd;
|
||||||
|
|
||||||
let currentNode = isAbsolute ? fs.getRoot() : (fs.getNode(cwd) as DirectoryNode);
|
let currentNode = isAbsolute
|
||||||
if (!currentNode) {
|
? state.filesystem.getRoot()
|
||||||
throw {
|
: (state.filesystem.getNode(session.cwd) as DirectoryNode);
|
||||||
type: "NodeNotFound",
|
|
||||||
message: `CWD node under inode ${cwd} not found`,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
inode: cwd,
|
|
||||||
} satisfies NodeNotFoundError;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const name of pathComponents) {
|
if (!currentNode) return -1;
|
||||||
|
|
||||||
|
for (let i = 0; i < pathComponents.length; i++) {
|
||||||
|
const name = pathComponents[i]!;
|
||||||
if (name === ".") continue;
|
if (name === ".") continue;
|
||||||
|
|
||||||
if (name === "..") {
|
if (name === "..") {
|
||||||
currentNode = fs.getNode(currentNode.parent) as DirectoryNode;
|
currentNode = state.filesystem.getNode(currentNode.parent) as DirectoryNode;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,7 +37,7 @@ export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
|||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
inode: currentNode.inode,
|
inode: currentNode.inode,
|
||||||
} satisfies NodeNotFoundError;
|
} satisfies NodeNotFoundError;
|
||||||
if (fs.isFile(inode))
|
if (state.filesystem.isFile(inode) && !(i === pathComponents.length - 1))
|
||||||
throw {
|
throw {
|
||||||
type: "NotADirectory",
|
type: "NotADirectory",
|
||||||
message: `Child node ${name} is not a directory`,
|
message: `Child node ${name} is not a directory`,
|
||||||
@@ -47,27 +46,66 @@ export function resolvePath(fs: FileSystem, cwd: number, path: string): number {
|
|||||||
nodeType: TreeNodeType.File,
|
nodeType: TreeNodeType.File,
|
||||||
} satisfies NotADirectoryError;
|
} satisfies NotADirectoryError;
|
||||||
|
|
||||||
currentNode = fs.getNode(inode) as DirectoryNode;
|
currentNode = state.filesystem.getNode(inode) as DirectoryNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentNode.inode;
|
return currentNode.inode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveInode(fs: FileSystem, inode: number): string {
|
export function resolveInode(state: ShellState, inode: number): string {
|
||||||
const node = fs.getNode(inode);
|
const node = state.filesystem.getNode(inode);
|
||||||
const components: string[] = [];
|
const components: string[] = [];
|
||||||
|
|
||||||
if (node === undefined) return "";
|
if (node === undefined) return "";
|
||||||
|
|
||||||
let currentInode = inode;
|
let currentInode = inode;
|
||||||
while (currentInode !== 0) {
|
while (currentInode !== 0) {
|
||||||
const node = fs.getNode(currentInode) as TreeNode;
|
const node = state.filesystem.getNode(currentInode) as TreeNode;
|
||||||
if (!node) break;
|
if (!node) break;
|
||||||
|
|
||||||
components.push(node.name);
|
components.push(node.name);
|
||||||
currentInode = node.parent;
|
currentInode = node.parent;
|
||||||
}
|
}
|
||||||
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 resolveInodeToHome(state: ShellState, inode: number): string {
|
||||||
|
const home = resolveInode(state, getCurrentSession(state).user.home);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
|
if (result.startsWith(home)) {
|
||||||
|
result = `~${result.slice(home.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveInodeToCwd(state: ShellState, inode: number): string {
|
||||||
|
const cwd = resolveInode(state, getCurrentSession(state).cwd);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
|
if (result.startsWith(cwd)) {
|
||||||
|
result = `.${result.slice(cwd.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveInodeRelative(state: ShellState, inode: number, relative: number): string {
|
||||||
|
const rel = resolveInode(state, relative);
|
||||||
|
let result = resolveInode(state, inode);
|
||||||
|
|
||||||
|
if (result.startsWith(rel)) {
|
||||||
|
result = `.${result.slice(rel.length)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import type { FileNode, TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import { Posix } from "@termos/util/posix";
|
||||||
|
|
||||||
|
export enum SortTreeNodeBy {
|
||||||
|
NAME = "name",
|
||||||
|
INODE = "inode",
|
||||||
|
SIZE = "size",
|
||||||
|
EXTENSION = "extension",
|
||||||
|
TYPE = "type",
|
||||||
|
MTIME = "mtime",
|
||||||
|
ATIME = "atime",
|
||||||
|
CTIME = "ctime",
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortTreeNodes<T extends TreeNode | number>(
|
||||||
|
state: ShellState,
|
||||||
|
arr: T[],
|
||||||
|
r: boolean = false,
|
||||||
|
by: SortTreeNodeBy = SortTreeNodeBy.NAME,
|
||||||
|
): T[] {
|
||||||
|
if (arr.length === 0) return [];
|
||||||
|
|
||||||
|
const nodes: TreeNode[] = [];
|
||||||
|
|
||||||
|
if (typeof arr[0] === "number") {
|
||||||
|
for (const e of arr as number[]) {
|
||||||
|
const node = state.filesystem.getNode(e);
|
||||||
|
if (!node) continue;
|
||||||
|
|
||||||
|
nodes.push(node);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
nodes.push(...(arr as TreeNode[]));
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeQS(nodes, r, by, 0, nodes.length - 1);
|
||||||
|
|
||||||
|
if (typeof arr[0] === "number") {
|
||||||
|
return nodes.map(n => n.inode) as T[];
|
||||||
|
} else {
|
||||||
|
return nodes as T[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function nodeQS(arr: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): void {
|
||||||
|
if (end <= start) return;
|
||||||
|
|
||||||
|
const pivot = partitionNodeArray(arr, r, by, start, end);
|
||||||
|
nodeQS(arr, r, by, start, pivot - 1);
|
||||||
|
nodeQS(arr, r, by, pivot + 1, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
function partitionNodeArray(part: TreeNode[], r: boolean, by: SortTreeNodeBy, start: number, end: number): number {
|
||||||
|
const pivot = part[end];
|
||||||
|
let i = start - 1;
|
||||||
|
|
||||||
|
for (let j = start; j <= end; j++) {
|
||||||
|
if (compareTreeNode(part[j]!, pivot!, by, r) < 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 compareTreeNode(a: TreeNode, b: TreeNode, by: SortTreeNodeBy, r: boolean): number {
|
||||||
|
switch (by) {
|
||||||
|
case SortTreeNodeBy.NAME: {
|
||||||
|
const A: string = a.name.startsWith(".") ? a.name.slice(1) : a.name;
|
||||||
|
const B: string = b.name.startsWith(".") ? b.name.slice(1) : 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 SortTreeNodeBy.MTIME:
|
||||||
|
case SortTreeNodeBy.ATIME:
|
||||||
|
case SortTreeNodeBy.CTIME: {
|
||||||
|
const A: number = a[by];
|
||||||
|
const B: number = b[by];
|
||||||
|
|
||||||
|
return r ? A - B : B - A;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortTreeNodeBy.SIZE: {
|
||||||
|
const A: number = (a as FileNode).content.byteSize();
|
||||||
|
const B: number = (b as FileNode).content.byteSize();
|
||||||
|
|
||||||
|
return r ? A - B : B - A;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortTreeNodeBy.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 SortTreeNodeBy.INODE: {
|
||||||
|
return r ? a.inode - b.inode : b.inode - a.inode;
|
||||||
|
}
|
||||||
|
|
||||||
|
case SortTreeNodeBy.TYPE: {
|
||||||
|
return r ? b.type - a.type : a.type - b.type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,8 +14,9 @@ export function dnTraverseTree(fs: FileSystem, root: number): number[] {
|
|||||||
result.push(node.inode);
|
result.push(node.inode);
|
||||||
|
|
||||||
if (node.type === TreeNodeType.Directory) {
|
if (node.type === TreeNodeType.Directory) {
|
||||||
for (const value of Object.values(node.children)) {
|
const children = Object.values(node.children);
|
||||||
stack.push(value);
|
for (let i = children.length - 1; i >= 0; i--) {
|
||||||
|
stack.push(children[i] as number);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-5
@@ -1,15 +1,85 @@
|
|||||||
import { defaultConfig, TermosConfig } from "./config";
|
/* import { defaultConfig, TermosConfig } from "./config";
|
||||||
|
|
||||||
let config: TermosConfig = { ...defaultConfig };
|
let config: TermosConfig = { ...defaultConfig };
|
||||||
|
|
||||||
namespace Termos {
|
namespace Termos {
|
||||||
export function init(config: Partial<TermosConfig>) {
|
export function init(config: Partial<TermosConfig>) {
|
||||||
config = { ...defaultConfig, ...config};
|
config = { ...defaultConfig, ...config };
|
||||||
console.log("termos initialized");
|
console.log("termos initialized");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
const message: string = "Hello, World!";
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
console.log(message);
|
import type { TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import { getCurrentSession, type GroupInfo, type UserInfo } from "@core/session_manager";
|
||||||
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
|
import { resolveInodeToHome } from "@core/util/path_resolver";
|
||||||
|
import { deserializeFileSystem } from "@shell/serializer";
|
||||||
|
import { Shell } from "@shell/shell";
|
||||||
|
import { printTree } from "./util/tree_visualizer";
|
||||||
|
|
||||||
export { Termos };
|
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"}`;
|
||||||
|
const base = deserializeFileSystem(rawJson);
|
||||||
|
|
||||||
|
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
||||||
|
|
||||||
|
const fs = FileSystem.init(base, overlay, base.size - 1);
|
||||||
|
|
||||||
|
console.log(printTree(fs, 0));
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const groups: Map<number, GroupInfo> = new Map();
|
||||||
|
const user: UserInfo = {
|
||||||
|
username: "root",
|
||||||
|
uid: 1000,
|
||||||
|
gid: 1000, // <- PRIMARY GID
|
||||||
|
group: [1000], // <- GROUPS ARRAY
|
||||||
|
home: 3,
|
||||||
|
};
|
||||||
|
const group: GroupInfo = {
|
||||||
|
groupname: "root",
|
||||||
|
gid: 1000,
|
||||||
|
members: [1000], // <- UID
|
||||||
|
};
|
||||||
|
users.set(1000, user);
|
||||||
|
groups.set(1000, group);
|
||||||
|
|
||||||
|
const state: ShellState = createInitialShellState(fs, users, groups, user);
|
||||||
|
await Shell.init(state);
|
||||||
|
|
||||||
|
//console.log(resolveInode(Shell.Instance?.State!, 6));
|
||||||
|
//console.log(resolveInode(Shell.Instance?.State!, 6, true));
|
||||||
|
|
||||||
|
//console.log(sortTreeNodes(Shell.Instance?.State!, dnTraverseTree(Shell.Instance?.State.filesystem!, 0)));
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
const decoded = new TextDecoder().decode(payload.result.stdout.toArray());
|
||||||
|
process.stdout.write(decoded + "\n");
|
||||||
|
process.stdout.write(resolveInodeToHome(payload.state, getCurrentSession(payload.state).cwd) + "\n> ");
|
||||||
|
});
|
||||||
|
|
||||||
|
/*
|
||||||
|
Cant do it like this because commands also use the stdout event right before returning a result so e.g. echo will print twice
|
||||||
|
|
||||||
|
Need to use this only if a continuous process is running
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Shell.Instance?.on("stdout", payload => {
|
||||||
|
const decoded = new TextDecoder().decode(payload.data);
|
||||||
|
process.stdout.write(decoded + "\n");
|
||||||
|
}); */
|
||||||
|
|
||||||
|
//console.clear();
|
||||||
|
process.stdout.write(resolveInodeToHome(state, getCurrentSession(state).cwd) + "\n> ");
|
||||||
|
process.stdin.on("data", async data => {
|
||||||
|
if (Shell.Instance?.BoundPID !== null) {
|
||||||
|
Shell.Instance?.sendInput(data.toString().trim());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = data.toString().trim();
|
||||||
|
await Shell.Instance?.execute(input);
|
||||||
|
});
|
||||||
|
|
||||||
|
//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]) {
|
||||||
|
|||||||
+99
-95
@@ -2,110 +2,85 @@ import type { CommandDescriptor } from "@core/command";
|
|||||||
import type { CommandIO } from "@core/command_io";
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result";
|
||||||
import type { ShellState } from "@core/shell_state";
|
import type { ShellState } from "@core/shell_state";
|
||||||
import type { Signal } from "@core/signal";
|
import { SIGNAL_MAP, type Signal } from "@core/signal";
|
||||||
import type { ShellError, SignalTerminationError } from "@core/util/errors";
|
import type { ShellError, SignalTerminationError } from "@core/util/errors";
|
||||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||||
|
import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat";
|
||||||
import { EventEmitter } from "./event_emitter";
|
import { EventEmitter } from "./event_emitter";
|
||||||
import type { ShellEventMap } from "./shell";
|
import type { ShellEventMap } from "./shell";
|
||||||
|
|
||||||
export class Process {
|
export class Process {
|
||||||
private signalQueue: Signal[] = [];
|
private _SignalQueue: Signal[] = [];
|
||||||
private signalHandler: ((signal: Signal) => void) | null = null;
|
private _SignalHandler: ((signal: Signal) => void) | null = null;
|
||||||
private stdoutChunks: Uint8Array[] = [];
|
private _StdoutChunks: Uint8Array[] = [];
|
||||||
private stderrChunks: Uint8Array[] = [];
|
private _StderrChunks: Uint8Array[] = [];
|
||||||
private settled: boolean = false;
|
private _Settled: boolean = false;
|
||||||
private readonly maxChunkByteSize: number;
|
private _EventEmitter: EventEmitter<ShellEventMap>;
|
||||||
|
private readonly _MaxChunkByteSize: number;
|
||||||
|
|
||||||
readonly pid: number;
|
readonly PID: number;
|
||||||
readonly commandDescriptor: CommandDescriptor;
|
readonly Name: string;
|
||||||
readonly state: ShellState;
|
readonly CommandDescriptor: CommandDescriptor;
|
||||||
readonly args: string[];
|
readonly State: ShellState;
|
||||||
readonly flags: string[];
|
readonly Args: string[];
|
||||||
events: EventEmitter<ShellEventMap>;
|
readonly Flags: string[];
|
||||||
|
|
||||||
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
|
constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) {
|
||||||
this.pid = pid;
|
this.PID = pid;
|
||||||
this.state = state;
|
this.State = state;
|
||||||
this.commandDescriptor = descriptor;
|
this.Name = descriptor.name;
|
||||||
this.flags = flags;
|
this.CommandDescriptor = descriptor;
|
||||||
this.args = args;
|
this.Flags = flags;
|
||||||
|
this.Args = args;
|
||||||
// Check if positive later and throw an error if so
|
// Check if positive later and throw an error if so
|
||||||
this.maxChunkByteSize = 1024;
|
this._MaxChunkByteSize = 1024;
|
||||||
this.events = new EventEmitter<ShellEventMap>();
|
this._EventEmitter = new EventEmitter<ShellEventMap>();
|
||||||
}
|
|
||||||
|
|
||||||
private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
|
|
||||||
const size = arrays.reduce((sum, arr) => sum + arr.length, 0);
|
|
||||||
const result = new Uint8Array(size);
|
|
||||||
|
|
||||||
let offset = 0;
|
|
||||||
for (const arr of arrays) {
|
|
||||||
result.set(arr, offset);
|
|
||||||
offset += arr.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tested
|
|
||||||
private divideToChunks(data: Uint8Array): Uint8Array[] {
|
|
||||||
const nChunks: number = Math.ceil(data.length / this.maxChunkByteSize);
|
|
||||||
const chunks: Uint8Array[] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < nChunks; i++) {
|
|
||||||
const start = this.maxChunkByteSize * i;
|
|
||||||
const end = this.maxChunkByteSize * (i + 1);
|
|
||||||
|
|
||||||
chunks.push(data.subarray(start, end));
|
|
||||||
}
|
|
||||||
|
|
||||||
return chunks;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
private writeToOutput(chunks: Uint8Array[], eventType: "stdout" | "stderr", data: Uint8Array): void {
|
||||||
if (this.settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
if (data.length <= this.maxChunkByteSize) {
|
if (data.length <= this._MaxChunkByteSize) {
|
||||||
chunks.push(data);
|
chunks.push(data);
|
||||||
this.events.emit(eventType, { pid: this.pid, data });
|
this._EventEmitter.emit(eventType, { pid: this.PID, data });
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
const arr = this.divideToChunks(data);
|
const arr = splitUint8Array(data, this._MaxChunkByteSize);
|
||||||
for (const ent of arr) {
|
for (const ent of arr) {
|
||||||
chunks.push(ent);
|
chunks.push(ent);
|
||||||
this.events.emit(eventType, { pid: this.pid, data: ent });
|
this._EventEmitter.emit(eventType, { pid: this.PID, data: ent });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
public execute(): void {
|
||||||
const io: CommandIO = {
|
const io: CommandIO = {
|
||||||
writeStdout: (data: Uint8Array) => this.writeToOutput(this.stdoutChunks, "stdout", data),
|
writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data),
|
||||||
writeStderr: (data: Uint8Array) => this.writeToOutput(this.stderrChunks, "stderr", data),
|
writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data),
|
||||||
getSignal: () => {
|
getSignal: () => {
|
||||||
const signal: Signal | undefined = this.signalQueue.shift();
|
const signal: Signal | undefined = this._SignalQueue.shift();
|
||||||
if (signal !== undefined) return Promise.resolve(signal);
|
if (signal !== undefined) return Promise.resolve(signal);
|
||||||
|
|
||||||
const promise = new Promise<Signal>(resolve => {
|
const promise = new Promise<Signal>(resolve => {
|
||||||
this.signalHandler = resolve;
|
this._SignalHandler = resolve;
|
||||||
});
|
});
|
||||||
return promise;
|
return promise;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const promise = this.commandDescriptor.fn(io, this.state, this.flags, this.args);
|
const promise = this.CommandDescriptor.fn(io, this.State, this.Flags, this.Args);
|
||||||
|
|
||||||
promise
|
promise
|
||||||
.then(output => {
|
.then(output => {
|
||||||
if (this.settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
let result: ResultSuccess | ResultError<ShellError>;
|
let result: ResultSuccess | ResultError<ShellError>;
|
||||||
const stdout: Uint8Array = this.concatUint8Arrays(this.stdoutChunks);
|
const stdout: Uint8Array = concatUint8Arrays(this._StdoutChunks);
|
||||||
const stderr: Uint8Array = this.concatUint8Arrays(this.stderrChunks);
|
const stderr: Uint8Array = concatUint8Arrays(this._StderrChunks);
|
||||||
|
|
||||||
if (output.result.type === "success") {
|
if (output.result.type === "success") {
|
||||||
result = createSuccessResult(
|
result = createSuccessResult(
|
||||||
this.commandDescriptor.name,
|
this.CommandDescriptor.name,
|
||||||
0,
|
0,
|
||||||
createImmutableBuffer(stdout),
|
createImmutableBuffer(stdout),
|
||||||
createImmutableBuffer(stderr),
|
createImmutableBuffer(stderr),
|
||||||
@@ -118,57 +93,86 @@ export class Process {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
this.events.emit("result", { pid: this.pid, result, state: output.state });
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state });
|
||||||
this.settled = true;
|
this._Settled = true;
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
if (this.settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
const result: ResultError<ShellError> = createErrorResult(
|
const result: ResultError<ShellError> = createErrorResult(
|
||||||
"GenericError",
|
"GenericError",
|
||||||
"Promised output from command function rejected",
|
"Promised output from command function rejected",
|
||||||
{},
|
{},
|
||||||
createImmutableBuffer(new Uint8Array()),
|
this.CommandDescriptor.name,
|
||||||
createImmutableBuffer(new Uint8Array()),
|
undefined,
|
||||||
this.commandDescriptor.name,
|
undefined,
|
||||||
{
|
{
|
||||||
name: "Caught error",
|
name: "Caught error",
|
||||||
message: String(error),
|
message: String(error),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
this.events.emit("result", { pid: this.pid, result, state: this.state });
|
this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
sendSignal(signal: Signal): void {
|
public sendSignal(signal: Signal): void {
|
||||||
if (this.settled) return;
|
if (this._Settled) return;
|
||||||
|
|
||||||
if (signal.type === "SIGKILL") {
|
const result: ResultError<SignalTerminationError> = createErrorResult(
|
||||||
if (this.signalHandler !== null) {
|
"SignalTermination",
|
||||||
this.signalHandler(signal);
|
`Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`,
|
||||||
this.signalHandler = null;
|
{ signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] },
|
||||||
}
|
this.CommandDescriptor.name,
|
||||||
|
);
|
||||||
|
|
||||||
this.settled = true;
|
switch (signal.type) {
|
||||||
const result: ResultError<SignalTerminationError> = createErrorResult(
|
case SIGNAL_MAP.SIGKILL:
|
||||||
"SignalTermination",
|
this._SignalHandler = null;
|
||||||
`Process ${this.pid} killed by signal sigkill`,
|
this._Settled = true;
|
||||||
{ signalNumber: 9, signalName: signal.type },
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
this.commandDescriptor.name,
|
|
||||||
);
|
|
||||||
|
|
||||||
this.events.emit("result", { pid: this.pid, result, state: this.state });
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
return;
|
return;
|
||||||
} else {
|
|
||||||
if (this.signalHandler !== null) {
|
case SIGNAL_MAP.SIGTERM:
|
||||||
this.signalHandler(signal);
|
if (this._SignalHandler !== null) {
|
||||||
this.signalHandler = null;
|
this._SignalHandler(signal);
|
||||||
} else {
|
this._SignalHandler = null;
|
||||||
this.signalQueue.push(signal);
|
}
|
||||||
}
|
|
||||||
|
this._Settled = true;
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
|
|
||||||
|
return;
|
||||||
|
case SIGNAL_MAP.SIGINT:
|
||||||
|
if (this._SignalHandler !== null) {
|
||||||
|
this._SignalHandler(signal);
|
||||||
|
this._SignalHandler = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._Settled = true;
|
||||||
|
|
||||||
|
this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State });
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
if (this._SignalHandler !== null) {
|
||||||
|
this._SignalHandler(signal);
|
||||||
|
this._SignalHandler = null;
|
||||||
|
} else {
|
||||||
|
this._SignalQueue.push(signal);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,68 @@
|
|||||||
|
import type { CommandDescriptor } from "@core/command";
|
||||||
|
import type { ShellState } from "@core/shell_state";
|
||||||
|
import type { Signal } from "@core/signal";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { Process } from "./process";
|
||||||
|
import type { ShellEventMap } 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, flags: string[], args: string[]): number {
|
||||||
|
const pid = ++this._PIDIndex;
|
||||||
|
const process = new Process(pid, state, descriptor, flags, args);
|
||||||
|
this._Processes.set(pid, process);
|
||||||
|
|
||||||
|
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): 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 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({ type: "SIGKILL" } satisfies Signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,12 +27,15 @@ const DirectoryNodeSchema = z.object({
|
|||||||
ctime: z.number(),
|
ctime: z.number(),
|
||||||
atime: z.number(),
|
atime: z.number(),
|
||||||
type: z.literal("directory"),
|
type: z.literal("directory"),
|
||||||
children: z.array(z.lazy((): any => TreeNodeSchema)),
|
//eslint-ignore
|
||||||
|
children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
});
|
});
|
||||||
|
|
||||||
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
|
const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]);
|
||||||
|
|
||||||
export function serializeFileSystem() {}
|
/* export function serializeFileSystem(map: ReadonlyMap<number, TreeNode | null>): string {
|
||||||
|
|
||||||
|
} */
|
||||||
|
|
||||||
export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNode> {
|
export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNode> {
|
||||||
const raw = JSON.parse(json);
|
const raw = JSON.parse(json);
|
||||||
@@ -40,7 +43,8 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
|
|||||||
|
|
||||||
const map = new Map<number, TreeNode>();
|
const map = new Map<number, TreeNode>();
|
||||||
|
|
||||||
function parseNode(tree: any, parent: number): void {
|
// prettier-ignore
|
||||||
|
function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
if (tree.type === "directory") {
|
if (tree.type === "directory") {
|
||||||
const children: Record<string, number> = {};
|
const children: Record<string, number> = {};
|
||||||
|
|
||||||
@@ -75,7 +79,7 @@ export function deserializeFileSystem(json: string): ReadonlyMap<number, TreeNod
|
|||||||
mtime: tree.mtime,
|
mtime: tree.mtime,
|
||||||
ctime: tree.ctime,
|
ctime: tree.ctime,
|
||||||
atime: tree.atime,
|
atime: tree.atime,
|
||||||
content: createImmutableBuffer(new Uint8Array()),
|
content: createImmutableBuffer(Uint8Array.from(tree.content)),
|
||||||
};
|
};
|
||||||
map.set(tree.inode, Object.freeze(fileNode));
|
map.set(tree.inode, Object.freeze(fileNode));
|
||||||
}
|
}
|
||||||
|
|||||||
+97
-52
@@ -1,110 +1,155 @@
|
|||||||
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 } 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 { SIGNAL_MAP } from "@core/signal";
|
||||||
|
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 { parseCommand } from "@core/util/parser";
|
||||||
|
import { EventEmitter } from "./event_emitter";
|
||||||
|
import { ProcessManager } from "./process_manager";
|
||||||
|
|
||||||
export class Shell {
|
export class Shell {
|
||||||
static #instance: Shell;
|
static #Instance: Shell;
|
||||||
static #promise: Promise<Shell> | null = null;
|
static #Promise: Promise<Shell> | null = null;
|
||||||
private _state: Readonly<ShellState>;
|
private _State: Readonly<ShellState>;
|
||||||
|
private _ProcessManager: ProcessManager = new ProcessManager();
|
||||||
|
private _EventEmitter: EventEmitter<ShellEventMap> = new EventEmitter();
|
||||||
|
private _GlobalKeyMap: ReadonlyMap<string, SIGNAL_MAP>;
|
||||||
|
|
||||||
|
public BoundPID: number | null = null;
|
||||||
|
|
||||||
private constructor(state: ShellState) {
|
private constructor(state: ShellState) {
|
||||||
this._state = Object.freeze(state);
|
this._State = Object.freeze(state);
|
||||||
|
|
||||||
|
//Temporary solution for sigint keybind
|
||||||
|
const map = new Map();
|
||||||
|
map.set("ctrl+c", SIGNAL_MAP.SIGINT);
|
||||||
|
|
||||||
|
this._GlobalKeyMap = map;
|
||||||
|
|
||||||
|
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._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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
static async init(initialState: ShellState): Promise<Shell> {
|
static async init(initialState: ShellState): Promise<Shell> {
|
||||||
if (Shell.#instance) {
|
if (Shell.#Instance) {
|
||||||
console.warn("Shell already initialized");
|
console.warn("Shell already initialized");
|
||||||
return this.#instance;
|
return this.#Instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Shell.#promise) return Shell.#promise;
|
if (Shell.#Promise) return Shell.#Promise;
|
||||||
|
|
||||||
Shell.#promise = (async () => {
|
Shell.#Promise = (async () => {
|
||||||
try {
|
try {
|
||||||
Shell.#instance = new Shell(initialState);
|
Shell.#Instance = new Shell(initialState);
|
||||||
return Shell.#instance;
|
return Shell.#Instance;
|
||||||
} finally {
|
} finally {
|
||||||
Shell.#promise = null;
|
Shell.#Promise = null;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
return Shell.#promise;
|
return Shell.#Promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Execute(input: string): Promise<Result<ShellError>> {
|
public async execute(input: string): Promise<void> {
|
||||||
let parsed;
|
let parsed;
|
||||||
try {
|
try {
|
||||||
parsed = parseCommand(input);
|
parsed = parseCommand(input);
|
||||||
} catch {
|
} catch {
|
||||||
return createErrorResult(
|
const result = createErrorResult("ParseError", `Parsing error - ${input}`, {});
|
||||||
"ParseError",
|
|
||||||
`Parsing error - ${input}`,
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
{},
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
createImmutableBuffer(new Uint8Array()),
|
return;
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
"",
|
|
||||||
) satisfies ResultError<ParseError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parsed.command === "") {
|
if (parsed.command === "") return;
|
||||||
return createSuccessResult(
|
|
||||||
"",
|
|
||||||
0,
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._state = withHistory(this._state, input);
|
this._State = withHistory(this._State, input);
|
||||||
const command = COMMAND_REGISTRY.get(parsed.command);
|
const command = COMMAND_REGISTRY.get(parsed.command);
|
||||||
|
|
||||||
if (!command)
|
if (!command) {
|
||||||
return createErrorResult(
|
const encoded = new TextEncoder().encode(`Command ${parsed.command} not found`);
|
||||||
|
|
||||||
|
const result = createErrorResult(
|
||||||
"CommandNotFound",
|
"CommandNotFound",
|
||||||
`Command ${parsed.command} not found`,
|
`Command ${parsed.command} not found`,
|
||||||
{ command: parsed.command },
|
{ command: parsed.command },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
parsed.command,
|
parsed.command,
|
||||||
) satisfies ResultError<CommandNotFoundError>;
|
createImmutableBuffer(encoded),
|
||||||
|
createImmutableBuffer(new Uint8Array()),
|
||||||
|
);
|
||||||
|
|
||||||
if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) {
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
return createErrorResult(
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) {
|
||||||
|
const result = createErrorResult(
|
||||||
"PermissionDenied",
|
"PermissionDenied",
|
||||||
`Permission Denied`,
|
`Permission Denied`,
|
||||||
{ resource: `Execution of the ${command.name} command` },
|
{ resource: `Execution of the ${command.name} command` },
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
createImmutableBuffer(new Uint8Array()),
|
|
||||||
parsed.command,
|
parsed.command,
|
||||||
) satisfies ResultError<PermissionDeniedError>;
|
);
|
||||||
|
|
||||||
|
this._State = withExitCode(this._State, result.error.exitCode);
|
||||||
|
this._EventEmitter.emit("result", { pid: 0, result, state: this._State });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const out = command.fn(this._state, parsed.flags, parsed.args);
|
const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args);
|
||||||
this._state = out.state;
|
this.BoundPID = pid;
|
||||||
|
}
|
||||||
|
|
||||||
if (out.result.type === "error") {
|
public sendInput(input: string): void {
|
||||||
this._state = withExitCode(this._state, out.result.error.exitCode);
|
const signal = this._GlobalKeyMap.get(input);
|
||||||
|
|
||||||
|
if (signal !== undefined) {
|
||||||
|
if (this.BoundPID !== null) {
|
||||||
|
this._ProcessManager.sendSignal(this.BoundPID, { type: signal });
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
this._state = withExitCode(this._state, out.result.exitCode);
|
if (this.BoundPID !== null) {
|
||||||
|
this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return out.result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public get State(): Readonly<ShellState> {
|
public get State(): Readonly<ShellState> {
|
||||||
return this._state;
|
return this._State;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static get Instance(): Shell | undefined {
|
public static get Instance(): Shell | undefined {
|
||||||
if (!Shell.#instance) {
|
if (!Shell.#Instance) {
|
||||||
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return Shell.#instance;
|
return Shell.#Instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { MD5 } from "./hash";
|
/* import { MD5 } from "./hash";
|
||||||
|
|
||||||
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
||||||
|
|
||||||
@@ -71,3 +71,4 @@ function isChecksumMatching(json: string, checksum: string): boolean {
|
|||||||
const resourceChksm = MD5.hash(json);
|
const resourceChksm = MD5.hash(json);
|
||||||
return resourceChksm === checksum;
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ export function printTree(fs: FileSystem, root: number): string {
|
|||||||
|
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
|
||||||
lines.push(rootNode.name);
|
lines.push(rootNode.name + ` (${rootNode.inode})`);
|
||||||
|
|
||||||
type Frame = {
|
type Frame = {
|
||||||
inode: number;
|
inode: number;
|
||||||
@@ -42,7 +42,7 @@ export function printTree(fs: FileSystem, root: number): string {
|
|||||||
|
|
||||||
const name = node.name;
|
const name = node.name;
|
||||||
const connector = frame.isLast ? "└── " : "├── ";
|
const connector = frame.isLast ? "└── " : "├── ";
|
||||||
lines.push(frame.prefix + connector + name);
|
lines.push(frame.prefix + connector + name + ` (${node.inode})`);
|
||||||
|
|
||||||
if (node.type === TreeNodeType.Directory) {
|
if (node.type === TreeNodeType.Directory) {
|
||||||
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
|
const childPrefix = frame.prefix + (frame.isLast ? " " : "│ ");
|
||||||
|
|||||||
@@ -1,48 +1,27 @@
|
|||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { descriptor as cd } from "@core/commands/cd";
|
import { descriptor as cd } from "@core/commands/cd";
|
||||||
import type { ResultError, ResultSuccess } from "@core/result";
|
import type { ResultError, ResultSuccess } from "@core/result";
|
||||||
import type { UserInfo } from "@core/session_manager";
|
import type { UserInfo } from "@core/session_manager";
|
||||||
import { getCurrentSession } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { createInitialShellState, withCwd, type ShellState } from "@core/shell_state";
|
import { withCwd, type ShellState } from "@core/shell_state";
|
||||||
import type { PathResolutionError } from "@core/util/errors";
|
import type { PathResolutionError } from "@core/util/errors";
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
import { expect, test } from "vitest";
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
const stdout: Uint8Array[] = [];
|
||||||
inode: 0,
|
const stderr: Uint8Array[] = [];
|
||||||
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 io: CommandIO = {
|
||||||
|
writeStdout: (data: Uint8Array) => {
|
||||||
|
stdout.push(data);
|
||||||
|
},
|
||||||
|
writeStderr: (data: Uint8Array) => {
|
||||||
|
stderr.push(data);
|
||||||
|
},
|
||||||
|
getSignal: () => {
|
||||||
|
return new Promise(() => {});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
const users: Map<number, UserInfo> = new Map();
|
||||||
const user: UserInfo = {
|
const user: UserInfo = {
|
||||||
@@ -54,11 +33,23 @@ const user: UserInfo = {
|
|||||||
};
|
};
|
||||||
users.set(0, user);
|
users.set(0, user);
|
||||||
|
|
||||||
const state: ShellState = createInitialShellState(fs, users, user);
|
const state: ShellState = Fixture.State;
|
||||||
|
|
||||||
test("changes cwd to home", () => {
|
test("changes cwd to home", async () => {
|
||||||
let newState = withCwd(state, 2);
|
let newState = withCwd(state, 2);
|
||||||
const output = cd.fn(newState, [], []);
|
const output = await cd.fn(io, newState, [], []);
|
||||||
|
newState = output.state;
|
||||||
|
const result = output.result;
|
||||||
|
const session = getCurrentSession(newState);
|
||||||
|
|
||||||
|
expect((result as ResultSuccess).exitCode).toBe(0);
|
||||||
|
expect(session.cwd).toBe(Fixture.user.home);
|
||||||
|
expect(session.pwd).toBe(2);
|
||||||
|
});
|
||||||
|
test("changes cwd to pwd", async () => {
|
||||||
|
let newState = withCwd(state, 2);
|
||||||
|
|
||||||
|
const output = await cd.fn(io, newState, [], ["-"]);
|
||||||
newState = output.state;
|
newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -67,20 +58,8 @@ test("changes cwd to home", () => {
|
|||||||
expect(session.cwd).toBe(0);
|
expect(session.cwd).toBe(0);
|
||||||
expect(session.pwd).toBe(2);
|
expect(session.pwd).toBe(2);
|
||||||
});
|
});
|
||||||
test("changes cwd to pwd", () => {
|
test("changes cwd to 4", async () => {
|
||||||
let newState = withCwd(state, 2);
|
const output = await cd.fn(io, state, [], ["/folder2/subdir2"]);
|
||||||
|
|
||||||
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 newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -90,8 +69,8 @@ test("changes cwd to 4", () => {
|
|||||||
expect(session.pwd).toBe(0);
|
expect(session.pwd).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an error result (tried to enter a non existent location)", () => {
|
test("returns an error result (tried to enter a non existent location)", async () => {
|
||||||
const output = cd.fn(state, [], ["/not/real"]);
|
const output = await cd.fn(io, state, [], ["/not/real"]);
|
||||||
const newState = output.state;
|
const newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
@@ -101,8 +80,8 @@ test("returns an error result (tried to enter a non existent location)", () => {
|
|||||||
expect(session.pwd).toBe(0);
|
expect(session.pwd).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an error result (tried to enter a file)", () => {
|
test("returns an error result (tried to enter a file)", async () => {
|
||||||
const output = cd.fn(state, [], ["/hello.txt"]);
|
const output = await cd.fn(io, state, [], ["/some-file"]);
|
||||||
const newState = output.state;
|
const newState = output.state;
|
||||||
const result = output.result;
|
const result = output.result;
|
||||||
const session = getCurrentSession(newState);
|
const session = getCurrentSession(newState);
|
||||||
|
|||||||
@@ -1,64 +1,33 @@
|
|||||||
|
import type { CommandIO } from "@core/command_io";
|
||||||
import { descriptor as echo } from "@core/commands/echo";
|
import { descriptor as echo } from "@core/commands/echo";
|
||||||
import type { ResultSuccess } from "@core/result";
|
import type { ResultSuccess } from "@core/result";
|
||||||
import type { UserInfo } from "@core/session_manager";
|
import { type ShellState } from "@core/shell_state";
|
||||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { expect, test } from "vitest";
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
const stdout: Uint8Array[] = [];
|
||||||
inode: 0,
|
const stderr: Uint8Array[] = [];
|
||||||
name: "root",
|
|
||||||
type: "Dir",
|
const io: CommandIO = {
|
||||||
children: [
|
writeStdout: (data: Uint8Array) => {
|
||||||
{
|
stdout.push(data);
|
||||||
inode: 1,
|
},
|
||||||
name: "hello.txt",
|
writeStderr: (data: Uint8Array) => {
|
||||||
type: "File",
|
stderr.push(data);
|
||||||
content: "Goodbye World!",
|
},
|
||||||
children: [],
|
getSignal: () => {
|
||||||
},
|
return new Promise(() => {});
|
||||||
{
|
},
|
||||||
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 state: ShellState = Fixture.State;
|
||||||
|
|
||||||
const users: Map<number, UserInfo> = new Map();
|
test("returns a Result of type success", async () => {
|
||||||
const user: UserInfo = {
|
const output = await echo.fn(io, state, [], ["hello", "world"]);
|
||||||
username: "root",
|
const string = new TextDecoder().decode(stdout[0]);
|
||||||
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.type).toBe("success");
|
||||||
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
expect((output.result as ResultSuccess).exitCode).toBe(0);
|
||||||
expect(string).toBe("hello world");
|
// Fix: added a newline character
|
||||||
|
expect(string).toEqual("hello world\n");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { ResultError } from "@core/result";
|
||||||
|
import { type ShellState } from "@core/shell_state";
|
||||||
|
import { SIGNAL_MAP } from "@core/signal";
|
||||||
|
import type { SignalTerminationError } from "@core/util/errors";
|
||||||
|
import { Shell } from "@shell/shell";
|
||||||
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
|
const state: ShellState = Fixture.State;
|
||||||
|
|
||||||
|
test("returns a Result of type success", async () => {
|
||||||
|
await Shell.init(state);
|
||||||
|
|
||||||
|
let result;
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
//const decoder = new TextDecoder();
|
||||||
|
//console.log(decoder.decode(payload.result.stdout.toArray()));
|
||||||
|
//console.log(payload);
|
||||||
|
result = payload.result;
|
||||||
|
|
||||||
|
expect(result.type).toBe("error");
|
||||||
|
expect((result as ResultError<SignalTerminationError>).error.exitCode).toEqual(130);
|
||||||
|
expect((result as ResultError<SignalTerminationError>).error.signalNumber).toEqual(SIGNAL_MAP.SIGINT);
|
||||||
|
});
|
||||||
|
|
||||||
|
await Shell.Instance?.execute("async");
|
||||||
|
Shell.Instance?.sendInput("a");
|
||||||
|
Shell.Instance?.sendInput("b");
|
||||||
|
Shell.Instance?.sendInput("c");
|
||||||
|
Shell.Instance?.sendInput("d");
|
||||||
|
Shell.Instance?.sendInput(
|
||||||
|
"right now technically anything goes because its just a plain string however i plan on improving this system a bit later on",
|
||||||
|
);
|
||||||
|
Shell.Instance?.sendInput("ctrl+c");
|
||||||
|
});
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { resolveInode, resolvePath } from "@core/util/path_resolver";
|
import { resolveInode, 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 { Fixture7Depth } from "@tests/helpers/state_fixture";
|
||||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
|
||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
const fs = buildTestFS(depth7Tree);
|
const state = Fixture7Depth.State;
|
||||||
|
const fs = state.filesystem;
|
||||||
|
|
||||||
describe("resolvePath", () => {
|
describe("resolvePath", () => {
|
||||||
test("returns an inode from an absolute path", () => {
|
test("returns an inode from an absolute path", () => {
|
||||||
@@ -64,10 +64,10 @@ describe("resolvePath", () => {
|
|||||||
|
|
||||||
describe("resolveInode", () => {
|
describe("resolveInode", () => {
|
||||||
test("returns an the path from the d4 node", () => {
|
test("returns an the path from the d4 node", () => {
|
||||||
expect(resolveInode(fs, 4)).toBe("/d1/d2/d3/d4");
|
expect(resolveInode(state, 4, true)).toBe("/d1/d2/d3/d4");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns an empty string from a non existent inode", () => {
|
test("returns an empty string from a non existent inode", () => {
|
||||||
expect(resolveInode(fs, 999)).toBe("");
|
expect(resolveInode(state, 999)).toBe("");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,65 +1,32 @@
|
|||||||
import type { UserInfo } from "@core/session_manager";
|
|
||||||
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
|
import { createInitialSessionState, getCurrentSession, login, logout } from "@core/session_manager";
|
||||||
import { createInitialShellState } from "@core/shell_state";
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
import { buildTestFS } from "@tests/helpers/filesystems_fixture";
|
|
||||||
import { depth7Tree } from "@tests/helpers/tree_fixture";
|
|
||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
const root: UserInfo = {
|
const state = Fixture.State;
|
||||||
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();
|
const passMap = new Map();
|
||||||
passMap.set(0, "123");
|
passMap.set(0, "123");
|
||||||
passMap.set(1, "321");
|
passMap.set(1000, "321");
|
||||||
|
|
||||||
test("createInitialSessionState - successfully creates a new session state", () => {
|
test("createInitialSessionState - successfully creates a new session state", () => {
|
||||||
const state = createInitialSessionState(root);
|
const state = createInitialSessionState(Fixture.user);
|
||||||
|
|
||||||
expect(state.cwd).toEqual(root.home);
|
expect(state.cwd).toEqual(Fixture.user.home);
|
||||||
expect(state.pwd).toEqual(root.home);
|
expect(state.pwd).toEqual(Fixture.user.home);
|
||||||
expect(state.exitCode).toEqual(0);
|
expect(state.exitCode).toEqual(0);
|
||||||
expect(state.user).toBe(root);
|
expect(state.user).toBe(Fixture.user);
|
||||||
expect(Object.isFrozen(state)).toBe(true);
|
expect(Object.isFrozen(state)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("login", () => {
|
describe("login", () => {
|
||||||
test("it successfully starts a new session under the user test", () => {
|
test("it successfully starts a new session under the user test", () => {
|
||||||
const newState = login(state, "test", "321", passMap);
|
const newState = login(state, "user", "321", passMap);
|
||||||
const pop = getCurrentSession(newState);
|
const pop = getCurrentSession(newState);
|
||||||
|
|
||||||
expect(pop.user).toEqual(testU);
|
expect(pop.user).toEqual(Fixture.user2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("fails to start a new session. Cause: no password mapped to the uid", () => {
|
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;
|
//TODO: Fix to expect the correct object;
|
||||||
expect(() => login(state, "no pass", "321", passMap)).toThrow();
|
expect(() => login(state, "no pass", "321", passMap)).toThrow();
|
||||||
});
|
});
|
||||||
@@ -77,14 +44,14 @@ describe("login", () => {
|
|||||||
|
|
||||||
describe("logout", () => {
|
describe("logout", () => {
|
||||||
test("returns the state with the current user poped from the stack", () => {
|
test("returns the state with the current user poped from the stack", () => {
|
||||||
const newState = login(state, "test", "321", passMap);
|
const newState = login(state, "user", "321", passMap);
|
||||||
const newPop = getCurrentSession(newState);
|
const newPop = getCurrentSession(newState);
|
||||||
|
|
||||||
expect(newPop.user).toEqual(testU);
|
expect(newPop.user).toEqual(Fixture.user2);
|
||||||
|
|
||||||
const newNewState = logout(state);
|
const newNewState = logout(state);
|
||||||
const pop = getCurrentSession(newNewState);
|
const pop = getCurrentSession(newNewState);
|
||||||
|
|
||||||
expect(pop.user).toEqual(root);
|
expect(pop.user).toEqual(Fixture.user);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,48 +1,14 @@
|
|||||||
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 { getCurrentSession } from "@core/session_manager";
|
||||||
import { createInitialShellState, withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
|
import { withCwd, withEnv, withExitCode, withHistory } from "@core/shell_state";
|
||||||
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
import { expect, test } from "vitest";
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
const map: Map<number, TreeNode> = new Map();
|
const state = Fixture.State;
|
||||||
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", () => {
|
test("createInitialShellState - initializes successfully", () => {
|
||||||
expect(state.sessionStack.at(0)).toBeDefined();
|
expect(state.sessionStack.at(0)).toBeDefined();
|
||||||
|
|
||||||
expect(state.users.get(user.uid)).toEqual(user);
|
expect(state.users.get(Fixture.user.uid)).toEqual(Fixture.user);
|
||||||
expect(Object.isFrozen(state)).toBe(true);
|
expect(Object.isFrozen(state)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -61,7 +27,7 @@ test("getCurrentSession - successfully returns the current (top most) session fr
|
|||||||
expect(session.exitCode).toBe(0);
|
expect(session.exitCode).toBe(0);
|
||||||
expect(session.history).toEqual([]);
|
expect(session.history).toEqual([]);
|
||||||
expect(session.envVars.size).toBe(0);
|
expect(session.envVars.size).toBe(0);
|
||||||
expect(session.user).toBe(user);
|
expect(session.user).toBe(Fixture.user);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("withCwd", () => {
|
test("withCwd", () => {
|
||||||
|
|||||||
@@ -38,7 +38,10 @@ const fsTwo = buildTestFS(depth7Tree);
|
|||||||
describe("dnTraverseTree", () => {
|
describe("dnTraverseTree", () => {
|
||||||
test("successfully traverses down the tree in depth-first pre-order", () => {
|
test("successfully traverses down the tree in depth-first pre-order", () => {
|
||||||
const result = dnTraverseTree(fs, 0);
|
const result = dnTraverseTree(fs, 0);
|
||||||
expect(result, `Checking the result ${result} to be [0, 1, 2, 3]`).toEqual([0, 2, 3, 1]);
|
// This got changed from [0, 2, 3, 1] to [1, 2, 3]
|
||||||
|
// A bug in dnTraverseTree resulted in the tree traversal not respecting order of nodes, and including root.
|
||||||
|
// Including root in results caused further problems so it was decided that results wont include the passed root node;
|
||||||
|
expect(result, `Checking the result ${result} to be [1, 2, 3]`).toEqual([1, 2, 3]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("returns empty array for a non existent root inode", () => {
|
test("returns empty array for a non existent root inode", () => {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export function expectNotADirectoryError(fn: () => unknown, overrides?: Partial<
|
|||||||
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 TreeNodeType,
|
||||||
...overrides,
|
...overrides,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { FileSystem } from "@core/filesystem/filesystem";
|
||||||
|
import type { TreeNode } from "@core/filesystem/treenode";
|
||||||
|
import type { GroupInfo, UserInfo } from "@core/session_manager";
|
||||||
|
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||||
|
import { deserializeFileSystem } from "@shell/serializer";
|
||||||
|
import { buildTestFS } from "./filesystems_fixture";
|
||||||
|
import { depth7Tree } from "./tree_fixture";
|
||||||
|
|
||||||
|
export class Fixture {
|
||||||
|
/*
|
||||||
|
root (0)
|
||||||
|
├── folder1 (1)
|
||||||
|
│ └── subdir1 (2)
|
||||||
|
├── folder2 (3)
|
||||||
|
│ ├── subdir2 (4)
|
||||||
|
│ └── subdir3 (5)
|
||||||
|
│ └── empty-foo (6)
|
||||||
|
└── some-file (7)
|
||||||
|
*/
|
||||||
|
|
||||||
|
static 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"}`;
|
||||||
|
static user: UserInfo = {
|
||||||
|
username: "root",
|
||||||
|
uid: 0,
|
||||||
|
gid: 0, // <- PRIMARY GID
|
||||||
|
group: [0], // <- GROUPS ARRAY
|
||||||
|
home: 0,
|
||||||
|
};
|
||||||
|
static user2: UserInfo = {
|
||||||
|
username: "user",
|
||||||
|
uid: 1000,
|
||||||
|
gid: 1000,
|
||||||
|
group: [1000],
|
||||||
|
home: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
static nopass: UserInfo = {
|
||||||
|
username: "no pass",
|
||||||
|
uid: 1001,
|
||||||
|
gid: 1000,
|
||||||
|
group: [1000],
|
||||||
|
home: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
static group: GroupInfo = {
|
||||||
|
groupname: "root",
|
||||||
|
gid: 0,
|
||||||
|
members: [0], // <- UID
|
||||||
|
};
|
||||||
|
static group2: GroupInfo = {
|
||||||
|
groupname: "user",
|
||||||
|
gid: 1000,
|
||||||
|
members: [1000, 1001], // <- UID
|
||||||
|
};
|
||||||
|
|
||||||
|
public static get State(): ShellState {
|
||||||
|
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"}`;
|
||||||
|
const base = deserializeFileSystem(rawJson);
|
||||||
|
|
||||||
|
const overlay: ReadonlyMap<number, TreeNode | null> = new Map();
|
||||||
|
|
||||||
|
const fs = FileSystem.init(base, overlay, base.size - 1);
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const groups: Map<number, GroupInfo> = new Map();
|
||||||
|
|
||||||
|
users.set(0, Fixture.user);
|
||||||
|
users.set(1000, Fixture.user2);
|
||||||
|
users.set(1001, Fixture.nopass);
|
||||||
|
groups.set(0, Fixture.group);
|
||||||
|
groups.set(1000, Fixture.group2);
|
||||||
|
|
||||||
|
return createInitialShellState(fs, users, groups, Fixture.user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Fixture7Depth extends Fixture {
|
||||||
|
public static get State(): ShellState {
|
||||||
|
const fs = buildTestFS(depth7Tree);
|
||||||
|
|
||||||
|
const users: Map<number, UserInfo> = new Map();
|
||||||
|
const groups: Map<number, GroupInfo> = new Map();
|
||||||
|
|
||||||
|
users.set(0, Fixture7Depth.user);
|
||||||
|
users.set(1000, Fixture7Depth.user2);
|
||||||
|
groups.set(0, Fixture7Depth.group);
|
||||||
|
groups.set(1000, Fixture7Depth.group2);
|
||||||
|
|
||||||
|
return createInitialShellState(fs, users, groups, Fixture7Depth.user);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { expect, test } from "vitest";
|
|
||||||
|
|
||||||
function divideToChunks(data: Uint8Array): Uint8Array[] {
|
|
||||||
const nChunks: number = Math.ceil(data.length / 1024);
|
|
||||||
|
|
||||||
const chunks: Uint8Array[] = [];
|
|
||||||
for (let i = 0; i < nChunks; i++) {
|
|
||||||
const start = 1024 * i;
|
|
||||||
const end = 1024 * (i + 1);
|
|
||||||
|
|
||||||
chunks.push(data.slice(start, end));
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(chunks.length);
|
|
||||||
|
|
||||||
return chunks;
|
|
||||||
}
|
|
||||||
|
|
||||||
test("divide to chunks", () => {
|
|
||||||
const data: Uint8Array = new Uint8Array(2048);
|
|
||||||
const result: Uint8Array[] = divideToChunks(data);
|
|
||||||
expect(result.length).toEqual(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("divide to chunks", () => {
|
|
||||||
const data: Uint8Array = new Uint8Array(2049);
|
|
||||||
const result = divideToChunks(data);
|
|
||||||
expect(result.length).toEqual(3);
|
|
||||||
});
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
import { deserializeFileSystem } from "@shell/serializer";
|
|
||||||
import { test } from "vitest";
|
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"}`;
|
//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", () => {
|
test("deserialize json into the correct tree structure", () => {
|
||||||
const base = deserializeFileSystem(rawJson);
|
//const base = deserializeFileSystem(rawJson);
|
||||||
console.log(base);
|
//expect(true).toEqual(false);
|
||||||
});
|
});
|
||||||
|
|||||||
+14
-55
@@ -1,68 +1,27 @@
|
|||||||
import { getCurrentSession, type UserInfo } from "@core/session_manager";
|
import { getCurrentSession } from "@core/session_manager";
|
||||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
|
||||||
import { Shell } from "@shell/shell";
|
import { Shell } from "@shell/shell";
|
||||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
import { Fixture } from "@tests/helpers/state_fixture";
|
||||||
import { describe, expect, test } from "vitest";
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
const testTree: FixtureNode = {
|
const state = Fixture.State;
|
||||||
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", () => {
|
describe("Shell tests", () => {
|
||||||
test("Successfully executes the cd command", async () => {
|
test("Successfully executes the cd command", async () => {
|
||||||
await Shell.init(state);
|
await Shell.init(state);
|
||||||
const result = await Shell.Instance?.Execute("cd /sub");
|
|
||||||
|
let result;
|
||||||
|
|
||||||
|
Shell.Instance?.on("result", payload => {
|
||||||
|
result = payload.result;
|
||||||
|
});
|
||||||
|
|
||||||
|
await Shell.Instance?.execute("cd /folder1");
|
||||||
const statee = Shell.Instance?.State;
|
const statee = Shell.Instance?.State;
|
||||||
|
|
||||||
expect(result?.type).toEqual("success");
|
expect(result!.type).toEqual("success");
|
||||||
expect(getCurrentSession(statee!).history.length).toBe(1);
|
expect(getCurrentSession(statee!).history.length).toBe(1);
|
||||||
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
|
expect(getCurrentSession(statee!).history[0]).toEqual("cd /folder1");
|
||||||
expect(getCurrentSession(statee!).cwd).toBe(2);
|
expect(getCurrentSession(statee!).cwd).toBe(1);
|
||||||
expect(getCurrentSession(statee!).exitCode).toBe(0);
|
expect(getCurrentSession(statee!).exitCode).toBe(0);
|
||||||
});
|
});
|
||||||
test("Returns a proper command error from cd", () => {});
|
test("Returns a proper command error from cd", () => {});
|
||||||
|
|||||||
@@ -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/*"],
|
||||||
|
|||||||
Reference in New Issue
Block a user