-
Notifications
You must be signed in to change notification settings - Fork 27
/
java.ts
269 lines (245 loc) · 8.46 KB
/
java.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
import { getPlatform, Platform } from '@xmcl/core'
import { Task, task } from '@xmcl/task'
import { exec } from 'child_process'
import { unlink } from 'fs/promises'
import { arch, EOL, platform, tmpdir } from 'os'
import { basename, join, resolve } from 'path'
import { Dispatcher, request } from 'undici'
import { DownloadTask } from './downloadTask'
import { DownloadBaseOptions } from '@xmcl/file-transfer'
import { ensureDir, missing } from './utils'
export interface JavaInfo {
/**
* Full java executable path
*/
path: string
/**
* Java version string
*/
version: string
/**
* Major version of java
*/
majorVersion: number
}
export interface InstallJavaOptions extends DownloadBaseOptions {
/**
* The destination of this installation
*/
destination: string
/**
* The cached directory which compressed java lzma will be download to.
* @default os.tempdir()
*/
cacheDir?: string
/**
* The platform to install. It will be auto-resolved by default.
* @default currentPlatform
*/
platform?: Platform
/**
* Unpack lzma function. It must present, else it will not be able to unpack mojang provided LZMA.
*/
unpackLZMA: UnpackLZMAFunction
/**
* The dispatcher for API
*/
dispatcher?: Dispatcher
}
export type UnpackLZMAFunction =
((src: string, dest: string) => Promise<void>) |
((src: string, dest: string) => Task<void>)
export class DownloadJRETask extends DownloadTask {
constructor(jre: DownloadInfo, dir: string, options: InstallJavaOptions) {
const { sha1, url } = jre
const filename = basename(url)
const downloadDestination = resolve(dir, filename)
super({
url,
destination: downloadDestination,
validator: {
algorithm: 'sha1',
hash: sha1,
},
agent: options.agent,
headers: options.headers,
})
this.name = 'downloadJre'
this.param = jre
}
}
interface DownloadInfo { sha1: string; url: string; version: string }
/**
* Install JRE from Mojang offical resource. It should install jdk 8.
* @param options The install options
*/
export function installJreFromMojangTask(options: InstallJavaOptions) {
const {
destination,
unpackLZMA,
cacheDir = tmpdir(),
platform = getPlatform(),
} = options
return task('installJreFromMojang', async function () {
const info: { [system: string]: { [arch: string]: { jre: DownloadInfo } } } =
await this.yield(task('fetchInfo', async () => {
const response = await request('https://launchermeta.mojang.com/mc/launcher.json', { dispatcher: options.dispatcher, throwOnError: true })
return response.body.json() as any
}))
const system = platform.name
function resolveArch() {
switch (platform.arch) {
case 'x86':
case 'x32': return '32'
case 'x64': return '64'
default: return '32'
}
}
const currentArch = resolveArch()
if (!info[system] || !info[system][currentArch] || !info[system][currentArch].jre) {
throw new Error('No Java package available for your platform')
}
const lzmaPath = await this.yield(new DownloadJRETask(info[system][currentArch].jre, cacheDir, options).map(function () { return this.to! }))
const result = unpackLZMA(lzmaPath, destination)
await ensureDir(destination)
if (result instanceof Promise) {
await this.yield(task('decompress', () => result))
} else {
await this.yield(result)
}
await this.yield(task('cleanup', () => unlink(lzmaPath)))
})
}
/**
* Install JRE from Mojang offical resource. It should install jdk 8.
* @param options The install options
*/
export function installJreFromMojang(options: InstallJavaOptions) {
return installJreFromMojangTask(options).startAndWait()
}
/**
* Try to resolve a java info at this path. This will call `java -version`
* @param path The java exectuable path.
*/
export async function resolveJava(path: string): Promise<JavaInfo | undefined> {
if (await missing(path)) { return undefined }
return new Promise((resolve) => {
exec(`"${path}" -version`, (_err, _sout, serr) => {
if (serr) {
const ver = parseJavaVersion(serr)
if (ver) {
resolve({ path, ...ver })
} else {
resolve(undefined)
}
} else {
resolve(undefined)
}
})
})
}
export class ParseJavaVersionError extends Error {
name = 'ParseJavaVersionError'
constructor(message: string) { super(message) }
}
/**
* Parse version string and major version number from stderr of java process.
*
* @param versionText The stderr for `java -version`
*/
export function parseJavaVersion(versionText: string): { version: string; majorVersion: number; patch: number } | undefined {
const getVersion = (str?: string) => {
if (!str) { return undefined }
const match = /(\d+)\.(\d)+\.(\d+)(_\d+)?/.exec(str)
if (match === null) { return undefined }
if (match[1] === '1') {
return {
version: match[0],
majorVersion: Number.parseInt(match[2]),
patch: Number.parseInt(match[4].substring(1) ?? '-1'),
}
}
return {
version: match[0],
majorVersion: Number.parseInt(match[1]),
patch: Number.parseInt(match[3]),
}
}
try {
const javaVersion = getVersion(versionText)
if (!javaVersion) { return undefined }
return javaVersion
} catch (e) {
throw new ParseJavaVersionError(`Fail to parse java version [${versionText}]: ${(e as any).message}`)
}
}
/**
* Get all potential java locations for Minecraft.
*
* On mac/linux, it will perform `which java`. On win32, it will perform `where java`
*
* @returns The absolute java locations path
*/
export async function getPotentialJavaLocations(): Promise<string[]> {
const unchecked = new Set<string>()
const currentPlatform = platform()
const javaFile = currentPlatform === 'win32' ? 'javaw.exe' : 'java'
if (process.env.JAVA_HOME) {
unchecked.add(join(process.env.JAVA_HOME, 'bin', javaFile))
}
const which = () => new Promise<string>((resolve) => {
exec('which java', (_error, stdout) => {
if (!_error) resolve(stdout.replace('\n', ''))
else resolve('')
}).once('error', () => resolve(''))
})
const where = () => new Promise<string[]>((resolve) => {
exec('where java', (_error, stdout) => {
if (!_error) resolve(stdout.split('\r\n'))
else resolve([])
}).once('error', () => resolve([]))
})
if (currentPlatform === 'win32') {
const out = await new Promise<string[]>((resolve) => {
exec('REG QUERY HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\ /s /v JavaHome', (_error, stdout) => {
if (!stdout) { resolve([]) }
resolve(stdout.split(EOL).map((item) => item.replace(/[\r\n]/g, ''))
.filter((item) => item != null && item !== undefined)
.filter((item) => item[0] === ' ')
.map((item) => `${item.split(' ')[3]}\\bin\\javaw.exe`))
})
})
for (const o of [...out, ...await where()]) {
unchecked.add(o)
}
const currentArch = arch()
unchecked.add('C:\\Program Files (x86)\\Minecraft Launcher\\runtime\\jre-x64/X86')
unchecked.add(`C:\\Program Files (x86)\\Minecraft Launcher\\runtime\\jre-legacy\\windows-${currentArch}\\jre-legacy`)
} else if (currentPlatform === 'darwin') {
unchecked.add('/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java')
unchecked.add(await which())
} else {
unchecked.add(await which())
}
const checkingList = Array.from(unchecked).filter((jPath) => typeof jPath === 'string').filter((p) => p !== '')
return checkingList
}
/**
* Scan local java version on the disk.
*
* It will check if the passed `locations` are the home of java.
* Notice that the locations should not be the executable, but the path of java installation, like JAVA_HOME.
*
* This will call `getPotentialJavaLocations` and then `resolveJava`
*
* @param locations The location (like java_home) want to check.
* @returns All validate java info
*/
export async function scanLocalJava(locations: string[]): Promise<JavaInfo[]> {
const unchecked = new Set(locations)
const potential = await getPotentialJavaLocations()
potential.forEach((p) => unchecked.add(p))
const checkingList = [...unchecked].filter((jPath) => typeof jPath === 'string').filter((p) => p !== '')
const javas = await Promise.all(checkingList.map((jPath) => resolveJava(jPath)))
return javas.filter(((j) => j !== undefined) as (j?: JavaInfo) => j is JavaInfo)
}