source: trip-planner-front/node_modules/node-gyp/lib/find-python.js@ bdd6491

Last change on this file since bdd6491 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 10.5 KB
Line 
1'use strict'
2
3const path = require('path')
4const log = require('npmlog')
5const semver = require('semver')
6const cp = require('child_process')
7const extend = require('util')._extend // eslint-disable-line
8const win = process.platform === 'win32'
9const logWithPrefix = require('./util').logWithPrefix
10
11function PythonFinder (configPython, callback) {
12 this.callback = callback
13 this.configPython = configPython
14 this.errorLog = []
15}
16
17PythonFinder.prototype = {
18 log: logWithPrefix(log, 'find Python'),
19 argsExecutable: ['-c', 'import sys; print(sys.executable);'],
20 argsVersion: ['-c', 'import sys; print("%s.%s.%s" % sys.version_info[:3]);'],
21 semverRange: '2.7.x || >=3.5.0',
22
23 // These can be overridden for testing:
24 execFile: cp.execFile,
25 env: process.env,
26 win: win,
27 pyLauncher: 'py.exe',
28 winDefaultLocations: [
29 path.join(process.env.SystemDrive || 'C:', 'Python37', 'python.exe'),
30 path.join(process.env.SystemDrive || 'C:', 'Python27', 'python.exe')
31 ],
32
33 // Logs a message at verbose level, but also saves it to be displayed later
34 // at error level if an error occurs. This should help diagnose the problem.
35 addLog: function addLog (message) {
36 this.log.verbose(message)
37 this.errorLog.push(message)
38 },
39
40 // Find Python by trying a sequence of possibilities.
41 // Ignore errors, keep trying until Python is found.
42 findPython: function findPython () {
43 const SKIP = 0; const FAIL = 1
44 var toCheck = getChecks.apply(this)
45
46 function getChecks () {
47 if (this.env.NODE_GYP_FORCE_PYTHON) {
48 return [{
49 before: () => {
50 this.addLog(
51 'checking Python explicitly set from NODE_GYP_FORCE_PYTHON')
52 this.addLog('- process.env.NODE_GYP_FORCE_PYTHON is ' +
53 `"${this.env.NODE_GYP_FORCE_PYTHON}"`)
54 },
55 check: this.checkCommand,
56 arg: this.env.NODE_GYP_FORCE_PYTHON
57 }]
58 }
59
60 var checks = [
61 {
62 before: () => {
63 if (!this.configPython) {
64 this.addLog(
65 'Python is not set from command line or npm configuration')
66 return SKIP
67 }
68 this.addLog('checking Python explicitly set from command line or ' +
69 'npm configuration')
70 this.addLog('- "--python=" or "npm config get python" is ' +
71 `"${this.configPython}"`)
72 },
73 check: this.checkCommand,
74 arg: this.configPython
75 },
76 {
77 before: () => {
78 if (!this.env.PYTHON) {
79 this.addLog('Python is not set from environment variable ' +
80 'PYTHON')
81 return SKIP
82 }
83 this.addLog('checking Python explicitly set from environment ' +
84 'variable PYTHON')
85 this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`)
86 },
87 check: this.checkCommand,
88 arg: this.env.PYTHON
89 },
90 {
91 before: () => { this.addLog('checking if "python3" can be used') },
92 check: this.checkCommand,
93 arg: 'python3'
94 },
95 {
96 before: () => { this.addLog('checking if "python" can be used') },
97 check: this.checkCommand,
98 arg: 'python'
99 },
100 {
101 before: () => { this.addLog('checking if "python2" can be used') },
102 check: this.checkCommand,
103 arg: 'python2'
104 }
105 ]
106
107 if (this.win) {
108 for (var i = 0; i < this.winDefaultLocations.length; ++i) {
109 const location = this.winDefaultLocations[i]
110 checks.push({
111 before: () => {
112 this.addLog('checking if Python is ' +
113 `${location}`)
114 },
115 check: this.checkExecPath,
116 arg: location
117 })
118 }
119 checks.push({
120 before: () => {
121 this.addLog(
122 'checking if the py launcher can be used to find Python')
123 },
124 check: this.checkPyLauncher
125 })
126 }
127
128 return checks
129 }
130
131 function runChecks (err) {
132 this.log.silly('runChecks: err = %j', (err && err.stack) || err)
133
134 const check = toCheck.shift()
135 if (!check) {
136 return this.fail()
137 }
138
139 const before = check.before.apply(this)
140 if (before === SKIP) {
141 return runChecks.apply(this)
142 }
143 if (before === FAIL) {
144 return this.fail()
145 }
146
147 const args = [runChecks.bind(this)]
148 if (check.arg) {
149 args.unshift(check.arg)
150 }
151 check.check.apply(this, args)
152 }
153
154 runChecks.apply(this)
155 },
156
157 // Check if command is a valid Python to use.
158 // Will exit the Python finder on success.
159 // If on Windows, run in a CMD shell to support BAT/CMD launchers.
160 checkCommand: function checkCommand (command, errorCallback) {
161 var exec = command
162 var args = this.argsExecutable
163 var shell = false
164 if (this.win) {
165 // Arguments have to be manually quoted
166 exec = `"${exec}"`
167 args = args.map(a => `"${a}"`)
168 shell = true
169 }
170
171 this.log.verbose(`- executing "${command}" to get executable path`)
172 this.run(exec, args, shell, function (err, execPath) {
173 // Possible outcomes:
174 // - Error: not in PATH, not executable or execution fails
175 // - Gibberish: the next command to check version will fail
176 // - Absolute path to executable
177 if (err) {
178 this.addLog(`- "${command}" is not in PATH or produced an error`)
179 return errorCallback(err)
180 }
181 this.addLog(`- executable path is "${execPath}"`)
182 this.checkExecPath(execPath, errorCallback)
183 }.bind(this))
184 },
185
186 // Check if the py launcher can find a valid Python to use.
187 // Will exit the Python finder on success.
188 // Distributions of Python on Windows by default install with the "py.exe"
189 // Python launcher which is more likely to exist than the Python executable
190 // being in the $PATH.
191 checkPyLauncher: function checkPyLauncher (errorCallback) {
192 this.log.verbose(
193 `- executing "${this.pyLauncher}" to get Python executable path`)
194 this.run(this.pyLauncher, this.argsExecutable, false,
195 function (err, execPath) {
196 // Possible outcomes: same as checkCommand
197 if (err) {
198 this.addLog(
199 `- "${this.pyLauncher}" is not in PATH or produced an error`)
200 return errorCallback(err)
201 }
202 this.addLog(`- executable path is "${execPath}"`)
203 this.checkExecPath(execPath, errorCallback)
204 }.bind(this))
205 },
206
207 // Check if a Python executable is the correct version to use.
208 // Will exit the Python finder on success.
209 checkExecPath: function checkExecPath (execPath, errorCallback) {
210 this.log.verbose(`- executing "${execPath}" to get version`)
211 this.run(execPath, this.argsVersion, false, function (err, version) {
212 // Possible outcomes:
213 // - Error: executable can not be run (likely meaning the command wasn't
214 // a Python executable and the previous command produced gibberish)
215 // - Gibberish: somehow the last command produced an executable path,
216 // this will fail when verifying the version
217 // - Version of the Python executable
218 if (err) {
219 this.addLog(`- "${execPath}" could not be run`)
220 return errorCallback(err)
221 }
222 this.addLog(`- version is "${version}"`)
223
224 const range = new semver.Range(this.semverRange)
225 var valid = false
226 try {
227 valid = range.test(version)
228 } catch (err) {
229 this.log.silly('range.test() threw:\n%s', err.stack)
230 this.addLog(`- "${execPath}" does not have a valid version`)
231 this.addLog('- is it a Python executable?')
232 return errorCallback(err)
233 }
234
235 if (!valid) {
236 this.addLog(`- version is ${version} - should be ${this.semverRange}`)
237 this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED')
238 return errorCallback(new Error(
239 `Found unsupported Python version ${version}`))
240 }
241 this.succeed(execPath, version)
242 }.bind(this))
243 },
244
245 // Run an executable or shell command, trimming the output.
246 run: function run (exec, args, shell, callback) {
247 var env = extend({}, this.env)
248 env.TERM = 'dumb'
249 const opts = { env: env, shell: shell }
250
251 this.log.silly('execFile: exec = %j', exec)
252 this.log.silly('execFile: args = %j', args)
253 this.log.silly('execFile: opts = %j', opts)
254 try {
255 this.execFile(exec, args, opts, execFileCallback.bind(this))
256 } catch (err) {
257 this.log.silly('execFile: threw:\n%s', err.stack)
258 return callback(err)
259 }
260
261 function execFileCallback (err, stdout, stderr) {
262 this.log.silly('execFile result: err = %j', (err && err.stack) || err)
263 this.log.silly('execFile result: stdout = %j', stdout)
264 this.log.silly('execFile result: stderr = %j', stderr)
265 if (err) {
266 return callback(err)
267 }
268 const execPath = stdout.trim()
269 callback(null, execPath)
270 }
271 },
272
273 succeed: function succeed (execPath, version) {
274 this.log.info(`using Python version ${version} found at "${execPath}"`)
275 process.nextTick(this.callback.bind(null, null, execPath))
276 },
277
278 fail: function fail () {
279 const errorLog = this.errorLog.join('\n')
280
281 const pathExample = this.win ? 'C:\\Path\\To\\python.exe'
282 : '/path/to/pythonexecutable'
283 // For Windows 80 col console, use up to the column before the one marked
284 // with X (total 79 chars including logger prefix, 58 chars usable here):
285 // X
286 const info = [
287 '**********************************************************',
288 'You need to install the latest version of Python.',
289 'Node-gyp should be able to find and use Python. If not,',
290 'you can try one of the following options:',
291 `- Use the switch --python="${pathExample}"`,
292 ' (accepted by both node-gyp and npm)',
293 '- Set the environment variable PYTHON',
294 '- Set the npm configuration variable python:',
295 ` npm config set python "${pathExample}"`,
296 'For more information consult the documentation at:',
297 'https://github.com/nodejs/node-gyp#installation',
298 '**********************************************************'
299 ].join('\n')
300
301 this.log.error(`\n${errorLog}\n\n${info}\n`)
302 process.nextTick(this.callback.bind(null, new Error(
303 'Could not find any Python installation to use')))
304 }
305}
306
307function findPython (configPython, callback) {
308 var finder = new PythonFinder(configPython, callback)
309 finder.findPython()
310}
311
312module.exports = findPython
313module.exports.test = {
314 PythonFinder: PythonFinder,
315 findPython: findPython
316}
Note: See TracBrowser for help on using the repository browser.