@skathio/somi 5.1.0 → 5.2.0
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +13 -5
- package/VERSION +1 -1
- package/agents/somi-reviewer.md +1 -1
- package/agents/somi-security-reviewer.md +1 -1
- package/commands/somi-deliver.md +1 -1
- package/commands/somi.md +2 -2
- package/hooks/pre-tool/apply-tier.mjs +12 -6
- package/package.json +1 -2
- package/rules/digest.md +6 -0
- package/scripts/lib/advisor.mjs +34 -10
- package/scripts/lib/chat-commands.mjs +65 -0
- package/scripts/lib/git-tree.mjs +32 -8
- package/scripts/lib/policy.mjs +30 -4
- package/scripts/lib/pr.mjs +2 -2
- package/scripts/lib/quality/clones.mjs +113 -26
- package/scripts/lib/quality/coupling.mjs +115 -0
- package/scripts/lib/quality/exports.mjs +33 -0
- package/scripts/lib/quality/findings.mjs +18 -0
- package/scripts/lib/quality/functions.mjs +71 -0
- package/scripts/lib/quality/gate.mjs +134 -144
- package/scripts/lib/quality/imports.mjs +88 -0
- package/scripts/lib/quality/js-source.mjs +55 -0
- package/scripts/lib/quality/limits.mjs +102 -23
- package/scripts/lib/quality/metrics.mjs +65 -16
- package/scripts/lib/quality/parse.mjs +16 -11
- package/scripts/lib/quality/path-aliases.mjs +36 -0
- package/scripts/lib/quality/python-exports.mjs +31 -0
- package/scripts/lib/quality/python-findings.mjs +82 -0
- package/scripts/lib/quality/python-imports.mjs +64 -0
- package/scripts/lib/quality/python.mjs +50 -0
- package/scripts/lib/quality/repo.mjs +31 -12
- package/scripts/lib/quality/run.mjs +2 -2
- package/scripts/lib/quality/slop.mjs +168 -0
- package/scripts/lib/quality/suppressions.mjs +38 -0
- package/scripts/lib/quality/totals.mjs +39 -0
- package/scripts/lib/reviews.mjs +12 -6
- package/scripts/lib/views.mjs +3 -1
- package/scripts/lib/workflows.mjs +22 -1
- package/scripts/somi-mcp.mjs +7 -2
- package/scripts/somi.mjs +7 -5
- package/scripts/vendor/tree-sitter/LICENSE.tree-sitter-python +21 -0
- package/scripts/vendor/tree-sitter/manifest.json +11 -1
- package/scripts/vendor/tree-sitter/tree-sitter-python.wasm +0 -0
- package/workflows/deliver-stages.js +360 -37
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// quality/limits.mjs: the gate's thresholds, calibrated on 12 well-kept JavaScript and TypeScript projects (benchmarks/quality/). The
|
|
2
2
|
// function limits are the common SonarSource and ESLint ones, which a few percent of those projects' functions exceed. Tests may run
|
|
3
3
|
// longer, and a copy has to be SonarQube's 100 tokens, about ten lines, because shorter repeated patterns were most of the false alarms.
|
|
4
|
+
// Python is held to the same limits: on 8 well-kept Python projects they fail about 8% of recent commits (the Python record in the
|
|
5
|
+
// same folder).
|
|
4
6
|
//
|
|
5
7
|
// The gate runs at two scopes. A commit is a small step, checked before it is made against the last commit. A pull request is the whole
|
|
6
8
|
// branch since it left the shared history. A function over a limit is over it at either scope, so every limit is shared except how much
|
|
@@ -16,10 +18,12 @@ export const CHANGE_SCOPES = Object.freeze(['commit', 'pr']);
|
|
|
16
18
|
export const SCOPES = Object.freeze([...CHANGE_SCOPES, 'repo']);
|
|
17
19
|
|
|
18
20
|
export const DEFAULT_LIMITS = Object.freeze({
|
|
19
|
-
function: Object.freeze({ cognitive: 15, depth: 4, lines: 60, params: 4 }),
|
|
20
|
-
component: Object.freeze({ cognitive: 15, depth: 4, lines: 150, params: 4 }),
|
|
21
|
-
test: Object.freeze({ cognitive: 8, depth: 3, lines: 150, params: 4 }),
|
|
22
|
-
|
|
21
|
+
function: Object.freeze({ cognitive: 15, depth: 4, lines: 60, params: 4, options: 6 }),
|
|
22
|
+
component: Object.freeze({ cognitive: 15, depth: 4, lines: 150, params: 4, options: 12 }),
|
|
23
|
+
test: Object.freeze({ cognitive: 8, depth: 3, lines: 150, params: 4, options: 6 }),
|
|
24
|
+
growth: Object.freeze({ cognitive: 10, lines: 40 }),
|
|
25
|
+
file: Object.freeze({ cognitive: 100, added_cognitive: 25, lines: 400, added_lines: 300, functions: 40 }),
|
|
26
|
+
imports: Object.freeze({ fan_out: 15 }),
|
|
23
27
|
clones: Object.freeze({ tokens: 100 }),
|
|
24
28
|
css: Object.freeze({ nesting: 3, compound: 3, ids: 0, important: 0 }),
|
|
25
29
|
suppressions: Object.freeze({ added: 0 }),
|
|
@@ -32,16 +36,74 @@ export const DEFAULT_LIMITS = Object.freeze({
|
|
|
32
36
|
// hooks/hooks.json, is set above the maximum, so the host never cuts the gate off first.
|
|
33
37
|
export const QUALITY_TIMEOUT = Object.freeze({ default: 300, min: 10, max: 1800 });
|
|
34
38
|
|
|
35
|
-
|
|
39
|
+
// A user who wants a looser gate names a level in their own config, as quality.level, rather than tuning limits one by one. strict is
|
|
40
|
+
// the default and the calibrated one. standard loosens each limit by about a third; relaxed puts the function limits near what the
|
|
41
|
+
// 99th percentile of well-kept projects' functions reach. No level allows a new suppression or loosens the rules that are not limits,
|
|
42
|
+
// such as a debugger left behind or a swallowed error. A level only loosens, and a value set under quality still applies after it.
|
|
43
|
+
export const LEVELS = Object.freeze(['strict', 'standard', 'relaxed']);
|
|
44
|
+
const LEVEL_LIMITS = Object.freeze({
|
|
45
|
+
strict: {},
|
|
46
|
+
standard: {
|
|
47
|
+
function: { cognitive: 20, depth: 5, lines: 80, params: 5, options: 8 },
|
|
48
|
+
component: { cognitive: 20, depth: 5, lines: 200, params: 5, options: 16 },
|
|
49
|
+
test: { cognitive: 12, depth: 4, lines: 200, params: 5, options: 8 },
|
|
50
|
+
growth: { cognitive: 15, lines: 60 },
|
|
51
|
+
file: { cognitive: 150, added_cognitive: 40, lines: 600, added_lines: 450, functions: 60 },
|
|
52
|
+
imports: { fan_out: 20 },
|
|
53
|
+
clones: { tokens: 150 },
|
|
54
|
+
css: { nesting: 4, compound: 4 },
|
|
55
|
+
},
|
|
56
|
+
relaxed: {
|
|
57
|
+
function: { cognitive: 30, depth: 6, lines: 120, params: 6, options: 10 },
|
|
58
|
+
component: { cognitive: 30, depth: 6, lines: 300, params: 6, options: 20 },
|
|
59
|
+
test: { cognitive: 16, depth: 5, lines: 300, params: 6, options: 10 },
|
|
60
|
+
growth: { cognitive: 25, lines: 100 },
|
|
61
|
+
file: { cognitive: 250, added_cognitive: 60, lines: 1000, added_lines: 600, functions: 100 },
|
|
62
|
+
imports: { fan_out: 30 },
|
|
63
|
+
clones: { tokens: 250 },
|
|
64
|
+
css: { nesting: 5, compound: 5 },
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const SCOPE_DEFAULTS = Object.freeze({ commit: {}, pr: { file: { added_cognitive: 100, added_lines: 1000 } }, repo: {} });
|
|
36
69
|
|
|
37
|
-
/** The
|
|
38
|
-
export function limitsFor(scope = 'pr') {
|
|
70
|
+
/** The limits at one scope and level, strict by default, as a fresh object. A level never tightens a scope's own default. */
|
|
71
|
+
export function limitsFor(scope = 'pr', level = 'strict') {
|
|
39
72
|
if (!SCOPES.includes(scope)) throw new Error(`the quality scope is ${SCOPES.join(', ')}, not ${scope}`);
|
|
40
73
|
const limits = Object.fromEntries(Object.entries(DEFAULT_LIMITS).map(([group, values]) => [group, { ...values }]));
|
|
41
74
|
for (const [group, values] of Object.entries(SCOPE_DEFAULTS[scope])) Object.assign(limits[group], values);
|
|
75
|
+
for (const [group, values] of Object.entries(LEVEL_LIMITS[level] ?? {})) {
|
|
76
|
+
for (const [key, value] of Object.entries(values)) limits[group][key] = Math.max(limits[group][key], value);
|
|
77
|
+
}
|
|
42
78
|
return limits;
|
|
43
79
|
}
|
|
44
80
|
|
|
81
|
+
/**
|
|
82
|
+
* { level, ignored }: strict, then the user's own quality.level, then a project's only where it is stricter, since a project's config
|
|
83
|
+
* is cloned input.
|
|
84
|
+
*/
|
|
85
|
+
export function resolveLevel({ global = {}, project = {} } = {}) {
|
|
86
|
+
const r = resolveSetting({ global, project }, {
|
|
87
|
+
name: 'level', start: 'strict', valid: (v) => LEVELS.includes(v), invalid: `not one of ${LEVELS.join(', ')}`,
|
|
88
|
+
projectMay: (v, now) => LEVELS.indexOf(v) <= LEVELS.indexOf(now), refused: (v, now) => `a project may only tighten the level, and ${v} is looser than ${now}`,
|
|
89
|
+
});
|
|
90
|
+
return { level: r.value, ignored: r.ignored };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// One quality setting from both files: the user's own sets it either way, and a project's only in the direction projectMay allows.
|
|
94
|
+
function resolveSetting({ global, project }, { name, start, valid, invalid, projectMay, refused }) {
|
|
95
|
+
let value = start;
|
|
96
|
+
const ignored = [];
|
|
97
|
+
for (const [where, file] of [['global', global], ['project', project]]) {
|
|
98
|
+
const v = file?.quality?.[name];
|
|
99
|
+
if (v === undefined) continue;
|
|
100
|
+
if (!valid(v)) ignored.push({ where, key: `quality.${name}`, reason: invalid });
|
|
101
|
+
else if (where === 'project' && !projectMay(v, value)) ignored.push({ where, key: `quality.${name}`, reason: refused(v, value) });
|
|
102
|
+
else value = v;
|
|
103
|
+
}
|
|
104
|
+
return { value, ignored };
|
|
105
|
+
}
|
|
106
|
+
|
|
45
107
|
const valid = (v) => Number.isInteger(v) && v >= 0 && v <= 100000;
|
|
46
108
|
const NOT_A_LIMIT = 'not a quality limit';
|
|
47
109
|
const NOT_A_NUMBER = 'not a whole number from 0 to 100000';
|
|
@@ -59,39 +121,56 @@ function apply(limits, ignored, { where, prefix, group, key, value }) {
|
|
|
59
121
|
|
|
60
122
|
function applyLayer(limits, ignored, { where, prefix, layer }) {
|
|
61
123
|
for (const [group, values] of Object.entries(layer ?? {})) {
|
|
62
|
-
if (prefix === 'quality' && (SCOPES.includes(group) ||
|
|
124
|
+
if (prefix === 'quality' && (SCOPES.includes(group) || ['timeout_seconds', 'level', FORBID_KEY].includes(group))) continue;
|
|
63
125
|
if (!DEFAULT_LIMITS[group]) { ignored.push({ where, key: `${prefix}.${group}`, reason: NOT_A_LIMIT }); continue; }
|
|
64
126
|
for (const [key, value] of Object.entries(values ?? {})) apply(limits, ignored, { where, prefix, group, key, value });
|
|
65
127
|
}
|
|
66
128
|
}
|
|
67
129
|
|
|
68
130
|
/**
|
|
69
|
-
* { limits, ignored } at one scope: the scope's defaults, then the global file's shared quality and its quality.<scope>, then the
|
|
131
|
+
* { limits, level, ignored } at one scope: the scope's defaults at the chosen level, then the global file's shared quality and its quality.<scope>, then the
|
|
70
132
|
* project file's, in that order.
|
|
71
133
|
*/
|
|
72
134
|
export function resolveLimits({ global = {}, project = {}, scope = 'pr' } = {}) {
|
|
73
|
-
const
|
|
74
|
-
const
|
|
135
|
+
const chosen = resolveLevel({ global, project });
|
|
136
|
+
const limits = limitsFor(scope, chosen.level);
|
|
137
|
+
const ignored = [...chosen.ignored];
|
|
75
138
|
for (const [where, file] of [['global', global], ['project', project]]) {
|
|
76
139
|
applyLayer(limits, ignored, { where, prefix: 'quality', layer: file?.quality });
|
|
77
140
|
applyLayer(limits, ignored, { where, prefix: `quality.${scope}`, layer: file?.quality?.[scope] });
|
|
78
141
|
}
|
|
79
|
-
return { limits, ignored: [...ignored, ...resolveTimeout({ global, project }).ignored] };
|
|
142
|
+
return { limits, level: chosen.level, ignored: [...ignored, ...resolveTimeout({ global, project }).ignored] };
|
|
80
143
|
}
|
|
81
144
|
|
|
82
|
-
|
|
83
|
-
|
|
145
|
+
// Folders that must not import others, as quality.forbid_imports: [{ "from": "src/ui/", "to": "src/db/" }]. Each rule only adds a
|
|
146
|
+
// restriction, so both the user's file and a project's may set them, and the gate holds a change to all of them.
|
|
147
|
+
const FORBID_KEY = 'forbid_imports';
|
|
148
|
+
const MAX_FORBID = 100;
|
|
149
|
+
const prefix = (v) => typeof v === 'string' && v.length > 0 && v.length <= 200;
|
|
84
150
|
|
|
85
|
-
/** {
|
|
86
|
-
export function
|
|
87
|
-
|
|
151
|
+
/** { forbid: [{ from, to }], ignored } from both files. */
|
|
152
|
+
export function resolveForbidden({ global = {}, project = {} } = {}) {
|
|
153
|
+
const forbid = [];
|
|
88
154
|
const ignored = [];
|
|
89
155
|
for (const [where, file] of [['global', global], ['project', project]]) {
|
|
90
|
-
const
|
|
91
|
-
if (
|
|
92
|
-
if (!
|
|
93
|
-
|
|
94
|
-
|
|
156
|
+
const rules = file?.quality?.[FORBID_KEY];
|
|
157
|
+
if (rules === undefined) continue;
|
|
158
|
+
if (!Array.isArray(rules) || rules.length > MAX_FORBID) { ignored.push({ where, key: `quality.${FORBID_KEY}`, reason: `not a list of at most ${MAX_FORBID} { from, to } folder rules` }); continue; }
|
|
159
|
+
for (const r of rules) {
|
|
160
|
+
if (prefix(r?.from) && prefix(r?.to)) forbid.push({ from: r.from, to: r.to });
|
|
161
|
+
else ignored.push({ where, key: `quality.${FORBID_KEY}`, reason: 'a rule needs from and to, each a path prefix' });
|
|
162
|
+
}
|
|
95
163
|
}
|
|
96
|
-
return {
|
|
164
|
+
return { forbid, ignored };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const timeoutValid = (v) => Number.isInteger(v) && v >= QUALITY_TIMEOUT.min && v <= QUALITY_TIMEOUT.max;
|
|
168
|
+
|
|
169
|
+
/** { seconds, ignored }: the default, then the global file's quality.timeout_seconds, then the project's if it is longer. */
|
|
170
|
+
export function resolveTimeout({ global = {}, project = {} } = {}) {
|
|
171
|
+
const r = resolveSetting({ global, project }, {
|
|
172
|
+
name: 'timeout_seconds', start: QUALITY_TIMEOUT.default, valid: timeoutValid, invalid: `not a whole number of seconds from ${QUALITY_TIMEOUT.min} to ${QUALITY_TIMEOUT.max}`,
|
|
173
|
+
projectMay: (v, now) => v >= now, refused: (v, now) => `a project may only lengthen the time, and ${v} is shorter than ${now}`,
|
|
174
|
+
});
|
|
175
|
+
return { seconds: r.value, ignored: r.ignored };
|
|
97
176
|
}
|
|
@@ -1,15 +1,21 @@
|
|
|
1
|
-
// quality/metrics.mjs: per-function structure of JavaScript, TypeScript and
|
|
1
|
+
// quality/metrics.mjs: per-function structure of JavaScript, TypeScript, C# and Python, from a tree-sitter tree. SoMi-CC v1 follows SonarSource's
|
|
2
2
|
// cognitive complexity: +1 for each break in linear flow, plus the nesting level for one that is nested, +1 per sequence of like
|
|
3
3
|
// boolean operators, +1 for recursion, and nothing for shorthand such as ?? or ?. . It deviates in one way, written down so nobody
|
|
4
4
|
// reads it as Sonar parity: a function nested in another is scored as its own unit, starting at the control-flow nesting around the
|
|
5
5
|
// point where it is defined. Sonar folds it into the outer function, which would score a test file's describe block as one function.
|
|
6
6
|
|
|
7
|
-
// The C#
|
|
7
|
+
// The C# and Python grammars' node types sit beside the JavaScript ones. An else-if in C# is an if_statement held directly as the
|
|
8
|
+
// alternative. Python holds every elif and the else as alternatives of the one if, catches with except, and branches with match.
|
|
8
9
|
const FUNCTIONS = new Set(['function_declaration', 'function_expression', 'function', 'arrow_function', 'method_definition', 'generator_function_declaration', 'generator_function',
|
|
9
|
-
'method_declaration', 'constructor_declaration', 'destructor_declaration', 'operator_declaration', 'conversion_operator_declaration', 'local_function_statement', 'lambda_expression', 'anonymous_method_expression'
|
|
10
|
+
'method_declaration', 'constructor_declaration', 'destructor_declaration', 'operator_declaration', 'conversion_operator_declaration', 'local_function_statement', 'lambda_expression', 'anonymous_method_expression',
|
|
11
|
+
'accessor_declaration', 'function_definition', 'lambda']);
|
|
10
12
|
const LOOPS = new Set(['for_statement', 'for_in_statement', 'for_of_statement', 'while_statement', 'do_statement', 'foreach_statement']);
|
|
11
13
|
const TERNARY = new Set(['ternary_expression', 'conditional_expression', 'switch_expression']);
|
|
12
|
-
const DEPTH = new Set(['if_statement', 'switch_statement', 'try_statement', ...LOOPS]);
|
|
14
|
+
const DEPTH = new Set(['if_statement', 'switch_statement', 'match_statement', 'try_statement', ...LOOPS]);
|
|
15
|
+
const CATCHES = new Set(['catch_clause', 'except_clause', 'except_group_clause']);
|
|
16
|
+
const NOT_A_PARAMETER = new Set(['comment', 'positional_separator', 'keyword_separator']);
|
|
17
|
+
// Python parameters a caller may leave out. Together they do the work of one options object in JavaScript, so they count as one.
|
|
18
|
+
const OPTIONAL_PARAMETER = new Set(['default_parameter', 'typed_default_parameter', 'list_splat_pattern', 'dictionary_splat_pattern']);
|
|
13
19
|
const BOOLEAN = new Set(['&&', '||']);
|
|
14
20
|
const JSX = new Set(['jsx_element', 'jsx_self_closing_element', 'jsx_fragment']);
|
|
15
21
|
|
|
@@ -19,12 +25,14 @@ const isElseIf = (node) => node.type === 'if_statement' && (node.parent?.type ==
|
|
|
19
25
|
const operator = (node) => field(node, 'operator')?.type ?? node.children.find((c) => !c.isNamed && BOOLEAN.has(c.type))?.type;
|
|
20
26
|
|
|
21
27
|
function nameOf(node) {
|
|
28
|
+
// A C# property's get and set are named for the property, so every property's getter is not the same function called get.
|
|
29
|
+
if (node.type === 'accessor_declaration') return `${field(node.parent?.parent, 'name')?.text ?? '<property>'}.${field(node, 'name')?.text ?? node.children[0]?.text}`;
|
|
22
30
|
const own = field(node, 'name');
|
|
23
31
|
if (own) return own.text;
|
|
24
32
|
const p = node.parent;
|
|
25
33
|
if (p?.type === 'variable_declarator') return field(p, 'name')?.text ?? null;
|
|
26
34
|
if (p?.type === 'pair') return field(p, 'key')?.text ?? null;
|
|
27
|
-
if (p?.type === 'assignment_expression') return field(p, 'left')?.text ?? null;
|
|
35
|
+
if (p?.type === 'assignment_expression' || p?.type === 'assignment') return field(p, 'left')?.text ?? null;
|
|
28
36
|
if (p?.type === 'public_field_definition' || p?.type === 'field_definition') return field(p, 'property')?.text ?? field(p, 'name')?.text ?? null;
|
|
29
37
|
return null;
|
|
30
38
|
}
|
|
@@ -33,15 +41,33 @@ function paramCount(node) {
|
|
|
33
41
|
if (field(node, 'parameter')) return 1;
|
|
34
42
|
const params = field(node, 'parameters');
|
|
35
43
|
if (params?.type === 'implicit_parameter') return 1;
|
|
36
|
-
|
|
44
|
+
if (!params) return 0;
|
|
45
|
+
// A Python method's self or cls is how the language passes the object, not an argument a caller gives.
|
|
46
|
+
const receiver = (c, i) => i === 0 && node.type === 'function_definition' && c.type === 'identifier' && (c.text === 'self' || c.text === 'cls');
|
|
47
|
+
const given = params.namedChildren.filter((c, i) => !NOT_A_PARAMETER.has(c.type) && !receiver(c, i));
|
|
48
|
+
const required = given.filter((c) => !OPTIONAL_PARAMETER.has(c.type)).length;
|
|
49
|
+
return required + (required < given.length ? 1 : 0);
|
|
37
50
|
}
|
|
38
51
|
|
|
52
|
+
// Names a function takes through destructured parameters: `function f({ a, b, c })` takes three, though it has one parameter. A
|
|
53
|
+
// large options object hides as many inputs as a long parameter list.
|
|
54
|
+
const PATTERNS = new Set(['object_pattern', 'array_pattern']);
|
|
55
|
+
function optionCount(node) {
|
|
56
|
+
const params = field(node, 'parameters');
|
|
57
|
+
if (!params) return 0;
|
|
58
|
+
const patternOf = (p) => (PATTERNS.has(p.type) ? p : [field(p, 'pattern'), field(p, 'left')].find((x) => x && PATTERNS.has(x.type)));
|
|
59
|
+
return params.namedChildren.map(patternOf).filter(Boolean).reduce((n, p) => n + p.namedChildren.filter((c) => c.type !== 'comment').length, 0);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A Python docstring is documentation held in a string statement, so it is not a line of code.
|
|
63
|
+
const isDocstring = (n) => n.type === 'expression_statement' && n.parent?.type === 'block' && n.namedChildCount === 1 && n.namedChildren[0].type === 'string';
|
|
64
|
+
|
|
39
65
|
// Lines that hold code: the start row of every token that is not a comment. A nested function's lines are its own, as its complexity
|
|
40
66
|
// is, so a test file's describe block is not as long as every test inside it.
|
|
41
|
-
function logicalLines(node) {
|
|
67
|
+
function logicalLines(node, { nested = false } = {}) {
|
|
42
68
|
const rows = new Set();
|
|
43
69
|
const visit = (n) => {
|
|
44
|
-
if (n !== node && FUNCTIONS.has(n.type)) return;
|
|
70
|
+
if ((!nested && n !== node && FUNCTIONS.has(n.type)) || isDocstring(n)) return;
|
|
45
71
|
if (n.childCount === 0) { if (n.type !== 'comment' && n.text.trim() !== '') rows.add(n.startPosition.row); return; }
|
|
46
72
|
for (const c of n.children) visit(c);
|
|
47
73
|
};
|
|
@@ -62,12 +88,25 @@ function ifStatement(node, nesting, ctx) {
|
|
|
62
88
|
const base = elseIf ? nesting - 1 : nesting;
|
|
63
89
|
ctx.walk(field(node, 'condition'), base);
|
|
64
90
|
ctx.walk(field(node, 'consequence'), base + 1);
|
|
65
|
-
const alternative
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
91
|
+
for (const alternative of node.childrenForFieldName('alternative')) {
|
|
92
|
+
if (alternative.type === 'elif_clause') {
|
|
93
|
+
ctx.score += 1;
|
|
94
|
+
ctx.walk(field(alternative, 'condition'), base);
|
|
95
|
+
ctx.walk(field(alternative, 'consequence'), base + 1);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const inner = alternative.type === 'else_clause' ? alternative.namedChildren.find((c) => c.type !== 'comment') : alternative;
|
|
99
|
+
if (inner && inner.type !== 'if_statement') ctx.score += 1;
|
|
100
|
+
ctx.walk(inner, base + 1);
|
|
101
|
+
}
|
|
69
102
|
}
|
|
70
103
|
|
|
104
|
+
// An except clause has no body field: everything it holds sits one level deeper.
|
|
105
|
+
const catches = (node, nesting, ctx) => {
|
|
106
|
+
ctx.score += 1 + nesting;
|
|
107
|
+
for (const c of node.namedChildren) ctx.walk(c, nesting + 1);
|
|
108
|
+
};
|
|
109
|
+
|
|
71
110
|
const nestsIn = (fields) => (node, nesting, ctx) => {
|
|
72
111
|
ctx.score += 1 + nesting;
|
|
73
112
|
const deeper = fields.map((f) => field(node, f));
|
|
@@ -83,7 +122,10 @@ const STRUCTURES = {
|
|
|
83
122
|
for (const c of node.namedChildren) ctx.walk(c, c.type === 'switch_expression_arm' ? nesting + 1 : nesting);
|
|
84
123
|
},
|
|
85
124
|
switch_statement: nestsIn(['body']),
|
|
125
|
+
match_statement: nestsIn(['body']),
|
|
86
126
|
catch_clause: nestsIn(['body']),
|
|
127
|
+
except_clause: catches,
|
|
128
|
+
except_group_clause: catches,
|
|
87
129
|
...Object.fromEntries([...LOOPS].map((type) => [type, nestsIn(['body'])])),
|
|
88
130
|
};
|
|
89
131
|
|
|
@@ -97,7 +139,9 @@ const recursion = (node, ctx) => {
|
|
|
97
139
|
const callee = field(node, 'function');
|
|
98
140
|
return ctx.name && callee?.type === 'identifier' && callee.text === ctx.name ? 1 : 0;
|
|
99
141
|
};
|
|
100
|
-
|
|
142
|
+
// Python spells its boolean operators as words and keeps them in a node type of their own.
|
|
143
|
+
const wordSequence = (node) => (node.parent?.type === 'boolean_operator' && operator(node.parent) === operator(node) ? 0 : 1);
|
|
144
|
+
const FLAT = { break_statement: labelled, continue_statement: labelled, goto_statement: () => 1, binary_expression: sequence, boolean_operator: wordSequence, call_expression: recursion, invocation_expression: recursion, call: recursion };
|
|
101
145
|
|
|
102
146
|
// Cognitive complexity of one unit. Nested functions are left out here and scored as their own units by unitsOf.
|
|
103
147
|
function cognitive(unit, name, startNesting) {
|
|
@@ -131,13 +175,13 @@ function maxDepth(unit) {
|
|
|
131
175
|
function nestingAt(node) {
|
|
132
176
|
let n = 0;
|
|
133
177
|
for (let p = node.parent, child = node; p && !FUNCTIONS.has(p.type); child = p, p = p.parent) {
|
|
134
|
-
if (LOOPS.has(p.type) || p.type === 'switch_statement' || p.type === '
|
|
178
|
+
if (LOOPS.has(p.type) || p.type === 'switch_statement' || p.type === 'match_statement' || CATCHES.has(p.type) || TERNARY.has(p.type)) n += 1;
|
|
135
179
|
if (p.type === 'if_statement' && !same(child, field(p, 'condition'))) n += 1;
|
|
136
180
|
}
|
|
137
181
|
return n;
|
|
138
182
|
}
|
|
139
183
|
|
|
140
|
-
/** Every function in the tree with its metrics: name, kind, lines, cognitive, depth and
|
|
184
|
+
/** Every function in the tree with its metrics: name, kind, lines, cognitive, depth, params and options, oldest-first by position. */
|
|
141
185
|
export function unitsOf(tree, { file = '', isTest = false } = {}) {
|
|
142
186
|
const units = [];
|
|
143
187
|
const visit = (node, inherited) => {
|
|
@@ -153,7 +197,9 @@ export function unitsOf(tree, { file = '', isTest = false } = {}) {
|
|
|
153
197
|
lines: logicalLines(node),
|
|
154
198
|
cognitive: cognitive(node, name, start),
|
|
155
199
|
depth: maxDepth(node),
|
|
156
|
-
|
|
200
|
+
// A pytest test names the fixtures it wants as parameters. Nobody passes them, so they are not arguments to count.
|
|
201
|
+
params: isTest && node.type === 'function_definition' ? 0 : paramCount(node),
|
|
202
|
+
options: optionCount(node),
|
|
157
203
|
// C# overloads, and a constructor beside its destructor, share a name: the gate tells them apart by this.
|
|
158
204
|
signature: `${node.type}(${(field(node, 'parameters') ?? field(node, 'parameter'))?.text.replace(/\s+/g, ' ') ?? ''})`,
|
|
159
205
|
});
|
|
@@ -166,6 +212,9 @@ export function unitsOf(tree, { file = '', isTest = false } = {}) {
|
|
|
166
212
|
return units;
|
|
167
213
|
}
|
|
168
214
|
|
|
215
|
+
/** Lines that hold code in the whole file, functions included. */
|
|
216
|
+
export const codeLines = (tree) => logicalLines(tree.rootNode, { nested: true });
|
|
217
|
+
|
|
169
218
|
/** Complexity of code outside any function, which counts toward the file's total. */
|
|
170
219
|
export function topLevelCognitive(tree) {
|
|
171
220
|
return cognitive(tree.rootNode, null, 0);
|
|
@@ -10,7 +10,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
10
10
|
const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'vendor', 'tree-sitter');
|
|
11
11
|
export const MAX_FILE_BYTES = 512 * 1024;
|
|
12
12
|
export const PARSE_TIMEOUT_MS = 5000;
|
|
13
|
-
const LANGUAGES = { '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascript', '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'tsx', '.css': 'css', '.cs': 'c-sharp' };
|
|
13
|
+
const LANGUAGES = { '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascript', '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'tsx', '.css': 'css', '.cs': 'c-sharp', '.py': 'python' };
|
|
14
14
|
|
|
15
15
|
/** The grammar a file is parsed with, or null when the gate does not cover its language yet. */
|
|
16
16
|
export const languageOf = (file) => LANGUAGES[path.extname(file).toLowerCase()] ?? null;
|
|
@@ -29,17 +29,22 @@ export function verifiedFile(name, dir = DIR) {
|
|
|
29
29
|
return bytes;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// The runtime and each grammar are loaded once, as promises, so two parses that start together share one load. Each used to start its
|
|
33
|
+
// own, and the second start of the runtime broke the grammar the first had loaded: "Incompatible language version 0".
|
|
34
|
+
async function startRuntime() {
|
|
35
|
+
verifiedFile('web-tree-sitter.js');
|
|
36
|
+
const wasmBinary = verifiedFile('web-tree-sitter.wasm');
|
|
37
|
+
const mod = await import(pathToFileURL(path.join(DIR, 'web-tree-sitter.js')).href);
|
|
38
|
+
await mod.Parser.init({ wasmBinary });
|
|
39
|
+
return mod;
|
|
40
|
+
}
|
|
41
|
+
|
|
32
42
|
async function load(language) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
runtime = mod;
|
|
39
|
-
}
|
|
40
|
-
if (!grammars.has(language)) grammars.set(language, await runtime.Language.load(verifiedFile(`tree-sitter-${language}.wasm`)));
|
|
41
|
-
const parser = new runtime.Parser();
|
|
42
|
-
parser.setLanguage(grammars.get(language));
|
|
43
|
+
runtime ??= startRuntime();
|
|
44
|
+
const mod = await runtime;
|
|
45
|
+
if (!grammars.has(language)) grammars.set(language, mod.Language.load(verifiedFile(`tree-sitter-${language}.wasm`)));
|
|
46
|
+
const parser = new mod.Parser();
|
|
47
|
+
parser.setLanguage(await grammars.get(language));
|
|
43
48
|
return parser;
|
|
44
49
|
}
|
|
45
50
|
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// quality/path-aliases.mjs: the import aliases a root tsconfig.json or jsconfig.json declares under compilerOptions.paths and baseUrl,
|
|
2
|
+
// and the repository paths an aliased import may name. The config is JSON with comments and trailing commas, so its comments are blanked
|
|
3
|
+
// the way source comments are and its trailing commas dropped before it is parsed. Anything that cannot be read declares no alias.
|
|
4
|
+
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { codeOnly } from './js-source.mjs';
|
|
7
|
+
|
|
8
|
+
const MAX_ALIASES = 100;
|
|
9
|
+
const pattern = (p) => { const star = p.indexOf('*'); return star === -1 ? { prefix: p, suffix: null } : { prefix: p.slice(0, star), suffix: p.slice(star + 1) }; };
|
|
10
|
+
|
|
11
|
+
/** The path aliases a tsconfig.json or jsconfig.json declares: [{ prefix, suffix, targets }], or [] when it has none or cannot be read. */
|
|
12
|
+
export function aliasesFrom(text) {
|
|
13
|
+
let options;
|
|
14
|
+
try { options = JSON.parse(codeOnly(text).replace(/,(\s*[}\]])/g, '$1'))?.compilerOptions; } catch { return []; }
|
|
15
|
+
if (!options || typeof options !== 'object') return [];
|
|
16
|
+
const base = typeof options.baseUrl === 'string' ? path.posix.normalize(options.baseUrl) : '.';
|
|
17
|
+
const paths = options.paths && typeof options.paths === 'object' ? Object.entries(options.paths) : [];
|
|
18
|
+
const out = paths.filter(([, to]) => Array.isArray(to)).slice(0, MAX_ALIASES)
|
|
19
|
+
.map(([from, to]) => ({ ...pattern(from), targets: to.filter((t) => typeof t === 'string').map((t) => ({ ...pattern(path.posix.join(base, t)) })) }));
|
|
20
|
+
// baseUrl alone lets 'src/x' name the file src/x from the configured root, as a catch-all after the declared aliases.
|
|
21
|
+
if (typeof options.baseUrl === 'string') out.push({ prefix: '', suffix: '', targets: [{ prefix: base === '.' ? '' : `${base}/`, suffix: '' }] });
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The paths an aliased import may name, in the order TypeScript tries them.
|
|
26
|
+
export function aliased(spec, aliases) {
|
|
27
|
+
for (const a of aliases) {
|
|
28
|
+
if (a.suffix === null) { if (spec === a.prefix) return a.targets.map((t) => t.prefix); continue; }
|
|
29
|
+
if (!spec.startsWith(a.prefix) || !spec.endsWith(a.suffix) || spec.length < a.prefix.length + a.suffix.length) continue;
|
|
30
|
+
const star = spec.slice(a.prefix.length, spec.length - a.suffix.length);
|
|
31
|
+
const hits = a.targets.map((t) => (t.suffix === null ? t.prefix : `${t.prefix}${star}${t.suffix}`)).map((p) => path.posix.normalize(p));
|
|
32
|
+
if (hits.length > 0) return hits;
|
|
33
|
+
}
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// quality/python-exports.mjs: what a Python module offers to other files, read from its tree.
|
|
2
|
+
|
|
3
|
+
import { field, line } from './python-findings.mjs';
|
|
4
|
+
|
|
5
|
+
const DEFINITIONS = new Set(['function_definition', 'class_definition']);
|
|
6
|
+
|
|
7
|
+
const strings = (node) => node.namedChildren.filter((c) => c.type === 'string').map((c) => ({ name: c.namedChildren.find((p) => p.type === 'string_content')?.text ?? '', line: line(c) }));
|
|
8
|
+
|
|
9
|
+
// The names __all__ lists, from every assignment to it at the top of the file, or null when the file has none.
|
|
10
|
+
function declaredAll(root) {
|
|
11
|
+
let all = null;
|
|
12
|
+
for (const statement of root.namedChildren.filter((c) => c.type === 'expression_statement')) {
|
|
13
|
+
const assign = statement.namedChildren[0];
|
|
14
|
+
if (!assign || !['assignment', 'augmented_assignment'].includes(assign.type) || field(assign, 'left')?.text !== '__all__') continue;
|
|
15
|
+
const right = field(assign, 'right');
|
|
16
|
+
all = [...(all ?? []), ...(right && ['list', 'tuple'].includes(right.type) ? strings(right) : [])];
|
|
17
|
+
}
|
|
18
|
+
return all;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What a module offers to others: the names in __all__ when it has one, or else its top-level functions and classes whose name has no
|
|
23
|
+
* leading underscore. A decorated definition is left out, because a decorator often registers it somewhere, so nothing imports it.
|
|
24
|
+
* [{ name, line, declared }], where declared says the name came from __all__.
|
|
25
|
+
*/
|
|
26
|
+
export function exportsOf(tree) {
|
|
27
|
+
const root = tree.rootNode;
|
|
28
|
+
const all = declaredAll(root);
|
|
29
|
+
if (all) return all.filter((x) => x.name !== '' && !x.name.startsWith('_')).map((x) => ({ ...x, declared: true }));
|
|
30
|
+
return root.namedChildren.filter((c) => DEFINITIONS.has(c.type)).map((c) => ({ name: field(c, 'name')?.text ?? '', line: line(c), declared: false })).filter((x) => x.name !== '' && !x.name.startsWith('_'));
|
|
31
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// quality/python-findings.mjs: what the gate reads from one Python file's tree alone: leftover debugging and a swallowed error, under
|
|
2
|
+
// the rule names the other languages use, so findings.mjs decides what fails. A debugger and a catch-all that does nothing fail. print
|
|
3
|
+
// (console) and passing on one named exception (empty-catch) are advice: the calibration on known-good Python projects
|
|
4
|
+
// (benchmarks/quality/records/) found print is also how a command-line tool talks, and passing on one named exception is often meant.
|
|
5
|
+
|
|
6
|
+
// breakpoint(), and set_trace() however pdb, ipdb or pudb was imported: pdb.set_trace(), from pdb import set_trace, import pdb as p.
|
|
7
|
+
const DEBUGGER = /^(breakpoint|set_trace|[\w.]+\.set_trace)$/;
|
|
8
|
+
const BROAD = /\b(BaseException|Exception)\b/;
|
|
9
|
+
const EXCEPT = new Set(['except_clause', 'except_group_clause']);
|
|
10
|
+
const PASSES = new Set(['pass_statement', 'comment']);
|
|
11
|
+
|
|
12
|
+
export const field = (node, name) => node.childForFieldName(name);
|
|
13
|
+
export const line = (node) => node.startPosition.row + 1;
|
|
14
|
+
const isEllipsis = (n) => n.type === 'expression_statement' && n.namedChildCount === 1 && n.namedChildren[0].type === 'ellipsis';
|
|
15
|
+
|
|
16
|
+
function debugCall(node, test) {
|
|
17
|
+
const callee = field(node, 'function')?.text ?? '';
|
|
18
|
+
if (DEBUGGER.test(callee)) return { rule: 'debugger', level: 'violation', line: line(node), name: callee };
|
|
19
|
+
if (callee === 'print' && !test) return { rule: 'console', level: 'warning', line: line(node), name: 'print' };
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// An except that does nothing hides the failure. Catching everything that way fails, a broad type anywhere in a tuple included;
|
|
24
|
+
// passing on one named exception is advice.
|
|
25
|
+
function swallowed(node, test) {
|
|
26
|
+
const body = node.namedChildren.find((c) => c.type === 'block');
|
|
27
|
+
if (!body || !body.namedChildren.every((c) => PASSES.has(c.type) || isEllipsis(c))) return null;
|
|
28
|
+
const caught = node.namedChildren.find((c) => c.type !== 'block' && c.type !== 'comment');
|
|
29
|
+
// `except (A, B) as e` names the types in the pattern's first child; the alias is not a type.
|
|
30
|
+
const types = caught?.type === 'as_pattern' ? caught.namedChildren[0]?.text ?? '' : caught?.text ?? '';
|
|
31
|
+
const name = caught ? caught.text.slice(0, 60) : 'except';
|
|
32
|
+
if (!caught || BROAD.test(types)) return { rule: 'swallowed-error', level: 'violation', line: line(node), name };
|
|
33
|
+
return test ? null : { rule: 'empty-catch', level: 'warning', line: line(node), name };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The names an import binds: import a.b binds a, import a.b as c binds c, from x import y binds y. A star import binds nothing we can
|
|
37
|
+
// see, and from __future__ is an instruction to the compiler, not a name.
|
|
38
|
+
function importedNames(node) {
|
|
39
|
+
if (node.type === 'import_from_statement' && field(node, 'module_name')?.text === '__future__') return [];
|
|
40
|
+
const module = field(node, 'module_name')?.startIndex;
|
|
41
|
+
const names = node.type === 'import_from_statement' ? node.namedChildren.filter((c) => c.startIndex !== module) : node.namedChildren;
|
|
42
|
+
return names.flatMap((c) => {
|
|
43
|
+
// import x as x and from x import y as y are PEP 484's way to say a name is re-exported on purpose.
|
|
44
|
+
if (c.type === 'aliased_import') return field(c, 'name')?.text === field(c, 'alias')?.text ? [] : [field(c, 'alias') ?? c.namedChildren.at(-1)];
|
|
45
|
+
return c.type === 'dotted_name' ? [c.namedChildren[0] ?? c] : [];
|
|
46
|
+
}).filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// An import nothing in the file uses: no identifier outside the imports reads it, and no string names it, which covers __all__ and a
|
|
50
|
+
// type written as a string. A package's __init__.py imports to re-export, so it is not read, and neither is an import marked noqa. Advice, as unused-binding is elsewhere.
|
|
51
|
+
function unusedImports(root) {
|
|
52
|
+
const imports = [];
|
|
53
|
+
const used = new Set();
|
|
54
|
+
const strings = [];
|
|
55
|
+
const visit = (n, inImport) => {
|
|
56
|
+
const here = inImport || n.type === 'import_statement' || n.type === 'import_from_statement';
|
|
57
|
+
const quiet = n.nextSibling?.type === 'comment' && n.nextSibling.startPosition.row === n.endPosition.row && /noqa/.test(n.nextSibling.text);
|
|
58
|
+
if ((n.type === 'import_statement' || n.type === 'import_from_statement') && !quiet) imports.push(...importedNames(n));
|
|
59
|
+
if (!here && n.type === 'identifier') used.add(n.text);
|
|
60
|
+
if (n.type === 'string') strings.push(n.text);
|
|
61
|
+
for (const c of n.namedChildren) visit(c, here);
|
|
62
|
+
};
|
|
63
|
+
visit(root, false);
|
|
64
|
+
const named = (name) => strings.some((t) => new RegExp(`\\b${name}\\b`).test(t));
|
|
65
|
+
return imports.filter((id) => !used.has(id.text) && !named(id.text)).map((id) => ({ rule: 'unused-import', level: 'warning', line: line(id), name: id.text }));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Leftover debugging, swallowed errors and unused imports in one file: [{ rule, level, line, name }]. reexports is true for a package's
|
|
70
|
+
* __init__.py, whose imports are its interface. A test may print and may pass on one named error,
|
|
71
|
+
* but a debugger stops the suite and a catch-all that does nothing hides what failed, in a test as anywhere.
|
|
72
|
+
*/
|
|
73
|
+
export function pythonFindings(tree, { test = false, reexports = false } = {}) {
|
|
74
|
+
const out = [];
|
|
75
|
+
const visit = (n) => {
|
|
76
|
+
const found = n.type === 'call' ? debugCall(n, test) : EXCEPT.has(n.type) ? swallowed(n, test) : null;
|
|
77
|
+
if (found) out.push(found);
|
|
78
|
+
for (const c of n.namedChildren) visit(c);
|
|
79
|
+
};
|
|
80
|
+
visit(tree.rootNode);
|
|
81
|
+
return reexports ? out : [...out, ...unusedImports(tree.rootNode)];
|
|
82
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// quality/python-imports.mjs: what a Python file imports, and whether another file uses a name a module offers. An absolute import is
|
|
2
|
+
// matched against the end of a file's path, because the gate does not know the import roots.
|
|
3
|
+
|
|
4
|
+
import { field } from './python-findings.mjs';
|
|
5
|
+
|
|
6
|
+
const dotted = (file) => file.replace(/\.py$/i, '').replace(/\/__init__$/, '').split('/').filter(Boolean);
|
|
7
|
+
const endsWith = (whole, tail) => tail.length > 0 && tail.length <= whole.length && tail.every((part, i) => whole[whole.length - tail.length + i] === part);
|
|
8
|
+
|
|
9
|
+
// The module an import names, as path parts. A relative import counts up from the importing file's own package.
|
|
10
|
+
function importedModule(node, importer) {
|
|
11
|
+
const module = field(node, 'module_name');
|
|
12
|
+
if (module?.type !== 'relative_import') return { parts: module ? module.text.split('.') : [], absolute: true };
|
|
13
|
+
const level = module.namedChildren.find((c) => c.type === 'import_prefix')?.text.length ?? 1;
|
|
14
|
+
const base = importer.split('/').slice(0, -1);
|
|
15
|
+
const name = module.namedChildren.find((c) => c.type === 'dotted_name')?.text.split('.') ?? [];
|
|
16
|
+
return { parts: [...base.slice(0, base.length - (level - 1)), ...name], absolute: false };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const importedName = (node) => (node.type === 'aliased_import' ? field(node, 'name')?.text : node.text) ?? '';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What one file imports: [{ parts, absolute, names, star }] for each `from x import a, b`, and { parts, absolute: true, whole: true }
|
|
23
|
+
* for each `import x.y`. parts is the module as path parts, resolved against the importing file for a relative import.
|
|
24
|
+
*/
|
|
25
|
+
export function importsOf(tree, importer) {
|
|
26
|
+
const out = [];
|
|
27
|
+
const visit = (n) => {
|
|
28
|
+
if (n.type === 'import_from_statement') {
|
|
29
|
+
const module = field(n, 'module_name');
|
|
30
|
+
const named = n.namedChildren.filter((c) => !module || c.startIndex !== module.startIndex);
|
|
31
|
+
out.push({ ...importedModule(n, importer), names: named.filter((c) => c.type !== 'wildcard_import').map(importedName), star: named.some((c) => c.type === 'wildcard_import') });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (n.type === 'import_statement') { for (const c of n.namedChildren) out.push({ parts: importedName(c).split('.'), absolute: true, whole: true }); return; }
|
|
35
|
+
for (const c of n.namedChildren) visit(c);
|
|
36
|
+
};
|
|
37
|
+
visit(tree.rootNode);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// An absolute import names a module from some root the gate does not know (src/, the repository, an installed name), so it matches a
|
|
42
|
+
// file when it is the end of the file's path. A relative one was resolved from the importer, so it must be the whole path.
|
|
43
|
+
const names = (imp, target) => (imp.absolute ? endsWith(target, imp.parts) : imp.parts.join('/') === target.join('/'));
|
|
44
|
+
// A name can come from the text of an __all__ string, which is repository content, so it is matched literally. Python names may be
|
|
45
|
+
// any letters, so a word's edge is any letter, digit or underscore, not ASCII's \b.
|
|
46
|
+
const literal = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
47
|
+
const EDGE = '[\\p{L}\\p{N}_]';
|
|
48
|
+
/** A pattern for `name` as a whole word, optionally after a dot. */
|
|
49
|
+
export const wordOf = (name, { dotted = false } = {}) => new RegExp(`${dotted ? '\\.' : `(?<!${EDGE})`}${literal(name)}(?!${EDGE})`, 'u');
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether another file uses `name` from the module at `file`: it imports the name, imports everything, or imports the module and
|
|
53
|
+
* reaches the name through it. `others` is [{ file, text, imports }].
|
|
54
|
+
*/
|
|
55
|
+
export function isImported(file, name, others) {
|
|
56
|
+
const target = dotted(file);
|
|
57
|
+
const through = wordOf(name, { dotted: true });
|
|
58
|
+
return others.some((o) => o.file !== file && o.imports.some((imp) => {
|
|
59
|
+
if (imp.whole) return names(imp, target) && through.test(o.text);
|
|
60
|
+
if (names(imp, target)) return imp.star || imp.names.includes(name);
|
|
61
|
+
// `from pkg import util` brings the module itself, and the name is then reached as util.name.
|
|
62
|
+
return imp.names.some((n) => names({ ...imp, parts: [...imp.parts, n] }, target)) && through.test(o.text);
|
|
63
|
+
}));
|
|
64
|
+
}
|