-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathupdate.ts
481 lines (410 loc) · 15.1 KB
/
update.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import {Config, Interfaces, ux} from '@oclif/core'
import {green, yellow} from 'ansis'
import makeDebug from 'debug'
import fileSize from 'filesize'
import {got, HTTPError} from 'got'
import {existsSync, Stats} from 'node:fs'
import {mkdir, readdir, readFile, rm, stat, symlink, utimes, writeFile} from 'node:fs/promises'
import {basename, dirname, join} from 'node:path'
import {ProxyAgent} from 'proxy-agent'
import {Extractor} from './tar.js'
import {ls, wait} from './util.js'
const debug = makeDebug('oclif:update')
const filesize = (n: number): string => {
const [num, suffix] = fileSize(n, {output: 'array'})
return Number.parseFloat(num).toFixed(1) + ` ${suffix}`
}
async function httpGet<T>(url: string) {
debug(`[${url}] GET`)
return got
.get<T>(url, {
agent: {https: new ProxyAgent()},
})
.then((res) => {
debug(`[${url}] ${res.statusCode}`)
return res
})
.catch((error) => {
debug(`[${url}] ${error.response?.statusCode ?? error.code}`)
// constructing a new HTTPError here will produce a more actionable stack trace
debug(new HTTPError(error.response))
throw error
})
}
type Options = {
autoUpdate: boolean
channel?: string | undefined
force?: boolean
version?: string | undefined
}
type VersionIndex = Record<string, string>
export class Updater {
private readonly clientBin: string
private readonly clientRoot: string
constructor(private config: Config) {
this.clientRoot = config.scopedEnvVar('OCLIF_CLIENT_HOME') ?? join(config.dataDir, 'client')
this.clientBin = join(this.clientRoot, 'bin', config.windows ? `${config.bin}.cmd` : config.bin)
}
public async fetchVersionIndex(): Promise<VersionIndex> {
const newIndexUrl = this.config.s3Url(s3VersionIndexKey(this.config))
try {
const {body} = await httpGet<VersionIndex>(newIndexUrl)
return typeof body === 'string' ? JSON.parse(body) : body
} catch {
throw new Error(`No version indices exist for ${this.config.name}.`)
}
}
public async findLocalVersions(): Promise<string[]> {
await ensureClientDir(this.clientRoot)
const dirOrFiles = await readdir(this.clientRoot)
return dirOrFiles
.filter((dirOrFile) => dirOrFile !== 'bin' && dirOrFile !== 'current')
.map((f) => join(this.clientRoot, f))
}
public async runUpdate(options: Options): Promise<void> {
const {autoUpdate, force = false, version} = options
if (autoUpdate) await debounce(this.config.cacheDir)
ux.action.start(`${this.config.name}: Updating CLI`)
if (notUpdatable(this.config)) {
ux.action.stop('not updatable')
return
}
const [channel, current] = await Promise.all([
options.channel ?? determineChannel({config: this.config, version}),
determineCurrentVersion(this.clientBin, this.config.version),
])
if (version) {
const localVersion = force ? null : await this.findLocalVersion(version)
if (alreadyOnVersion(current, localVersion || null)) {
ux.action.stop(this.config.scopedEnvVar('HIDE_UPDATED_MESSAGE') ? 'done' : `already on version ${current}`)
return
}
await this.config.runHook('preupdate', {channel, version})
if (localVersion) {
await this.updateToExistingVersion(current, localVersion)
} else {
ux.action.status = 'fetching version index'
const index = await this.fetchVersionIndex()
const url = index[version]
if (!url) {
throw new Error(`${version} not found in index:\n${Object.keys(index).join(', ')}`)
}
const manifest = await this.fetchVersionManifest(version, url)
const updated = manifest.sha ? `${manifest.version}-${manifest.sha}` : manifest.version
await this.update(manifest, current, updated, force, channel)
}
await this.config.runHook('update', {channel, version})
ux.action.stop()
ux.stdout()
ux.stdout(
`Updating to a specific version will not update the channel. If autoupdate is enabled, the CLI will eventually be updated back to ${channel}.`,
)
} else {
const manifest = await fetchChannelManifest(channel, this.config)
const updated = manifest.sha ? `${manifest.version}-${manifest.sha}` : manifest.version
if (!force && alreadyOnVersion(current, updated)) {
ux.action.stop(this.config.scopedEnvVar('HIDE_UPDATED_MESSAGE') ? 'done' : `already on version ${current}`)
} else {
await this.config.runHook('preupdate', {channel, version: updated})
await this.update(manifest, current, updated, force, channel)
}
await this.config.runHook('update', {channel, version: updated})
ux.action.stop()
}
await this.touch()
await this.tidy()
debug('done')
}
private async createBin(version: string): Promise<void> {
const dst = this.clientBin
const {bin, windows} = this.config
const binPathEnvVar = this.config.scopedEnvVarKey('BINPATH')
const redirectedEnvVar = this.config.scopedEnvVarKey('REDIRECTED')
await mkdir(dirname(dst), {recursive: true})
if (windows) {
const body = `@echo off
setlocal enableextensions
set ${redirectedEnvVar}=1
set ${binPathEnvVar}=%~dp0${bin}
"%~dp0..\\${version}\\bin\\${bin}.cmd" %*
`
await writeFile(dst, body)
} else {
/* eslint-disable no-useless-escape */
const body = `#!/usr/bin/env bash
set -e
get_script_dir () {
SOURCE="\${BASH_SOURCE[0]}"
# While $SOURCE is a symlink, resolve it
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$( readlink "$SOURCE" )"
# If $SOURCE was a relative symlink (so no "/" as prefix, need to resolve it relative to the symlink base directory
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
echo "$DIR"
}
DIR=$(get_script_dir)
${binPathEnvVar}="\$DIR/${bin}" ${redirectedEnvVar}=1 "$DIR/../${version}/bin/${bin}" "$@"
`
/* eslint-enable no-useless-escape */
await writeFile(dst, body, {mode: 0o755})
await rm(join(this.clientRoot, 'current'), {force: true, recursive: true})
await symlink(`./${version}`, join(this.clientRoot, 'current'))
}
}
private async fetchVersionManifest(version: string, url: string): Promise<Interfaces.S3Manifest> {
const parts = url.split('/')
const hashIndex = parts.indexOf(version) + 1
const hash = parts[hashIndex]
const s3Key = s3VersionManifestKey({config: this.config, hash, version})
return fetchManifest(s3Key, this.config)
}
private async findLocalVersion(version: string): Promise<string | undefined> {
const versions = await this.findLocalVersions()
return versions.map((file) => basename(file)).find((file) => file.startsWith(version))
}
private async refreshConfig(version: string): Promise<void> {
this.config = await Config.load({root: join(this.clientRoot, version)})
}
// removes any unused CLIs
private async tidy(): Promise<void> {
debug('tidy')
try {
const root = this.clientRoot
if (!existsSync(root)) return
const files = await ls(root)
const isNotSpecial = (fPath: string, version: string): boolean =>
!['bin', 'current', version].includes(basename(fPath))
const isOld = (fStat: Stats): boolean => {
const {mtime} = fStat
mtime.setHours(mtime.getHours() + 42 * 24)
return mtime < new Date()
}
await Promise.all(
files
.filter((f) => isNotSpecial(this.config.version, f.path) && isOld(f.stat))
.map((f) => rm(f.path, {force: true, recursive: true})),
)
} catch (error: unknown) {
ux.warn(error as Error | string)
}
}
private async touch(): Promise<void> {
// touch the client so it won't be tidied up right away
try {
const p = join(this.clientRoot, this.config.version)
debug('touching client at', p)
if (!existsSync(p)) return
return utimes(p, new Date(), new Date())
} catch (error: unknown) {
ux.warn(error as Error | string)
}
}
// eslint-disable-next-line max-params
private async update(
manifest: Interfaces.S3Manifest,
current: string,
updated: string,
force: boolean,
channel: string,
) {
ux.action.start(
`${this.config.name}: Updating CLI from ${green(current)} to ${green(updated)}${
channel === 'stable' ? '' : ' (' + yellow(channel) + ')'
}`,
)
await ensureClientDir(this.clientRoot)
const output = join(this.clientRoot, updated)
if (force || !existsSync(output)) await downloadAndExtract(output, manifest, channel, this.config)
await this.refreshConfig(updated)
await setChannel(channel, this.config.dataDir)
await this.createBin(updated)
}
private async updateToExistingVersion(current: string, updated: string): Promise<void> {
ux.action.start(`${this.config.name}: Updating CLI from ${green(current)} to ${green(updated)}`)
await ensureClientDir(this.clientRoot)
await this.refreshConfig(updated)
await this.createBin(updated)
}
}
const alreadyOnVersion = (current: string, updated: null | string): boolean => current === updated
const ensureClientDir = async (clientRoot: string): Promise<void> => {
try {
await mkdir(clientRoot, {recursive: true})
} catch (error: unknown) {
const {code} = error as {code: string}
if (code === 'EEXIST') {
// for some reason the client directory is sometimes a file
// if so, this happens. Delete it and recreate
await rm(clientRoot, {force: true, recursive: true})
await mkdir(clientRoot, {recursive: true})
} else {
throw error
}
}
}
const mtime = async (f: string): Promise<Date> => (await stat(f)).mtime
const notUpdatable = (config: Config): boolean => {
if (!config.binPath) {
const instructions = config.scopedEnvVar('UPDATE_INSTRUCTIONS')
if (instructions) {
ux.warn(instructions)
// once the spinner stops, it'll eat this blank line
// https://github.com/oclif/core/issues/799
ux.stdout()
}
return true
}
return false
}
const composeS3SubDir = (config: Config): string => {
let s3SubDir = config.pjson.oclif.update?.s3?.folder || ''
if (s3SubDir !== '' && s3SubDir.slice(-1) !== '/') s3SubDir = `${s3SubDir}/`
return s3SubDir
}
const fetchManifest = async (s3Key: string, config: Config): Promise<Interfaces.S3Manifest> => {
ux.action.status = 'fetching manifest'
const url = config.s3Url(s3Key)
const {body} = await httpGet<Interfaces.S3Manifest | string>(url)
if (typeof body === 'string') {
return JSON.parse(body)
}
return body
}
const s3VersionIndexKey = (config: Config): string => {
const {arch, bin} = config
const s3SubDir = composeS3SubDir(config)
return join(s3SubDir, 'versions', `${bin}-${determinePlatform(config)}-${arch}-tar-gz.json`)
}
const determinePlatform = (config: Config): Interfaces.PlatformTypes =>
config.platform === 'wsl' ? 'linux' : config.platform
const s3ChannelManifestKey = (channel: string, config: Config): string => {
const {arch, bin} = config
const s3SubDir = composeS3SubDir(config)
return join(s3SubDir, 'channels', channel, `${bin}-${determinePlatform(config)}-${arch}-buildmanifest`)
}
const s3VersionManifestKey = ({config, hash, version}: {config: Config; hash: string; version: string}): string => {
const {arch, bin} = config
const s3SubDir = composeS3SubDir(config)
return join(
s3SubDir,
'versions',
version,
hash,
`${bin}-v${version}-${hash}-${determinePlatform(config)}-${arch}-buildmanifest`,
)
}
// when autoupdating, wait until the CLI isn't active
const debounce = async (cacheDir: string): Promise<void> => {
let output = false
const lastrunfile = join(cacheDir, 'lastrun')
const m = await mtime(lastrunfile)
m.setHours(m.getHours() + 1)
if (m > new Date()) {
const msg = `waiting until ${m.toISOString()} to update`
if (output) {
debug(msg)
} else {
ux.stdout(msg)
output = true
}
await wait(60 * 1000) // wait 1 minute
return debounce(cacheDir)
}
ux.stdout('time to update')
}
const setChannel = async (channel: string, dataDir: string): Promise<void> =>
writeFile(join(dataDir, 'channel'), channel, 'utf8')
const fetchChannelManifest = async (channel: string, config: Config): Promise<Interfaces.S3Manifest> => {
const s3Key = s3ChannelManifestKey(channel, config)
try {
return await fetchManifest(s3Key, config)
} catch (error: unknown) {
const {code, statusCode} = error as {code?: string; statusCode?: number}
if (statusCode === 403 || code === 'ERR_NON_2XX_3XX_RESPONSE')
throw new Error(`HTTP 403: Invalid channel ${channel}`)
throw error
}
}
const downloadAndExtract = async (
output: string,
manifest: Interfaces.S3Manifest,
channel: string,
config: Config,
): Promise<void> => {
const {gz, sha256gz, version} = manifest
const gzUrl =
gz ??
config.s3Url(
config.s3Key('versioned', {
arch: config.arch,
bin: config.bin,
channel,
ext: 'gz',
platform: determinePlatform(config),
version,
}),
)
debug(`Streaming ${gzUrl} to ${output}`)
const stream = got.stream(gzUrl, {
agent: {https: new ProxyAgent()},
})
stream.pause()
const baseDir =
manifest.baseDir ??
config.s3Key('baseDir', {
arch: config.arch,
bin: config.bin,
channel,
platform: determinePlatform(config),
version,
})
const extraction = Extractor.extract(stream, baseDir, output, sha256gz)
if (ux.action.type === 'spinner') {
stream.on('downloadProgress', (progress) => {
ux.action.status =
progress.percent === 1
? `${filesize(progress.transferred)}/${filesize(progress.total)} - Finishing up...`
: `${filesize(progress.transferred)}/${filesize(progress.total)}`
})
}
stream.resume()
await extraction
}
const determineChannel = async ({config, version}: {config: Config; version?: string}): Promise<string> => {
ux.action.status = version ? `Determining channel for ${version}` : 'Determining channel'
const channelPath = join(config.dataDir, 'channel')
const channel = existsSync(channelPath) ? (await readFile(channelPath, 'utf8')).trim() : 'stable'
if (config.pjson.oclif.update?.disableNpmLookup ?? false) {
return channel
}
try {
const {body} = await httpGet<{'dist-tags': Record<string, string>}>(
`${config.npmRegistry ?? 'https://registry.npmjs.org'}/${config.pjson.name}`,
)
const tags = body['dist-tags']
const tag = Object.keys(tags).find((v) => tags[v] === version) ?? channel
// convert from npm style tag defaults to OCLIF style
if (tag === 'latest') return 'stable'
if (tag === 'latest-rc') return 'stable-rc'
return tag
} catch {
return channel
}
}
const determineCurrentVersion = async (clientBin: string, version: string): Promise<string> => {
try {
const currentVersion = await readFile(clientBin, 'utf8')
const matches = currentVersion.match(/\.\.[/\\|](.+)[/\\|]bin/)
return matches ? matches[1] : version
} catch (error) {
if (error instanceof Error) {
debug(error.name, error.message)
} else if (typeof error === 'string') {
debug(error)
}
}
return version
}