forked from actions/setup-java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstaller.ts
More file actions
380 lines (354 loc) · 11.5 KB
/
Copy pathinstaller.ts
File metadata and controls
380 lines (354 loc) · 11.5 KB
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
import * as core from '@actions/core';
import * as io from '@actions/io';
import * as exec from '@actions/exec';
import * as httpm from '@actions/http-client';
import * as tc from '@actions/tool-cache';
import * as fs from 'fs';
import * as path from 'path';
import * as semver from 'semver';
import * as util from './util';
import * as constants from './constants';
import {DISCO_URL, DISTROS, PACKAGES_PATH} from './constants';
const tempDirectory = util.getTempDir();
const IS_WINDOWS = util.isWindows();
export async function getJava(
version: string,
arch: string,
jdkFile: string,
javaPackage: string,
distro: string = 'zulu'
): Promise<void> {
let toolPath = tc.find(javaPackage, version);
if (toolPath) {
core.debug(`Tool found in cache ${toolPath}`);
} else {
let compressedFileExtension = '';
if (!jdkFile) {
core.debug('Downloading JDK from Azul');
const http = new httpm.HttpClient('setup-java', undefined, {
allowRetries: true,
maxRetries: 3
});
const url = 'https://static.azul.com/zulu/bin/';
const response = await http.get(url);
const statusCode = response.message.statusCode || 0;
if (statusCode < 200 || statusCode > 299) {
let body = '';
try {
body = await response.readBody();
} catch (err) {
core.debug(`Unable to read body: ${err.message}`);
}
const message = `Unexpected HTTP status code '${response.message.statusCode}' when retrieving versions from '${url}'. ${body}`.trim();
throw new Error(message);
}
const contents = await response.readBody();
const refs = contents.match(/<a href.*\">/gi) || [];
const downloadInfo = await getDownloadInfo(
refs,
version,
arch,
javaPackage,
distro
);
jdkFile = await tc.downloadTool(downloadInfo.url);
version = downloadInfo.version;
compressedFileExtension = IS_WINDOWS ? '.zip' : '.tar.gz';
} else {
core.debug('Retrieving Jdk from local path');
}
compressedFileExtension = compressedFileExtension || getFileEnding(jdkFile);
let tempDir: string = path.join(
tempDirectory,
'temp_' + Math.floor(Math.random() * 2000000000)
);
const jdkDir = await unzipJavaDownload(
jdkFile,
compressedFileExtension,
tempDir
);
core.debug(`jdk extracted to ${jdkDir}`);
toolPath = await tc.cacheDir(
jdkDir,
javaPackage,
getCacheVersionString(version),
arch
);
}
let extendedJavaHome = 'JAVA_HOME_' + version + '_' + arch;
core.exportVariable(extendedJavaHome, toolPath); //TODO: remove for v2
// For portability reasons environment variables should only consist of
// uppercase letters, digits, and the underscore. Therefore we convert
// the extendedJavaHome variable to upper case and replace '.' symbols and
// any other non-alphanumeric characters with an underscore.
extendedJavaHome = extendedJavaHome.toUpperCase().replace(/[^0-9A-Z_]/g, '_');
core.exportVariable('JAVA_HOME', toolPath);
core.exportVariable(extendedJavaHome, toolPath);
core.addPath(path.join(toolPath, 'bin'));
core.setOutput('path', toolPath);
core.setOutput('version', version);
}
function getCacheVersionString(version: string) {
const versionArray = version.split('.');
const major = versionArray[0];
const minor = versionArray.length > 1 ? versionArray[1] : '0';
const patch = versionArray.length > 2 ? versionArray[2] : '0';
return `${major}.${minor}.${patch}`;
}
function getFileEnding(file: string): string {
let fileEnding = '';
if (file.endsWith('.tar')) {
fileEnding = '.tar';
} else if (file.endsWith('.tar.gz')) {
fileEnding = '.tar.gz';
} else if (file.endsWith('.zip')) {
fileEnding = '.zip';
} else if (file.endsWith('.7z')) {
fileEnding = '.7z';
} else {
throw new Error(`${file} has an unsupported file extension`);
}
return fileEnding;
}
async function extractFiles(
file: string,
fileEnding: string,
destinationFolder: string
): Promise<void> {
const stats = fs.statSync(file);
if (!stats) {
throw new Error(`Failed to extract ${file} - it doesn't exist`);
} else if (stats.isDirectory()) {
throw new Error(`Failed to extract ${file} - it is a directory`);
}
if ('.tar' === fileEnding || '.tar.gz' === fileEnding) {
await tc.extractTar(file, destinationFolder);
} else if ('.zip' === fileEnding) {
await tc.extractZip(file, destinationFolder);
} else {
// fall through and use sevenZip
await tc.extract7z(file, destinationFolder);
}
}
// This method recursively finds all .pack files under fsPath and unpacks them with the unpack200 tool
async function unpackJars(fsPath: string, javaBinPath: string) {
if (fs.existsSync(fsPath)) {
if (fs.lstatSync(fsPath).isDirectory()) {
for (const file in fs.readdirSync(fsPath)) {
const curPath = path.join(fsPath, file);
await unpackJars(curPath, javaBinPath);
}
} else if (path.extname(fsPath).toLowerCase() === '.pack') {
// Unpack the pack file synchonously
const p = path.parse(fsPath);
const toolName = IS_WINDOWS ? 'unpack200.exe' : 'unpack200';
const args = IS_WINDOWS ? '-r -v -l ""' : '';
const name = path.join(p.dir, p.name);
await exec.exec(`"${path.join(javaBinPath, toolName)}"`, [
`${args} "${name}.pack" "${name}.jar"`
]);
}
}
}
async function unzipJavaDownload(
repoRoot: string,
fileEnding: string,
destinationFolder: string,
extension?: string
): Promise<string> {
// Create the destination folder if it doesn't exist
await io.mkdirP(destinationFolder);
const jdkFile = path.normalize(repoRoot);
const stats = fs.statSync(jdkFile);
if (stats.isFile()) {
await extractFiles(jdkFile, fileEnding, destinationFolder);
const jdkDirectory = getJdkDirectory(destinationFolder);
await unpackJars(jdkDirectory, path.join(jdkDirectory, 'bin'));
return jdkDirectory;
} else {
throw new Error(`Jdk argument ${jdkFile} is not a file`);
}
}
async function getDownloadInfo(
refs: string[],
version: string,
arch: string,
javaPackage: string,
distro: string = 'zulu'
): Promise<{version: string; url: string}> {
const architecture = arch === 'x86' ? 'i686' : 'x64';
let operatingSystem = '';
let packageType = '';
if (javaPackage === 'jdk') {
packageType = 'jdk';
} else if (javaPackage === 'jre') {
packageType = 'jre';
} else if (javaPackage === 'jdk+fx') {
packageType = 'jdk+fx';
} else {
throw new Error(
`package argument ${javaPackage} is not in [jdk | jre | jdk+fx]`
);
}
let distribution = '';
if (distro) {
if (distro === '') {
distribution = 'zulu';
} else if (DISTROS.indexOf(distro.toLowerCase()) > -1) {
distribution = distro.toLowerCase();
} else {
throw new Error(
`distro argument '${distro}' is not in [aoj | aoj_openj9 | bisheng | corretto | dragonwell | jetbrains| kona | liberica | microsoft | ojdk_build | openlogic | oracle_openjdk | oracle | sap_machine | semeru | semeru_certified | temurin | trava | zulu | zulu_prime]`
);
}
} else {
distribution = 'zulu';
}
let archiveType;
let libCType;
if (IS_WINDOWS) {
operatingSystem = 'windows';
archiveType = 'zip';
libCType = 'c_std_lib';
} else {
if (process.platform === 'darwin') {
operatingSystem = 'macos';
let zipArchive =
distribution === 'liberica' || distribution === 'openlogic';
archiveType = zipArchive ? 'zip' : 'tar.gz';
libCType = 'libc';
} else {
operatingSystem = 'linux';
archiveType = distribution === 'ojdk_build' ? 'zip' : 'tar.gz';
libCType = 'glibc';
}
}
let url = DISCO_URL + PACKAGES_PATH;
url += '?distro=' + distribution;
if (version.length != 0) {
url += '&version=' + version;
}
if (javaPackage === 'jdk+fx') {
url += '&package_type=jdk';
url += '&javafx_bundled=true';
} else {
url += '&package_type=' + packageType;
}
if (version.includes('ea')) {
url += '&release_status=ea';
}
url += '&release_status=ga';
url += '&architecture=' + architecture;
url += '&operating_system=' + operatingSystem;
url += '&archive_type=' + archiveType;
url += '&libc_type=' + libCType;
if (
version.includes('x') ||
version.includes('ea') ||
version.startsWith('1.')
) {
url += '&latest=available';
}
const http = new httpm.HttpClient('bundles', undefined, {
allowRetries: true,
maxRetries: 3
});
let json: any = '';
const response = await http.get(url);
const statusCode = response.message.statusCode || 0;
if (statusCode == 200) {
let body = '';
try {
body = await response.readBody();
json = JSON.parse(body);
json = json.result;
} catch (err) {
core.debug(`Unable to read body: ${err.message}`);
}
} else {
const message =
'Unexpected HTTP status code ' +
response.message.statusCode +
' when retrieving versions from ' +
url;
throw new Error(message);
}
// Choose the most recent satisfying version
let curVersion = '0.0.0';
let curUrl = '';
console.log('json: ' + json);
if (json.length > 0) {
curVersion = json[0].feature_version + '';
var updateEqualZero = json[0].update_version == 0;
var patchEqualZero = json[0].patch_version == 0;
if (!updateEqualZero) {
curVersion += '.';
curVersion += json[0].interim_version;
curVersion += '.';
curVersion += json[0].update_version;
if (!patchEqualZero) {
curVersion += '.';
curVersion += json[0].patch_version;
}
} else if (updateEqualZero && !patchEqualZero) {
curVersion += '.';
curVersion += json[0].interim_version;
curVersion += '.';
curVersion += json[0].update_version;
curVersion += '.';
curVersion += json[0].patch_version;
}
curUrl = await getPackageFileUrl(json[0].links.pkg_info_uri);
}
if (curUrl == '') {
throw new Error(
`No valid download found for ${distribution} with version ${version} and package ${packageType}. Please download your own jdk file and add the jdkFile argument`
);
}
return {version: curVersion, url: curUrl};
}
async function getPackageFileUrl(url: string) {
const http = new httpm.HttpClient('bundle-info', undefined, {
allowRetries: true,
maxRetries: 3,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Disco-User-Info': 'setup-java@v1'
}
});
const response = await http.get(url);
const statusCode = response.message.statusCode || 0;
if (statusCode == 200) {
let body = '';
try {
body = await response.readBody();
let json = JSON.parse(body);
json = json.result;
if (json.length > 0) {
return json[0].direct_download_uri;
}
} catch (err) {
core.debug(`Unable to read body: ${err.message}`);
}
const message = `Unexpected HTTP status code '${response.message.statusCode}' when retrieving versions from '${url}'. ${body}`.trim();
throw new Error(message);
}
return '';
}
function getJdkDirectory(destinationFolder: string): string {
const jdkRoot: string = path.join(
destinationFolder,
fs.readdirSync(destinationFolder)[0]
);
if (process.platform === 'darwin') {
const binDirectory: string = path.join(jdkRoot, 'bin');
if (fs.existsSync(binDirectory)) {
return jdkRoot;
} else {
return path.join(jdkRoot, 'Contents', 'Home');
}
} else {
return jdkRoot;
}
}