test: use chrome-launcher for detecting chrome installation (#8758)

This commit is contained in:
Xin Du (Clark) 2021-02-03 17:38:30 +00:00 committed by GitHub
parent f35bcc61ce
commit 7d43e1fa38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 274 deletions

View File

@ -49,6 +49,7 @@
"@vue/test-utils": "^1.1.2", "@vue/test-utils": "^1.1.2",
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"babel-jest": "^26.6.3", "babel-jest": "^26.6.3",
"chrome-launcher": "^0.13.4",
"consola": "^2.15.1", "consola": "^2.15.1",
"create-require": "^1.1.1", "create-require": "^1.1.1",
"cross-spawn": "^7.0.3", "cross-spawn": "^7.0.3",
@ -62,7 +63,6 @@
"glob": "^7.1.6", "glob": "^7.1.6",
"got": "^11.8.1", "got": "^11.8.1",
"improved-yarn-audit": "^2.3.2", "improved-yarn-audit": "^2.3.2",
"is-wsl": "^2.2.0",
"jest": "^26.6.3", "jest": "^26.6.3",
"jiti": "^1.3.0", "jiti": "^1.3.0",
"jsdom": "^16.4.0", "jsdom": "^16.4.0",

View File

@ -1,12 +1,7 @@
import puppeteer from 'puppeteer-core' import puppeteer from 'puppeteer-core'
import { Launcher } from 'chrome-launcher'
import ChromeDetector from './chrome'
export default class Browser { export default class Browser {
constructor () {
this.detector = new ChromeDetector()
}
async start (options = {}) { async start (options = {}) {
// https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions // https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions
const _opts = { const _opts = {
@ -19,7 +14,7 @@ export default class Browser {
} }
if (!_opts.executablePath) { if (!_opts.executablePath) {
_opts.executablePath = this.detector.detect() _opts.executablePath = Launcher.getInstallations()[0]
} }
this.browser = await puppeteer.launch(_opts) this.browser = await puppeteer.launch(_opts)

View File

@ -1,265 +0,0 @@
/**
* @license Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import fs from 'fs'
import path from 'path'
import { execSync, execFileSync } from 'child_process'
import isWsl from 'is-wsl'
import consola from 'consola'
import { uniq } from 'lodash'
const newLineRegex = /\r?\n/
/**
* This class is based on node-get-chrome
* https://github.com/mrlee23/node-get-chrome
* https://github.com/gwuhaolin/chrome-finder
*/
export default class ChromeDetector {
constructor () {
this.platform = isWsl ? 'wsl' : process.platform
}
detect (platform = this.platform) {
const handler = this[platform]
if (typeof handler !== 'function') {
throw new TypeError(`${platform} is not supported.`)
}
return this[platform]()[0]
}
darwin () {
const suffixes = [
'/Contents/MacOS/Chromium',
'/Contents/MacOS/Google Chrome Canary',
'/Contents/MacOS/Google Chrome'
]
const LSREGISTER =
'/System/Library/Frameworks/CoreServices.framework' +
'/Versions/A/Frameworks/LaunchServices.framework' +
'/Versions/A/Support/lsregister'
const installations = []
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
execSync(
`${LSREGISTER} -dump` +
" | grep -E -i -o '/.+(google chrome( canary)?|chromium)\\.app(\\s|$)'" +
" | grep -E -v 'Caches|TimeMachine|Temporary|/Volumes|\\.Trash'"
)
.toString()
.split(newLineRegex)
.forEach((inst) => {
suffixes.forEach((suffix) => {
const execPath = path.join(inst.trim(), suffix)
if (this.canAccess(execPath)) {
installations.push(execPath)
}
})
})
// Retains one per line to maintain readability.
// clang-format off
const priorities = [
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome.app`), weight: 50 },
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome Canary.app`), weight: 51 },
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chromium.app`), weight: 52 },
{ regex: /^\/Applications\/.*Chrome.app/, weight: 100 },
{ regex: /^\/Applications\/.*Chrome Canary.app/, weight: 101 },
{ regex: /^\/Applications\/.*Chromium.app/, weight: 102 },
{ regex: /^\/Volumes\/.*Chrome.app/, weight: -3 },
{ regex: /^\/Volumes\/.*Chrome Canary.app/, weight: -2 },
{ regex: /^\/Volumes\/.*Chromium.app/, weight: -1 }
]
if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {
priorities.push({ regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH), weight: 150 })
}
if (process.env.CHROME_PATH) {
priorities.push({ regex: new RegExp(process.env.CHROME_PATH), weight: 151 })
}
// clang-format on
return this.sort(installations, priorities)
}
/**
* Look for linux executables in 3 ways
* 1. Look into CHROME_PATH env variable
* 2. Look into the directories where .desktop are saved on gnome based distro's
* 3. Look for google-chrome-stable & google-chrome executables by using the which command
*/
linux () {
let installations = []
// 1. Look into CHROME_PATH env variable
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
// 2. Look into the directories where .desktop are saved on gnome based distro's
const desktopInstallationFolders = [
path.join(require('os').homedir(), '.local/share/applications/'),
'/usr/share/applications/'
]
desktopInstallationFolders.forEach((folder) => {
installations = installations.concat(this.findChromeExecutables(folder))
})
// Look for chromium(-browser) & google-chrome(-stable) executables by using the which command
const executables = [
'chromium-browser',
'chromium',
'google-chrome-stable',
'google-chrome'
]
executables.forEach((executable) => {
try {
const chromePath = execFileSync('which', [executable])
.toString()
.split(newLineRegex)[0]
if (this.canAccess(chromePath)) {
installations.push(chromePath)
}
} catch (e) {
// Not installed.
}
})
if (!installations.length) {
throw new Error(
'The environment variable CHROME_PATH must be set to ' +
'executable of a build of Chromium version 54.0 or later.'
)
}
const priorities = [
{ regex: /chromium-browser$/, weight: 51 },
{ regex: /chromium$/, weight: 50 },
{ regex: /chrome-wrapper$/, weight: 49 },
{ regex: /google-chrome-stable$/, weight: 48 },
{ regex: /google-chrome$/, weight: 47 }
]
if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {
priorities.push({
regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH),
weight: 100
})
}
if (process.env.CHROME_PATH) {
priorities.push({ regex: new RegExp(process.env.CHROME_PATH), weight: 101 })
}
return this.sort(uniq(installations.filter(Boolean)), priorities)
}
wsl () {
// Manually populate the environment variables assuming it's the default config
process.env.LOCALAPPDATA = this.getLocalAppDataPath(process.env.PATH)
process.env.PROGRAMFILES = '/mnt/c/Program Files'
process.env['PROGRAMFILES(X86)'] = '/mnt/c/Program Files (x86)'
return this.win32()
}
win32 () {
const installations = []
const sep = path.sep
const suffixes = [
`${sep}Chromium${sep}Application${sep}chrome.exe`,
`${sep}Google${sep}Chrome SxS${sep}Application${sep}chrome.exe`,
`${sep}Google${sep}Chrome${sep}Application${sep}chrome.exe`,
`${sep}chrome-win32${sep}chrome.exe`,
`${sep}Google${sep}Chrome Beta${sep}Application${sep}chrome.exe`
]
const prefixes = [
process.env.LOCALAPPDATA,
process.env.PROGRAMFILES,
process.env['PROGRAMFILES(X86)']
].filter(Boolean)
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
prefixes.forEach(prefix =>
suffixes.forEach((suffix) => {
const chromePath = path.join(prefix, suffix)
if (this.canAccess(chromePath)) {
installations.push(chromePath)
}
})
)
return installations
}
resolveChromePath () {
if (this.canAccess(process.env.CHROME_PATH)) {
return process.env.CHROME_PATH
}
if (this.canAccess(process.env.LIGHTHOUSE_CHROMIUM_PATH)) {
consola.warn(
'ChromeLauncher',
'LIGHTHOUSE_CHROMIUM_PATH is deprecated, use CHROME_PATH env variable instead.'
)
return process.env.LIGHTHOUSE_CHROMIUM_PATH
}
}
getLocalAppDataPath (path) {
const userRegExp = /\/mnt\/([a-z])\/Users\/([^/:]+)\/AppData\//
const results = userRegExp.exec(path) || []
return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`
}
sort (installations, priorities) {
const defaultPriority = 10
return installations
.map((inst) => {
for (const pair of priorities) {
if (pair.regex.test(inst)) {
return { path: inst, weight: pair.weight }
}
}
return { path: inst, weight: defaultPriority }
})
.sort((a, b) => b.weight - a.weight)
.map(pair => pair.path)
}
canAccess (file) {
if (!file) {
return false
}
try {
fs.accessSync(file)
return true
} catch (e) {
return false
}
}
findChromeExecutables (folder) {
const argumentsRegex = /(^[^ ]+).*/ // Take everything up to the first space
const chromeExecRegex = '^Exec=/.*/(google-chrome|chrome|chromium)-.*'
const installations = []
if (this.canAccess(folder)) {
// Output of the grep & print looks like:
// /opt/google/chrome/google-chrome --profile-directory
// /home/user/Downloads/chrome-linux/chrome-wrapper %U
let execPaths
// Some systems do not support grep -R so fallback to -r.
// See https://github.com/GoogleChrome/chrome-launcher/issues/46 for more context.
try {
execPaths = execSync(
`grep -ER "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`
)
} catch (e) {
execPaths = execSync(
`grep -Er "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`
)
}
execPaths = execPaths
.toString()
.split(newLineRegex)
.map(execPath => execPath.replace(argumentsRegex, '$1'))
execPaths.forEach(
execPath => this.canAccess(execPath) && installations.push(execPath)
)
}
return installations
}
}

View File

@ -4421,6 +4421,18 @@ chownr@^2.0.0:
resolved "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" resolved "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece"
integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==
chrome-launcher@^0.13.4:
version "0.13.4"
resolved "https://registry.npmjs.org/chrome-launcher/-/chrome-launcher-0.13.4.tgz#4c7d81333c98282899c4e38256da23e00ed32f73"
integrity sha512-nnzXiDbGKjDSK6t2I+35OAPBy5Pw/39bgkb/ZAFwMhwJbdYBp6aH+vW28ZgtjdU890Q7D+3wN/tB8N66q5Gi2A==
dependencies:
"@types/node" "*"
escape-string-regexp "^1.0.5"
is-wsl "^2.2.0"
lighthouse-logger "^1.0.0"
mkdirp "^0.5.3"
rimraf "^3.0.2"
chrome-trace-event@^1.0.2: chrome-trace-event@^1.0.2:
version "1.0.2" version "1.0.2"
resolved "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" resolved "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4"
@ -5301,7 +5313,7 @@ de-indent@^1.0.2:
resolved "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz#b2038e846dc33baa5796128d0804b455b8c1e21d" resolved "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz#b2038e846dc33baa5796128d0804b455b8c1e21d"
integrity sha1-sgOOhG3DO6pXlhKNCAS0VbjB4h0= integrity sha1-sgOOhG3DO6pXlhKNCAS0VbjB4h0=
debug@2.6.9, debug@^2.2.0, debug@^2.3.3, debug@^2.6.9: debug@2.6.9, debug@^2.2.0, debug@^2.3.3, debug@^2.6.8, debug@^2.6.9:
version "2.6.9" version "2.6.9"
resolved "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" resolved "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==
@ -8679,6 +8691,14 @@ levn@~0.3.0:
prelude-ls "~1.1.2" prelude-ls "~1.1.2"
type-check "~0.3.2" type-check "~0.3.2"
lighthouse-logger@^1.0.0:
version "1.2.0"
resolved "https://registry.npmjs.org/lighthouse-logger/-/lighthouse-logger-1.2.0.tgz#b76d56935e9c137e86a04741f6bb9b2776e886ca"
integrity sha512-wzUvdIeJZhRsG6gpZfmSCfysaxNEr43i+QT+Hie94wvHDKFLi4n7C2GqZ4sTC+PH5b5iktmXJvU87rWvhP3lHw==
dependencies:
debug "^2.6.8"
marky "^1.2.0"
lines-and-columns@^1.1.6: lines-and-columns@^1.1.6:
version "1.1.6" version "1.1.6"
resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00"
@ -8996,6 +9016,11 @@ map-visit@^1.0.0:
dependencies: dependencies:
object-visit "^1.0.0" object-visit "^1.0.0"
marky@^1.2.0:
version "1.2.1"
resolved "https://registry.npmjs.org/marky/-/marky-1.2.1.tgz#a3fcf82ffd357756b8b8affec9fdbf3a30dc1b02"
integrity sha512-md9k+Gxa3qLH6sUKpeC2CNkJK/Ld+bEz5X96nYwloqphQE0CKCVEKco/6jxEZixinqNdz5RFi/KaCyfbMDMAXQ==
md5.js@^1.3.4: md5.js@^1.3.4:
version "1.3.5" version "1.3.5"
resolved "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f" resolved "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f"