|
| 1 | +import { spawnSync } from 'node:child_process' |
| 2 | +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' |
| 3 | +import { dirname, join } from 'node:path' |
| 4 | +import { VERSION } from './help.js' |
| 5 | +import type { Output } from './output.js' |
| 6 | +import { readManifest, stateDirectory } from './commands/self.js' |
| 7 | + |
| 8 | +/** |
| 9 | + * Startup update check. |
| 10 | + * |
| 11 | + * Rate-limited rather than run on every invocation: a CLI that makes a network |
| 12 | + * request before each command is a CLI that hangs whenever GitHub is slow, and |
| 13 | + * `diskpush` is the kind of thing people put in a loop. |
| 14 | + */ |
| 15 | +const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000 |
| 16 | +const RELEASES_API = 'https://api.github.com/repos/profullstack/diskpush/releases/latest' |
| 17 | + |
| 18 | +function stampPath(): string { |
| 19 | + return join(stateDirectory(), 'last-update-check') |
| 20 | +} |
| 21 | + |
| 22 | +function readStamp(): number { |
| 23 | + try { |
| 24 | + return Number(readFileSync(stampPath(), 'utf8').trim()) || 0 |
| 25 | + } catch { |
| 26 | + return 0 |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +function writeStamp(): void { |
| 31 | + try { |
| 32 | + mkdirSync(dirname(stampPath()), { recursive: true }) |
| 33 | + writeFileSync(stampPath(), String(Date.now())) |
| 34 | + } catch { |
| 35 | + // A cache we cannot write is a check that runs more often, not an error. |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** Compares dotted versions numerically, so 0.10.0 is newer than 0.9.0. */ |
| 40 | +export function isNewer(candidate: string, current: string): boolean { |
| 41 | + const a = candidate.split('.').map(Number) |
| 42 | + const b = current.split('.').map(Number) |
| 43 | + for (let i = 0; i < Math.max(a.length, b.length); i += 1) { |
| 44 | + const left = a[i] ?? 0 |
| 45 | + const right = b[i] ?? 0 |
| 46 | + if (left !== right) return left > right |
| 47 | + } |
| 48 | + return false |
| 49 | +} |
| 50 | + |
| 51 | +async function latestVersion(timeoutMs = 4000): Promise<string | null> { |
| 52 | + try { |
| 53 | + const response = await fetch(RELEASES_API, { |
| 54 | + headers: { accept: 'application/vnd.github+json', 'user-agent': `diskpush/${VERSION}` }, |
| 55 | + signal: AbortSignal.timeout(timeoutMs), |
| 56 | + }) |
| 57 | + if (!response.ok) return null |
| 58 | + const release = (await response.json()) as { tag_name?: string; draft?: boolean } |
| 59 | + if (!release.tag_name || release.draft) return null |
| 60 | + return release.tag_name.replace(/^v/, '') |
| 61 | + } catch { |
| 62 | + // Offline, rate-limited, slow: none of these should stop the command the |
| 63 | + // user actually typed. |
| 64 | + return null |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export type AutoUpdateOutcome = 'skipped' | 'current' | 'updated' | 'failed' |
| 69 | + |
| 70 | +/** |
| 71 | + * Checks for a newer release and installs it before the requested command |
| 72 | + * runs, so the command executes on the version it just installed. |
| 73 | + * |
| 74 | + * Deliberately does nothing when: the copy was not installed by the installer, |
| 75 | + * output is machine-readable, the command is one where a surprise upgrade |
| 76 | + * would be wrong, or DISKPUSH_NO_AUTO_UPDATE is set. |
| 77 | + */ |
| 78 | +export async function autoUpdate(command: string | null, output: Output, force = false): Promise<AutoUpdateOutcome> { |
| 79 | + if (process.env.DISKPUSH_NO_AUTO_UPDATE) return 'skipped' |
| 80 | + // --json output is parsed by scripts; a progress line in it is a bug. |
| 81 | + if (output.isJson) return 'skipped' |
| 82 | + // Updating inside these would be circular, surprising, or both. |
| 83 | + if (command && ['update', 'upgrade', 'uninstall', 'remove', 'version', 'help', 'doctor'].includes(command)) { |
| 84 | + return 'skipped' |
| 85 | + } |
| 86 | + |
| 87 | + const manifest = readManifest() |
| 88 | + if (!manifest || manifest.method === 'source') return 'skipped' |
| 89 | + |
| 90 | + if (!force && Date.now() - readStamp() < CHECK_INTERVAL_MS) return 'skipped' |
| 91 | + writeStamp() |
| 92 | + |
| 93 | + const latest = await latestVersion() |
| 94 | + if (!latest) return 'skipped' |
| 95 | + if (!isNewer(latest, VERSION)) return 'current' |
| 96 | + |
| 97 | + output.warn(`DiskPush ${latest} is available (you have ${VERSION}). Updating...`) |
| 98 | + |
| 99 | + const script = spawnSync('sh', ['-c', `curl -fsSL ${manifest.installer} || wget -qO- ${manifest.installer}`], { |
| 100 | + encoding: 'utf8', |
| 101 | + maxBuffer: 16 * 1024 * 1024, |
| 102 | + }) |
| 103 | + if (script.status !== 0 || !script.stdout) { |
| 104 | + output.warn('Update check failed to download the installer; continuing on the current version.') |
| 105 | + return 'failed' |
| 106 | + } |
| 107 | + |
| 108 | + const run = spawnSync('sh', ['-s', '--', ...(manifest.desktop ? [] : ['--cli-only'])], { |
| 109 | + input: script.stdout, |
| 110 | + stdio: ['pipe', 'ignore', 'inherit'], |
| 111 | + }) |
| 112 | + if (run.status !== 0) { |
| 113 | + output.warn('Update failed; continuing on the current version.') |
| 114 | + return 'failed' |
| 115 | + } |
| 116 | + |
| 117 | + output.warn(`Updated to ${latest}.`) |
| 118 | + return 'updated' |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Re-runs the original command on the freshly installed version. |
| 123 | + * |
| 124 | + * Without this the process would carry on executing the code it loaded at |
| 125 | + * startup, which is the old version — so the update would appear to have had |
| 126 | + * no effect until the next invocation. |
| 127 | + */ |
| 128 | +export function reexec(): never { |
| 129 | + const manifest = readManifest() |
| 130 | + const binary = manifest ? join(dirname(stateDirectory()), '..', 'bin', 'diskpush') : null |
| 131 | + const target = binary && existsSync(binary) ? binary : process.argv[1] |
| 132 | + |
| 133 | + const result = spawnSync(target!, process.argv.slice(2), { |
| 134 | + stdio: 'inherit', |
| 135 | + env: { ...process.env, DISKPUSH_NO_AUTO_UPDATE: '1' }, |
| 136 | + }) |
| 137 | + process.exit(result.status ?? 0) |
| 138 | +} |
0 commit comments