mirror of
https://github.com/microsoft/playwright.git
synced 2024-11-29 01:53:54 +03:00
feat(cli): introduce basic playwright CLI tool (#2571)
This commit is contained in:
parent
456c865fe8
commit
f2c47b1d33
1098
package-lock.json
generated
1098
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -8,6 +8,9 @@
|
||||
"engines": {
|
||||
"node": ">=10.15.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "lib/cli/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"ctest": "cross-env BROWSER=chromium node --unhandled-rejections=strict test/test.js",
|
||||
"ftest": "cross-env BROWSER=firefox node --unhandled-rejections=strict test/test.js",
|
||||
@ -39,6 +42,7 @@
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"commander": "^5.1.0",
|
||||
"debug": "^4.1.1",
|
||||
"extract-zip": "^2.0.0",
|
||||
"https-proxy-agent": "^3.0.0",
|
||||
@ -69,7 +73,6 @@
|
||||
"eslint": "^6.6.0",
|
||||
"esprima": "^4.0.0",
|
||||
"formidable": "^1.2.1",
|
||||
"minimist": "^1.2.5",
|
||||
"ncp": "^2.0.0",
|
||||
"node-stream-zip": "^1.8.2",
|
||||
"pixelmatch": "^4.0.2",
|
||||
|
101
src/cli/index.ts
Executable file
101
src/cli/index.ts
Executable file
@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-console */
|
||||
|
||||
import * as program from 'commander';
|
||||
import { Playwright } from '../server/playwright';
|
||||
import { BrowserType, LaunchOptions } from '../server/browserType';
|
||||
import { DeviceDescriptors } from '../deviceDescriptors';
|
||||
import { BrowserContextOptions } from '../browserContext';
|
||||
|
||||
const playwright = new Playwright(__dirname, require('../../browsers.json')['browsers']);
|
||||
|
||||
program
|
||||
.version('Version ' + require('../../package.json').version)
|
||||
.option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium')
|
||||
.option('--headless', 'run in headless mode', false)
|
||||
.option('--device <deviceName>', 'emulate device, for example "iPhone 11"');
|
||||
|
||||
program
|
||||
.command('open [url]')
|
||||
.description('open page in browser specified via -b, --browser')
|
||||
.action(function(url, command) {
|
||||
open(command.parent, url);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ open');
|
||||
console.log(' $ -b webkit open https://example.com');
|
||||
});
|
||||
|
||||
const browsers = [
|
||||
{ initial: 'cr', name: 'Chromium', type: 'chromium' },
|
||||
{ initial: 'ff', name: 'Firefox', type: 'firefox' },
|
||||
{ initial: 'wk', name: 'WebKit', type: 'webkit' },
|
||||
];
|
||||
|
||||
for (const {initial, name, type} of browsers) {
|
||||
program
|
||||
.command(`${initial} [url]`)
|
||||
.description(`open page in ${name} browser`)
|
||||
.action(function(url, command) {
|
||||
open({ ...command.parent, browser: type }, url);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(` $ ${initial} https://example.com`);
|
||||
});
|
||||
}
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
type Options = {
|
||||
browser: string,
|
||||
device: string | undefined,
|
||||
verbose: boolean,
|
||||
headless: boolean,
|
||||
};
|
||||
|
||||
async function open(options: Options, url: string | undefined) {
|
||||
const browserType = lookupBrowserType(options.browser);
|
||||
const launchOptions: LaunchOptions = { headless: options.headless };
|
||||
const browser = await browserType.launch(launchOptions);
|
||||
const contextOptions: BrowserContextOptions = options.device ? DeviceDescriptors[options.device] || {} : {};
|
||||
const page = await browser.newPage(contextOptions);
|
||||
if (url) {
|
||||
if (!url.startsWith('http'))
|
||||
url = 'http://' + url;
|
||||
await page.goto(url);
|
||||
}
|
||||
return { browser, page };
|
||||
}
|
||||
|
||||
function lookupBrowserType(name: string): BrowserType {
|
||||
switch (name) {
|
||||
case 'chromium': return playwright.chromium!;
|
||||
case 'webkit': return playwright.webkit!;
|
||||
case 'firefox': return playwright.firefox!;
|
||||
case 'cr': return playwright.chromium!;
|
||||
case 'wk': return playwright.webkit!;
|
||||
case 'ff': return playwright.firefox!;
|
||||
}
|
||||
program.help();
|
||||
}
|
@ -78,7 +78,7 @@ function prepareTemplate(strings: TemplateStringsArray) {
|
||||
html += strings[strings.length - 1];
|
||||
template.innerHTML = html;
|
||||
|
||||
const walker = template.ownerDocument!.createTreeWalker(
|
||||
const walker = template.ownerDocument.createTreeWalker(
|
||||
template.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null, false);
|
||||
const emptyTextNodes: Node[] = [];
|
||||
const subs: Sub[] = [];
|
||||
@ -145,7 +145,7 @@ function shouldRemoveTextNode(node: Text) {
|
||||
}
|
||||
|
||||
function renderTemplate(template: HTMLTemplateElement, subs: Sub[], values: (string | Node)[]): DocumentFragment | ChildNode {
|
||||
const content = template.ownerDocument!.importNode(template.content, true)!;
|
||||
const content = template.ownerDocument.importNode(template.content, true)!;
|
||||
const boundElements = Array.from(content.querySelectorAll('[dom-template-marked]'));
|
||||
for (const node of boundElements)
|
||||
node.removeAttribute('dom-template-marked');
|
||||
|
@ -33,7 +33,7 @@ export type RegisteredListener = {
|
||||
|
||||
export type Listener = (...args: any[]) => void;
|
||||
|
||||
const isDebugModeEnv = !!getFromENV('PWDEBUG');
|
||||
let isInDebugMode = !!getFromENV('PWDEBUG');
|
||||
|
||||
class Helper {
|
||||
static evaluationString(fun: Function | string, ...args: any[]): string {
|
||||
@ -303,7 +303,11 @@ class Helper {
|
||||
}
|
||||
|
||||
static isDebugMode(): boolean {
|
||||
return isDebugModeEnv;
|
||||
return isInDebugMode;
|
||||
}
|
||||
|
||||
static setDebugMode() {
|
||||
isInDebugMode = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -59,7 +59,7 @@ function queryShadowInternal(root: SelectorRoot, attribute: string, value: strin
|
||||
}
|
||||
|
||||
function queryShadowAllInternal(root: SelectorRoot, attribute: string, value: string, result: Element[]) {
|
||||
const document = root instanceof Document ? root : root.ownerDocument!;
|
||||
const document = root instanceof Document ? root : root.ownerDocument;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
|
||||
const shadowRoots = [];
|
||||
while (walker.nextNode()) {
|
||||
|
@ -315,9 +315,9 @@ export default class InjectedScript {
|
||||
textarea.focus();
|
||||
return { value: 'done' };
|
||||
}
|
||||
const range = element.ownerDocument!.createRange();
|
||||
const range = element.ownerDocument.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = element.ownerDocument!.defaultView!.getSelection();
|
||||
const selection = element.ownerDocument.defaultView!.getSelection();
|
||||
if (!selection)
|
||||
return { error: 'Element belongs to invisible iframe.' };
|
||||
selection.removeAllRanges();
|
||||
|
@ -94,7 +94,7 @@ function isFilteredNode(root: SelectorRoot, document: Document) {
|
||||
}
|
||||
|
||||
function queryInternal(root: SelectorRoot, matcher: Matcher, shadow: boolean): Element | undefined {
|
||||
const document = root instanceof Document ? root : root.ownerDocument!;
|
||||
const document = root instanceof Document ? root : root.ownerDocument;
|
||||
if (isFilteredNode(root, document))
|
||||
return;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, nodeFilter);
|
||||
@ -136,7 +136,7 @@ function queryInternal(root: SelectorRoot, matcher: Matcher, shadow: boolean): E
|
||||
}
|
||||
|
||||
function queryAllInternal(root: SelectorRoot, matcher: Matcher, shadow: boolean, result: Element[]) {
|
||||
const document = root instanceof Document ? root : root.ownerDocument!;
|
||||
const document = root instanceof Document ? root : root.ownerDocument;
|
||||
if (isFilteredNode(root, document))
|
||||
return;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, nodeFilter);
|
||||
|
204
utils/bisect.js
204
utils/bisect.js
@ -1,204 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Copyright 2018 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.
|
||||
*/
|
||||
|
||||
const URL = require('url');
|
||||
const debug = require('debug');
|
||||
const playwright = require('..');
|
||||
const browserFetcher = playwright.chromium._createBrowserFetcher();
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const {fork} = require('child_process');
|
||||
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const COLOR_RED = '\x1b[31m';
|
||||
const COLOR_GREEN = '\x1b[32m';
|
||||
const COLOR_YELLOW = '\x1b[33m';
|
||||
|
||||
const argv = require('minimist')(process.argv.slice(2), {});
|
||||
|
||||
const help = `
|
||||
Usage:
|
||||
node bisect.js --good <revision> --bad <revision> <script>
|
||||
|
||||
Parameters:
|
||||
--good revision that is known to be GOOD
|
||||
--bad revision that is known to be BAD
|
||||
<script> path to the script that returns non-zero code for BAD revisions and 0 for good
|
||||
|
||||
Example:
|
||||
node utils/bisect.js --good 577361 --bad 599821 simple.js
|
||||
`;
|
||||
|
||||
if (argv.h || argv.help) {
|
||||
console.log(help);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (typeof argv.good !== 'number') {
|
||||
console.log(COLOR_RED + 'ERROR: expected --good argument to be a number' + COLOR_RESET);
|
||||
console.log(help);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (typeof argv.bad !== 'number') {
|
||||
console.log(COLOR_RED + 'ERROR: expected --bad argument to be a number' + COLOR_RESET);
|
||||
console.log(help);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scriptPath = path.resolve(argv._[0]);
|
||||
if (!fs.existsSync(scriptPath)) {
|
||||
console.log(COLOR_RED + 'ERROR: Expected to be given a path to a script to run' + COLOR_RESET);
|
||||
console.log(help);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
(async(scriptPath, good, bad) => {
|
||||
const span = Math.abs(good - bad);
|
||||
console.log(`Bisecting ${COLOR_YELLOW}${span}${COLOR_RESET} revisions in ${COLOR_YELLOW}~${span.toString(2).length}${COLOR_RESET} iterations`);
|
||||
|
||||
while (true) {
|
||||
const middle = Math.round((good + bad) / 2);
|
||||
const revision = await findDownloadableRevision(middle, good, bad);
|
||||
if (!revision || revision === good || revision === bad)
|
||||
break;
|
||||
let info = browserFetcher.revisionInfo(revision);
|
||||
const shouldRemove = !info.local;
|
||||
info = await downloadRevision(revision);
|
||||
const exitCode = await runScript(scriptPath, info);
|
||||
if (shouldRemove)
|
||||
await browserFetcher.remove(revision);
|
||||
let outcome;
|
||||
if (exitCode) {
|
||||
bad = revision;
|
||||
outcome = COLOR_RED + 'BAD' + COLOR_RESET;
|
||||
} else {
|
||||
good = revision;
|
||||
outcome = COLOR_GREEN + 'GOOD' + COLOR_RESET;
|
||||
}
|
||||
const span = Math.abs(good - bad);
|
||||
let fromText = '';
|
||||
let toText = '';
|
||||
if (good < bad) {
|
||||
fromText = COLOR_GREEN + good + COLOR_RESET;
|
||||
toText = COLOR_RED + bad + COLOR_RESET;
|
||||
} else {
|
||||
fromText = COLOR_RED + bad + COLOR_RESET;
|
||||
toText = COLOR_GREEN + good + COLOR_RESET;
|
||||
}
|
||||
console.log(`- ${COLOR_YELLOW}r${revision}${COLOR_RESET} was ${outcome}. Bisecting [${fromText}, ${toText}] - ${COLOR_YELLOW}${span}${COLOR_RESET} revisions and ${COLOR_YELLOW}~${span.toString(2).length}${COLOR_RESET} iterations`);
|
||||
}
|
||||
|
||||
const [fromSha, toSha] = await Promise.all([
|
||||
revisionToSha(Math.min(good, bad)),
|
||||
revisionToSha(Math.max(good, bad)),
|
||||
]);
|
||||
console.log(`RANGE: https://chromium.googlesource.com/chromium/src/+log/${fromSha}..${toSha}`);
|
||||
})(scriptPath, argv.good, argv.bad);
|
||||
|
||||
function runScript(scriptPath, revisionInfo) {
|
||||
const log = debug('bisect:runscript');
|
||||
log('Running script');
|
||||
const child = fork(scriptPath, [], {
|
||||
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
|
||||
env: {
|
||||
...process.env,
|
||||
PLAYWRIGHT_EXECUTABLE_PATH: revisionInfo.executablePath,
|
||||
},
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
child.on('error', err => reject(err));
|
||||
child.on('exit', code => resolve(code));
|
||||
});
|
||||
}
|
||||
|
||||
async function downloadRevision(revision) {
|
||||
const log = debug('bisect:download');
|
||||
log(`Downloading ${revision}`);
|
||||
let progressBar = null;
|
||||
let lastDownloadedBytes = 0;
|
||||
return await browserFetcher.download(revision, (downloadedBytes, totalBytes) => {
|
||||
if (!progressBar) {
|
||||
const ProgressBar = require('progress');
|
||||
progressBar = new ProgressBar(`- downloading Chromium r${revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
|
||||
complete: '=',
|
||||
incomplete: ' ',
|
||||
width: 20,
|
||||
total: totalBytes,
|
||||
});
|
||||
}
|
||||
const delta = downloadedBytes - lastDownloadedBytes;
|
||||
lastDownloadedBytes = downloadedBytes;
|
||||
progressBar.tick(delta);
|
||||
});
|
||||
function toMegabytes(bytes) {
|
||||
const mb = bytes / 1024 / 1024;
|
||||
return `${Math.round(mb * 10) / 10} Mb`;
|
||||
}
|
||||
}
|
||||
|
||||
async function findDownloadableRevision(rev, from, to) {
|
||||
const log = debug('bisect:findrev');
|
||||
const min = Math.min(from, to);
|
||||
const max = Math.max(from, to);
|
||||
log(`Looking around ${rev} from [${min}, ${max}]`);
|
||||
if (await browserFetcher.canDownload(rev))
|
||||
return rev;
|
||||
let down = rev;
|
||||
let up = rev;
|
||||
while (min <= down || up <= max) {
|
||||
const [downOk, upOk] = await Promise.all([
|
||||
down > min ? probe(--down) : Promise.resolve(false),
|
||||
up < max ? probe(++up) : Promise.resolve(false),
|
||||
]);
|
||||
if (downOk)
|
||||
return down;
|
||||
if (upOk)
|
||||
return up;
|
||||
}
|
||||
return null;
|
||||
|
||||
async function probe(rev) {
|
||||
const result = await browserFetcher.canDownload(rev);
|
||||
log(` ${rev} - ${result ? 'OK' : 'missing'}`);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
async function revisionToSha(revision) {
|
||||
const json = await fetchJSON('https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/' + revision);
|
||||
return json.git_sha;
|
||||
}
|
||||
|
||||
function fetchJSON(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const agent = url.startsWith('https://') ? require('https') : require('http');
|
||||
const options = URL.parse(url);
|
||||
options.method = 'GET';
|
||||
options.headers = {
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
const req = agent.request(options, function(res) {
|
||||
let result = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', chunk => result += chunk);
|
||||
res.on('end', () => resolve(JSON.parse(result)));
|
||||
});
|
||||
req.on('error', err => reject(err));
|
||||
req.end();
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue
Block a user