-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.ts
298 lines (279 loc) · 8.43 KB
/
main.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
import { Temporal } from 'temporal-polyfill'
import * as core from '@actions/core'
import * as cache from '@actions/cache'
import { HttpClient } from '@actions/http-client'
import decompress from 'decompress'
import { exec } from '@actions/exec'
import * as fs from 'node:fs/promises'
import * as os from 'node:os'
import { getProfile } from './tlprofile.js'
type AliveMirror = {
status: 'Alive'
texlive_version: number
revision: number
}
type MirrorData =
| {
status: 'Dead' | 'Timeout'
}
| AliveMirror
type MirrorList = {
[continent: string]: {
[country: string]: {
[mirror: string]: MirrorData
}
}
}
function getMandatoryInput(name: string): string {
return core.getInput(name, { required: true })
}
function getOptionalInput(name: string): string | undefined {
return core.getInput(name) || undefined
}
async function inlineOrFilecontent(
inline: string | undefined,
filename: string | undefined
): Promise<string | undefined> {
if (inline !== undefined || filename === undefined) {
return inline
}
const file = await fs.open(filename, 'r')
const content = await file.readFile({ encoding: 'utf8' })
await file.close()
return content
}
export function parsePackages(packagesString: string): string[] {
return [...packagesString.replaceAll(/#.*?(\n|$)/g, '$1').matchAll(/\S+/g)]
.map(m => m[0])
.sort()
}
async function calculateCacheKey(
version: string,
packages: string[]
): Promise<{
prefix: string
full: string
}> {
const packageHash = Array.from(
new Uint8Array(
await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(packages.join())
)
)
)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
const osid = `${os.platform()}-${os.machine()}`
const cachePrefix = `texlive-${osid}-${version}-${packageHash}-`
const cacheKey = cachePrefix + Temporal.Now.plainDateISO('UTC').toString()
return {
prefix: cachePrefix,
full: cacheKey
}
}
type TlPlatform =
| 'universal-darwin'
| 'windows'
| 'x86_64-linux'
| 'aarch64-linux'
function detectTlPlatform(): TlPlatform {
const osPlatform = os.platform()
switch (osPlatform) {
case 'darwin':
return 'universal-darwin'
case 'win32':
return 'windows'
case 'linux': {
const osMachine = os.machine()
switch (osMachine) {
case 'x86_64':
return 'x86_64-linux'
case 'arm64':
return 'aarch64-linux'
default:
throw new Error(`Unsupported architecture ${osMachine}`)
}
}
default:
throw new Error(`Unsupported platform ${osPlatform}`)
}
}
async function findRepository(): Promise<string | undefined> {
const http = new HttpClient()
let mirrorList: MirrorList | undefined
try {
const mirrorListResponse = await http.get(
'https://zauguin.github.io/texlive-mirrors/mirrors.json'
)
if (mirrorListResponse.message.statusCode === 200) {
mirrorList = JSON.parse(await mirrorListResponse.readBody())
} else {
mirrorList = undefined
}
} catch (_) {
mirrorList = undefined
}
if (mirrorList === undefined) {
core.error(
'Unable to retrive mirror list, falling back to CTAN auto selection'
)
return undefined
}
const usMirrors = Object.entries(mirrorList['North America'].USA).filter(
([_, { status }]) => status === 'Alive'
) as [string, AliveMirror][]
if (usMirrors.length === 0) {
throw new Error('No mirror available')
}
const highestVersion = Math.max(
...usMirrors.map(([_, { texlive_version }]) => texlive_version)
)
const versionFilteredMirrors = usMirrors.filter(
([_, { texlive_version }]) => texlive_version === highestVersion
)
const highestRevision = Math.max(
...versionFilteredMirrors.map(([_, { revision }]) => revision)
)
const filteredMirrors = versionFilteredMirrors
.filter(([_, { revision }]) => revision === highestRevision)
.map(([mirror, _]) => mirror)
const mirror =
filteredMirrors[Math.floor(Math.random() * filteredMirrors.length)]
core.info(
`Selected mirror ${mirror} (TeX Live ${highestVersion}, rev. ${highestRevision})`
)
return mirror
}
function handleExecResult(description: string, status: number): void {
if (status === 0) return
throw new Error(`${description} failed with status code ${status}`)
}
async function installTexLive(
initialInstall: boolean,
repository: string | undefined,
tlPlatform: TlPlatform,
packages: string[]
): Promise<void> {
const tlmgr = tlPlatform === 'windows' ? 'tlmgr.bat' : 'tlmgr'
if (initialInstall) {
const http = new HttpClient()
const response = await http.get(
(repository ?? 'https://mirrors.ctan.org/systems/texlive/tlnet') +
(tlPlatform === 'windows'
? '/install-tl.zip'
: '/install-tl-unx.tar.gz')
)
if (response.message.statusCode !== 200) {
throw new Error(
`Downloading installer failed with status code ${response.message.statusCode}`
)
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const installerBlob = await response.readBodyBuffer!()
const tmpdir = os.tmpdir()
const installerDir = `${tmpdir}/install-texlive`
const profilePath = core.toPosixPath(`${tmpdir}/texlive.profile`)
await decompress(installerBlob, installerDir, {
strip: 1
})
await fs.writeFile(profilePath, getProfile())
handleExecResult(
'Installing TeX Live',
await exec(
core.toPlatformPath(
`${os.tmpdir()}/install-texlive/${tlPlatform === 'windows' ? 'install-tl-windows.bat' : 'install-tl'}`
),
repository === undefined
? [`--profile=${profilePath}`]
: [`--repository=${repository}`, `--profile=${profilePath}`],
{
windowsVerbatimArguments: true
}
)
)
handleExecResult(
'Setting tlmgr options',
await exec(tlmgr, ['option', '--', 'autobackup', '0'])
)
handleExecResult(
'Setting repository',
await exec(tlmgr, ['option', 'repository', repository ?? 'ctan'])
)
handleExecResult(
'Installing packages',
await exec(tlmgr, ['install', ...packages])
)
} else {
handleExecResult(
'Setting repository',
await exec(tlmgr, ['option', 'repository', repository ?? 'ctan'])
)
}
handleExecResult(
'Updating TeX Live',
await exec(tlmgr, ['update', '--self', '--all'], {
windowsVerbatimArguments: true
})
)
}
export async function run(): Promise<void> {
try {
const repository =
getOptionalInput('repository') ?? (await findRepository())
const packageFile = getOptionalInput('package_file')
const packagesInline = getOptionalInput('packages')
const cacheVersion = getMandatoryInput('cache_version')
const acceptStale = core.getBooleanInput('accept-stale')
const packages = await (async () => {
const packageString = await inlineOrFilecontent(
packagesInline,
packageFile
)
if (packageString === undefined) {
throw new Error('package-file or packages input required')
}
return parsePackages(packageString)
})()
const cacheKey = await calculateCacheKey(cacheVersion, packages)
const home = os.homedir()
const tlPlatform = detectTlPlatform()
core.addPath(`${home}/texlive/bin/${tlPlatform}`)
core.info(`Trying to restore with key ${cacheKey.full}`)
const restoredCache = await cache.restoreCache(
['~/texlive'],
cacheKey.full,
[cacheKey.prefix]
)
if (restoredCache === cacheKey.full) {
core.setOutput('cache_key', restoredCache)
core.info(`Restored cache with key ${restoredCache}`)
return
}
// Installing TeX Live gets another try clock to handle acceptStale
try {
await installTexLive(
restoredCache === undefined,
repository,
tlPlatform,
packages
)
} catch (error) {
if (!acceptStale) {
throw error
}
// We can't accept a failed update if we didn't restore a valid state before.
if (restoredCache === undefined) {
throw error
}
core.setOutput('cache_key', restoredCache)
return
}
await cache.saveCache(['~/texlive'], cacheKey.full)
core.info(`Updated cache with key ${cacheKey.full}`)
core.setOutput('cache_key', cacheKey.full)
} catch (error) {
// Fail the workflow run if an error occurs
if (error instanceof Error) core.setFailed(error.toString())
}
}