@peterbe/clorb 0.0.0-stage → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bunfig.toml ADDED
@@ -0,0 +1,9 @@
1
+ [fmt]
2
+ useTabs = true
3
+ printWidth = 100
4
+ semi = true
5
+ sortImports = true
6
+ sortPackageJson = true
7
+
8
+ [lint.rules]
9
+ "import/no-unused-modules" = "error" # or "warn"
package/justfile ADDED
@@ -0,0 +1,39 @@
1
+ dev:
2
+ echo "This will constantly build and copy executable to ./out/clorb"
3
+ bun run build:watch
4
+
5
+ build:
6
+ bun run build
7
+
8
+ ship: build linux-build
9
+
10
+ linux-build:
11
+ bun build src/index.ts --target=bun --outfile ./out/clorb-linux-x64-modern --compile --minify --sourcemap --bytecode --target=bun-linux-x64-modern
12
+ bun build src/index.ts --target=bun --outfile ./out/clorb-linux-arm64 --compile --minify --sourcemap --bytecode --target=bun-linux-arm64
13
+
14
+ check:
15
+ bun check
16
+
17
+ lint: check
18
+ bun run format
19
+
20
+ format: lint
21
+
22
+ install:
23
+ bun install
24
+
25
+ outdated:
26
+ bun outdated
27
+
28
+ test:
29
+ bun test
30
+
31
+ test-watch:
32
+ bun test --watch
33
+
34
+ release:
35
+ bun run release
36
+
37
+ upgrade:
38
+ bun update --interactive --minimum-release-age=86400 && bun install
39
+
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
- "name": "@peterbe/clorb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@peterbe/clorb",
3
+ "version": "0.0.8",
4
+ "description": "A CLI tool for cloning Orbstack VMs by git branches",
5
+ "keywords": [
6
+ "cli",
7
+ "datetime",
8
+ "timezones"
9
+ ],
10
+ "bugs": {
11
+ "url": "https://github.com/peterbe/clorb/issues"
12
+ },
13
+ "license": "MIT",
14
+ "author": "Peter Bengtsson",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git://github.com/peterbe/clorb"
18
+ },
19
+ "bin": {
20
+ "clorb": "src/index.ts"
21
+ },
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "format": "bun fmt",
28
+ "lint:check": "bun fmt --check",
29
+ "prepare": "husky",
30
+ "build": "bun build src/index.ts --target=bun --outfile out/clorb --compile --bytecode",
31
+ "build:watch": "bun build --watch src/index.ts --target=bun --outfile out/clorb --compile --bytecode",
32
+ "build:linux-arm64": "bun build src/index.ts --target=bun-linux-arm64 --outfile out/clorb-linux-arm64 --compile --bytecode",
33
+ "build:linux-x64": "bun build src/index.ts --target=bun-linux-x64 --outfile out/clorb-linux-x64 --compile --bytecode",
34
+ "release": "np --yolo"
35
+ },
36
+ "dependencies": {
37
+ "@inquirer/prompts": "^8.8.0",
38
+ "commander": "^15.1.0",
39
+ "ora": "^10.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/bun": "latest",
43
+ "husky": "^9.1.7",
44
+ "np": "^12.1.1"
45
+ },
46
+ "peerDependencies": {
47
+ "typescript": "^7"
48
+ }
49
+ }
package/src/actions.ts ADDED
@@ -0,0 +1,110 @@
1
+ import { confirm, input } from "@inquirer/prompts";
2
+ import ora from "ora";
3
+
4
+ import { CLORB_PREFIX } from "./constants";
5
+ import {
6
+ bold,
7
+ cloneOrb,
8
+ deleteOrb,
9
+ getCurrentOrbs,
10
+ getDefaultOrbName,
11
+ getOrbNameFromBranchName,
12
+ italic,
13
+ runOrb,
14
+ success,
15
+ warn,
16
+ } from "./utils";
17
+
18
+ export async function clorb(branchName: string, orbName: string): Promise<void> {
19
+ const currentOrbs = await getCurrentOrbs();
20
+ if (orbName) {
21
+ if (!currentOrbs[orbName]) {
22
+ throw new Error(`Orb '${orbName}' does not exist`);
23
+ }
24
+ }
25
+ const source = orbName || (await getDefaultOrbName());
26
+
27
+ const interactiveBranchName = branchName || (await askBranchName());
28
+ const destination = await getOrbNameFromBranchName(branchName || interactiveBranchName);
29
+
30
+ const currentOrb = currentOrbs[destination];
31
+ if (currentOrb) {
32
+ warn(`Orb ${bold(destination)} already exists`);
33
+ console.log(`It is currently ${bold(currentOrb.state)}.`);
34
+ console.log("");
35
+ if (currentOrb.state !== "running") {
36
+ await askToRunOrb(destination);
37
+ }
38
+ } else {
39
+ success(`Orb '${destination}' does not exist and will be created`);
40
+ console.log("");
41
+ const spinner = ora(`Cloning ${bold(source)} to ${bold(destination)}`).start();
42
+ await cloneOrb(source, destination);
43
+ spinner.succeed(`Cloned ${bold(source)} to ${bold(destination)}`);
44
+ await askToRunOrb(destination);
45
+ }
46
+
47
+ console.log(`To go into this orb, use:\n\n\t${bold(`orbctl run -m ${destination}`)}`);
48
+
49
+ console.log("");
50
+ }
51
+
52
+ async function askToRunOrb(orbName: string): Promise<void> {
53
+ if (await askBoolean(`Do you want to run the orb ${bold(orbName)} now?`)) {
54
+ await runOrb(orbName);
55
+ }
56
+ }
57
+
58
+ export async function askBoolean(message: string, defaultValue = true): Promise<boolean> {
59
+ return await confirm({
60
+ message,
61
+ default: defaultValue,
62
+ });
63
+ }
64
+
65
+ async function askBranchName(): Promise<string> {
66
+ const branchName = await input({
67
+ message: "Enter the git branch name:",
68
+ });
69
+ return branchName.trim();
70
+ }
71
+
72
+ export async function purge() {
73
+ const spinner = ora(`Gathering information`).start();
74
+ const orbs = await getCurrentOrbs();
75
+
76
+ const clorbs = Object.keys(orbs).filter((name) => name.startsWith(CLORB_PREFIX));
77
+
78
+ spinner.succeed(`Found ${clorbs.length} clorb${clorbs.length === 1 ? "" : "s"}`);
79
+ if (clorbs.length === 0) {
80
+ return;
81
+ }
82
+ const toDelete: string[] = [];
83
+ for (const orb of clorbs) {
84
+ if (orbs[orb]) {
85
+ console.log(`${orb.padEnd(60)} ${orbs[orb].state}`);
86
+ if (await askBoolean(`Do you want to delete the orb ${italic(orb)}?`)) {
87
+ toDelete.push(orb);
88
+ }
89
+ }
90
+ }
91
+ const spinner2 = ora(
92
+ `Deleting ${toDelete.length} orb${toDelete.length === 1 ? "" : "s"}`,
93
+ ).start();
94
+ for (const orb of toDelete) {
95
+ await deleteOrb(orb);
96
+ }
97
+ spinner2.succeed(`Deleted ${toDelete.length} orb${toDelete.length === 1 ? "" : "s"}`);
98
+ }
99
+
100
+ export async function list() {
101
+ const orbs = await getCurrentOrbs();
102
+ const clorbs = Object.keys(orbs).filter((name) => name.startsWith(CLORB_PREFIX));
103
+ if (clorbs.length === 0) {
104
+ console.log("No clorbs found");
105
+ return;
106
+ }
107
+ for (const orb of clorbs) {
108
+ if (orbs[orb]) console.log(`${orb.padEnd(60)} ${orbs[orb].state}`);
109
+ }
110
+ }
@@ -0,0 +1 @@
1
+ export const CLORB_PREFIX = "clorb--";
package/src/index.ts ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { Command } from "commander";
4
+
5
+ import { version } from "../package.json";
6
+ import { clorb, list, purge } from "./actions";
7
+ import { error } from "./utils";
8
+
9
+ const program = new Command();
10
+
11
+ program
12
+ .name("clorb")
13
+ .description("Clone Orbstack VMs by git branches")
14
+ .version(version)
15
+ .option("--debug", "Debug mode (shows traceback)")
16
+ .argument("[gitbranchname]", "name of the git branch (e.g. peterbe/foo-bar)")
17
+ .argument("[orbname]", "name of the orb to clone from (defaults to your default orb)")
18
+ .action(async (branchName: string, orbName: string, options: { debug: boolean }) => {
19
+ wrap(clorb(branchName, orbName), options.debug);
20
+ });
21
+
22
+ program
23
+ .command("_purge")
24
+ .description("Interactively purge all Orbstack VMs created with clorb")
25
+ .option("--debug", "Debug mode (shows traceback)")
26
+ .action(async (options: { debug: boolean }) => {
27
+ wrap(purge(), options.debug);
28
+ });
29
+
30
+ program
31
+ .command("_list")
32
+ .description("List all Orbstack VMs created with clorb")
33
+ .option("--debug", "Debug mode (shows traceback)")
34
+ .action(async (options: { debug: boolean }) => {
35
+ wrap(list(), options.debug);
36
+ });
37
+
38
+ program.parse();
39
+
40
+ function wrap(promise: Promise<void>, debug: boolean) {
41
+ promise
42
+ .then(() => {
43
+ process.exit(0);
44
+ })
45
+ .catch((err) => {
46
+ if (err instanceof Error && err.name === "ExitPromptError") {
47
+ // Ctrl-C
48
+ process.exit(0);
49
+ }
50
+
51
+ if (debug) {
52
+ throw err;
53
+ }
54
+ error(err.message);
55
+ process.exit(1);
56
+ });
57
+ }
@@ -0,0 +1,16 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { CLORB_PREFIX } from "./constants";
4
+ import { getOrbNameFromBranchName } from "./utils";
5
+
6
+ describe("utils", () => {
7
+ test.each([
8
+ ["peterbe/foo", "peterbe-foo"],
9
+ ["contains.dots'and'apostropåes", "containsdotsandapostropes"],
10
+ ["Upper:LOWER", "upper-lower"],
11
+ ["spaces in the name", "spaces-in-the-name"],
12
+ ])("generate orb name from branch name %s", async (input, expected) => {
13
+ const output = await getOrbNameFromBranchName(input);
14
+ expect(output).toBe(CLORB_PREFIX + expected);
15
+ });
16
+ });
package/src/utils.ts ADDED
@@ -0,0 +1,159 @@
1
+ import { input } from "@inquirer/prompts";
2
+
3
+ import { CLORB_PREFIX } from "./constants";
4
+
5
+ export function bold(text: string): string {
6
+ return `\x1b[1m${text}\x1b[0m`;
7
+ }
8
+ export function italic(text: string): string {
9
+ return `\x1b[3m${text}\x1b[0m`;
10
+ }
11
+ export function grey(text: string): string {
12
+ return `\x1b[90m${text}\x1b[0m`;
13
+ }
14
+ export function green(text: string): string {
15
+ return `\x1b[32m${text}\x1b[0m`;
16
+ }
17
+ export function red(text: string): string {
18
+ return `\x1b[31m${text}\x1b[0m`;
19
+ }
20
+ export function yellow(text: string): string {
21
+ return `\x1b[33m${text}\x1b[0m`;
22
+ }
23
+ export function error(...args: string[]) {
24
+ console.error(...args.map((arg) => red(arg)));
25
+ }
26
+
27
+ export function warn(...args: string[]) {
28
+ console.warn(...args.map((arg) => yellow(arg)));
29
+ }
30
+
31
+ export function success(text: string[] | string): void {
32
+ console.log(green(typeof text === "string" ? text : text.join("\n")));
33
+ }
34
+ export function failure(text: string[] | string): void {
35
+ console.error(red(typeof text === "string" ? text : text.join("\n")));
36
+ }
37
+
38
+ export async function runSshCommand(orbName: string, command: string): ReturnType<typeof run> {
39
+ if (!orbName) throw new Error("Orb name is required");
40
+ if (!command) throw new Error("Command is required");
41
+ if (orbName.includes("@")) throw new Error("Orb name should not include '@orb'");
42
+ if (orbName.includes(" ")) throw new Error("Orb name should not include spaces");
43
+
44
+ return await run(["ssh", `${orbName}@orb`, command]);
45
+ }
46
+
47
+ type Orb = {
48
+ id: string;
49
+ name: string;
50
+ image: {
51
+ distro: string;
52
+ version: string;
53
+ arch: string;
54
+ variant: string;
55
+ };
56
+ config: {
57
+ isolated: boolean;
58
+ forward_ssh_agent: boolean;
59
+ isolate_network: boolean;
60
+ default_username: string;
61
+ http_port: number;
62
+ https_port: number;
63
+ };
64
+ os_release: {
65
+ name: string;
66
+ version_id: string;
67
+ pretty_name: string;
68
+ };
69
+ builtin: boolean;
70
+ state: string;
71
+ };
72
+ export async function getCurrentOrbs(): Promise<Record<string, Orb>> {
73
+ const { exitCode, stdout, stderr } = await run(["orbctl", "list", "-f", "json"]);
74
+ if (exitCode !== 0) {
75
+ throw new Error(`Failed to get current orbs: ${stderr}`);
76
+ }
77
+ const orbs: Orb[] = JSON.parse(stdout);
78
+ const result: Record<string, Orb> = {};
79
+ for (const orb of orbs) {
80
+ result[orb.name] = orb;
81
+ }
82
+ return result;
83
+ }
84
+
85
+ async function run(cmd: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
86
+ const proc = Bun.spawn(cmd, {
87
+ stdout: "pipe",
88
+ stderr: "pipe", // default is "inherit", so set this explicitly
89
+ });
90
+
91
+ const [stdout, stderr, exitCode] = await Promise.all([
92
+ new Response(proc.stdout).text(),
93
+ new Response(proc.stderr).text(),
94
+ proc.exited,
95
+ ]);
96
+
97
+ return { exitCode, stdout, stderr };
98
+ }
99
+
100
+ export async function getDefaultOrbName(): Promise<string> {
101
+ const { exitCode, stdout, stderr } = await run(["orbctl", "default"]);
102
+ if (exitCode !== 0) {
103
+ throw new Error(`Failed to get default orb name: ${stderr}`);
104
+ }
105
+ return stdout.trim();
106
+ }
107
+
108
+ export async function runOrb(orbName: string): Promise<void> {
109
+ if (!orbName) throw new Error("Orb name is required");
110
+ const { exitCode, stderr } = await run(["orbctl", "run", "-m", orbName]);
111
+ if (exitCode !== 0) {
112
+ throw new Error(`Failed to run orb: ${stderr}`);
113
+ }
114
+ }
115
+
116
+ export async function deleteOrb(orbName: string): Promise<void> {
117
+ const { exitCode, stderr } = await run(["orbctl", "delete", orbName]);
118
+ if (exitCode !== 0) {
119
+ throw new Error(`Failed to delete orb: ${stderr}`);
120
+ }
121
+ }
122
+
123
+ export async function getOrbNameFromBranchName(
124
+ branchName: string,
125
+ prefix = CLORB_PREFIX,
126
+ maxLength = 63,
127
+ ): Promise<string> {
128
+ if (!branchName) throw new Error("Branch name is required");
129
+ const slug = branchName
130
+ .trim()
131
+ .replace(/\//g, "-")
132
+ .replace(/\s+/g, "-")
133
+ .replace(/:/g, "-")
134
+ .replace(/_/g, "-")
135
+ .replace(/^-+|-+$/g, "")
136
+ .replace(/-{2,}/g, "-")
137
+ .toLowerCase()
138
+ .replace(/[^a-z0-9-_/]/g, "")
139
+ .slice(0, maxLength - 6 - prefix.length - 2);
140
+ return `${prefix}${slug}`; //--${hash}`;
141
+ }
142
+
143
+ export async function interactiveInput(message: string): Promise<string> {
144
+ return await input({
145
+ message,
146
+ required: true,
147
+ });
148
+ }
149
+
150
+ export async function cloneOrb(source: string, destination: string, debug = false): Promise<void> {
151
+ console.log(["orbctl", "clone", source, destination].join(" "));
152
+ const { exitCode, stdout, stderr } = await run(["orbctl", "clone", source, destination]);
153
+ if (exitCode !== 0) {
154
+ throw new Error(`Failed to clone orb: ${stderr}`);
155
+ }
156
+ if (debug) {
157
+ console.log(stdout);
158
+ }
159
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+ "types": ["bun"],
11
+
12
+ // Bundler mode
13
+ "moduleResolution": "bundler",
14
+ "allowImportingTsExtensions": true,
15
+ "verbatimModuleSyntax": true,
16
+ "noEmit": true,
17
+
18
+ // Best practices
19
+ "strict": true,
20
+ "skipLibCheck": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUncheckedIndexedAccess": true,
23
+ "noImplicitOverride": true,
24
+
25
+ // Some stricter flags (disabled by default)
26
+ "noUnusedLocals": false,
27
+ "noUnusedParameters": false,
28
+ "noPropertyAccessFromIndexSignature": false
29
+ }
30
+ }