This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,282 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.enableAMDH = exports.enableHAXM = exports.enableWHPX = exports.getBestHypervisor = exports.createAVD = exports.installComponent = exports.getAndroidSdkRootInstallation = exports.getUserAndroidPath = void 0;
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
var _executeWinCommand = require("./executeWinCommand");
var _processorType = require("./processorType");
/**
* Returns the path to where all Android related things should be installed
* locally to the user.
*/
const getUserAndroidPath = () => {
return (0, _path().join)(process.env.LOCALAPPDATA || '', 'Android');
};
/**
* Deals with ANDROID_HOME, ANDROID_SDK_ROOT or generates a new one
*/
exports.getUserAndroidPath = getUserAndroidPath;
const getAndroidSdkRootInstallation = () => {
const env = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME;
const installPath = env ? // Happens if previous installations or not fully completed
env : // All Android zip files have a root folder, using `Android` as the common place
(0, _path().join)(getUserAndroidPath(), 'Sdk');
if ((0, _fsExtra().pathExistsSync)(installPath)) {
return installPath;
} else {
return '';
}
};
/**
* Installs an Android component (e.g.: `platform-tools`, `emulator`)
* using the `sdkmanager` tool and automatically accepting the licenses.
*/
exports.getAndroidSdkRootInstallation = getAndroidSdkRootInstallation;
const installComponent = (component, androidSdkRoot) => {
return new Promise((done, error) => {
const sdkmanager = (0, _path().join)(androidSdkRoot, 'tools', 'bin', 'sdkmanager.bat');
const command = `"${sdkmanager}" --sdk_root="${androidSdkRoot}" "${component}"`;
const child = (0, _executeWinCommand.executeCommand)(command);
let stderr = '';
child.stdout.on('data', data => {
if (data.includes('(y/N)')) {
child.stdin.write('y\n');
}
});
child.stderr.on('data', data => {
stderr += data.toString('utf-8');
});
child.on('close', exitStatus => {
if (exitStatus === 0) {
done();
} else {
error({
stderr
});
}
});
child.on('error', error);
});
};
/**
* For the given custom Hypervisor and the output of `emulator-check accel`
* returns the preferred Hypervisor to use and its installation status.
* The recommendation order is:
* 1. WHPX
* 2. HAXM if Intel
* 3. AMDH if AMD
*/
exports.installComponent = installComponent;
const parseHypervisor = (status, customHypervisor) => {
/**
* Messages:
* Android Emulator requires an Intel processor with VT-x and NX support. Your CPU: 'AuthenticAMD'
* HAXM is not installed, but Windows Hypervisor Platform is available.
* WHPX (10.0.19041) is installed and usable.
* * This message outputs for WHPX and when the AMD Hypervisor is installed
* HAXM version 6.2.1 (4) is installed and usable.
* HAXM is not installed on this machine
*/
if (status.includes('is not installed, but Windows Hypervisor Platform is available.')) {
return {
hypervisor: 'WHPX',
installed: false
};
}
if (/WHPX \((\d|\.)+\) is installed and usable\./.test(status)) {
return {
hypervisor: 'WHPX',
installed: true
};
}
if (/is installed and usable\./.test(status)) {
return {
hypervisor: customHypervisor,
installed: true
};
}
if (status.includes("Your CPU: 'AuthenticAMD'")) {
return {
hypervisor: customHypervisor,
installed: false
};
}
if (status.includes('is not installed on this machine')) {
return {
hypervisor: 'none',
installed: false
};
}
return null;
};
const getEmulatorAccelOutputInformation = async androidSDKRoot => {
/**
* The output of the following command is something like:
*
* ```
* accel:
* 0
* WHPX (10.0.19041) is installed and usable.
* accel
* ```
*
* If it fails it will still output to stdout with a similar format:
*
* ```
* accel:
* 1
* Android Emulator does not support nested virtualization. Your VM host: 'Microsoft Hv' (Hyper-V)
* accel
* ```
*
*/
try {
const {
stdout
} = await (0, _executeWinCommand.executeCommand)(`"${(0, _path().join)(androidSDKRoot, 'emulator', 'emulator-check.exe')}" accel`);
return stdout;
} catch (e) {
const {
stdout
} = e;
return stdout;
}
};
/**
* Creates a new Android Virtual Device in the default folder with the
* name, device and system image passed by parameter.
*/
const createAVD = async (androidSDKRoot, name, device, image) => {
try {
const abi = image.includes('x86_64') ? 'x86_64' : 'x86';
const tag = image.includes('google_apis') ? 'google_apis' : 'generic';
const avdmanager = (0, _path().join)(androidSDKRoot, 'tools', 'bin', 'avdmanager.bat');
const {
stdout
} = await (0, _executeWinCommand.executeCommand)(`${avdmanager} -s create avd --force --name "${name}" --device "${device}" --package "${image}" --tag "${tag}" --abi "${abi}"`); // For some reason `image.sysdir.1` in `config.ini` points to the wrong location and needs to be updated
const configPath = (0, _path().join)(process.env.HOMEPATH || '', '.android', 'avd', `${name}.avd`, 'config.ini');
const content = await (0, _fsExtra().readFile)(configPath, 'utf-8');
const updatedContent = content.replace(/Sdk\\system-images/g, 'system-images');
await (0, _fsExtra().writeFile)(configPath, updatedContent, 'utf-8');
return stdout;
} catch (e) {
const {
stderr
} = e;
return stderr;
}
};
/**
* Returns what hypervisor should be installed for the Android emulator
* using [Microsoft's official
* documentation](https://docs.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/hardware-acceleration?pivots=windows)
* as a reference.
*/
exports.createAVD = createAVD;
const getBestHypervisor = async androidSDKRoot => {
const customHypervisor = (0, _processorType.getProcessorType)() === 'Intel' ? 'HAXM' : 'AMDH';
const stdout = await getEmulatorAccelOutputInformation(androidSDKRoot);
const lines = stdout.split('\n');
for (const line of lines) {
const hypervisor = parseHypervisor(line, customHypervisor);
if (hypervisor) {
return hypervisor;
}
} // Couldn't identify the best one to run so not doing anything
return {
hypervisor: 'none',
installed: false
};
};
/**
* Enables the Windows HypervisorPlatform and Hyper-V features.
* Will prompt the User Account Control (UAC)
*/
exports.getBestHypervisor = getBestHypervisor;
const enableWHPX = () => {
return (0, _executeWinCommand.executeCommand)('DISM /Quiet /NoRestart /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V /FeatureName:HypervisorPlatform', true);
};
/**
* Installs and enables the [HAXM](https://github.com/intel/haxm)
* version available through the Android SDK manager.
* @param androidSdkInstallPath The path to the Android SDK installation
*/
exports.enableWHPX = enableWHPX;
const enableHAXM = async androidSdkInstallPath => {
await installComponent('extras;intel;Hardware_Accelerated_Execution_Manager', androidSdkInstallPath);
await (0, _executeWinCommand.executeCommand)((0, _path().join)(androidSdkInstallPath, 'Sdk', 'extras', 'intel', 'Hardware_Accelerated_Execution_Manager', 'silent_install.bat'));
};
/**
* Installs and enables the
* [Hypervisor Driver for AMD Processors](https://androidstudio.googleblog.com/2019/10/android-emulator-hypervisor-driver-for.html)
* version available through the Android SDK manager.
* @param androidSdkInstallPath The path to the Android SDK installation
*/
exports.enableHAXM = enableHAXM;
const enableAMDH = async androidSdkInstallPath => {
await installComponent('extras;google;Android_Emulator_Hypervisor_Driver', androidSdkInstallPath);
await (0, _executeWinCommand.executeCommand)((0, _path().join)(androidSdkInstallPath, 'Sdk', 'extras', 'google', 'Android_Emulator_Hypervisor_Driver', 'silent_install.bat'));
};
exports.enableAMDH = enableAMDH;
//# sourceMappingURL=androidWinHelpers.js.map

