ghusage 0.1.1 → 0.1.3

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.
Files changed (3) hide show
  1. package/README.md +14 -6
  2. package/package.json +7 -7
  3. package/src/cli.js +336 -12
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  **Know what you actually did on GitHub.**
4
4
 
5
+ 日本語のドキュメント: <https://ghusage.under18.dev/ja/>
6
+
5
7
  `ghusage` is a command-line tool and terminal UI that analyzes a developer's
6
8
  GitHub activity. It goes beyond contribution graphs and treats a pull request
7
9
  as a process: the commits in it, the reviews and their states, inline review
@@ -64,11 +66,17 @@ You only install `ghusage`. It is a small launcher; npm also installs the
64
66
  prebuilt native binary for your OS and CPU (one of the `@ghusage/ghusage-*`
65
67
  packages, as an optional dependency) and the launcher runs it. Supported
66
68
  platforms: macOS (Apple Silicon, Intel), Linux (x64, arm64; statically
67
- linked) and Windows (x64, arm64). Node.js 18 or newer is required. If your
68
- package manager skips optional dependencies (`--omit=optional`) or a minimum
69
- release age setting holds the binary package back, `ghusage` exits with an
70
- explanation. `GHUSAGE_BINARY` can point the
71
- launcher at a binary you built yourself.
69
+ linked) and Windows (x64, arm64). Node.js 18 or newer is required. Update
70
+ with `npm install -g ghusage@latest`.
71
+
72
+ If npm did not install the binary package (for example `--omit=optional`, a
73
+ minimum release age setting, or a registry proxy that does not serve the new
74
+ version yet), the launcher fetches it on first run with `npm pack`, using your
75
+ npm configuration, and keeps it in a per-user cache. Set
76
+ `GHUSAGE_NO_AUTO_INSTALL=1` to turn this off. If that fails, `ghusage` exits
77
+ with an explanation; see
78
+ [Missing native package](https://ghusage.under18.dev/guide/getting-started#missing-native-package).
79
+ `GHUSAGE_BINARY` can point the launcher at a binary you built yourself.
72
80
 
73
81
  ### From source
74
82
 
@@ -169,7 +177,7 @@ every command. See the [CLI reference](docs/reference/cli.md).
169
177
  ## Documentation
170
178
 
171
179
  The full documentation lives in [`docs/`](docs/index.md) and is built as the
172
- documentation site at <https://tanahiro2010.github.io/ghusage/>.
180
+ documentation site at <https://ghusage.under18.dev/>.
173
181
 
174
182
  - [Getting started](docs/guide/getting-started.md)
175
183
  - [Authentication](docs/guide/authentication.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ghusage",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Know what you actually did on GitHub: commits, pull requests, reviews and the activity inside pull requests.",
5
5
  "keywords": [
6
6
  "github",
@@ -31,11 +31,11 @@
31
31
  "access": "public"
32
32
  },
33
33
  "optionalDependencies": {
34
- "@ghusage/ghusage-darwin-arm64": "0.1.1",
35
- "@ghusage/ghusage-darwin-x64": "0.1.1",
36
- "@ghusage/ghusage-linux-arm64": "0.1.1",
37
- "@ghusage/ghusage-linux-x64": "0.1.1",
38
- "@ghusage/ghusage-win32-arm64": "0.1.1",
39
- "@ghusage/ghusage-win32-x64": "0.1.1"
34
+ "@ghusage/ghusage-darwin-arm64": "0.1.3",
35
+ "@ghusage/ghusage-darwin-x64": "0.1.3",
36
+ "@ghusage/ghusage-linux-arm64": "0.1.3",
37
+ "@ghusage/ghusage-linux-x64": "0.1.3",
38
+ "@ghusage/ghusage-win32-arm64": "0.1.3",
39
+ "@ghusage/ghusage-win32-x64": "0.1.3"
40
40
  }
41
41
  }
package/src/cli.js CHANGED
@@ -1,11 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  // Runs the native ghusage binary from the platform package that npm
3
- // installed as an optional dependency.
4
- import { spawn } from "node:child_process";
5
- import { chmodSync, realpathSync, statSync } from "node:fs";
3
+ // installed as an optional dependency. When that package is missing, the
4
+ // launcher fetches it once with `npm pack` (so the user's npm registry,
5
+ // proxy, authentication and integrity checks apply) and keeps the binary in
6
+ // a per-user cache.
7
+ import { spawn, spawnSync } from "node:child_process";
8
+ import {
9
+ chmodSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ mkdtempSync,
13
+ readdirSync,
14
+ readFileSync,
15
+ realpathSync,
16
+ renameSync,
17
+ rmSync,
18
+ statSync,
19
+ writeFileSync,
20
+ } from "node:fs";
6
21
  import { createRequire } from "node:module";
22
+ import os from "node:os";
23
+ import path from "node:path";
7
24
  import process from "node:process";
8
25
  import { fileURLToPath } from "node:url";
26
+ import { gunzipSync } from "node:zlib";
9
27
 
10
28
  const require = createRequire(import.meta.url);
11
29
  const { version } = require("../package.json");
@@ -19,6 +37,11 @@ const PACKAGES = {
19
37
  "win32-x64": "@ghusage/ghusage-win32-x64",
20
38
  };
21
39
 
40
+ const PUBLIC_REGISTRY = "https://registry.npmjs.org";
41
+ // Upper bounds for a fetched package; the real ones are a few MB.
42
+ const MAX_UNPACKED_BYTES = 512 * 1024 * 1024;
43
+ const PACK_TIMEOUT_MS = 5 * 60 * 1000;
44
+
22
45
  /** Name of the platform package for this platform, if one exists. */
23
46
  export function nativePackageName(platform = process.platform, arch = process.arch) {
24
47
  return PACKAGES[`${platform}-${arch}`];
@@ -29,9 +52,61 @@ export function nativeBinarySubpath(platform = process.platform) {
29
52
  return platform === "win32" ? "bin/ghusage.exe" : "bin/ghusage";
30
53
  }
31
54
 
55
+ /** Explains a missing platform package and how to get it back. */
56
+ export function missingPackageMessage({
57
+ pkg,
58
+ target,
59
+ launcherVersion = version,
60
+ fetchError,
61
+ autoInstallDisabled = false,
62
+ }) {
63
+ const spec = `${pkg}@${launcherVersion}`;
64
+ const lines = [
65
+ `ghusage: the native binary for ${target} is missing.`,
66
+ "",
67
+ `ghusage@${launcherVersion} runs its binary from the optional package "${spec}",`,
68
+ "but npm did not install it.",
69
+ ];
70
+ if (autoInstallDisabled) {
71
+ lines.push("Fetching it automatically is turned off (GHUSAGE_NO_AUTO_INSTALL).");
72
+ } else if (fetchError) {
73
+ lines.push("Fetching it automatically with `npm pack` failed:");
74
+ for (const l of String(fetchError).trim().split(/\r?\n/).slice(0, 8)) lines.push(` ${l}`);
75
+ }
76
+ lines.push(
77
+ "",
78
+ "Possible causes:",
79
+ " - The release was published moments ago and your registry does not serve the",
80
+ " platform package yet.",
81
+ " - A registry proxy, mirror or security tool configured as your npm registry",
82
+ " holds new versions back.",
83
+ " - Optional dependencies were skipped (--omit=optional, --no-optional).",
84
+ " - A minimum release age setting (npm --before / --min-release-age,",
85
+ " mise minimum_release_age) held the platform package back.",
86
+ "",
87
+ "How to fix:",
88
+ " 1. Reinstall the same version so npm installs the platform package:",
89
+ ` npm uninstall -g ghusage && npm install -g ghusage@${launcherVersion}`,
90
+ " 2. Check which registry npm uses:",
91
+ " npm config get registry",
92
+ ` If it is a proxy or mirror rather than ${PUBLIC_REGISTRY}/, wait until it`,
93
+ ` serves ${spec}, or install the previous version of ghusage meanwhile`,
94
+ " (list versions with `npm view ghusage versions`):",
95
+ " npm install -g ghusage@<previous version>",
96
+ " 3. Or install from the public npm registry:",
97
+ ` npm install -g ghusage@${launcherVersion} --registry ${PUBLIC_REGISTRY}`,
98
+ " If your organization requires a registry proxy, follow that policy instead.",
99
+ "",
100
+ "To run a binary you built yourself, set GHUSAGE_BINARY to its path.",
101
+ "",
102
+ );
103
+ return lines.join("\n");
104
+ }
105
+
32
106
  /**
33
- * Decides what to run: the native binary, or an error message.
34
- * `GHUSAGE_BINARY` overrides the binary (e.g. one built from source).
107
+ * Decides what to run from what is installed: the `GHUSAGE_BINARY`
108
+ * override, the installed platform package, or an error. A missing
109
+ * platform package also reports `missing` so the caller can fetch it.
35
110
  */
36
111
  export function resolveRuntime({
37
112
  platform = process.platform,
@@ -55,15 +130,263 @@ export function resolveRuntime({
55
130
  return { command: resolvePath(`${pkg}/${nativeBinarySubpath(platform)}`) };
56
131
  } catch {
57
132
  return {
58
- error:
59
- `Missing optional native package "${pkg}@${version}" for ${target}. ` +
60
- "It may be absent because of --omit=optional, --no-optional, or a minimum release age " +
61
- "setting (npm --before / --min-release-age, mise minimum_release_age). " +
62
- "Reinstall ghusage with optional dependencies enabled.\n",
133
+ missing: { pkg, target },
134
+ error: missingPackageMessage({ pkg, target }),
63
135
  };
64
136
  }
65
137
  }
66
138
 
139
+ /** Per-user cache directory of the launcher. `GHUSAGE_CACHE_DIR` overrides it. */
140
+ export function cacheRoot({ platform = process.platform, env = process.env, homedir = os.homedir() } = {}) {
141
+ if (env.GHUSAGE_CACHE_DIR) return path.resolve(env.GHUSAGE_CACHE_DIR);
142
+ if (platform === "darwin") return path.join(homedir, "Library", "Caches", "ghusage");
143
+ if (platform === "win32") {
144
+ const local = env.LOCALAPPDATA || path.join(homedir, "AppData", "Local");
145
+ return path.win32.join(local, "ghusage", "cache");
146
+ }
147
+ const xdg = env.XDG_CACHE_HOME;
148
+ // The XDG spec says relative paths are invalid and must be ignored.
149
+ const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(homedir, ".cache");
150
+ return path.join(base, "ghusage");
151
+ }
152
+
153
+ /** Directory that holds the fetched binary for one version and platform. */
154
+ export function cachedPackageDir({ root, launcherVersion = version, target }) {
155
+ return path.join(root, "native", launcherVersion, target);
156
+ }
157
+
158
+ function isTruthyEnv(value) {
159
+ return value != null && value !== "" && !/^(0|false|no|off)$/i.test(value);
160
+ }
161
+
162
+ /** Rejects archive paths that are absolute or climb out of the archive. */
163
+ function checkArchivePath(name) {
164
+ const p = name.replace(/\\/g, "/");
165
+ if (p.startsWith("/") || /^[A-Za-z]:/.test(p) || p.split("/").includes("..")) {
166
+ throw new Error(`refusing unsafe path in package archive: ${JSON.stringify(name)}`);
167
+ }
168
+ return p.replace(/^\.\//, "");
169
+ }
170
+
171
+ function tarString(buf, start, length) {
172
+ const end = buf.indexOf(0, start);
173
+ return buf.toString("utf8", start, end === -1 || end > start + length ? start + length : end);
174
+ }
175
+
176
+ function tarNumber(buf, start, length) {
177
+ if (buf[start] & 0x80) {
178
+ // Base-256 encoding for large values.
179
+ let n = 0;
180
+ for (let i = start + 1; i < start + length; i++) n = n * 256 + buf[i];
181
+ return n;
182
+ }
183
+ const s = tarString(buf, start, length).trim();
184
+ return s === "" ? 0 : parseInt(s, 8);
185
+ }
186
+
187
+ function parsePax(data) {
188
+ const out = {};
189
+ let i = 0;
190
+ while (i < data.length) {
191
+ const space = data.indexOf(0x20, i);
192
+ if (space === -1) break;
193
+ const len = parseInt(data.toString("utf8", i, space), 10);
194
+ if (!(len > 0)) break;
195
+ const record = data.toString("utf8", space + 1, i + len - 1);
196
+ const eq = record.indexOf("=");
197
+ if (eq !== -1) out[record.slice(0, eq)] = record.slice(eq + 1);
198
+ i += len;
199
+ }
200
+ return out;
201
+ }
202
+
203
+ /**
204
+ * Reads the regular files of a gzip-compressed tar archive (ustar, with
205
+ * pax and GNU long names). Returns a Map from path to contents. Throws on
206
+ * a corrupt archive or an absolute or `..` path.
207
+ */
208
+ export function readTarGz(gz) {
209
+ const tar = gunzipSync(gz, { maxOutputLength: MAX_UNPACKED_BYTES });
210
+ const files = new Map();
211
+ let offset = 0;
212
+ let nextName;
213
+ while (offset + 512 <= tar.length) {
214
+ const header = tar.subarray(offset, offset + 512);
215
+ if (header.every((b) => b === 0)) break;
216
+ let sum = 0;
217
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 0x20 : header[i];
218
+ if (sum !== tarNumber(header, 148, 8)) throw new Error("corrupt package archive (bad header checksum)");
219
+ const size = tarNumber(header, 124, 12);
220
+ const type = String.fromCharCode(header[156] || 0x30);
221
+ const dataStart = offset + 512;
222
+ const dataEnd = dataStart + size;
223
+ if (dataEnd > tar.length) throw new Error("corrupt package archive (truncated)");
224
+ const data = tar.subarray(dataStart, dataEnd);
225
+ offset = dataStart + Math.ceil(size / 512) * 512;
226
+
227
+ if (type === "x") {
228
+ const pax = parsePax(data);
229
+ if (pax.path != null) nextName = pax.path;
230
+ continue;
231
+ }
232
+ if (type === "L") {
233
+ nextName = tarString(data, 0, data.length);
234
+ continue;
235
+ }
236
+ if (type === "g") continue;
237
+
238
+ let name = tarString(header, 0, 100);
239
+ const prefix = header.toString("latin1", 257, 262) === "ustar" ? tarString(header, 345, 155) : "";
240
+ if (prefix) name = `${prefix}/${name}`;
241
+ if (nextName != null) name = nextName;
242
+ nextName = undefined;
243
+ const safe = checkArchivePath(name);
244
+ if (type === "0" || type === "7") files.set(safe, Buffer.from(data));
245
+ }
246
+ return files;
247
+ }
248
+
249
+ /**
250
+ * The first lines of npm's error output (code and reason) and its log path,
251
+ * without control characters (the text may quote a registry response).
252
+ */
253
+ export function summarizeNpmError(stderr) {
254
+ const lines = String(stderr ?? "")
255
+ .split(/\r?\n/)
256
+ .map((l) => l.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trimEnd())
257
+ .filter((l) => l.trim() !== "" && !/^npm (error|ERR!)\s*$/.test(l));
258
+ const head = lines.slice(0, 4);
259
+ const log = lines.slice(4).find((l) => /complete log/i.test(l));
260
+ return (log ? [...head, log] : head).join("\n");
261
+ }
262
+
263
+ function npmInvocation(env, platform) {
264
+ const execpath = env.npm_execpath;
265
+ if (execpath && /^npm-cli\.c?js$/.test(path.basename(execpath))) {
266
+ return { command: process.execPath, prefix: [execpath], shell: false };
267
+ }
268
+ if (platform === "win32") return { command: "npm", prefix: [], shell: true };
269
+ return { command: "npm", prefix: [], shell: false };
270
+ }
271
+
272
+ /**
273
+ * Downloads `<pkg>@<version>` into `dest` with `npm pack`, which honours the
274
+ * user's npm configuration, and returns the path of the tarball.
275
+ */
276
+ export function npmPack({ pkg, version: v, dest, env = process.env, platform = process.platform }) {
277
+ const npm = npmInvocation(env, platform);
278
+ const args = [...npm.prefix, "pack", `${pkg}@${v}`, "--pack-destination", dest, "--ignore-scripts"];
279
+ // Windows runs npm.cmd through the shell: pass one command line, quoting
280
+ // each argument ourselves (paths may contain spaces).
281
+ const [command, commandArgs] = npm.shell
282
+ ? [[npm.command, ...args.map((a) => `"${a}"`)].join(" "), []]
283
+ : [npm.command, args];
284
+ const r = spawnSync(command, commandArgs, {
285
+ env,
286
+ shell: npm.shell,
287
+ encoding: "utf8",
288
+ stdio: ["ignore", "pipe", "pipe"],
289
+ timeout: PACK_TIMEOUT_MS,
290
+ windowsHide: true,
291
+ });
292
+ if (r.error) {
293
+ if (r.error.code === "ENOENT") throw new Error("npm was not found on PATH");
294
+ throw new Error(`could not run npm: ${r.error.message}`);
295
+ }
296
+ if (r.status !== 0) {
297
+ throw new Error(summarizeNpmError(r.stderr) || `npm pack exited with status ${r.status ?? r.signal}`);
298
+ }
299
+ const tgz = readdirSync(dest).filter((f) => f.endsWith(".tgz"));
300
+ if (tgz.length !== 1) throw new Error("npm pack did not produce a package tarball");
301
+ return path.join(dest, tgz[0]);
302
+ }
303
+
304
+ /**
305
+ * Fetches the platform package and places its binary in the cache.
306
+ * Concurrent launchers are safe: each extracts into its own temporary
307
+ * directory and renames it into place; whoever loses the race uses the
308
+ * winner's copy. Returns the path of the binary.
309
+ */
310
+ export function installFromRegistry({
311
+ pkg,
312
+ target,
313
+ platform = process.platform,
314
+ launcherVersion = version,
315
+ root,
316
+ env = process.env,
317
+ pack = npmPack,
318
+ }) {
319
+ const subpath = nativeBinarySubpath(platform);
320
+ const finalDir = cachedPackageDir({ root, launcherVersion, target });
321
+ const versionDir = path.dirname(finalDir);
322
+ mkdirSync(versionDir, { recursive: true, mode: 0o700 });
323
+ const work = mkdtempSync(path.join(versionDir, `.fetch-${process.pid}-`));
324
+ try {
325
+ const downloads = path.join(work, "download");
326
+ mkdirSync(downloads);
327
+ const tgzPath = pack({ pkg, version: launcherVersion, dest: downloads, env, platform });
328
+ const files = readTarGz(readFileSync(tgzPath));
329
+
330
+ const manifest = files.get("package/package.json");
331
+ if (manifest == null) throw new Error("the package has no package.json");
332
+ const meta = JSON.parse(manifest.toString("utf8"));
333
+ if (meta.name !== pkg || meta.version !== launcherVersion) {
334
+ throw new Error(`expected ${pkg}@${launcherVersion} but got ${meta.name}@${meta.version}`);
335
+ }
336
+ const binary = files.get(`package/${subpath}`);
337
+ if (binary == null) throw new Error(`the package has no ${subpath}`);
338
+
339
+ const staged = path.join(work, "pkg");
340
+ mkdirSync(path.join(staged, path.dirname(subpath)), { recursive: true, mode: 0o700 });
341
+ const stagedBinary = path.join(staged, subpath);
342
+ writeFileSync(stagedBinary, binary, { mode: 0o700 });
343
+ if (platform !== "win32") chmodSync(stagedBinary, 0o755);
344
+ writeFileSync(path.join(staged, "package.json"), manifest);
345
+
346
+ try {
347
+ renameSync(staged, finalDir);
348
+ } catch (error) {
349
+ // Another launcher finished first; use its copy if it is complete.
350
+ if (!existsSync(path.join(finalDir, subpath))) throw error;
351
+ }
352
+ return path.join(finalDir, subpath);
353
+ } finally {
354
+ rmSync(work, { recursive: true, force: true });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Decides what to run, fetching the platform package into the cache when
360
+ * npm did not install it. Resolves with `{ command }` or `{ error }`.
361
+ */
362
+ export async function prepareRuntime({
363
+ platform = process.platform,
364
+ arch = process.arch,
365
+ env = process.env,
366
+ resolvePath,
367
+ homedir = os.homedir(),
368
+ launcherVersion = version,
369
+ pack = npmPack,
370
+ stderr = process.stderr,
371
+ } = {}) {
372
+ const runtime = resolveRuntime({ platform, arch, env, resolvePath });
373
+ if (!runtime.missing) return runtime;
374
+ const { pkg, target } = runtime.missing;
375
+ const root = cacheRoot({ platform, env, homedir });
376
+ const cached = path.join(cachedPackageDir({ root, launcherVersion, target }), nativeBinarySubpath(platform));
377
+ if (existsSync(cached)) return { command: cached };
378
+ if (isTruthyEnv(env.GHUSAGE_NO_AUTO_INSTALL)) {
379
+ return { error: missingPackageMessage({ pkg, target, launcherVersion, autoInstallDisabled: true }) };
380
+ }
381
+ stderr.write(`ghusage: fetching ${pkg}@${launcherVersion} ...\n`);
382
+ try {
383
+ return { command: installFromRegistry({ pkg, target, platform, launcherVersion, root, env, pack }) };
384
+ } catch (error) {
385
+ const fetchError = error instanceof Error ? error.message : String(error);
386
+ return { error: missingPackageMessage({ pkg, target, launcherVersion, fetchError }) };
387
+ }
388
+ }
389
+
67
390
  /** Restores the executable bit if a package manager dropped it. */
68
391
  export function ensureExecutable(path, platform = process.platform) {
69
392
  if (platform === "win32") return undefined;
@@ -107,8 +430,9 @@ export function runNative(command, args) {
107
430
  });
108
431
  }
109
432
 
110
- export async function main(argv) {
111
- const runtime = resolveRuntime();
433
+ /** Runs ghusage. `options` are passed to `prepareRuntime` (for tests). */
434
+ export async function main(argv, options = {}) {
435
+ const runtime = await prepareRuntime(options);
112
436
  if ("error" in runtime) {
113
437
  process.stderr.write(runtime.error);
114
438
  return 1;