@ref0/workspace 0.0.0-stage → 0.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/LICENSE +201 -0
- package/README.md +169 -2
- package/dist/bin.d.mts +1 -0
- package/dist/bin.mjs +113 -0
- package/dist/docs-budget.mjs +122 -0
- package/dist/lint/anti-slop/LICENSE +21 -0
- package/dist/lint/anti-slop/UPSTREAM.md +11 -0
- package/dist/lint/anti-slop/effect/plugin.d.mts +3 -0
- package/dist/lint/anti-slop/effect/plugin.mjs +19 -0
- package/dist/lint/anti-slop/effect/rules/no-manual-effect-error-tag.mjs +33 -0
- package/dist/lint/anti-slop/effect/rules/no-manual-tag-comparison.mjs +32 -0
- package/dist/lint/anti-slop/effect/rules/no-manual-tagged-construction.mjs +22 -0
- package/dist/lint/anti-slop/effect/rules/no-service-constructor-imports.mjs +36 -0
- package/dist/lint/anti-slop/effect/rules/prefer-effect-match.mjs +40 -0
- package/dist/lint/anti-slop/effect/shared/tagged-values.mjs +40 -0
- package/dist/lint/anti-slop/plugin.d.mts +3 -0
- package/dist/lint/anti-slop/plugin.mjs +45 -0
- package/dist/lint/anti-slop/rules/no-array-filter-map.mjs +31 -0
- package/dist/lint/anti-slop/rules/no-chained-type-assertions.mjs +56 -0
- package/dist/lint/anti-slop/rules/no-conditional-empty-object-spread.mjs +32 -0
- package/dist/lint/anti-slop/rules/no-known-value-widening.mjs +236 -0
- package/dist/lint/anti-slop/rules/no-module-mocking.mjs +48 -0
- package/dist/lint/anti-slop/rules/no-object-parameters.mjs +48 -0
- package/dist/lint/anti-slop/rules/no-reduce-accumulator-copy.mjs +85 -0
- package/dist/lint/anti-slop/rules/no-reflect-apply.mjs +21 -0
- package/dist/lint/anti-slop/rules/no-reflect-get.mjs +21 -0
- package/dist/lint/anti-slop/rules/no-runtime-typeof.mjs +52 -0
- package/dist/lint/anti-slop/rules/no-shape-in-symbol-names.mjs +36 -0
- package/dist/lint/anti-slop/rules/no-unknown-parameters.mjs +44 -0
- package/dist/lint/anti-slop/rules/no-unknown-returns.mjs +47 -0
- package/dist/lint/anti-slop/rules/no-unknown-type-aliases.mjs +33 -0
- package/dist/lint/anti-slop/rules/no-unsafe-dictionary-type.mjs +121 -0
- package/dist/lint/anti-slop/rules/no-widen-then-assert.mjs +191 -0
- package/dist/lint/anti-slop/rules/require-readable-spacing.mjs +86 -0
- package/dist/lint/anti-slop/rules/require-safety-comment-for-type-assertion.mjs +82 -0
- package/dist/lint/anti-slop/shared/array-method.mjs +70 -0
- package/dist/lint/anti-slop/shared/child-nodes.mjs +24 -0
- package/dist/lint/anti-slop/shared/dictionary-types.mjs +248 -0
- package/dist/lint/anti-slop/shared/function-parameters.mjs +25 -0
- package/dist/lint/anti-slop/shared/lexical-type-parameters.mjs +21 -0
- package/dist/lint/anti-slop/shared/reflect-method.mjs +16 -0
- package/dist/lint/anti-slop/shared/scope.mjs +12 -0
- package/dist/lint/anti-slop/shared/string-literal.mjs +6 -0
- package/dist/lint/anti-slop/shared/type-alias-resolution.mjs +134 -0
- package/dist/lint/anti-slop/vendor/eslint-stylistic/LICENSE +22 -0
- package/dist/lint/anti-slop/vendor/eslint-stylistic/UPSTREAM.md +29 -0
- package/dist/lint/anti-slop/vendor/eslint-stylistic/padding-line-ast.mjs +32 -0
- package/dist/lint/anti-slop/vendor/eslint-stylistic/padding-line-between-statements.mjs +608 -0
- package/dist/lint/config.d.mts +20 -0
- package/dist/lint/config.mjs +135 -0
- package/dist/lint/generic/effect-encoding.mjs +45 -0
- package/dist/lint/generic/entry-reexports.mjs +81 -0
- package/dist/lint/generic/env-at-entrypoints.mjs +65 -0
- package/dist/lint/generic/export-type-side-effects.mjs +22 -0
- package/dist/lint/generic/index-barrel.mjs +14 -0
- package/dist/lint/generic/log-messages.mjs +39 -0
- package/dist/lint/generic/plugin.d.mts +6 -0
- package/dist/lint/generic/plugin.mjs +26 -0
- package/dist/lint/generic/seeded-properties.mjs +78 -0
- package/dist/lint/plugins.d.mts +9 -0
- package/dist/lint/plugins.mjs +14 -0
- package/dist/lint/t3code/LICENSE +21 -0
- package/dist/lint/t3code/UPSTREAM.md +24 -0
- package/dist/lint/t3code/plugin.d.mts +2 -0
- package/dist/lint/t3code/plugin.mjs +20 -0
- package/dist/lint/t3code/rules/no-global-process-runtime.mjs +76 -0
- package/dist/lint/t3code/rules/no-inline-schema-compile.mjs +112 -0
- package/dist/lint/t3code/rules/no-manual-effect-runtime-in-tests.mjs +67 -0
- package/dist/lint/t3code/rules/no-native-title-tooltip.mjs +33 -0
- package/dist/lint/t3code/rules/no-test-in-loop.mjs +69 -0
- package/dist/lint/t3code/rules/no-unscoped-has.mjs +147 -0
- package/dist/lint/t3code/utils.mjs +21 -0
- package/dist/package-exports.mjs +157 -0
- package/dist/symbols/check.mjs +209 -0
- package/dist/symbols/find.mjs +63 -0
- package/dist/symbols/symbols.mjs +390 -0
- package/dist/type-coverage.mjs +68 -0
- package/dist/types/cache.mjs +157 -0
- package/dist/types/inputs.mjs +71 -0
- package/dist/types/projects.mjs +65 -0
- package/dist/types/types.mjs +175 -0
- package/package.json +68 -3
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, globSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join, posix } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { Schema } from "effect";
|
|
6
|
+
// src/package-exports.ts
|
|
7
|
+
/**
|
|
8
|
+
* Fails when a workspace package's `exports` names a file nothing has or builds, or a generated
|
|
9
|
+
* file.
|
|
10
|
+
*
|
|
11
|
+
* ref0-workspace package-exports [--packages <glob>]... [--condition <name>]
|
|
12
|
+
*
|
|
13
|
+
* It reads the `package.json` in each folder `--packages` matches, `packages/*` unless it's given,
|
|
14
|
+
* its `publishConfig.exports` too, and the `pack` of the package's `vite.config.ts`, and holds each
|
|
15
|
+
* to these:
|
|
16
|
+
*
|
|
17
|
+
* - It has an `exports` field, so no other package reaches a file it doesn't list. One nothing
|
|
18
|
+
* imports, such as a CLI's, is empty.
|
|
19
|
+
* - Each target, condition by condition, names a tracked file, or a `dist/` file one of its pack
|
|
20
|
+
* entries builds: `dist/<entry>.mjs`, and `dist/<entry>.d.mts` when it packs types. A `*`
|
|
21
|
+
* target matches at least one tracked file.
|
|
22
|
+
* - No target names a `*.gen.ts` file, which a tool writes and git ignores.
|
|
23
|
+
* - A package that packs builds each entry point that has a `types` condition from a pack entry.
|
|
24
|
+
* - Each entry point in `exports` with a `types` or `import` target gives its source, a tracked
|
|
25
|
+
* file, under the source condition first, `--condition`, `@ref0/source` unless it's given, so
|
|
26
|
+
* the workspace reads source and only the published package reads what's built.
|
|
27
|
+
* `publishConfig.exports`, what the published package exports, has none.
|
|
28
|
+
*
|
|
29
|
+
* Under 1 s.
|
|
30
|
+
*/
|
|
31
|
+
/** An entry point's target: a path, or a path for each condition. */
|
|
32
|
+
const Target = Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.String)]);
|
|
33
|
+
const Exports = Schema.Record(Schema.String, Target);
|
|
34
|
+
const Manifest = Schema.Struct({
|
|
35
|
+
name: Schema.String,
|
|
36
|
+
exports: Schema.optionalKey(Exports),
|
|
37
|
+
publishConfig: Schema.optionalKey(Schema.Struct({ exports: Schema.optionalKey(Exports) }))
|
|
38
|
+
});
|
|
39
|
+
/** What the check reads of one `vp pack` build: its entries, and whether it packs types. */
|
|
40
|
+
const PackBuild = Schema.Struct({
|
|
41
|
+
entry: Schema.Union([Schema.Array(Schema.String), Schema.Record(Schema.String, Schema.String)]),
|
|
42
|
+
dts: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Struct({})]))
|
|
43
|
+
});
|
|
44
|
+
/** A `vite.config.ts` module, as far as its `pack`. */
|
|
45
|
+
const ConfigModule = Schema.Struct({ default: Schema.Struct({ pack: Schema.optionalKey(Schema.Union([PackBuild, Schema.Array(PackBuild)])) }) });
|
|
46
|
+
const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(Manifest));
|
|
47
|
+
const decodeConfigModule = Schema.decodeUnknownSync(ConfigModule);
|
|
48
|
+
const isPaths = Schema.is(Schema.Array(Schema.String));
|
|
49
|
+
const isBuilds = Schema.is(Schema.Array(PackBuild));
|
|
50
|
+
const isPath = Schema.is(Schema.String);
|
|
51
|
+
/** The folder every path in `paths` is in, as `vp pack` names entries below it. */
|
|
52
|
+
const commonFolder = (paths) => {
|
|
53
|
+
const [first = [], ...rest] = paths.map((path) => posix.dirname(path).split("/"));
|
|
54
|
+
let length = first.length;
|
|
55
|
+
for (const parts of rest) while (length > 0 && parts.slice(0, length).join("/") !== first.slice(0, length).join("/")) length -= 1;
|
|
56
|
+
return first.slice(0, length).join("/");
|
|
57
|
+
};
|
|
58
|
+
/** Each pack entry's output name: the object's key, or its path below the entries' folder. */
|
|
59
|
+
const entryNames = ({ entry }) => {
|
|
60
|
+
if (!isPaths(entry)) return Object.keys(entry);
|
|
61
|
+
const folder = commonFolder(entry);
|
|
62
|
+
return entry.map((path) => posix.relative(folder, path).replace(/\.[cm]?[jt]sx?$/, ""));
|
|
63
|
+
};
|
|
64
|
+
/** The `dist/` files a package's pack builds, by path from the package's folder. */
|
|
65
|
+
const builtFiles = (pack) => new Set(pack.flatMap((build) => entryNames(build).flatMap((name) => build.dts === void 0 || build.dts === false ? [`dist/${name}.mjs`] : [`dist/${name}.mjs`, `dist/${name}.d.mts`])));
|
|
66
|
+
/** Each `[condition, path]` of a target; a plain path has no condition. */
|
|
67
|
+
const paths = (target) => isPath(target) ? [[void 0, target]] : Object.entries(target);
|
|
68
|
+
/** Whether `pattern`, a target with at most one `*`, matches any of `files`. */
|
|
69
|
+
const matches = (pattern, files) => {
|
|
70
|
+
if (!pattern.includes("*")) return files.has(pattern);
|
|
71
|
+
const [before = "", after = ""] = pattern.split("*");
|
|
72
|
+
return [...files].some((file) => file.length > before.length + after.length && file.startsWith(before) && file.endsWith(after));
|
|
73
|
+
};
|
|
74
|
+
/** The source condition `problems` asks for unless it's given another. */
|
|
75
|
+
const defaultCondition = "@ref0/source";
|
|
76
|
+
/**
|
|
77
|
+
* What each package's exports break, one line each, with what to do about it. `condition` is the
|
|
78
|
+
* condition each entry point names its source under.
|
|
79
|
+
*/
|
|
80
|
+
const problems = (packages, tracked, condition = defaultCondition) => {
|
|
81
|
+
const found = [];
|
|
82
|
+
for (const { directory, manifest, pack } of packages) {
|
|
83
|
+
const at = `${directory}/package.json`;
|
|
84
|
+
const built = new Set([...builtFiles(pack)].map((path) => `${directory}/${path}`));
|
|
85
|
+
const files = /* @__PURE__ */ new Set([...tracked, ...built]);
|
|
86
|
+
if (manifest.exports === void 0) {
|
|
87
|
+
found.push(`${at}: has no exports, so any of its files can be imported. List its entry points, or write "exports": {} if nothing imports it.`);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const maps = [["exports", manifest.exports], ["publishConfig.exports", manifest.publishConfig?.exports ?? {}]];
|
|
91
|
+
for (const [field, exports] of maps) for (const [entry, target] of Object.entries(exports)) {
|
|
92
|
+
const name = `${field}["${entry}"]`;
|
|
93
|
+
for (const [named, path] of paths(target)) {
|
|
94
|
+
const where = named === void 0 ? name : `${name}["${named}"]`;
|
|
95
|
+
const file = posix.join(directory, path);
|
|
96
|
+
if (/\.gen\.ts$/.test(path)) {
|
|
97
|
+
found.push(`${at}: ${where} names ${path}, which a tool writes. Export the module that uses it instead.`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (named === condition && !matches(file, tracked) && matches(file, files)) {
|
|
101
|
+
found.push(`${at}: ${where} names ${path}, which a build writes. Point it at the source the build reads.`);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (matches(file, files)) continue;
|
|
105
|
+
found.push(path.startsWith("./dist/") ? `${at}: ${where} names ${path}, which no pack entry builds. Add its entry to pack in vite.config.ts, or point it at a file that's there.` : `${at}: ${where} names ${path}, which isn't tracked. Point it at a file that's there.`);
|
|
106
|
+
}
|
|
107
|
+
const types = isPath(target) ? void 0 : target["types"];
|
|
108
|
+
const packed = isPath(target) ? [] : ["types", "import"].filter((key) => key in target);
|
|
109
|
+
const first = isPath(target) ? void 0 : Object.keys(target)[0];
|
|
110
|
+
if (field === "exports" && packed.length > 0 && first !== condition) found.push(`${at}: ${name} has ${packed.join(" and ")} but not its source under "${condition}" first. Add "${condition}": its source file, ahead of ${packed.join(" and ")}.`);
|
|
111
|
+
if (pack.length > 0 && types !== void 0 && !built.has(posix.join(directory, types))) found.push(`${at}: ${name} has types at ${types}, which no pack entry builds. Add "${entry}"'s source to pack's entry in vite.config.ts.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return found;
|
|
115
|
+
};
|
|
116
|
+
/** The folders `patterns` match at `root` that hold a `package.json`, from the root, sorted. */
|
|
117
|
+
const packageFolders = (root, patterns) => [...new Set(patterns.flatMap((pattern) => globSync(posix.join(pattern, "package.json"), { cwd: root }).map((path) => posix.dirname(path))))].sort();
|
|
118
|
+
/** Each package in `folders`, with the pack its `vite.config.ts` sets. */
|
|
119
|
+
const readPackages = async (root, folders) => Promise.all(folders.map(async (directory) => {
|
|
120
|
+
const manifest = decodeManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
|
|
121
|
+
const config = join(root, directory, "vite.config.ts");
|
|
122
|
+
if (!existsSync(config)) return {
|
|
123
|
+
directory,
|
|
124
|
+
manifest,
|
|
125
|
+
pack: []
|
|
126
|
+
};
|
|
127
|
+
const { pack } = decodeConfigModule(await import(pathToFileURL(config).href)).default;
|
|
128
|
+
return {
|
|
129
|
+
directory,
|
|
130
|
+
manifest,
|
|
131
|
+
pack: pack === void 0 ? [] : isBuilds(pack) ? pack : [pack]
|
|
132
|
+
};
|
|
133
|
+
}));
|
|
134
|
+
/** Checks the packages of the repo at `root`, prints each problem, and answers the exit code. */
|
|
135
|
+
const packageExports = async (root, { packages, condition }) => {
|
|
136
|
+
const folders = packageFolders(root, packages);
|
|
137
|
+
if (folders.length === 0) {
|
|
138
|
+
console.error(`package-exports: no package.json in ${packages.join(" or ")}. Name the packages' folders with --packages.`);
|
|
139
|
+
return 1;
|
|
140
|
+
}
|
|
141
|
+
const tracked = new Set(execFileSync("git", [
|
|
142
|
+
"ls-files",
|
|
143
|
+
"-z",
|
|
144
|
+
"--",
|
|
145
|
+
...folders
|
|
146
|
+
], {
|
|
147
|
+
cwd: root,
|
|
148
|
+
encoding: "utf8",
|
|
149
|
+
maxBuffer: 67108864
|
|
150
|
+
}).split("\0").filter((path) => path !== ""));
|
|
151
|
+
const found = problems(await readPackages(root, folders), tracked, condition);
|
|
152
|
+
for (const line of found) console.error(line);
|
|
153
|
+
if (found.length > 0) return 1;
|
|
154
|
+
console.error(`package-exports: the exports of ${folders.length} packages hold`);
|
|
155
|
+
return 0;
|
|
156
|
+
};
|
|
157
|
+
export { builtFiles, defaultCondition, packageExports, packageFolders, problems };
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { filesAt, git, indexed, likeness, repoRoot, symbolCache, workingFiles } from "./symbols.mjs";
|
|
2
|
+
import { env } from "node:process";
|
|
3
|
+
// src/symbols/check.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fails when a change adds a copy of a function, class or const the repo already has, and warns
|
|
6
|
+
* when it adds a near copy.
|
|
7
|
+
*
|
|
8
|
+
* ref0-workspace symbols check <base> [<head>]
|
|
9
|
+
* ref0-workspace symbols check --all
|
|
10
|
+
*
|
|
11
|
+
* It checks the top-level declarations a change adds or changes since it left `<base>`: those in
|
|
12
|
+
* `<head>`, or in the working tree without one, whose body differs from the same name's in the
|
|
13
|
+
* same file at the merge base. It compares each with every other declaration at the head. So a
|
|
14
|
+
* function moved to another file isn't a copy, and copies already on `<base>` are left alone.
|
|
15
|
+
*
|
|
16
|
+
* An exact copy has the same fingerprint, as `symbols.ts` makes it. A near copy's looser
|
|
17
|
+
* fingerprint is at least 85% alike. A `// CLONE: <why>` comment above a declaration allows
|
|
18
|
+
* it to copy. Tests, types and bodies under 40 nodes are left out.
|
|
19
|
+
*
|
|
20
|
+
* `--all` lists every copy in the working tree, new or not, but those a CLONE comment allows,
|
|
21
|
+
* and always passes.
|
|
22
|
+
*
|
|
23
|
+
* CI runs it on a pull request's merge into main, against main.
|
|
24
|
+
*/
|
|
25
|
+
const minSize = 40;
|
|
26
|
+
const nearAlike = .85;
|
|
27
|
+
const commonRun = 64;
|
|
28
|
+
const comparable = (symbol) => !symbol.test && symbol.kind !== "type" && symbol.size >= minSize;
|
|
29
|
+
const indexOf = (all) => {
|
|
30
|
+
const symbols = all.filter(comparable);
|
|
31
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
32
|
+
const byRun = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const [at, symbol] of symbols.entries()) {
|
|
34
|
+
byHash.set(symbol.hash, [...byHash.get(symbol.hash) ?? [], symbol]);
|
|
35
|
+
for (const run of symbol.runs) {
|
|
36
|
+
const holders = byRun.get(run);
|
|
37
|
+
if (holders === void 0) byRun.set(run, [at]);
|
|
38
|
+
else holders.push(at);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
symbols,
|
|
43
|
+
byHash,
|
|
44
|
+
byRun
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/** The declarations at least `nearAlike` like `target`, most alike first. */
|
|
48
|
+
const nearCopies = (target, index) => {
|
|
49
|
+
const counts = /* @__PURE__ */ new Map();
|
|
50
|
+
let common = 0;
|
|
51
|
+
for (const run of target.runs) {
|
|
52
|
+
const holders = index.byRun.get(run) ?? [];
|
|
53
|
+
if (holders.length > commonRun) {
|
|
54
|
+
common += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
for (const holder of holders) counts.set(holder, (counts.get(holder) ?? 0) + 1);
|
|
58
|
+
}
|
|
59
|
+
const needed = nearAlike * target.runs.length - common;
|
|
60
|
+
return [...counts].flatMap(([at, count]) => {
|
|
61
|
+
const other = index.symbols[at];
|
|
62
|
+
if (other === void 0 || other === target || count < needed) return [];
|
|
63
|
+
const sizes = [other.runs.length, target.runs.length];
|
|
64
|
+
if (Math.min(...sizes) < nearAlike * Math.max(...sizes)) return [];
|
|
65
|
+
const alike = likeness(target.runs, other.runs);
|
|
66
|
+
return alike >= nearAlike ? [{
|
|
67
|
+
other,
|
|
68
|
+
alike
|
|
69
|
+
}] : [];
|
|
70
|
+
}).sort((a, b) => b.alike - a.alike);
|
|
71
|
+
};
|
|
72
|
+
const pairKey = (a, b) => [`${a.file}:${a.name}`, `${b.file}:${b.name}`].sort().join(" ");
|
|
73
|
+
/**
|
|
74
|
+
* The copies among `changed`: each with every declaration that has its fingerprint, or failing
|
|
75
|
+
* that, the one most like it. Each group of exact copies and each near pair is listed once, and a
|
|
76
|
+
* declaration with a CLONE comment never.
|
|
77
|
+
*/
|
|
78
|
+
const copiesIn = (symbols, changed) => {
|
|
79
|
+
const index = indexOf(symbols);
|
|
80
|
+
const listed = /* @__PURE__ */ new Set();
|
|
81
|
+
const copies = [];
|
|
82
|
+
for (const copy of changed) {
|
|
83
|
+
if (!comparable(copy) || copy.clone !== void 0) continue;
|
|
84
|
+
const same = (index.byHash.get(copy.hash) ?? []).filter((other) => other !== copy).sort((a, b) => Number(b.exported) - Number(a.exported) || a.file.localeCompare(b.file));
|
|
85
|
+
if (same.length > 0) {
|
|
86
|
+
if (!listed.has(copy.hash)) copies.push({
|
|
87
|
+
exact: true,
|
|
88
|
+
copy,
|
|
89
|
+
of: same,
|
|
90
|
+
alike: 1
|
|
91
|
+
});
|
|
92
|
+
listed.add(copy.hash);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const [nearest] = nearCopies(copy, index);
|
|
96
|
+
const pair = nearest === void 0 ? void 0 : pairKey(copy, nearest.other);
|
|
97
|
+
if (nearest === void 0 || pair === void 0 || listed.has(pair)) continue;
|
|
98
|
+
listed.add(pair);
|
|
99
|
+
copies.push({
|
|
100
|
+
exact: false,
|
|
101
|
+
copy,
|
|
102
|
+
of: [nearest.other],
|
|
103
|
+
alike: nearest.alike
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return copies;
|
|
107
|
+
};
|
|
108
|
+
const gitText = (root, args) => git(root, args).toString("utf8");
|
|
109
|
+
const pathList = (output) => output.split("\0").filter((path) => indexed(path));
|
|
110
|
+
/** A declaration's file, name and body together, which a change to any of them changes. */
|
|
111
|
+
const versionOf = (symbol) => `${symbol.file}\0${symbol.name}\0${symbol.hash}`;
|
|
112
|
+
/**
|
|
113
|
+
* The declarations at `head`, or in the working tree without one, and those of them the change
|
|
114
|
+
* since it left `base` adds, or whose body it changes.
|
|
115
|
+
*/
|
|
116
|
+
const changedSince = (root, base, head) => {
|
|
117
|
+
const mergeBase = gitText(root, [
|
|
118
|
+
"merge-base",
|
|
119
|
+
base,
|
|
120
|
+
head ?? "HEAD"
|
|
121
|
+
]).trim();
|
|
122
|
+
const paths = new Set(head === void 0 ? [...pathList(gitText(root, [
|
|
123
|
+
"diff",
|
|
124
|
+
"--name-only",
|
|
125
|
+
"-z",
|
|
126
|
+
mergeBase
|
|
127
|
+
])), ...pathList(gitText(root, [
|
|
128
|
+
"ls-files",
|
|
129
|
+
"-z",
|
|
130
|
+
"--others",
|
|
131
|
+
"--exclude-standard"
|
|
132
|
+
]))] : pathList(gitText(root, [
|
|
133
|
+
"diff",
|
|
134
|
+
"--name-only",
|
|
135
|
+
"-z",
|
|
136
|
+
mergeBase,
|
|
137
|
+
head
|
|
138
|
+
])));
|
|
139
|
+
const cache = symbolCache(root);
|
|
140
|
+
const before = new Set(filesAt(root, mergeBase, [...paths]).flatMap(cache.symbolsOf).map(versionOf));
|
|
141
|
+
const symbols = (head === void 0 ? workingFiles(root) : filesAt(root, head)).flatMap(cache.symbolsOf);
|
|
142
|
+
const changed = symbols.filter((symbol) => paths.has(symbol.file) && !before.has(versionOf(symbol)));
|
|
143
|
+
cache.save();
|
|
144
|
+
return {
|
|
145
|
+
symbols,
|
|
146
|
+
changed
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
const where = (symbol) => `${symbol.file}:${symbol.line}`;
|
|
150
|
+
const percent = (alike) => `${Math.floor(alike * 100)}%`;
|
|
151
|
+
/** The declarations a copy copies, as `joined at a.ts:3, joined at b.ts:9 and 1 more`. */
|
|
152
|
+
const named = (symbols) => {
|
|
153
|
+
const shown = symbols.slice(0, 2).map((symbol) => `${symbol.name} at ${where(symbol)}`);
|
|
154
|
+
const more = symbols.length - shown.length;
|
|
155
|
+
return more > 0 ? `${shown.join(", ")} and ${more} more` : shown.join(" and ");
|
|
156
|
+
};
|
|
157
|
+
/** One line for a copy: a GitHub annotation on its line in CI, or plain text. */
|
|
158
|
+
const reported = (copy, github) => {
|
|
159
|
+
const original = copy.of[0]?.name ?? "";
|
|
160
|
+
const what = copy.exact ? `${copy.copy.name} has the same body as ${named(copy.of)}` : copy.alike === 1 ? `${copy.copy.name} is ${named(copy.of)} with other names in it` : `${copy.copy.name} is ${percent(copy.alike)} like ${named(copy.of)}`;
|
|
161
|
+
const advice = copy.exact ? `Reuse ${original}, or say why not in a "// CLONE: <why>" comment above ${copy.copy.name}.` : `If they do the same job, reuse ${original}.`;
|
|
162
|
+
if (!github) return `${copy.exact ? "copy" : "near copy"}: ${where(copy.copy)} ${what}`;
|
|
163
|
+
const level = copy.exact ? "error" : "warning";
|
|
164
|
+
const title = `${copy.exact ? "Copy" : "Near copy"} of ${original}`;
|
|
165
|
+
return `::${level} file=${copy.copy.file},line=${copy.copy.line},title=${title}::${what}. ${advice}`;
|
|
166
|
+
};
|
|
167
|
+
const count = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
168
|
+
/**
|
|
169
|
+
* Every copy in the working tree but those a CLONE comment allows, largest first: the exact
|
|
170
|
+
* groups, then the near pairs.
|
|
171
|
+
*/
|
|
172
|
+
const reportAll = (root) => {
|
|
173
|
+
const cache = symbolCache(root);
|
|
174
|
+
const symbols = workingFiles(root).flatMap(cache.symbolsOf).filter((symbol) => symbol.clone === void 0);
|
|
175
|
+
cache.save();
|
|
176
|
+
const exact = [...indexOf(symbols).byHash.values()].filter((group) => group.length > 1).sort((a, b) => (b[0]?.size ?? 0) - (a[0]?.size ?? 0));
|
|
177
|
+
const near = copiesIn(symbols, symbols.filter(comparable)).filter((copy) => !copy.exact);
|
|
178
|
+
console.log(`Exact copies, ${count(exact.length, "group")}:`);
|
|
179
|
+
for (const group of exact) console.log(` ${group[0]?.size} nodes: ${group.map((s) => `${s.name} ${where(s)}`).join(", ")}`);
|
|
180
|
+
console.log(`\nNear copies, ${count(near.length, "pair")}:`);
|
|
181
|
+
for (const copy of near.sort((a, b) => b.copy.size - a.copy.size)) console.log(` ${percent(copy.alike)}: ${copy.copy.name} ${where(copy.copy)}, ${named(copy.of)}`);
|
|
182
|
+
};
|
|
183
|
+
const checkUsage = ["usage: ref0-workspace symbols check <base> [<head>]", " ref0-workspace symbols check --all"].join("\n");
|
|
184
|
+
/** Checks the repo `from` is in, as `args` ask, and answers the exit code. */
|
|
185
|
+
const symbolsCheck = (args, from) => {
|
|
186
|
+
const root = repoRoot(from);
|
|
187
|
+
const [base, head, ...rest] = args.filter((arg) => arg !== "--all");
|
|
188
|
+
if (args.includes("--all")) {
|
|
189
|
+
if (base !== void 0) {
|
|
190
|
+
console.error(checkUsage);
|
|
191
|
+
return 2;
|
|
192
|
+
}
|
|
193
|
+
reportAll(root);
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
if (base === void 0 || rest.length > 0 || base.startsWith("-")) {
|
|
197
|
+
console.error(checkUsage);
|
|
198
|
+
return 2;
|
|
199
|
+
}
|
|
200
|
+
const { symbols, changed } = changedSince(root, base, head);
|
|
201
|
+
const copies = copiesIn(symbols, changed);
|
|
202
|
+
const exact = copies.filter((copy) => copy.exact).length;
|
|
203
|
+
const github = env["GITHUB_ACTIONS"] === "true";
|
|
204
|
+
for (const copy of copies) console.log(reported(copy, github));
|
|
205
|
+
if (exact > 0 && !github) console.log("Reuse the existing one, or say why not in a \"// CLONE: <why>\" comment above the copy.");
|
|
206
|
+
console.log(`symbols: ${count(changed.length, "new or changed declaration")}, of ${count(symbols.length, "declaration")} in all: ${count(exact, "copy", "copies")}, ${count(copies.length - exact, "near copy", "near copies")}`);
|
|
207
|
+
return exact > 0 ? 1 : 0;
|
|
208
|
+
};
|
|
209
|
+
export { changedSince, checkUsage, copiesIn, symbolsCheck };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { repoRoot, symbolCache, workingFiles } from "./symbols.mjs";
|
|
2
|
+
// src/symbols/find.ts
|
|
3
|
+
/**
|
|
4
|
+
* Finds the functions, classes, consts and types the repo already has, by words in their name,
|
|
5
|
+
* signature, doc comment or path, so you can reuse one instead of writing it again.
|
|
6
|
+
*
|
|
7
|
+
* ref0-workspace symbols find <words...>
|
|
8
|
+
*
|
|
9
|
+
* Prints the ten best matches in the working tree, tests included. A word in the name counts
|
|
10
|
+
* most, then a word in the doc comment, then one in the signature or path, and a symbol that
|
|
11
|
+
* matches every word ranks above one that doesn't.
|
|
12
|
+
*/
|
|
13
|
+
/** `storedCheckCode` or `stored_check_code` as `['stored', 'check', 'code']`. */
|
|
14
|
+
const wordsOf = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((word) => word !== "");
|
|
15
|
+
/** `bytes` as `byte`, so it matches `byte` and `bytes` alike. */
|
|
16
|
+
const stem = (word) => word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
|
|
17
|
+
/** How well `symbol` matches one query word, or 0. */
|
|
18
|
+
const wordScore = (symbol, word) => {
|
|
19
|
+
const name = symbol.name.toLowerCase();
|
|
20
|
+
const nameWords = wordsOf(symbol.name);
|
|
21
|
+
if (name === word) return 12;
|
|
22
|
+
if (nameWords.includes(word)) return 6;
|
|
23
|
+
if (nameWords.some((nameWord) => nameWord.startsWith(word))) return 4;
|
|
24
|
+
if (name.includes(word)) return 3;
|
|
25
|
+
if (wordsOf(symbol.doc).some((docWord) => docWord.startsWith(word))) return 2;
|
|
26
|
+
if (symbol.signature.toLowerCase().includes(word)) return 1;
|
|
27
|
+
return symbol.file.toLowerCase().includes(word) ? .5 : 0;
|
|
28
|
+
};
|
|
29
|
+
/** The ten symbols that best match the words in `query`, best first. */
|
|
30
|
+
const best = (symbols, query) => {
|
|
31
|
+
const words = query.flatMap(wordsOf).map(stem);
|
|
32
|
+
return symbols.flatMap((symbol) => {
|
|
33
|
+
const scores = words.map((word) => wordScore(symbol, word));
|
|
34
|
+
if (scores.every((score) => score === 0)) return [];
|
|
35
|
+
return [{
|
|
36
|
+
symbol,
|
|
37
|
+
score: scores.reduce((sum, each) => sum + each, 0) + (scores.includes(0) ? 0 : 5) + (symbol.exported ? 1 : 0) - (symbol.test ? 2 : 0)
|
|
38
|
+
}];
|
|
39
|
+
}).sort((a, b) => b.score - a.score || a.symbol.name.length - b.symbol.name.length || a.symbol.file.localeCompare(b.symbol.file)).slice(0, 10).map(({ symbol }) => symbol);
|
|
40
|
+
};
|
|
41
|
+
const findUsage = "usage: ref0-workspace symbols find <words...>";
|
|
42
|
+
/** Prints what in the repo `from` is in best matches `query`, and answers the exit code. */
|
|
43
|
+
const symbolsFind = (query, from) => {
|
|
44
|
+
if (query.length === 0) {
|
|
45
|
+
console.error(findUsage);
|
|
46
|
+
return 2;
|
|
47
|
+
}
|
|
48
|
+
const root = repoRoot(from);
|
|
49
|
+
const cache = symbolCache(root);
|
|
50
|
+
const found = best(workingFiles(root).flatMap(cache.symbolsOf), query);
|
|
51
|
+
cache.save();
|
|
52
|
+
if (found.length === 0) {
|
|
53
|
+
console.log(`Nothing matches ${query.join(" ")}.`);
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
for (const symbol of found) {
|
|
57
|
+
console.log(`${symbol.name} ${symbol.kind}${symbol.exported ? ", exported" : ""} ${symbol.file}:${symbol.line}`);
|
|
58
|
+
console.log(` ${symbol.signature}`);
|
|
59
|
+
if (symbol.doc !== "") console.log(` ${symbol.doc}`);
|
|
60
|
+
}
|
|
61
|
+
return 0;
|
|
62
|
+
};
|
|
63
|
+
export { best, findUsage, symbolsFind };
|