playwright-smart-test 1.0.5 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +24 -3
- package/dist/diff/git-diff-analyzer.d.ts +2 -1
- package/dist/diff/git-diff-analyzer.js +25 -6
- package/dist/reporters/github-commenter.d.ts +26 -0
- package/dist/reporters/github-commenter.js +145 -0
- package/dist/reporters/github-reporter.js +6 -1
- package/dist/reporters/terminal-reporter.js +6 -1
- package/dist/selector/test-selector.d.ts +4 -0
- package/dist/selector/test-selector.js +22 -9
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -9,12 +9,13 @@ import { TestCatalogIndexer } from '../catalog/test-catalog.js';
|
|
|
9
9
|
import { TestSelector } from '../selector/test-selector.js';
|
|
10
10
|
import { TerminalReporter } from '../reporters/terminal-reporter.js';
|
|
11
11
|
import { GitHubReporter } from '../reporters/github-reporter.js';
|
|
12
|
+
import { GitHubCommenter } from '../reporters/github-commenter.js';
|
|
12
13
|
import { PlaywrightRunner } from '../runner/playwright-runner.js';
|
|
13
14
|
const program = new Command();
|
|
14
15
|
program
|
|
15
16
|
.name('playwright-smart-test')
|
|
16
17
|
.description('AI-Powered Smart Regression Test Selection Agent for Playwright')
|
|
17
|
-
.version('1.0.
|
|
18
|
+
.version('1.0.7');
|
|
18
19
|
async function executeAnalysis(options) {
|
|
19
20
|
const cwd = options.cwd ? path.resolve(options.cwd) : process.cwd();
|
|
20
21
|
const config = loadConfig(cwd, options.config);
|
|
@@ -73,10 +74,15 @@ program
|
|
|
73
74
|
.option('-c, --config <path>', 'Path to custom config file')
|
|
74
75
|
.option('--cwd <dir>', 'Working directory', process.cwd())
|
|
75
76
|
.option('--dry-run', 'Print the command without executing')
|
|
77
|
+
.option('--comment', 'Automatically post or update PR comment and step summary on GitHub')
|
|
76
78
|
.action(async (options) => {
|
|
77
79
|
try {
|
|
78
80
|
const { result, cwd } = await executeAnalysis(options);
|
|
79
81
|
TerminalReporter.report(result);
|
|
82
|
+
if (options.comment) {
|
|
83
|
+
const markdown = GitHubReporter.generateMarkdown(result);
|
|
84
|
+
await GitHubCommenter.postOrUpdateComment(markdown);
|
|
85
|
+
}
|
|
80
86
|
if (options.dryRun) {
|
|
81
87
|
console.log(pc.yellow(`[Dry-run] Would execute: ${result.playwrightCommand}`));
|
|
82
88
|
return;
|
|
@@ -95,17 +101,32 @@ program
|
|
|
95
101
|
});
|
|
96
102
|
program
|
|
97
103
|
.command('comment')
|
|
98
|
-
.description('Generate GitHub PR comment
|
|
104
|
+
.description('Generate and post GitHub PR comment report')
|
|
99
105
|
.option('-b, --base <ref>', 'Base git commit/branch')
|
|
100
106
|
.option('-h, --head <ref>', 'Head git commit/branch')
|
|
101
107
|
.option('--staged', 'Analyze only staged changes')
|
|
102
108
|
.option('-c, --config <path>', 'Path to custom config file')
|
|
103
109
|
.option('--cwd <dir>', 'Working directory', process.cwd())
|
|
110
|
+
.option('--pr <number>', 'Explicit pull request number')
|
|
111
|
+
.option('--repo <owner/repo>', 'Explicit GitHub repository')
|
|
112
|
+
.option('--token <token>', 'Explicit GitHub Token')
|
|
113
|
+
.option('--stdout', 'Only output markdown to stdout without attempting GitHub API post')
|
|
104
114
|
.action(async (options) => {
|
|
105
115
|
try {
|
|
106
116
|
const { result } = await executeAnalysis(options);
|
|
107
117
|
const markdown = GitHubReporter.generateMarkdown(result);
|
|
108
|
-
|
|
118
|
+
if (options.stdout) {
|
|
119
|
+
console.log(markdown);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const posted = await GitHubCommenter.postOrUpdateComment(markdown, {
|
|
123
|
+
pr: options.pr ? parseInt(options.pr, 10) : undefined,
|
|
124
|
+
repo: options.repo,
|
|
125
|
+
token: options.token,
|
|
126
|
+
});
|
|
127
|
+
if (!posted) {
|
|
128
|
+
console.log(markdown);
|
|
129
|
+
}
|
|
109
130
|
}
|
|
110
131
|
catch (err) {
|
|
111
132
|
console.error(pc.red(`Error: ${err instanceof Error ? err.message : String(err)}`));
|
|
@@ -18,7 +18,8 @@ export declare class GitDiffAnalyzer {
|
|
|
18
18
|
deletions: number;
|
|
19
19
|
}>;
|
|
20
20
|
/**
|
|
21
|
-
* Split unified diff output into per-file patches
|
|
21
|
+
* Split unified diff output into per-file patches.
|
|
22
|
+
* Uses safe deterministic string operations to prevent polynomial regular expression DoS (CWE-1333).
|
|
22
23
|
*/
|
|
23
24
|
splitPatches(rawDiff: string): Map<string, string>;
|
|
24
25
|
}
|
|
@@ -84,7 +84,8 @@ export class GitDiffAnalyzer {
|
|
|
84
84
|
return map;
|
|
85
85
|
}
|
|
86
86
|
/**
|
|
87
|
-
* Split unified diff output into per-file patches
|
|
87
|
+
* Split unified diff output into per-file patches.
|
|
88
|
+
* Uses safe deterministic string operations to prevent polynomial regular expression DoS (CWE-1333).
|
|
88
89
|
*/
|
|
89
90
|
splitPatches(rawDiff) {
|
|
90
91
|
const filePatches = new Map();
|
|
@@ -92,12 +93,30 @@ export class GitDiffAnalyzer {
|
|
|
92
93
|
return filePatches;
|
|
93
94
|
const diffSections = rawDiff.split(/(?=^diff --git )/m);
|
|
94
95
|
for (const section of diffSections) {
|
|
95
|
-
|
|
96
|
+
const trimmed = section.trim();
|
|
97
|
+
if (!trimmed)
|
|
98
|
+
continue;
|
|
99
|
+
// Extract the header line without regex backtracking
|
|
100
|
+
const newlineIndex = trimmed.indexOf('\n');
|
|
101
|
+
const headerLine = (newlineIndex === -1 ? trimmed : trimmed.slice(0, newlineIndex)).trim();
|
|
102
|
+
if (!headerLine.startsWith('diff --git '))
|
|
96
103
|
continue;
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
104
|
+
const line = headerLine.slice(11); // Remove 'diff --git '
|
|
105
|
+
const sepIndex = line.lastIndexOf(' b/');
|
|
106
|
+
if (sepIndex !== -1) {
|
|
107
|
+
let filePath = line.slice(sepIndex + 3).trim();
|
|
108
|
+
// Fallback for deleted files where b/ is /dev/null
|
|
109
|
+
if (filePath === '/dev/null' || filePath === 'dev/null') {
|
|
110
|
+
const aPath = line.slice(0, sepIndex).trim();
|
|
111
|
+
filePath = aPath.startsWith('a/') ? aPath.slice(2) : aPath;
|
|
112
|
+
}
|
|
113
|
+
// Clean quotes if path was enclosed in quotes by git
|
|
114
|
+
if (filePath.startsWith('"') && filePath.endsWith('"')) {
|
|
115
|
+
filePath = filePath.slice(1, -1);
|
|
116
|
+
}
|
|
117
|
+
if (filePath) {
|
|
118
|
+
filePatches.set(filePath.replace(/\\/g, '/'), trimmed);
|
|
119
|
+
}
|
|
101
120
|
}
|
|
102
121
|
}
|
|
103
122
|
return filePatches;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface GitHubCommentOptions {
|
|
2
|
+
pr?: number;
|
|
3
|
+
repo?: string;
|
|
4
|
+
token?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare class GitHubCommenter {
|
|
7
|
+
/**
|
|
8
|
+
* Retrieves GitHub authentication token from environment or GitHub CLI
|
|
9
|
+
*/
|
|
10
|
+
static getAuthToken(overrideToken?: string): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Identifies repository and PR number from environment or GitHub Actions event payload
|
|
13
|
+
*/
|
|
14
|
+
static getPRContext(options?: GitHubCommentOptions): {
|
|
15
|
+
repo?: string;
|
|
16
|
+
prNumber?: number;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Appends report to GitHub Actions Step Summary if running in CI
|
|
20
|
+
*/
|
|
21
|
+
static writeStepSummary(markdown: string): void;
|
|
22
|
+
/**
|
|
23
|
+
* Posts or updates the comment directly on the GitHub PR
|
|
24
|
+
*/
|
|
25
|
+
static postOrUpdateComment(markdown: string, options?: GitHubCommentOptions): Promise<boolean>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { execSync } from 'node:child_process';
|
|
3
|
+
import pc from 'picocolors';
|
|
4
|
+
export class GitHubCommenter {
|
|
5
|
+
/**
|
|
6
|
+
* Retrieves GitHub authentication token from environment or GitHub CLI
|
|
7
|
+
*/
|
|
8
|
+
static getAuthToken(overrideToken) {
|
|
9
|
+
if (overrideToken)
|
|
10
|
+
return overrideToken;
|
|
11
|
+
if (process.env.GITHUB_TOKEN)
|
|
12
|
+
return process.env.GITHUB_TOKEN;
|
|
13
|
+
if (process.env.GH_TOKEN)
|
|
14
|
+
return process.env.GH_TOKEN;
|
|
15
|
+
// Fallback: check if GitHub CLI is authenticated in the current runner
|
|
16
|
+
try {
|
|
17
|
+
const output = execSync('gh auth token', { stdio: ['pipe', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
|
|
18
|
+
if (output)
|
|
19
|
+
return output;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// gh cli not installed or not authenticated
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Identifies repository and PR number from environment or GitHub Actions event payload
|
|
28
|
+
*/
|
|
29
|
+
static getPRContext(options) {
|
|
30
|
+
let repo = options?.repo || process.env.GITHUB_REPOSITORY;
|
|
31
|
+
let prNumber = options?.pr;
|
|
32
|
+
if (!prNumber && process.env.GITHUB_EVENT_PATH && fs.existsSync(process.env.GITHUB_EVENT_PATH)) {
|
|
33
|
+
try {
|
|
34
|
+
const eventData = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'));
|
|
35
|
+
if (eventData.pull_request?.number) {
|
|
36
|
+
prNumber = eventData.pull_request.number;
|
|
37
|
+
}
|
|
38
|
+
else if (eventData.issue?.number) {
|
|
39
|
+
prNumber = eventData.issue.number;
|
|
40
|
+
}
|
|
41
|
+
else if (eventData.number) {
|
|
42
|
+
prNumber = eventData.number;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// failed to parse event payload
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { repo, prNumber };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Appends report to GitHub Actions Step Summary if running in CI
|
|
53
|
+
*/
|
|
54
|
+
static writeStepSummary(markdown) {
|
|
55
|
+
const summaryFile = process.env.GITHUB_STEP_SUMMARY;
|
|
56
|
+
if (summaryFile) {
|
|
57
|
+
try {
|
|
58
|
+
fs.appendFileSync(summaryFile, `\n${markdown}\n`, 'utf8');
|
|
59
|
+
console.log(pc.green('✓ Report added to GitHub Actions Step Summary.'));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// ignore summary write error
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Posts or updates the comment directly on the GitHub PR
|
|
68
|
+
*/
|
|
69
|
+
static async postOrUpdateComment(markdown, options) {
|
|
70
|
+
// 1. Always append to GitHub Step Summary if running in Actions
|
|
71
|
+
this.writeStepSummary(markdown);
|
|
72
|
+
const token = this.getAuthToken(options?.token);
|
|
73
|
+
const { repo, prNumber } = this.getPRContext(options);
|
|
74
|
+
if (!token) {
|
|
75
|
+
console.log(pc.yellow('ℹ No GITHUB_TOKEN or gh CLI auth detected. Skipped posting PR comment (printed to console).'));
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
if (!repo || !prNumber) {
|
|
79
|
+
console.log(pc.yellow(`ℹ Not running in a pull request context (repo=${repo || 'none'}, pr=${prNumber || 'none'}). Skipped posting comment.`));
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
const apiUrl = process.env.GITHUB_API_URL || 'https://api.github.com';
|
|
83
|
+
const commentHeaderTag = '## 🤖 Playwright Smart Regression Selection Report';
|
|
84
|
+
try {
|
|
85
|
+
// 2. Fetch existing comments to see if we should update or create
|
|
86
|
+
const listRes = await fetch(`${apiUrl}/repos/${repo}/issues/${prNumber}/comments?per_page=100`, {
|
|
87
|
+
headers: {
|
|
88
|
+
Authorization: `Bearer ${token}`,
|
|
89
|
+
Accept: 'application/vnd.github+json',
|
|
90
|
+
'User-Agent': 'playwright-smart-test',
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
if (!listRes.ok) {
|
|
94
|
+
console.error(pc.red(`Failed to fetch existing PR comments: ${listRes.status} ${listRes.statusText}`));
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
const comments = (await listRes.json());
|
|
98
|
+
const existingComment = comments.find((c) => c.body && c.body.includes(commentHeaderTag));
|
|
99
|
+
if (existingComment) {
|
|
100
|
+
// Update existing comment
|
|
101
|
+
const updateRes = await fetch(`${apiUrl}/repos/${repo}/issues/comments/${existingComment.id}`, {
|
|
102
|
+
method: 'PATCH',
|
|
103
|
+
headers: {
|
|
104
|
+
Authorization: `Bearer ${token}`,
|
|
105
|
+
Accept: 'application/vnd.github+json',
|
|
106
|
+
'Content-Type': 'application/json',
|
|
107
|
+
'User-Agent': 'playwright-smart-test',
|
|
108
|
+
},
|
|
109
|
+
body: JSON.stringify({ body: markdown }),
|
|
110
|
+
});
|
|
111
|
+
if (updateRes.ok) {
|
|
112
|
+
console.log(pc.green(`✓ Updated Smart Regression comment on PR #${prNumber} in ${repo}`));
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
console.error(pc.red(`Failed to update PR comment: ${updateRes.status} ${updateRes.statusText}`));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
// Create new comment
|
|
121
|
+
const postRes = await fetch(`${apiUrl}/repos/${repo}/issues/${prNumber}/comments`, {
|
|
122
|
+
method: 'POST',
|
|
123
|
+
headers: {
|
|
124
|
+
Authorization: `Bearer ${token}`,
|
|
125
|
+
Accept: 'application/vnd.github+json',
|
|
126
|
+
'Content-Type': 'application/json',
|
|
127
|
+
'User-Agent': 'playwright-smart-test',
|
|
128
|
+
},
|
|
129
|
+
body: JSON.stringify({ body: markdown }),
|
|
130
|
+
});
|
|
131
|
+
if (postRes.ok) {
|
|
132
|
+
console.log(pc.green(`✓ Created Smart Regression comment on PR #${prNumber} in ${repo}`));
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
console.error(pc.red(`Failed to post PR comment: ${postRes.status} ${postRes.statusText}`));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
console.error(pc.red(`Error posting GitHub PR comment: ${err instanceof Error ? err.message : String(err)}`));
|
|
142
|
+
}
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -52,7 +52,12 @@ export class GitHubReporter {
|
|
|
52
52
|
markdown += `\n`;
|
|
53
53
|
}
|
|
54
54
|
markdown += `### ⚡ Playwright Execution Command\n`;
|
|
55
|
-
|
|
55
|
+
if (result.selectedSpecs.length === 0 && !result.isFullRegression) {
|
|
56
|
+
markdown += `_No tests executed (0 impacted tests identified)._\n\n`;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
markdown += `\`\`\`bash\n${result.playwrightCommand}\n\`\`\`\n\n`;
|
|
60
|
+
}
|
|
56
61
|
markdown += `---\n*Generated automatically by Smart Regression Selection Agent*`;
|
|
57
62
|
return markdown;
|
|
58
63
|
}
|
|
@@ -51,7 +51,12 @@ export class TerminalReporter {
|
|
|
51
51
|
}
|
|
52
52
|
console.log(table.toString());
|
|
53
53
|
console.log(`\n${pc.bold('⚡ Playwright Execution Command:')}`);
|
|
54
|
-
|
|
54
|
+
if (result.selectedSpecs.length === 0 && !result.isFullRegression) {
|
|
55
|
+
console.log(` ${pc.gray('No tests required for this change (0 impacted tests identified).')}\n`);
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
console.log(` ${pc.green(result.playwrightCommand)}\n`);
|
|
59
|
+
}
|
|
55
60
|
}
|
|
56
61
|
static formatRisk(score) {
|
|
57
62
|
switch (score) {
|
|
@@ -13,6 +13,10 @@ export declare class TestSelector {
|
|
|
13
13
|
private findComponentRuleSpecs;
|
|
14
14
|
private findSmokeTests;
|
|
15
15
|
private normalizeAndFilterSpecs;
|
|
16
|
+
/**
|
|
17
|
+
* Safe glob matching preventing CodeQL js/incomplete-sanitization alerts (CWE-20, CWE-80, CWE-116).
|
|
18
|
+
* Backslashes are escaped first, followed by all regex metacharacters, then converting glob wildcards.
|
|
19
|
+
*/
|
|
16
20
|
private simpleGlobMatch;
|
|
17
21
|
private buildPlaywrightCommand;
|
|
18
22
|
}
|
|
@@ -278,20 +278,33 @@ export class TestSelector {
|
|
|
278
278
|
}
|
|
279
279
|
return selected;
|
|
280
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Safe glob matching preventing CodeQL js/incomplete-sanitization alerts (CWE-20, CWE-80, CWE-116).
|
|
283
|
+
* Backslashes are escaped first, followed by all regex metacharacters, then converting glob wildcards.
|
|
284
|
+
*/
|
|
281
285
|
simpleGlobMatch(str, pattern) {
|
|
282
|
-
|
|
286
|
+
const normalizedStr = str.replace(/\\/g, '/');
|
|
287
|
+
let p = pattern.replace(/\\/g, '/');
|
|
288
|
+
let prefix = '';
|
|
289
|
+
let suffix = '';
|
|
283
290
|
if (p.startsWith('**/')) {
|
|
284
|
-
|
|
291
|
+
prefix = '(?:.+/)?';
|
|
292
|
+
p = p.slice(3);
|
|
285
293
|
}
|
|
286
294
|
if (p.endsWith('/**')) {
|
|
287
|
-
|
|
295
|
+
suffix = '(?:/.*)?';
|
|
296
|
+
p = p.slice(0, -3);
|
|
288
297
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
298
|
+
// CodeQL compliance:
|
|
299
|
+
// 1. Explicitly escape backslashes before other operations
|
|
300
|
+
// 2. Escape all special regex metacharacters: . + ? ^ $ { } ( ) | [ ]
|
|
301
|
+
// 3. Translate glob wildcards: ** -> .*, * -> [^/]*
|
|
302
|
+
const escaped = p
|
|
303
|
+
.replace(/\\/g, '\\\\')
|
|
304
|
+
.replace(/[.+?^${}()|[\]]/g, '\\$&')
|
|
305
|
+
.replace(/\*\*/g, '.*')
|
|
306
|
+
.replace(/\*/g, '[^/]*');
|
|
307
|
+
return new RegExp(`^${prefix}${escaped}${suffix}$`, 'i').test(normalizedStr);
|
|
295
308
|
}
|
|
296
309
|
buildPlaywrightCommand(selectedSpecs, isFull) {
|
|
297
310
|
if (isFull || selectedSpecs.length === 0) {
|