View File

@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createShortcut = void 0;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _os() {
const data = require("os");
_os = function () {
return data;
};
return data;
}
var _executeWinCommand = require("./executeWinCommand");
/**
* Creates a script in the user's Startup menu
*/
const createShortcut = async ({
path,
name,
ico
}) => {
// prettier-ignore
const script = `option explicit
sub createLnk()
dim objShell, strStartMenuPath, objLink
set objShell = CreateObject("WScript.Shell")
strStartMenuPath = objShell.SpecialFolders("StartMenu")
set objLink = objShell.CreateShortcut(strStartMenuPath + "\\" + "${name}.lnk")
objLink.TargetPath = "${path}"
objLink.IconLocation = "${ico}"
objLink.Save
end sub
call createLnk()`;
const scriptPath = (0, _path().join)((0, _os().tmpdir)(), `shortcut-${Math.random()}.vbs`);
(0, _fs().writeFileSync)(scriptPath, script, 'utf-8');
await (0, _executeWinCommand.executeCommand)(scriptPath);
};
exports.createShortcut = createShortcut;
//# sourceMappingURL=create-shortcut.js.map

View File

@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.updateEnvironment = exports.setEnvironment = void 0;
var _executeWinCommand = require("./executeWinCommand");
/**
* Creates a new variable in the user's environment
*/
const setEnvironment = async (variable, value) => {
// https://superuser.com/a/601034
const command = `setx ${variable} "${value}"`;
await (0, _executeWinCommand.executeCommand)(command);
process.env[variable] = value;
};
/**
* Prepends the given `value` to the user's environment `variable`.
* @param {string} variable The environment variable to modify
* @param {string} value The value to add to the variable
* @returns {Promise<void>}
*/
exports.setEnvironment = setEnvironment;
const updateEnvironment = async (variable, value) => {
// Avoid adding the value multiple times to PATH
// Need to do the following to avoid TSLint complaining about possible
// undefined values even if I check before via `typeof` or another way
const envVariable = process.env[variable] || '';
if (variable === 'PATH' && envVariable.includes(`${value};`)) {
return;
} // https://superuser.com/a/601034
const command = `for /f "skip=2 tokens=3*" %a in ('reg query HKCU\\Environment /v ${variable}') do @if [%b]==[] ( @setx ${variable} "${value};%~a" ) else ( @setx ${variable} "${value};%~a %~b" )
`;
await (0, _executeWinCommand.executeCommand)(command);
process.env[variable] = `${process.env[variable]}${value};`;
};
exports.updateEnvironment = updateEnvironment;
//# sourceMappingURL=environmentVariables.js.map

