/
cli.ts
261 lines (227 loc) · 7.71 KB
/
cli.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
#!/usr/bin/env node
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import * as exec from "child_process";
import * as fs from "fs";
import * as path from "path";
import { argv, platform } from "process";
import { promisify } from "util";
import log, { LoggingLevel } from "./core/log.js";
const LOG_TAG = "CLI";
// The name of the directory which contains / will contain the Python virtual environment
// used to run the glean-parser.
//
// > When a virtual environment is active, the VIRTUAL_ENV environment variable
// > is set to the path of the virtual environment. This can be used to check if
// > one is running inside a virtual environment.
//
// See: https://docs.python.org/3/library/venv.html
// (Also applies to envs created using virtualenv though)
const VIRTUAL_ENVIRONMENT_DIR = process.env.VIRTUAL_ENV?.split("/").slice(-1)[0] || ".venv";
// The version of glean_parser to install from PyPI.
const GLEAN_PARSER_VERSION = "4.1.1";
// This script runs a given Python module as a "main" module, like
// `python -m module`. However, it first checks that the installed
// package is at the desired version, and if not, upgrades it using `pip`.
//
// ** IMPORTANT**
// Keep this script in sync with the one in the Glean SDK (Gradle Plugin).
//
// Note: Groovy doesn't support embedded " in multi-line strings, so care
// should be taken to use ' everywhere in this code snippet.
const PYTHON_SCRIPT = `
import importlib
import subprocess
import sys
offline = sys.argv[1] == 'offline'
module_name = sys.argv[2]
expected_version = sys.argv[3]
try:
module = importlib.import_module(module_name)
except ImportError:
found_version = None
else:
found_version = getattr(module, '__version__')
if found_version != expected_version:
if not offline:
subprocess.check_call([
sys.executable,
'-m',
'pip',
'install',
'--upgrade',
f'{module_name}=={expected_version}'
])
else:
print(f'Using Python environment at {sys.executable},')
print(f'expected glean_parser version {expected_version}, found {found_version}.')
sys.exit(1)
try:
subprocess.check_call([
sys.executable,
'-m',
module_name
] + sys.argv[4:])
except:
# We don't need to show a traceback in this helper script.
# Only the output of the subprocess is interesting.
sys.exit(1)
`;
/**
* Gets the name of the Python binary, based on the host OS.
*
* @returns the name of the Python executable.
*/
function getSystemPythonBinName(): string {
return (platform === "win32") ? "python.exe" : "python3";
}
/**
* Gets the full path to the directory containing the python
* binaries in the virtual environment.
*
* Note that this directory changes depending on the host OS.
*
* @param venvRoot the root path of the virtual environment.
* @returns the full path to the directory containing the python
* binaries in the virtual environment.
*/
function getPythonVenvBinariesPath(venvRoot: string): string {
if (platform === "win32") {
return path.join(venvRoot, "Scripts");
}
return path.join(venvRoot, "bin");
}
/**
* Checks if a Python virtual environment is available.
*
* @param venvPath the Python virtual environment directory.
* @returns `true` if the Python virtual environment exists and
* is accessible, `false` otherwise.
*/
async function checkPythonVenvExists(venvPath: string): Promise<boolean> {
log(LOG_TAG, `Checking for a Glean virtual environment at ${venvPath}`);
const venvPython =
path.join(getPythonVenvBinariesPath(venvPath), getSystemPythonBinName());
const access = promisify(fs.access);
try {
await access(venvPath, fs.constants.F_OK);
await access(venvPython, fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
}
/**
* Uses the system's Python interpreter to create a Python3 virtual environment.
*
* @param venvPath the directory in which to create the virtual environment.
* @returns `true` if the environment was correctly created, `false` otherwise.
*/
async function createPythonVenv(venvPath: string): Promise<boolean> {
log(LOG_TAG, `Creating a Glean virtual environment at ${venvPath}`);
const pipFilename = (platform === "win32") ? "pip3.exe" : "pip3";
const venvPip =
path.join(getPythonVenvBinariesPath(VIRTUAL_ENVIRONMENT_DIR), pipFilename);
const pipCmd = `${venvPip} install wheel`;
const venvCmd = `${getSystemPythonBinName()} -m venv ${VIRTUAL_ENVIRONMENT_DIR}`;
for (const cmd of [venvCmd, pipCmd]) {
const spinner = getStartedSpinner();
const {err, stdout, stderr} = await new Promise<{err: exec.ExecException | null, stdout: string, stderr: string}>(resolve => {
exec.exec(cmd, (err, stdout, stderr) => resolve({err, stdout, stderr}));
});
stopSpinner(spinner);
log(LOG_TAG, `${stdout}`);
if (err) {
log(LOG_TAG, `${stderr}`);
return false;
}
}
return true;
}
/**
* Checks if a virtual environment for running the glean_parser exists,
* otherwise it creates it.
*
* @param projectRoot the project's root directory.
*/
async function setup(projectRoot: string) {
const venvRoot = path.join(projectRoot, VIRTUAL_ENVIRONMENT_DIR);
const venvExists = await checkPythonVenvExists(venvRoot);
if (venvExists) {
log(LOG_TAG, `Using Glean virtual environment at ${venvRoot}`);
} else if (!await createPythonVenv(venvRoot)){
log(LOG_TAG, `Failed to create a Glean virtual environment at ${venvRoot}`);
process.exit(1);
}
}
/**
* Runs the glean_parser with the provided options.
*
* @param projectRoot the project's root directory.
* @param parserArgs the list of arguments passed to this command.
*/
async function runGlean(projectRoot: string, parserArgs: string[]) {
const spinner = getStartedSpinner();
const venvRoot = path.join(projectRoot, VIRTUAL_ENVIRONMENT_DIR);
const pythonBin = path.join(getPythonVenvBinariesPath(venvRoot), getSystemPythonBinName());
const cmd = `${pythonBin} -c "${PYTHON_SCRIPT}" online glean_parser ${GLEAN_PARSER_VERSION} ${parserArgs.join(" ")}`;
const {err, stdout, stderr} = await new Promise<{err: exec.ExecException | null, stdout: string, stderr: string}>(resolve => {
exec.exec(cmd, (err, stdout, stderr) => resolve({err, stdout, stderr}));
});
stopSpinner(spinner);
log(LOG_TAG, `${stdout}`);
if (err) {
log(LOG_TAG, `${stderr}`);
process.exit(1);
}
}
/**
* Returns a spinner
*
* @returns an Interval ID that logs certain characters
*/
function getStartedSpinner() {
const ticks = ["\\", "|", "/", "-"];
let i = 0;
return setInterval(function() {
process.stdout.write(" "+ticks[i++]+"\r\r");
i %= 4;
}, 250);
}
/**
* Stops the spinner
*
* @param spinner is created by getStartedSpinner
*/
function stopSpinner(spinner: NodeJS.Timeout) {
process.stdout.write(" \r");
clearInterval(spinner);
}
/**
* Runs the command.
*
* @param args the arguments passed to this process.
*/
async function run(args: string[]) {
if (args.length < 3) {
throw new Error("Not enough arguments. Please refer to https://mozilla.github.io/glean_parser/readme.html");
}
const projectRoot = process.cwd();
try {
await setup(projectRoot);
} catch (err) {
log(
LOG_TAG,
["Failed to setup the Glean build environment.\n", err],
LoggingLevel.Error
);
process.exit(1);
}
await runGlean(projectRoot, args.slice(2));
}
// For discoverability, try to leave this function as the last one on this file.
run(argv).catch(e => {
log(LOG_TAG, ["There was an error running Glean.\n", e], LoggingLevel.Error);
process.exit(1);
});