mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 13:40:42 +00:00
Compare commits
1 Commits
split/1-lo
...
feat/affec
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3b573be22 |
@@ -29,6 +29,7 @@
|
||||
"commitlint": "commitlint --edit $1",
|
||||
"test": "jest",
|
||||
"test:changedsince": "jest --changedSince=main --coverage --silent",
|
||||
"test:affected": "node scripts/affected-tests.mjs",
|
||||
"generate:api": "orval --config ./orval.config.ts && sh scripts/post-types-generation.sh",
|
||||
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'",
|
||||
"build:geo-outlines": "node scripts/geo-outlines/build.mjs"
|
||||
|
||||
210
frontend/scripts/affected-tests.mjs
Normal file
210
frontend/scripts/affected-tests.mjs
Normal file
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env node
|
||||
// Usage: node scripts/affected-tests.mjs [--suite unit|storybook|e2e|all] [--base <ref>] [--list] [-- <runner args>]
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
E2E,
|
||||
e2eIndex,
|
||||
specsImporting,
|
||||
specsVisiting,
|
||||
} from './affected/e2e.mjs';
|
||||
import {
|
||||
REPO,
|
||||
changedFiles,
|
||||
changedPackages,
|
||||
git,
|
||||
importersOf,
|
||||
} from './affected/git.mjs';
|
||||
import { FRONTEND, pnpm, relatedFiles } from './affected/jestGraph.mjs';
|
||||
import { log } from './affected/log.mjs';
|
||||
import { SHELL_ENTRY, pageEntries } from './affected/routes.mjs';
|
||||
|
||||
const SHARED = String.raw`^frontend/(pnpm-lock\.yaml|pnpm-workspace\.yaml|tsconfig.*\.json)$`;
|
||||
|
||||
// Any change here can affect every test of the suite, so the import graph cannot narrow it.
|
||||
const RUN_ALL = {
|
||||
unit: [
|
||||
SHARED,
|
||||
String.raw`^frontend/(jest\.\w+\.\w+|babel\.config\.cjs)$`,
|
||||
'^frontend/(__mocks__|src/__tests__)/',
|
||||
],
|
||||
storybook: [
|
||||
SHARED,
|
||||
String.raw`^frontend/vite\.config\.ts$`,
|
||||
'^frontend/(\\.storybook|src/storybook/mocks|vite-plugins)/',
|
||||
],
|
||||
e2e: [
|
||||
SHARED,
|
||||
String.raw`^frontend/(vite\.config\.ts|index\.html)$`,
|
||||
'^frontend/vite-plugins/',
|
||||
String.raw`^tests/e2e/(package\.json|pnpm-lock\.yaml|playwright\.config\.ts|tsconfig\.json)$`,
|
||||
'^tests/e2e/bootstrap/',
|
||||
],
|
||||
};
|
||||
|
||||
const STORY_MATCH = [
|
||||
'<rootDir>/src/**/*.stories.ts',
|
||||
'<rootDir>/src/**/*.stories.tsx',
|
||||
];
|
||||
const SHELL_SPEC_DIRS = ['app-shell', 'routing'];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const sep = argv.indexOf('--');
|
||||
const own = sep === -1 ? argv : argv.slice(0, sep);
|
||||
const opts = {
|
||||
base: 'origin/main',
|
||||
list: false,
|
||||
suite: 'unit',
|
||||
extra: sep === -1 ? [] : argv.slice(sep + 1),
|
||||
};
|
||||
for (let i = 0; i < own.length; i++) {
|
||||
if (own[i] === '--base') {
|
||||
opts.base = own[++i];
|
||||
} else if (own[i] === '--suite') {
|
||||
opts.suite = own[++i];
|
||||
} else if (own[i] === '--list') {
|
||||
opts.list = true;
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
// src/pages/DashboardPage/x/y.test.tsx -> pages/DashboardPage
|
||||
function srcFeature(file) {
|
||||
const parts = path.relative(path.join(FRONTEND, 'src'), file).split(path.sep);
|
||||
return parts.length > 2 ? `${parts[0]}/${parts[1]}` : parts[0];
|
||||
}
|
||||
|
||||
function printGroups(title, files, feature) {
|
||||
const groups = Object.entries(Object.groupBy(files, feature)).sort(
|
||||
(a, b) => b[1].length - a[1].length,
|
||||
);
|
||||
log(`\n[${title}] ${groups.length} features, ${files.length} files:`);
|
||||
groups.forEach(([name, list]) =>
|
||||
log(` ${String(list.length).padStart(4)} ${name}`),
|
||||
);
|
||||
}
|
||||
|
||||
// Swaps a dependency-only package.json bump for the source files that import the bumped packages.
|
||||
function expandBumps(files, mergeBase) {
|
||||
if (!files.includes('frontend/package.json')) {
|
||||
return { files };
|
||||
}
|
||||
const pkgs = changedPackages(mergeBase, 'frontend/package.json');
|
||||
if (!pkgs) {
|
||||
return {
|
||||
files,
|
||||
reason: 'frontend/package.json changed beyond dependency versions',
|
||||
};
|
||||
}
|
||||
log(`\nBumped packages: ${pkgs.join(', ')}`);
|
||||
const rest = files.filter(
|
||||
(f) => f !== 'frontend/package.json' && f !== 'frontend/pnpm-lock.yaml',
|
||||
);
|
||||
return {
|
||||
files: [
|
||||
...new Set([
|
||||
...rest,
|
||||
...pkgs.flatMap((p) => importersOf(p, 'frontend/src')),
|
||||
]),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const planners = {
|
||||
unit: (src) => ({ files: relatedFiles(src), feature: srcFeature }),
|
||||
storybook: (src) => ({
|
||||
files: relatedFiles(src, STORY_MATCH),
|
||||
feature: srcFeature,
|
||||
}),
|
||||
e2e: (src, changed) => {
|
||||
const pages = pageEntries();
|
||||
const hit = new Set(
|
||||
relatedFiles(src, [...pages.map((p) => p.file), SHELL_ENTRY]),
|
||||
);
|
||||
const routes = pages.filter((p) => hit.has(p.file)).flatMap((p) => p.paths);
|
||||
log(
|
||||
`\n[e2e] routes reached: ${routes.join(' ') || 'none'}${hit.has(SHELL_ENTRY) ? ' + app shell' : ''}`,
|
||||
);
|
||||
const index = e2eIndex(pages.flatMap((p) => p.paths));
|
||||
const shell = hit.has(SHELL_ENTRY)
|
||||
? index.specs.filter((s) => SHELL_SPEC_DIRS.includes(index.feature(s)))
|
||||
: [];
|
||||
const own = specsImporting(
|
||||
index,
|
||||
changed.filter((f) => f.startsWith('tests/e2e/')),
|
||||
);
|
||||
return {
|
||||
files: [...new Set([...specsVisiting(index, routes), ...own, ...shell])],
|
||||
feature: index.feature,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const runners = {
|
||||
unit: (files, extra) =>
|
||||
pnpm(
|
||||
['exec', 'jest', ...(files ? ['--runTestsByPath', ...files] : []), ...extra],
|
||||
FRONTEND,
|
||||
),
|
||||
storybook: (files, extra) =>
|
||||
pnpm(
|
||||
[
|
||||
'test:storybook',
|
||||
...(files ?? []).map((f) => path.relative(FRONTEND, f)),
|
||||
...extra,
|
||||
],
|
||||
FRONTEND,
|
||||
),
|
||||
e2e: (files, extra) =>
|
||||
pnpm(
|
||||
[
|
||||
'exec',
|
||||
'playwright',
|
||||
'test',
|
||||
...(files ?? []).map((f) => path.relative(E2E, f)),
|
||||
...extra,
|
||||
],
|
||||
E2E,
|
||||
),
|
||||
};
|
||||
|
||||
function runSuite(suite, changed, bumpReason, src, opts) {
|
||||
const trigger = changed.find((f) =>
|
||||
RUN_ALL[suite].some((re) => new RegExp(re).test(f)),
|
||||
);
|
||||
const reason = bumpReason ?? (trigger && `${trigger} affects every test`);
|
||||
if (reason) {
|
||||
log(`\n[${suite}] ${reason}; running the full suite.`);
|
||||
return opts.list ? 0 : runners[suite](null, opts.extra).status;
|
||||
}
|
||||
const { files, feature } = planners[suite](src, changed);
|
||||
printGroups(suite, files, feature);
|
||||
if (opts.list || !files.length) {
|
||||
return 0;
|
||||
}
|
||||
return runners[suite](files, opts.extra).status;
|
||||
}
|
||||
|
||||
const opts = parseArgs(process.argv.slice(2));
|
||||
const mergeBase = git('merge-base', opts.base, 'HEAD');
|
||||
const original = changedFiles(mergeBase);
|
||||
if (!original.length) {
|
||||
log(`No frontend or e2e changes since ${opts.base}.`);
|
||||
process.exit(0);
|
||||
}
|
||||
log(`Changed files since ${opts.base} (${original.length}):`);
|
||||
original.forEach((f) => log(` ${f}`));
|
||||
|
||||
const { files: changed, reason: bumpReason } = expandBumps(original, mergeBase);
|
||||
const src = changed
|
||||
.filter((f) => f.startsWith('frontend/'))
|
||||
.map((f) => path.join(REPO, f));
|
||||
const suites = opts.suite === 'all' ? Object.keys(planners) : [opts.suite];
|
||||
const failed = suites.filter(
|
||||
(s) => runSuite(s, changed, bumpReason, src, opts) !== 0,
|
||||
);
|
||||
if (failed.length) {
|
||||
log(`\nFailed: ${failed.join(', ')}`);
|
||||
}
|
||||
process.exit(failed.length ? 1 : 0);
|
||||
107
frontend/scripts/affected/e2e.mjs
Normal file
107
frontend/scripts/affected/e2e.mjs
Normal file
@@ -0,0 +1,107 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { REPO } from './git.mjs';
|
||||
|
||||
export const E2E = path.join(REPO, 'tests/e2e');
|
||||
|
||||
// A driver used by this many features is infrastructure; its URLs say nothing about a spec's pages.
|
||||
const SHARED_FEATURE_COUNT = 5;
|
||||
|
||||
const feature = (spec) =>
|
||||
path.relative(path.join(E2E, 'tests'), spec).split(path.sep)[0];
|
||||
|
||||
function listSpecs(dir = path.join(E2E, 'tests')) {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((d) => {
|
||||
const full = path.join(dir, d.name);
|
||||
if (d.isDirectory()) {
|
||||
return listSpecs(full);
|
||||
}
|
||||
return d.name.endsWith('.spec.ts') ? [full] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function localImports(file) {
|
||||
const body = readFileSync(file, 'utf8');
|
||||
return [...body.matchAll(/(?:from|import)\s+'(\.[^']+)'/g)]
|
||||
.map(([, spec]) => path.resolve(path.dirname(file), spec))
|
||||
.map((base) =>
|
||||
[base, `${base}.ts`, `${base}/index.ts`].find(
|
||||
(f) => f.endsWith('.ts') && existsSync(f),
|
||||
),
|
||||
)
|
||||
.filter((f) => f?.startsWith(E2E));
|
||||
}
|
||||
|
||||
function closure(spec) {
|
||||
const seen = new Set();
|
||||
const visit = (f) => {
|
||||
if (seen.has(f)) {
|
||||
return;
|
||||
}
|
||||
seen.add(f);
|
||||
localImports(f).forEach(visit);
|
||||
};
|
||||
visit(spec);
|
||||
return seen;
|
||||
}
|
||||
|
||||
function routeRegex(route, nested) {
|
||||
const body = route.replace(/\/$/, '').replace(/:[^/]+/g, '[^/]+');
|
||||
return new RegExp(`^${body}${nested ? '(/.*)?' : '/?'}$`);
|
||||
}
|
||||
|
||||
// The routes a URL literal from a spec lands on; `/dashboard/` comes from `/dashboard/${id}`.
|
||||
function routesFor(literal, routes) {
|
||||
const probe = literal.endsWith('/') ? `${literal}x` : literal;
|
||||
const exact = routes.filter((r) => routeRegex(r, false).test(probe));
|
||||
if (exact.length) {
|
||||
return exact;
|
||||
}
|
||||
const nested = routes.filter((r) => routeRegex(r, true).test(probe));
|
||||
return nested.sort((a, b) => b.length - a.length).slice(0, 1);
|
||||
}
|
||||
|
||||
export function e2eIndex(routes) {
|
||||
const specs = listSpecs();
|
||||
const deps = new Map(specs.map((s) => [s, closure(s)]));
|
||||
const users = new Map();
|
||||
for (const [spec, files] of deps) {
|
||||
files.forEach((f) =>
|
||||
users.set(f, new Set([...(users.get(f) ?? []), feature(spec)])),
|
||||
);
|
||||
}
|
||||
const shared = new Set(
|
||||
[...users]
|
||||
.filter(([, feats]) => feats.size >= SHARED_FEATURE_COUNT)
|
||||
.map(([f]) => f),
|
||||
);
|
||||
const specRoutes = new Map(
|
||||
specs.map((spec) => {
|
||||
const own = [...deps.get(spec)].filter((f) => f === spec || !shared.has(f));
|
||||
const literals = own.flatMap((f) =>
|
||||
[...readFileSync(f, 'utf8').matchAll(/['"`](\/[a-z][a-z0-9/_-]*)/gi)].map(
|
||||
([, l]) => l,
|
||||
),
|
||||
);
|
||||
const hit = literals
|
||||
.filter((l) => !l.startsWith('/api/'))
|
||||
.flatMap((l) => routesFor(l, routes));
|
||||
return [spec, new Set(hit)];
|
||||
}),
|
||||
);
|
||||
return { specs, deps, specRoutes, feature };
|
||||
}
|
||||
|
||||
export function specsImporting(index, files) {
|
||||
const abs = new Set(files.map((f) => path.join(REPO, f)));
|
||||
return index.specs.filter((s) =>
|
||||
[...index.deps.get(s)].some((f) => abs.has(f)),
|
||||
);
|
||||
}
|
||||
|
||||
export function specsVisiting(index, routes) {
|
||||
return index.specs.filter((s) =>
|
||||
routes.some((r) => index.specRoutes.get(s).has(r)),
|
||||
);
|
||||
}
|
||||
60
frontend/scripts/affected/git.mjs
Normal file
60
frontend/scripts/affected/git.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export const REPO = execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
||||
cwd: import.meta.dirname,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
|
||||
const DEP_FIELDS = ['dependencies', 'devDependencies'];
|
||||
|
||||
export function git(...args) {
|
||||
return execFileSync('git', args, { cwd: REPO, encoding: 'utf8' }).trim();
|
||||
}
|
||||
|
||||
const lines = (out) => out.split('\n').filter(Boolean);
|
||||
|
||||
// Repo-relative paths under frontend/ and tests/e2e/ that differ from mergeBase, uncommitted included.
|
||||
export function changedFiles(mergeBase) {
|
||||
const scope = ['frontend', 'tests/e2e'];
|
||||
const tracked = lines(git('diff', '--name-only', mergeBase, '--', ...scope));
|
||||
const untracked = lines(
|
||||
git('ls-files', '--others', '--exclude-standard', '--', ...scope),
|
||||
);
|
||||
return [...new Set([...tracked, ...untracked])].filter((f) =>
|
||||
existsSync(path.join(REPO, f)),
|
||||
);
|
||||
}
|
||||
|
||||
// Changed package names, or null when anything besides dependency versions changed.
|
||||
export function changedPackages(mergeBase, pkgJson) {
|
||||
const before = JSON.parse(git('show', `${mergeBase}:${pkgJson}`));
|
||||
const after = JSON.parse(readFileSync(path.join(REPO, pkgJson), 'utf8'));
|
||||
const strip = (pkg) =>
|
||||
JSON.stringify({
|
||||
...pkg,
|
||||
...Object.fromEntries(DEP_FIELDS.map((k) => [k, null])),
|
||||
});
|
||||
if (strip(before) !== strip(after)) {
|
||||
return null;
|
||||
}
|
||||
const names = new Set(
|
||||
DEP_FIELDS.flatMap((k) => Object.keys({ ...before[k], ...after[k] })),
|
||||
);
|
||||
return [...names].filter((n) =>
|
||||
DEP_FIELDS.some((k) => before[k]?.[n] !== after[k]?.[n]),
|
||||
);
|
||||
}
|
||||
|
||||
export function importersOf(pkg, dir) {
|
||||
const out = spawnSync(
|
||||
'git',
|
||||
['grep', '-lE', `['"]${pkg}(/[^'"]*)?['"]`, '--', dir],
|
||||
{
|
||||
cwd: REPO,
|
||||
encoding: 'utf8',
|
||||
},
|
||||
).stdout;
|
||||
return lines(out);
|
||||
}
|
||||
30
frontend/scripts/affected/jestGraph.mjs
Normal file
30
frontend/scripts/affected/jestGraph.mjs
Normal file
@@ -0,0 +1,30 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
export const FRONTEND = path.resolve(import.meta.dirname, '../..');
|
||||
|
||||
export function pnpm(args, cwd, stdio = 'inherit') {
|
||||
return spawnSync('pnpm', args, {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
stdio,
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
}
|
||||
|
||||
// Absolute paths of files matching testMatch whose import graph reaches any of files.
|
||||
export function relatedFiles(files, testMatch) {
|
||||
if (!files.length) {
|
||||
return [];
|
||||
}
|
||||
const match = testMatch ? ['--testMatch', ...testMatch] : [];
|
||||
const res = pnpm(
|
||||
['exec', 'jest', '--listTests', '--findRelatedTests', ...files, ...match],
|
||||
FRONTEND,
|
||||
'pipe',
|
||||
);
|
||||
if (res.status !== 0) {
|
||||
throw new Error(`jest --listTests failed:\n${res.stderr}`);
|
||||
}
|
||||
return res.stdout.split('\n').filter((l) => l.startsWith('/'));
|
||||
}
|
||||
1
frontend/scripts/affected/log.mjs
Normal file
1
frontend/scripts/affected/log.mjs
Normal file
@@ -0,0 +1 @@
|
||||
export const log = (message) => process.stdout.write(`${message}\n`);
|
||||
57
frontend/scripts/affected/routes.mjs
Normal file
57
frontend/scripts/affected/routes.mjs
Normal file
@@ -0,0 +1,57 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { FRONTEND } from './jestGraph.mjs';
|
||||
|
||||
const SRC = path.join(FRONTEND, 'src');
|
||||
const read = (rel) => readFileSync(path.join(SRC, rel), 'utf8');
|
||||
|
||||
// Mounted around every page, so a change it reaches shows up as the shell, not as a page.
|
||||
export const SHELL_ENTRY = path.join(SRC, 'container/AppLayout/index.tsx');
|
||||
|
||||
function resolveModule(spec) {
|
||||
const base = path.join(SRC, spec);
|
||||
const candidates = ['.tsx', '.ts', '/index.tsx', '/index.ts'].map(
|
||||
(ext) => base + ext,
|
||||
);
|
||||
return candidates.find(existsSync);
|
||||
}
|
||||
|
||||
function routePaths() {
|
||||
const body = read('constants/routes.ts');
|
||||
return Object.fromEntries(
|
||||
[...body.matchAll(/^\s*(\w+):\s*'([^']+)'/gm)].map(([, k, v]) => [
|
||||
k,
|
||||
v.split('?')[0],
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function componentModules() {
|
||||
const body = read('AppRoutes/pageComponents.ts');
|
||||
const re =
|
||||
/export const (\w+) = Loadable\(\s*\(\)\s*=>\s*import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?'([^']+)'/g;
|
||||
return Object.fromEntries(
|
||||
[...body.matchAll(re)].map(([, name, spec]) => [name, resolveModule(spec)]),
|
||||
);
|
||||
}
|
||||
|
||||
// [{ file, paths }] for every page module the router mounts.
|
||||
export function pageEntries() {
|
||||
const paths = routePaths();
|
||||
const modules = componentModules();
|
||||
const byFile = new Map();
|
||||
for (const [block] of read('AppRoutes/routes.ts').matchAll(/\{[^{}]*\}/g)) {
|
||||
const component = block.match(/component:\s*(\w+)/)?.[1];
|
||||
const pathLine = block.match(/path:\s*([^\n]+)/)?.[1] ?? '';
|
||||
const file = modules[component];
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
const routeKeys = [...pathLine.matchAll(/ROUTES\.(\w+)/g)]
|
||||
.map(([, k]) => paths[k])
|
||||
.filter(Boolean);
|
||||
byFile.set(file, [...(byFile.get(file) ?? []), ...routeKeys]);
|
||||
}
|
||||
return [...byFile].map(([file, p]) => ({ file, paths: [...new Set(p)] }));
|
||||
}
|
||||
Reference in New Issue
Block a user