View File

@ -0,0 +1,146 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.executeCommand = void 0;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _os() {
const data = require("os");
_os = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _execa() {
const data = _interopRequireDefault(require("execa"));
_execa = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/** Runs a command requestion permission to run elevated. */
const runElevated = command => {
// TODO: escape double quotes in args
// https://www.winhelponline.com/blog/vbscripts-and-uac-elevation/
/**
* Need to use a couple of intermediary files to make this work as
* `ShellExecute` only accepts a command so
*/
// prettier-ignore
const script = `If WScript.Arguments.length = 0 Then
Set objShell = CreateObject("Shell.Application")
'Pass a bogus argument, say [ uac]
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "${command}"
Set oShell = Nothing
End If`;
const elevatedPath = (0, _path().join)((0, _os().tmpdir)(), `elevated-${Math.random()}.vbs`);
(0, _fs().writeFileSync)(elevatedPath, script, 'utf-8');
return (0, _execa().default)(elevatedPath);
};
/**
* Groups all string arguments into a single one. E.g.:
* ```js
* ['-m', '"Upgrade:', 'to', 'latest', 'version"'] --> ['-m', '"Upgrade: to latest version"']`
* ```
* @param args The arguments
* © webhint project
* (https://github.com/webhintio/hint/blob/30b8ba74f122d8b66fc5596d788dd1c7738f2d83/release/lib/utils.ts#L82)
* License: Apache-2
*/
const groupArgs = args => {
let isStringArgument = false;
const newArgs = args.reduce((acum, current) => {
if (isStringArgument) {
const last = acum[acum.length - 1];
acum[acum.length - 1] = `${last} ${current}`;
if (current.endsWith('"')) {
isStringArgument = false;
}
return acum;
}
if (current.startsWith('"')) {
/**
* Argument is split. I.e.: `['"part1', 'part2"'];`
*/
if (!current.endsWith('"')) {
isStringArgument = true;
acum.push(current);
return acum;
}
/**
* Argument is surrounded by "" that need to be removed.
* We just remove all the quotes because we don't escape any in our commands
*/
acum.push(current.replace(/"/g, ''));
return acum;
}
acum.push(current);
return acum;
}, []);
return newArgs;
};
/**
* Executes the given `command` on a shell taking care of slicing the parameters
* if needed.
*/
const executeShellCommand = (command, elevated = false) => {
const args = groupArgs(command.split(' '));
const program = args.shift();
if (elevated) {
return runElevated(command);
}
return (0, _execa().default)(program, args, {
shell: true
});
};
exports.executeCommand = executeShellCommand;
//# sourceMappingURL=executeWinCommand.js.map

View File

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getProcessorType = void 0;
/**
* Returns if the processor is Intel or AMD
*/
const getProcessorType = () => {
return process.env.PROCESSOR_IDENTIFIER.includes('Intel') ? 'Intel' : 'AMD';
};
exports.getProcessorType = getProcessorType;
//# sourceMappingURL=processorType.js.map