@infosupport/huddle-cli 0.0.0-experiment-137.147.1 → 0.0.0-experiment-137.149.1

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/README.md CHANGED
@@ -16,7 +16,7 @@ npm install -g @infosupport/huddle-cli
16
16
  huddle init
17
17
  ```
18
18
 
19
- Pulls `ghcr.io/infosupport/huddle:latest` and starts the container. Works with Docker and Podman: the runtime is detected automatically (Docker first, then Podman), or pick one explicitly with `huddle init --runtime <docker|podman>` or the `HUDDLE_RUNTIME` env var. If you run `huddle` while Huddle isn't running, you automatically get a hint to run this command.
19
+ Pulls `ghcr.io/infosupport/huddle:latest` and starts the container. Works with Docker, Podman and WSLc: the runtime is detected automatically (Docker first, then Podman, then WSLc), or pick one explicitly with `huddle init --runtime <docker|podman|wslc>` or the `HUDDLE_RUNTIME` env var. If you run `huddle` while Huddle isn't running, you automatically get a hint to run this command.
20
20
 
21
21
  ## Starting devcontainers
22
22
 
@@ -116,6 +116,7 @@ Main flags:
116
116
  --name <name>
117
117
  --image <image>
118
118
  --empty
119
+ --no-vscode-config
119
120
  -i, --interactive
120
121
  --container <name>
121
122
  --status <requested|allow|deny>
@@ -11,6 +11,7 @@ exports.readStatus = readStatus;
11
11
  exports.buildImages = buildImages;
12
12
  exports.startBackgroundBuild = startBackgroundBuild;
13
13
  exports.printStatus = printStatus;
14
+ exports.ensureImageForStart = ensureImageForStart;
14
15
  const child_process_1 = require("child_process");
15
16
  const fs_1 = __importDefault(require("fs"));
16
17
  const path_1 = __importDefault(require("path"));
@@ -160,3 +161,41 @@ function printStatus(rt, tag) {
160
161
  if (fs_1.default.existsSync(LOG_PATH))
161
162
  console.log((0, utils_1.dim)(`Log: ${LOG_PATH}`));
162
163
  }
164
+ const STALE_MS = 60 * 60 * 1000;
165
+ /**
166
+ * Called by `huddle start` before it asks the gateway to start a container.
167
+ * The gateway would otherwise block the request for the whole build and the
168
+ * CLI's HTTP call times out after 5 minutes. So: wait here for a running
169
+ * background build (with progress), or build in the foreground when nothing is
170
+ * building. Only for our own local images; a snapshot or custom image is left
171
+ * to the gateway.
172
+ */
173
+ async function ensureImageForStart(rt, ide, imageName) {
174
+ const m = /^localhost\/huddle\/base-devimage-[a-z]+:(.+)$/.exec(imageName);
175
+ if (!m || imageExists(rt, imageName))
176
+ return;
177
+ const tag = m[1];
178
+ let announced = false;
179
+ for (;;) {
180
+ const s = readStatus();
181
+ const building = s?.state === 'building' && Date.now() - Date.parse(s.updatedAt) < STALE_MS;
182
+ if (!building || imageExists(rt, imageName))
183
+ break;
184
+ if (!announced) {
185
+ console.log((0, utils_1.dim)(`Waiting for the base-image build to finish (${s?.image ?? imageName}); log: ${LOG_PATH}`));
186
+ announced = true;
187
+ }
188
+ else {
189
+ process.stdout.write((0, utils_1.dim)('.'));
190
+ }
191
+ await new Promise((r) => setTimeout(r, 10_000));
192
+ }
193
+ if (announced)
194
+ console.log();
195
+ if (imageExists(rt, imageName))
196
+ return;
197
+ console.log((0, utils_1.bold)(`Base image ${imageName} is missing; building it now (one-time, a few minutes).`));
198
+ if (!buildImages({ rt, tag, ides: [ide] })) {
199
+ throw new Error(`Could not build ${imageName}; see the output above or run "huddle images build"`);
200
+ }
201
+ }
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ const self_update_1 = require("./self-update");
22
22
  const utils_1 = require("./utils");
23
23
  const experiment_1 = require("./experiment");
24
24
  const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root', 'depth']);
25
- const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear']);
25
+ const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear', 'no-vscode-config']);
26
26
  const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'update-agent', 'triage-agent', 'images', 'help', 'version']);
27
27
  function parseArgs(argv) {
28
28
  const positional = [];
@@ -163,7 +163,7 @@ Usage:
163
163
  huddle images status Show which base images are present
164
164
 
165
165
  Init options:
166
- --runtime <docker|podman> Container runtime (default: auto-detected;
166
+ --runtime <docker|podman|wslc> Container runtime (default: auto-detected;
167
167
  also via the HUDDLE_RUNTIME env var)
168
168
  --experiment <nr> Use the experimental build of issue/PR <nr>
169
169
  (same as "huddle experiment use <nr>")
@@ -179,6 +179,8 @@ Start options:
179
179
  --name <name> Container name (default: devcontainer-<foldername>)
180
180
  --image <image> Use a specific image
181
181
  --empty Empty container without a workspace
182
+ --no-vscode-config Do not write the per-container attach config
183
+ that makes VS Code open the workspace folder
182
184
 
183
185
  Update-agent options:
184
186
  --dry-run Fix and verify, but print the diff instead of
@@ -278,6 +280,7 @@ async function main() {
278
280
  name: flagString(flags, 'name'),
279
281
  image: flagString(flags, 'image'),
280
282
  empty: flagBool(flags, 'empty'),
283
+ vscodeConfig: !flagBool(flags, 'no-vscode-config'),
281
284
  });
282
285
  return;
283
286
  }
package/dist/runtime.js CHANGED
@@ -14,8 +14,11 @@ function commandOutput(cmd) {
14
14
  }
15
15
  }
16
16
  function isAvailable(runtime) {
17
- // 'info' only succeeds if the daemon/machine is actually reachable.
18
- return commandOutput(`${runtime} info`) !== undefined;
17
+ // 'info' only succeeds if the daemon/machine is actually reachable. wslc has
18
+ // no 'info' subcommand at all (it exits with "Unrecognized command"), so use
19
+ // 'list' there instead — it equally requires a reachable daemon to succeed.
20
+ const probe = runtime === 'wslc' ? 'list' : 'info';
21
+ return commandOutput(`${runtime} ${probe}`) !== undefined;
19
22
  }
20
23
  /**
21
24
  * Determines the REAL engine behind a command, or undefined if the engine is
@@ -30,7 +33,7 @@ function detectEngine(command) {
30
33
  return 'podman';
31
34
  }
32
35
  if (isAvailable(command))
33
- return 'docker';
36
+ return command;
34
37
  return undefined;
35
38
  }
36
39
  function podmanSocketPath() {
@@ -130,14 +133,14 @@ function buildRuntime(name) {
130
133
  }
131
134
  function parseRuntimeName(value) {
132
135
  const normalized = value.toLowerCase().trim();
133
- if (normalized === 'docker' || normalized === 'podman')
136
+ if (normalized === 'docker' || normalized === 'podman' || normalized === 'wslc')
134
137
  return normalized;
135
- throw new Error(`Unknown container runtime: ${value}. Choose docker or podman.`);
138
+ throw new Error(`Unknown container runtime: ${value}. Choose docker, podman or wslc.`);
136
139
  }
137
140
  /**
138
141
  * Determines which container runtime to use.
139
142
  * An explicit choice (via --runtime or HUDDLE_RUNTIME) wins; otherwise it is
140
- * auto-detected: Docker first, then Podman.
143
+ * auto-detected: Docker first, then Podman, then wslc.
141
144
  */
142
145
  function resolveRuntime(explicit) {
143
146
  const requested = explicit ?? process.env.HUDDLE_RUNTIME;
@@ -148,12 +151,13 @@ function resolveRuntime(explicit) {
148
151
  }
149
152
  return buildRuntime(name);
150
153
  }
151
- // Auto-detection: first look behind the `docker` command (which may be a
152
- // Podman shim), then at `podman`. This way a real Docker engine wins if there
153
- // is one, but we also recognize Podman when it poses as `docker`.
154
- const detected = detectEngine('docker') ?? detectEngine('podman');
154
+ // Auto-detection: first look behind the docker command (which may be a
155
+ // Podman shim or Docker), then at podman, and finally at wslc. This way a
156
+ // real Docker engine wins if there is one, while we also recognize Podman when
157
+ // it poses as docker and fall back to wslc when neither is available.
158
+ const detected = detectEngine('docker') ?? detectEngine('podman') ?? detectEngine('wslc');
155
159
  if (detected)
156
160
  return buildRuntime(detected);
157
- throw new Error('No working container runtime found. Install and start Docker or Podman,\n' +
158
- 'or pick one explicitly with --runtime <docker|podman> or the HUDDLE_RUNTIME env var.');
161
+ throw new Error('No working container runtime found. Install and start Docker, Podman or wslc,\n' +
162
+ 'or pick one explicitly with --runtime <docker|podman|wslc> or the HUDDLE_RUNTIME env var.');
159
163
  }
package/dist/start.js CHANGED
@@ -8,6 +8,9 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const api_1 = require("./api");
10
10
  const utils_1 = require("./utils");
11
+ const vscode_1 = require("./vscode");
12
+ const base_images_1 = require("./base-images");
13
+ const runtime_1 = require("./runtime");
11
14
  async function runStart(opts) {
12
15
  const ide = parseIde(opts.ide);
13
16
  const hasMounts = !!opts.mounts && opts.mounts.length > 0;
@@ -73,16 +76,66 @@ async function runStart(opts) {
73
76
  else {
74
77
  body.workspaceDir = workspaceDir;
75
78
  }
79
+ // Our base images are built on this machine; make sure this one exists before the
80
+ // gateway starts the container (it would otherwise build it inside the request).
81
+ let rt;
82
+ try {
83
+ rt = (0, runtime_1.resolveRuntime)().name;
84
+ }
85
+ catch {
86
+ // No local container runtime (e.g. HUDDLE_URL points elsewhere): leave it to the gateway.
87
+ }
88
+ if (rt)
89
+ await (0, base_images_1.ensureImageForStart)(rt, ide, imageName);
76
90
  const result = await (0, api_1.post)('/api/docker/start', body);
77
91
  console.log((0, utils_1.green)(`[OK] Container started: ${result.containerName} (${result.id.slice(0, 12)})`));
78
92
  console.log();
79
93
  if (ide === 'vscode') {
94
+ const containerWorkspace = result.containerWorkspace ?? containerWorkspacePath(workspaceDir, containerName);
95
+ if (opts.vscodeConfig !== false) {
96
+ configureVscodeAttach(containerName, containerWorkspace, imageName);
97
+ }
80
98
  console.log(`Open in VS Code: ${(0, utils_1.cyan)('Dev Containers: Attach to Running Container')} -> ${(0, utils_1.bold)(result.containerName)}`);
81
99
  return;
82
100
  }
83
101
  console.log(`Open in JetBrains Gateway: ${(0, utils_1.cyan)('Remote Development > Dev Containers')} -> ${(0, utils_1.bold)(result.containerName)}`);
84
102
  await tryPrintIdeLink(result.containerName);
85
103
  }
104
+ /**
105
+ * Teach VS Code which folder to open on attach. Best-effort: a failure here
106
+ * costs one manual File > Open Folder, never the container itself.
107
+ */
108
+ function configureVscodeAttach(containerName, containerWorkspace, imageName) {
109
+ let result;
110
+ try {
111
+ result = (0, vscode_1.writeAttachedContainerConfig)(containerName, containerWorkspace);
112
+ }
113
+ catch (err) {
114
+ console.log((0, utils_1.yellow)(`! Could not configure VS Code: ${err instanceof Error ? err.message : String(err)}`));
115
+ return;
116
+ }
117
+ for (const file of result.written) {
118
+ console.log((0, utils_1.dim)(`VS Code will open ${containerWorkspace} on attach (${file})`));
119
+ }
120
+ for (const { file, reason } of result.skipped) {
121
+ console.log((0, utils_1.yellow)(`! Left ${file} untouched: ${reason}`));
122
+ }
123
+ if (!result.written.length && !result.skipped.length) {
124
+ console.log((0, utils_1.dim)('No VS Code config changes were made; if attach opens an empty window, use File > Open Folder on the container workspace.'));
125
+ }
126
+ // The name-level config above wins for THIS container, but a leftover
127
+ // image-level one still misdirects every other container on the same image.
128
+ for (const file of (0, vscode_1.findImageConfigs)(imageName)) {
129
+ console.log((0, utils_1.yellow)(`! Image-level config still present: ${file} (applies to every container from this image; consider deleting it)`));
130
+ }
131
+ }
132
+ /** Mirrors the gateway's containerWorkspacePath() for gateways that predate it. */
133
+ function containerWorkspacePath(workspaceDir, containerName) {
134
+ const leaf = workspaceDir
135
+ ? workspaceDir.replace(/\\/g, '/').replace(/\/$/, '').split('/').pop() || containerName
136
+ : containerName.replace(/^devcontainer-/, '') || containerName;
137
+ return `/workspaces/${leaf}`;
138
+ }
86
139
  async function tryPrintIdeLink(containerName) {
87
140
  await new Promise((resolve) => setTimeout(resolve, 3000));
88
141
  try {
package/dist/vscode.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.writeAttachedContainerConfig = writeAttachedContainerConfig;
7
+ exports.findImageConfigs = findImageConfigs;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const child_process_1 = require("child_process");
12
+ /**
13
+ * VS Code's "Attach to Running Container" decides which folder to open from an
14
+ * *attached container configuration file* on the host, and from nothing else:
15
+ * the Dev Containers extension reads `nameConfigs/<container>.json` first and
16
+ * falls back to `imageConfigs/<image>.json`; when neither holds a
17
+ * `workspaceFolder` it opens an empty window. Container labels play no part in
18
+ * that decision — `devcontainer.metadata` is only consumed by the build flow,
19
+ * and its merge drops every property outside the image-metadata spec (which
20
+ * does not include `workspaceFolder`).
21
+ *
22
+ * So huddle writes the per-container config itself. Per container, never per
23
+ * image: an image-level file would pin one workspace path for every container
24
+ * started from the same base image.
25
+ */
26
+ const EXT_DIR = 'ms-vscode-remote.remote-containers';
27
+ /** VS Code's own escaping for config file names (see `nameConfigs` lookup). */
28
+ function encodeConfigName(containerName) {
29
+ return containerName.replace(/[:/%]/g, (c) => `%${c.charCodeAt(0).toString(16)}`);
30
+ }
31
+ /**
32
+ * User-data directories of the installed VS Code flavours — the directory that
33
+ * holds `User/`, i.e. what `code --user-data-dir` points at. Insiders keeps its
34
+ * own tree, and a Flatpak install relocates the whole thing.
35
+ */
36
+ function userDataDirCandidates() {
37
+ const override = process.env.HUDDLE_VSCODE_USER_DIR?.trim();
38
+ if (override)
39
+ return [override];
40
+ const home = os_1.default.homedir();
41
+ const dirs = [];
42
+ if (process.platform === 'win32') {
43
+ const appData = process.env.APPDATA ?? path_1.default.join(home, 'AppData', 'Roaming');
44
+ dirs.push(path_1.default.join(appData, 'Code'), path_1.default.join(appData, 'Code - Insiders'));
45
+ }
46
+ else if (process.platform === 'darwin') {
47
+ const support = path_1.default.join(home, 'Library', 'Application Support');
48
+ dirs.push(path_1.default.join(support, 'Code'), path_1.default.join(support, 'Code - Insiders'));
49
+ }
50
+ else {
51
+ dirs.push(path_1.default.join(home, '.config', 'Code'), path_1.default.join(home, '.config', 'Code - Insiders'));
52
+ dirs.push(path_1.default.join(home, '.var', 'app', 'com.visualstudio.code', 'config', 'Code'));
53
+ dirs.push(path_1.default.join(home, '.var', 'app', 'com.visualstudio.code.insiders', 'config', 'Code - Insiders'));
54
+ // On WSL the CLI runs in the distro while VS Code runs on Windows and reads
55
+ // its config from %APPDATA% there, so the Linux paths above would never be
56
+ // seen by the editor doing the attach.
57
+ for (const appData of windowsAppDataFromWsl()) {
58
+ dirs.push(path_1.default.join(appData, 'Code'), path_1.default.join(appData, 'Code - Insiders'));
59
+ }
60
+ }
61
+ return dirs;
62
+ }
63
+ /** Best-effort %APPDATA% as seen from inside WSL; empty when not on WSL. */
64
+ function windowsAppDataFromWsl() {
65
+ try {
66
+ if (!fs_1.default.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft'))
67
+ return [];
68
+ const appData = (0, child_process_1.execFileSync)('cmd.exe', ['/c', 'echo %APPDATA%'], {
69
+ encoding: 'utf8',
70
+ stdio: ['ignore', 'pipe', 'ignore'],
71
+ cwd: '/',
72
+ }).trim();
73
+ if (!appData || appData.includes('%APPDATA%'))
74
+ return [];
75
+ const unix = (0, child_process_1.execFileSync)('wslpath', ['-u', appData], {
76
+ encoding: 'utf8',
77
+ stdio: ['ignore', 'pipe', 'ignore'],
78
+ }).trim();
79
+ return unix ? [unix] : [];
80
+ }
81
+ catch {
82
+ // No WSL interop (or cmd.exe/wslpath missing): nothing to configure there.
83
+ return [];
84
+ }
85
+ }
86
+ /**
87
+ * Point every installed VS Code flavour at `workspaceFolder` when attaching to
88
+ * `containerName`. Only flavours that already have a `User/globalStorage` tree
89
+ * are touched — creating that tree for an editor that is not installed would
90
+ * leave dead config behind.
91
+ */
92
+ function writeAttachedContainerConfig(containerName, workspaceFolder) {
93
+ const result = { written: [], skipped: [] };
94
+ for (const userDataDir of userDataDirCandidates()) {
95
+ const globalStorage = path_1.default.join(userDataDir, 'User', 'globalStorage');
96
+ if (!fs_1.default.existsSync(globalStorage))
97
+ continue;
98
+ const file = path_1.default.join(globalStorage, EXT_DIR, 'nameConfigs', `${encodeConfigName(containerName)}.json`);
99
+ let config = {};
100
+ if (fs_1.default.existsSync(file)) {
101
+ try {
102
+ const parsed = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
103
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
104
+ config = parsed;
105
+ }
106
+ }
107
+ catch {
108
+ // Hand-edited file with comments or a syntax error: leave it alone
109
+ // rather than throw away settings the user put there.
110
+ result.skipped.push({ file, reason: 'existing config is not valid JSON' });
111
+ continue;
112
+ }
113
+ if (config.workspaceFolder === workspaceFolder)
114
+ continue;
115
+ }
116
+ config.workspaceFolder = workspaceFolder;
117
+ try {
118
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
119
+ // Tab indentation matches what the extension itself writes back into
120
+ // this file when you open another folder inside the container.
121
+ fs_1.default.writeFileSync(file, `${JSON.stringify(config, null, '\t')}\n`);
122
+ result.written.push(file);
123
+ }
124
+ catch (err) {
125
+ result.skipped.push({ file, reason: err instanceof Error ? err.message : String(err) });
126
+ }
127
+ }
128
+ return result;
129
+ }
130
+ /**
131
+ * An image-level config outranks nothing (the name-level file wins) but it does
132
+ * apply to every other container from the same base image, where its workspace
133
+ * path does not exist. Report it so the operator can clean it up.
134
+ */
135
+ function findImageConfigs(imageName) {
136
+ const encoded = encodeConfigName(imageName);
137
+ const found = [];
138
+ for (const userDataDir of userDataDirCandidates()) {
139
+ const file = path_1.default.join(userDataDir, 'User', 'globalStorage', EXT_DIR, 'imageConfigs', `${encoded}.json`);
140
+ if (fs_1.default.existsSync(file))
141
+ found.push(file);
142
+ }
143
+ return found;
144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-137.147.1",
3
+ "version": "0.0.0-experiment-137.149.1",
4
4
  "description": "Huddle CLI — start devcontainers and manage firewall rules",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Info Support B.V.",