mo3ta-coverage 1.0.22 → 1.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/AGENT.md CHANGED
@@ -49,6 +49,8 @@ There is no lint/typecheck/format script. `npm run build` currently outputs
49
49
  | `src/cli.test.js` | Tests for lcov parsing, changed-line classification, summaries. |
50
50
  | `src/fileUtils.test.js` | Tests for file filtering, naming conventions, import scanning. |
51
51
  | `jest.config.json` | Jest config: `**/src/**/*.test.js`, node env, babel-jest transform. |
52
+ | `.github/workflows/dependency-audit.yml` | Daily dependency security audit; opens/updates a tracked issue on findings. |
53
+ | `.github/scripts/audit-open-issue.mjs` | Issue manager for the audit workflow (`gh` CLI). |
52
54
  | `.mo3ta-coverage.json` | Optional per-project config (gitignored here). |
53
55
 
54
56
  ## Execution flow
@@ -59,7 +61,8 @@ index.js
59
61
  ├─ verifyGitRepoExists() src/gitUtils.js
60
62
  ├─ getExplicitFiles(options) --files / --filesFrom, or
61
63
  ├─ getChangedFiles(base) merge-base diff + working tree, all authors
62
- ├─ runRelatedTests(files, mode, depth)
64
+ ├─ dryRun(files, mode, depth) --dryRun: print the would-run test list, exit 0
65
+ ├─ runRelatedTests(files, mode, depth)
63
66
  │ └─ npx jest ... --coverage
64
67
  └─ reportUncoveredChangedLines(...)
65
68
  ├─ parseLcov(path)
@@ -125,6 +128,9 @@ import a module which imports the changed file.
125
128
  the matching `*.test.js` file.
126
129
  - Do not add runtime dependencies without a clear need; the package ships only
127
130
  `commander`.
131
+ - All dependencies in `package.json` are pinned to exact versions (no `^`/`~`);
132
+ transitive fixes go through `overrides`. `npm audit` must be clean before
133
+ dependency changes are merged.
128
134
 
129
135
  ## Gotchas
130
136
 
@@ -137,8 +143,12 @@ import a module which imports the changed file.
137
143
  is matched against repo-relative paths by exact match or path suffix.
138
144
  Over-matching is acceptable (it may run extra tests) but under-matching is not.
139
145
  - `runRelatedTests` exits the process (`exit(0)`/`exit(1)`) rather than throwing.
146
+ - `--dryRun` must keep stdout a clean one-path-per-line list (other tools
147
+ consume it); informational messages go to stderr.
140
148
  - The config subcommand writes `.mo3ta-coverage.json` in `process.cwd()`.
141
149
  - CLI options with commander defaults (`mode`, `depth`) override config unless
142
150
  you check `program.getOptionValueSource(...) === 'cli'`.
143
- - Shell commands are built as strings and run with `execSync`; quote/escape file
144
- paths if this ever needs to support spaces.
151
+ - Git and Jest are always invoked with argument arrays (`execFileSync`),
152
+ never through a shell, so refs and file paths cannot inject commands.
153
+ `--base` values are validated with `git rev-parse --verify` before use;
154
+ file paths in `git diff` are protected by the `--` pathspec separator.
package/README.md CHANGED
@@ -6,7 +6,7 @@ mo3ta-coverage checks coverage for changed lines in a pull request. It finds cha
6
6
 
7
7
  ## Demo
8
8
 
9
- https://github.com/user-attachments/assets/5241bfa7-ba66-4405-bf42-fd6522be56a6
9
+ https://github.com/user-attachments/assets/1139ca7a-69e6-4b41-ad24-ff20e083c4e0
10
10
 
11
11
  A quick walkthrough of changed-file detection, related-test selection, and changed-line coverage.
12
12
 
@@ -19,6 +19,62 @@ A quick walkthrough of changed-file detection, related-test selection, and chang
19
19
  - Walks reverse imports in `smart` mode to a configurable depth (default `2`)
20
20
  - Parses `lcov.info` and reports uncovered changed lines
21
21
  - Enforces a minimum coverage threshold for changed lines
22
+ - `--dryRun` lists the test files that would run (machine-readable, for other tools)
23
+
24
+ ## GitHub Action
25
+
26
+ [mo3ta-coverage-action](https://github.com/MahmoudMabrok/mo3ta-coverage-action)
27
+ wraps the CLI as a reusable GitHub Action: it bundles the tool, runs it on
28
+ Node 20, and appends the markdown coverage table to the job summary
29
+ automatically.
30
+
31
+ It also auto-resolves what to diff against based on the triggering event,
32
+ so you usually don't set `base` at all:
33
+
34
+ | Event | Base used |
35
+ |-------|-----------|
36
+ | `pull_request` | the PR's exact base commit |
37
+ | `push` | the previous commit (`HEAD~1`) |
38
+ | other (schedule, dispatch) | `origin/main` |
39
+
40
+ ### Minimal setup (recommended)
41
+
42
+ ```yaml
43
+ # .github/workflows/changed-line-coverage.yml
44
+ name: Changed-line coverage
45
+
46
+ on:
47
+ pull_request:
48
+ push:
49
+ branches: [main]
50
+
51
+ jobs:
52
+ changed-line-coverage:
53
+ runs-on: ubuntu-latest
54
+ steps:
55
+ - uses: actions/checkout@v4
56
+ with:
57
+ fetch-depth: 0 # full history needed for the merge-base diff
58
+ - run: npm ci
59
+ - uses: MahmoudMabrok/mo3ta-coverage-action@v1
60
+ ```
61
+
62
+ ### Customizing
63
+
64
+ ```yaml
65
+ - uses: MahmoudMabrok/mo3ta-coverage-action@v1
66
+ with:
67
+ base: origin/develop # explicit base (overrides auto-resolution)
68
+ mode: smart # fast | smart (default) | full
69
+ depth: 2 # smart mode reverse-import depth
70
+ limit: 80 # minimum changed-line coverage, %
71
+ # ci: true # default; clean output + markdown table
72
+ # report-to-summary: true # default; append table to job summary
73
+ ```
74
+
75
+ All inputs, and how to scope the run to specific files (`files` /
76
+ `files-from`), are documented in the
77
+ [action README](https://github.com/MahmoudMabrok/mo3ta-coverage-action#inputs).
22
78
 
23
79
  ## Installation
24
80
 
@@ -26,12 +82,89 @@ A quick walkthrough of changed-file detection, related-test selection, and chang
26
82
  npm install -g mo3ta-coverage
27
83
  ```
28
84
 
85
+ ### Install from GitHub
86
+
87
+ Prefer the latest commit over the published npm release? Install directly from
88
+ this repository — no publish step, no clone needed:
89
+
90
+ ```sh
91
+ # Global install from the default branch
92
+ npm install -g github:MahmoudMabrok/mo3ta-coverage
93
+
94
+ # One-off, without installing at all
95
+ npx github:MahmoudMabrok/mo3ta-coverage --mode smart --base origin/main --limit 80
96
+ ```
97
+
98
+ Pin a release tag or a specific commit for reproducible installs:
99
+
100
+ ```sh
101
+ npm install -g github:MahmoudMabrok/mo3ta-coverage#v1.1.0
102
+ npm install -g github:MahmoudMabrok/mo3ta-coverage#<commit-sha>
103
+ ```
104
+
105
+ To build and run from a local checkout instead:
106
+
107
+ ```sh
108
+ git clone https://github.com/MahmoudMabrok/mo3ta-coverage.git
109
+ cd mo3ta-coverage
110
+ npm install
111
+ npm link # exposes the mo3ta-coverage binary globally
112
+ ```
113
+
29
114
  ## Usage
30
115
 
31
116
  ```sh
32
117
  mo3ta-coverage --mode smart --base origin/main --limit 80
33
118
  ```
34
119
 
120
+ ## Recipes
121
+
122
+ Two common ways to use the CLI straight from GitHub — no global install.
123
+
124
+ ### 1. Get the selected test files, then run Jest yourself
125
+
126
+ `--dryRun true` stops after test discovery and writes **only** the selected
127
+ test paths to stdout (one per line), so you can review them or hand them to
128
+ Jest directly — no coverage check, no extra runner:
129
+
130
+ ```sh
131
+ # 1. Discover the tests that cover the changed files
132
+ npx github:MahmoudMabrok/mo3ta-coverage \
133
+ --dryRun true \
134
+ --mode smart \
135
+ --base origin/main > selected-tests.txt
136
+
137
+ # 2. Run exactly those files with Jest
138
+ npx jest $(cat selected-tests.txt)
139
+ ```
140
+
141
+ Or pipe the list straight into Jest:
142
+
143
+ ```sh
144
+ npx github:MahmoudMabrok/mo3ta-coverage --dryRun true --base origin/main \
145
+ | xargs npx jest
146
+ ```
147
+
148
+ Diagnostics go to stderr, so the file/pipe contains paths only. See
149
+ [Dry Run](#dry-run-list-test-files-for-other-tools) for details.
150
+
151
+ ### 2. Run the coverage check in smart mode
152
+
153
+ Leave `--dryRun` off and the CLI does the whole job: select the tests, run
154
+ Jest, parse `coverage/lcov.info`, and fail when changed-line coverage is below
155
+ `--limit`:
156
+
157
+ ```sh
158
+ npx github:MahmoudMabrok/mo3ta-coverage \
159
+ --mode smart \
160
+ --base origin/main \
161
+ --limit 80
162
+ ```
163
+
164
+ `smart` follows reverse imports up to `--depth` (default `2`), which catches
165
+ specs that reach the changed file through barrel files. See
166
+ [Modes](#modes) for `fast`, `smart`, and `full`.
167
+
35
168
  ## CLI Options
36
169
 
37
170
  | Option | Description | Default |
@@ -44,6 +177,9 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
44
177
  | `--depth <number>` | Max reverse-import depth used by `smart` (`1` or `2` recommended) | `2` |
45
178
  | `--files <files...>` | Scan only these files instead of auto-detecting changed files (space- or comma-separated) | – |
46
179
  | `--filesFrom <path>` | Read the file list to scan from a newline-separated file | – |
180
+ | `--ci <bool>` | CI mode: emit results as a markdown table and save it to a file so CI can read it without parsing logs | `false` |
181
+ | `--ciReport <path>` | Where to save the CI markdown table | `coverage/mo3ta-coverage-report.md` |
182
+ | `--dryRun <bool>` | Print the test files that would run (one per line) and stop, without running Jest or the coverage check | `false` |
47
183
 
48
184
  ## Scanning Selected Files
49
185
 
@@ -67,6 +203,78 @@ Explicitly provided files skip git changed-file detection. Their changed lines
67
203
  are still computed against `--base`, so only lines that differ from the base
68
204
  branch are counted toward coverage.
69
205
 
206
+ ## CI Mode
207
+
208
+ Pass `--ci true` to print the coverage results as a markdown table **and**
209
+ save that same table to a file (default: `coverage/mo3ta-coverage-report.md`,
210
+ configurable with `--ciReport`), so a CI job can read only the table instead
211
+ of parsing through the logs:
212
+
213
+ ```sh
214
+ mo3ta-coverage --mode smart --base origin/main --ci true
215
+ # or save the table elsewhere
216
+ mo3ta-coverage --ci true --ciReport report.md
217
+ ```
218
+
219
+ The table includes a per-file breakdown plus an **Overall** row with the
220
+ overall coverage percentage, and a summary line showing the limit. The exit
221
+ code is unchanged: the run still fails when changed-line coverage is below
222
+ `--limit`. In CI mode the verbose per-file console output is replaced by the
223
+ markdown table.
224
+
225
+ If you use the
226
+ [GitHub Action](https://github.com/MahmoudMabrok/mo3ta-coverage-action),
227
+ `--ci` is enabled for you and the table is appended to the job summary
228
+ automatically — no `run:` step needed.
229
+
230
+ ## Dry Run (list test files for other tools)
231
+
232
+ Pass `--dryRun true` to stop after test discovery and print the test files
233
+ that the run *would* execute, one path per line, on stdout — without running
234
+ Jest and without the coverage check. This makes the tool's test selection
235
+ available to any other tool (e.g. a watch task or another coverage runner):
236
+
237
+ ```sh
238
+ mo3ta-coverage --mode smart --base origin/main --dryRun true
239
+ ```
240
+
241
+ stdout contains only the file list (repo-relative paths, one per line);
242
+ all human-readable diagnostics go to stderr, so `--dryRun` output is safe
243
+ to pipe or capture:
244
+
245
+ ```sh
246
+ # Feed the discovered tests to another tool
247
+ mo3ta-coverage --base origin/main --dryRun true | xargs -n 1 npx jest --silent
248
+
249
+ # Combine with an explicit file list
250
+ mo3ta-coverage --files src/a.js,src/b.ts --base origin/main --dryRun true
251
+ ```
252
+
253
+ Notes:
254
+
255
+ - Discovery follows the selected `--mode` (default `smart`), so the list
256
+ matches exactly what a normal run would execute.
257
+ - `--dryRun` still needs a `--base` (changed files are computed against it),
258
+ but does not need a valid `lcov.info` or a local Jest install.
259
+ - In `full` mode discovery is delegated to Jest's `--findRelatedTests`, so
260
+ `--dryRun` can only list the changed test files themselves (a warning is
261
+ printed to stderr).
262
+
263
+ ### Example output
264
+
265
+ On the demo app, a PR touching `src/ops.js`, the `src/math.js` barrel, and
266
+ `src/math.spec.js` selects exactly one test file:
267
+
268
+ ```console
269
+ $ mo3ta-coverage --base origin/main --mode smart --dryRun true
270
+ src/math.spec.js
271
+ ```
272
+
273
+ `src/ops.js` has no same-name spec, but it is re-exported by the
274
+ `src/math.js` barrel and `src/math.spec.js` imports that barrel, so the
275
+ reverse-import walk finds it at depth 2. Only the selected path reaches
276
+ stdout; the diagnostics (changed files, mode, depth) go to stderr.
277
+
70
278
  ## Modes
71
279
 
72
280
  - `fast`: Naming-convention matches only, plus a direct import-scan fallback. No dependency traversal.
@@ -120,6 +328,39 @@ npm install
120
328
  npm test
121
329
  ```
122
330
 
331
+ ## Security & dependencies
332
+
333
+ All dependencies in [`package.json`](package.json) are **pinned to exact
334
+ versions** (no `^` or `~`), so installs are reproducible and unaffected by
335
+ upstream releases. The `package-lock.json` is committed and CI installs with
336
+ `npm ci` against it.
337
+
338
+ ### Vulnerability policy
339
+
340
+ - Transitive dependencies with known advisories are pinned to fixed versions
341
+ through `overrides` in `package.json` when a compatible upstream release is
342
+ not yet available (this keeps Jest 30 instead of downgrading for a
343
+ transitive `glob`/`minimatch` advisory).
344
+ - `npm audit` must report **0 known vulnerabilities** before changes that
345
+ touch dependencies are merged.
346
+
347
+ ### Automated daily audit
348
+
349
+ The [`Dependency security audit` workflow](.github/workflows/dependency-audit.yml)
350
+ runs `npm audit` **daily** (plus on push, pull request, and manual dispatch):
351
+
352
+ - On vulnerabilities: opens (or refreshes) a single tracked issue —
353
+ **`[Security] Vulnerable dependencies`** (label: `security`) — with the
354
+ summary table, affected packages, advisory links, and fix steps.
355
+ - When the audit is clean again, it closes that issue automatically.
356
+ - The issue is managed by [`.github/scripts/audit-open-issue.mjs`](.github/scripts/audit-open-issue.mjs)
357
+ via the `gh` CLI, so repeated runs never create duplicates.
358
+
359
+ ## Pull requests
360
+
361
+ Security hardening (shell-injection-safe git/jest invocations) and dependency
362
+ pinning were introduced in [#12](https://github.com/MahmoudMabrok/mo3ta-coverage/pull/12).
363
+
123
364
  ## License
124
365
 
125
366
  MIT
@@ -69,6 +69,16 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
69
69
  run: npx mo3ta-coverage --mode smart --base origin/main --limit 80
70
70
  ```
71
71
 
72
+ ## Listing Tests For Other Tools
73
+
74
+ Use `--dryRun true` when another tool needs the same test selection this
75
+ tool would execute. It prints the test files (one path per line) on stdout
76
+ and stops before Jest and the coverage check:
77
+
78
+ ```bash
79
+ mo3ta-coverage --mode smart --base origin/main --dryRun true
80
+ ```
81
+
72
82
  ## When To Use `full`
73
83
 
74
84
  Use `full` only if you explicitly want Jest to discover more tests through dependency traversal and you accept that this may widen the run substantially.
package/VIDEO_PLAN.md CHANGED
@@ -53,9 +53,14 @@ export REPO=/Users/appleworld/Documents/mo3ta-coverage
53
53
  │ ├── index.html
54
54
  │ ├── gsap.min.js
55
55
  │ └── hyperframes.json
56
+ ├── mo3ta-modes-45s/
57
+ │ ├── index.html <- modes showcase (fast / smart / full, one scene each)
58
+ │ ├── gsap.min.js
59
+ │ └── hyperframes.json
56
60
  └── renders/
57
61
  ├── mo3ta-coverage-5s.mp4
58
- └── mo3ta-coverage-15s.mp4
62
+ ├── mo3ta-coverage-15s.mp4
63
+ └── mo3ta-modes-45s.mp4
59
64
  ```
60
65
 
61
66
  Output spec: **1920×1080, 30 fps, H.264 MP4, no audio track**.
@@ -142,12 +147,34 @@ Duration: **15.0s**.
142
147
 
143
148
  | Time | Scene | Content | Motion |
144
149
  | --- | --- | --- | --- |
145
- | 0.0–2.0 | Hook | Pill, wordmark, `Changed code. Related specs. Real coverage.` | title cascade |
146
- | 2.0–4.8 | Problem | Mini PR diff: 3 changed lines. Text `Running the whole suite is slow.` | diff rows slide in, muted clock motif |
147
- | 4.8–8.0 | Smart mode | Command types; graph builds: changed file → barrel → differently named spec, labels `depth 1` / `depth 2` | graph nodes + link draw, depth badges pulse once |
148
- | 8.0–11.0 | Coverage | Jest result panel: `PASS specs/custom-name.spec.js`, coverage table, changed lines turn green/red | rows cascade, line markers pop |
149
- | 11.0–13.0 | Verdict | `Overall changed-line coverage 100%` vs `limit 80%`, `Not covered: 0 of 3` | counter + progress bar fill |
150
- | 13.0–15.0 | CTA | End card: wordmark, `Changed code. Related specs. Real coverage.`, command pill | fade-up, hold |
150
+ | 0.0–2.6 | Hook | Pill, wordmark, `Changed code. Related specs. Real coverage.` | title cascade |
151
+ | 2.6–5.0 | Problem | Mini PR diff: 3 changed lines. Text `Run the full suite for a 3-line diff.` | diff rows slide in, suite meter fill |
152
+ | 4.8–11.3 | Modes showcase | Three cards (fast / smart / full) with command, one-line blurbs, chips. Spotlight sweeps: fast (orange) → smart (blue, default) → full (green) | cards rise staggered, spotlight ring + un-dim 0.5s per mode |
153
+ | 11.1–13.0 | Coverage result | Single result card: `smart · 3 changed lines · limit 80%`, PASS badge, `100%` counter, bar fill | card scales in, counter + bar |
154
+ | 12.9–15.0 | CTA | End card: wordmark, tagline, command pill `npx mo3ta-coverage --mode smart` | fade-up cascade, ~2s hold |
155
+
156
+ All transitions are slow by design: scene enter/exit 0.5s crossfades, 0.45–0.55s spotlight hand-offs, 1.0s counters (~25–35% slower than the original cut at the user's request).
157
+
158
+ ---
159
+
160
+ ## 6b. Storyboard — 45s modes showcase
161
+
162
+ Duration: **45.0s**. One dedicated, unhurried scene per execution mode so each
163
+ can be explained visually, with the same dark dev-tool language. Every scene
164
+ transition is a slow 0.9s exit / 0.9s enter with a 0.4s crosshanded overlap.
165
+
166
+ | Time | Scene | Content | Motion |
167
+ | --- | --- | --- | --- |
168
+ | 0.0–4.3 | Hook | Pill `CHANGED-LINE COVERAGE`, wordmark, `Three modes. One changed-line diff.` | slow title cascade |
169
+ | 3.7–10.1 | Problem | Left: `git diff` panel, 3 changed lines. Right: `1,284 tests` suite panel with fill bar. Caption `mo3ta-coverage answers with three modes — pick how hard it digs.` | panels rise, diff rows slide, meter fills 1.4s |
170
+ | 9.6–19.7 | **Mode 1 — fast** (orange badge, `Mode 1 of 3 · narrowest`) | `Names match? We're done.` Console: `$ npx mo3ta-coverage --mode fast` → `✓ helper.test.js — name match` / `✗ specs/custom-name.spec.js — no traversal, not found`. Node map: changed source → name/direct-import link → matched spec (0 hops). Caption: `No dependency traversal. Instant — when names line up.` | console lines type in, link draws 0.7s, caption fades |
171
+ | 19.5–31.1 | **Mode 2 — smart** (blue badge, `Mode 2 of 3 · balanced — default`) | `It follows your imports.` Console: `--mode smart` → walking import graph. Graph: changed source → depth 1 barrel `src/utils/index.js` → depth 2 `specs/custom-name.spec.js` (MATCHED, different name). `✓ 1 related test file · found through barrel · 4.1s`. Caption: `Names don't match. The import graph does.` | nodes + links draw left→right, depth labels, verdict line |
172
+ | 31.4–42.0 | **Mode 3 — full** (green badge, `Mode 3 of 3 · broadest`) | `Let Jest do the hunting.` Console: `--mode full` → `jest --findRelatedTests`, `✓ 7 related test files found · 11.2s`. File list: 4 related specs with why (name match / direct import / via barrel / 3 hops deep). Caption: `Everything Jest considers related. Zero guesses.` | delegation lines type, file rows stagger 0.32s |
173
+ | 42.1–45.0 | End | Wordmark, command pill `npx mo3ta-coverage --mode smart`, mode legend `fast · smart (default) · full` (colored), note `changed-line coverage after git diff` | slow fade-up cascade, hold to 45s |
174
+
175
+ Mode copy is sourced from `README.md` + `src/cli.js` (fast = naming + direct
176
+ import scan, no traversal; smart = reverse-import walk to `--depth`, default 2;
177
+ full = `jest --findRelatedTests`, unbounded).
151
178
 
152
179
  Narrative copy:
153
180
 
@@ -252,6 +279,17 @@ Acceptance:
252
279
  - [x] `check` / snapshots reviewed across all six beats.
253
280
  - [x] Render `video/renders/mo3ta-coverage-15s.mp4`.
254
281
  - [x] Verify duration / resolution / fps with `ffprobe`.
282
+ - [x] Slow all animations and rebalance scene dwell (user request).
283
+ - [x] Rebuild as modes showcase (fast / smart / full spotlight scene) — current cut.
284
+
285
+ ### 45s modes showcase
286
+ - [x] Create `video/mo3ta-modes-45s/` + `hyperframes.json` + local GSAP.
287
+ - [x] Author `index.html`: hook → problem → fast (10s) → smart (12s) → full (11s) → end.
288
+ - [x] Slow 0.9s scene transitions (user request: "not fast when switching scenes").
289
+ - [x] `lint` passes with 0 errors.
290
+ - [x] `check` passes, 0 errors; snapshots reviewed at 8 points across all beats.
291
+ - [x] Render `video/renders/mo3ta-modes-45s.mp4`.
292
+ - [x] Verify 45.000s / 1920×1080 / 30 fps / h264 with `ffprobe`.
255
293
 
256
294
  ### Wrap-up
257
295
  - [x] Add `/video/renders/` to `.gitignore`; add `/video` to `.npmignore`.
@@ -265,12 +303,13 @@ Acceptance:
265
303
 
266
304
  ### Status (2026-11-19)
267
305
 
268
- Both cuts are **rendered and verified**:
306
+ All three cuts are **rendered and verified**:
269
307
 
270
308
  | Output | Duration | Resolution | FPS | Codec | Size |
271
309
  | --- | --- | --- | --- | --- | --- |
272
310
  | `video/renders/mo3ta-coverage-5s.mp4` | 5.000s | 1920×1080 | 30 | h264 | 578 KB |
273
- | `video/renders/mo3ta-coverage-15s.mp4` | 15.000s | 1920×1080 | 30 | h264 | 1.1 MB |
311
+ | `video/renders/mo3ta-coverage-15s.mp4` | 15.000s | 1920×1080 | 30 | h264 | 1.7 MB |
312
+ | `video/renders/mo3ta-modes-45s.mp4` | 45.000s | 1920×1080 | 30 | h264 | 2.8 MB |
274
313
 
275
314
  `lint` → 0 errors on both. `check` → 0 errors on both; remaining items are
276
315
  advisory warnings only (`nested_structure_needs_subcomposition` for the single
package/index.js CHANGED
@@ -9,9 +9,11 @@ import { verifyBaseBranchExists } from './src/gitUtils.js';
9
9
 
10
10
  const CONFIG_PATH = path.resolve(process.cwd(), '.mo3ta-coverage.json');
11
11
 
12
- function readConfig() {
13
- console.log(`Reading config from: ${CONFIG_PATH}`);
14
-
12
+ function readConfig(quiet = false) {
13
+ if (!quiet) {
14
+ console.log(`Reading config from: ${CONFIG_PATH}`);
15
+ }
16
+
15
17
  if (fs.existsSync(CONFIG_PATH)) {
16
18
  return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
17
19
  }
@@ -38,10 +40,13 @@ program
38
40
  .option('--lcov <path>', 'Path to lcov.info file generated by test coverage tools', 'coverage/lcov.info')
39
41
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
40
42
  .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
43
+ .option('--ci <bool>', 'CI mode: print results as a markdown table and save it to a file for CI to read', false)
44
+ .option('--ciReport <path>', 'Where to save the CI markdown table', 'coverage/mo3ta-coverage-report.md')
41
45
  .option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
42
46
  .option('--depth <number>', 'Smart mode max reverse-dependency depth (1 = direct importers, 2 = also importers of importers)', '2')
43
47
  .option('--files <files...>', 'Scan only these files instead of detecting changed files (space- or comma-separated)')
44
48
  .option('--filesFrom <path>', 'Read the list of files to scan from a newline-separated file')
49
+ .option('--dryRun <bool>', 'Print the test files that would run (one per line) and exit, without running Jest or the coverage check', false)
45
50
  .enablePositionalOptions(); // used to allow using same options in subcommands
46
51
 
47
52
  // Usage help text (printed next to --help)
@@ -51,7 +56,9 @@ Examples:
51
56
  $ mo3ta-coverage --mode smart --base origin/main --limit 80
52
57
  $ mo3ta-coverage --files src/a.js,src/b.ts --base origin/main
53
58
  $ mo3ta-coverage --filesFrom changed.txt --base origin/main
59
+ $ mo3ta-coverage --dry-run true --files src/a.js,src/b.ts --base main
54
60
  $ mo3ta-coverage --mode fast --showCovered true
61
+ $ mo3ta-coverage --mode smart --base origin/main --ci true --ciReport coverage/report.md
55
62
  $ mo3ta-coverage config --mode smart --depth 2
56
63
  $ mo3ta-coverage --version
57
64
 
@@ -114,8 +121,9 @@ program
114
121
 
115
122
 
116
123
  program.action((opts) => {
117
- const config = readConfig();
118
124
  const options = program.opts();
125
+ const dryRun = options.dryRun === true || options.dryRun === 'true';
126
+ const config = readConfig(dryRun);
119
127
 
120
128
  const modeFromCli = program.getOptionValueSource('mode') === 'cli';
121
129
  const depthFromCli = program.getOptionValueSource('depth') === 'cli';
@@ -150,7 +158,8 @@ program.action((opts) => {
150
158
  options.depth = depth;
151
159
  }
152
160
 
153
- console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
161
+ // In dry run, keep stdout a clean one-path-per-line list for other tools.
162
+ (dryRun ? console.error : console.log)(`Final options: ${JSON.stringify(options, null, 2)}`);
154
163
 
155
164
  main(options);
156
165
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.22",
3
+ "version": "1.2.0",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -31,12 +31,16 @@
31
31
  "url": "https://github.com/MahmoudMabrok/mo3ta-coverage/issues"
32
32
  },
33
33
  "devDependencies": {
34
- "@babel/core": "^7.28.0",
35
- "@babel/preset-env": "^7.28.0",
36
- "babel-jest": "^30.0.5",
37
- "jest": "^30.0.5"
34
+ "@babel/core": "8.1.2",
35
+ "@babel/preset-env": "8.0.7",
36
+ "babel-jest": "30.5.2",
37
+ "jest": "30.5.2"
38
38
  },
39
39
  "dependencies": {
40
- "commander": "^14.0.0"
40
+ "commander": "15.1.0"
41
+ },
42
+ "overrides": {
43
+ "glob": "14.0.6",
44
+ "minimatch": "11.0.9"
41
45
  }
42
46
  }
package/src/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { execSync } from 'child_process';
1
+ import { execFileSync } from 'child_process';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { exit } from 'process';
@@ -22,8 +22,17 @@ export function main(options) {
22
22
  const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
23
23
  const MODE = options.mode;
24
24
  const DEPTH = Number.parseInt(options.depth, 10) || 2;
25
+ const DRY_RUN = options.dryRun === true || options.dryRun === 'true';
26
+ const CI = options.ci === true || options.ci === 'true';
27
+ const CI_REPORT_PATH = options.ciReport
28
+ ? path.resolve(options.ciReport)
29
+ : path.resolve('coverage', 'mo3ta-coverage-report.md');
25
30
 
26
- console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nDepth: ${DEPTH}`);
31
+ // In dry run, stdout must stay a clean one-path-per-line list, so
32
+ // diagnostics go to stderr instead of stdout.
33
+ const infoLog = DRY_RUN ? console.error : console.log;
34
+
35
+ infoLog(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nDepth: ${DEPTH} \nDry Run: ${DRY_RUN} \nCI Mode: ${CI}`);
27
36
 
28
37
  const explicitFiles = getExplicitFiles(options);
29
38
  let changedFiles;
@@ -31,14 +40,24 @@ export function main(options) {
31
40
  if (explicitFiles.length > 0) {
32
41
  // A base branch is still needed to compute the changed lines of each file.
33
42
  verifyBaseBranchExists(BASE_BRANCH);
34
- console.log(`Scanning ${explicitFiles.length} explicitly provided file(s) (git changed-file detection skipped):\n${explicitFiles.join('\n')}`);
43
+ infoLog(`Scanning ${explicitFiles.length} explicitly provided file(s) (git changed-file detection skipped):\n${explicitFiles.join('\n')}`);
35
44
  changedFiles = explicitFiles;
36
45
  } else {
37
- changedFiles = getChangedFiles(BASE_BRANCH);
46
+ changedFiles = getChangedFiles(BASE_BRANCH, infoLog);
47
+ }
48
+
49
+ if (DRY_RUN) {
50
+ dryRun(changedFiles, MODE, DEPTH);
51
+ return;
38
52
  }
39
53
 
40
54
  runRelatedTests(changedFiles, MODE, DEPTH);
41
- reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
55
+ reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED, CI, CI_REPORT_PATH);
56
+
57
+ if (testsFailed) {
58
+ console.error('\n❌ Finished with test failures (see Jest output above).');
59
+ exit(1);
60
+ }
42
61
  } catch (error) {
43
62
  console.error('❌ An unexpected error occurred:', error.message || error);
44
63
  exit(1);
@@ -108,28 +127,39 @@ export function getExplicitFiles(options = {}) {
108
127
  return Array.from(new Set(files));
109
128
  }
110
129
 
111
- export function getChangedFiles(BASE_BRANCH) {
112
- // Check if BASE_BRANCH exists
130
+ export function getChangedFiles(BASE_BRANCH, log = console.log) {
131
+ // Check if BASE_BRANCH exists (also rejects ref-like options before use)
113
132
  verifyBaseBranchExists(BASE_BRANCH);
114
133
 
115
134
  // Compare the merge base with HEAD so every file changed on this branch is
116
135
  // included, regardless of which author committed it.
136
+ //
137
+ // Git is always invoked with an argument array (never through a shell) so
138
+ // refs and file paths can't inject commands, and output is de-duplicated
139
+ // in JS instead of piping through `sort -u`.
117
140
  try {
118
- const mergeBase = execSync(`git merge-base HEAD ${BASE_BRANCH}`).toString().trim();
119
-
120
- const command = `(
121
- git diff --name-only --diff-filter=AM ${mergeBase}..HEAD
122
- git diff --name-only --diff-filter=AM
123
- git diff --cached --name-only --diff-filter=AM
124
- ) | sort -u`;
125
-
126
- const output = execSync(command).toString();
127
- const changedFiles = output
128
- .split('\n')
141
+ const gitFiles = (args) => execFileSync('git', args, { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
142
+
143
+ const mergeBase = gitFiles(['merge-base', 'HEAD', BASE_BRANCH]).trim();
144
+
145
+ const seen = new Set();
146
+ const changedFiles = [
147
+ // Added or renamed files between the merge base and HEAD
148
+ gitFiles(['diff', '--name-only', '--diff-filter=AM', `${mergeBase}..HEAD`]),
149
+ // Unstaged changes in the working tree
150
+ gitFiles(['diff', '--name-only', '--diff-filter=AM']),
151
+ // Staged changes
152
+ gitFiles(['diff', '--cached', '--name-only', '--diff-filter=AM'])
153
+ ]
154
+ .flatMap(output => output.split('\n'))
129
155
  .filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/))
130
156
  // Defensive: ignore dependency/build/coverage artifacts even if git tracked them
131
- .filter(f => !f.match(/(^|\/)(node_modules|coverage|dist|build)\/|(^|\/)\.git\//));
132
- console.log(`Changed files:\n${changedFiles.join('\n')}`);
157
+ .filter(f => !f.match(/(^|\/)(node_modules|coverage|dist|build)\/|(^|\/)\.git\//))
158
+ // De-duplicate (replaces `sort -u`); insertion order keeps first-seen wins
159
+ .filter(f => (seen.has(f) ? false : (seen.add(f), true)));
160
+
161
+ changedFiles.sort();
162
+ log(`Changed files:\n${changedFiles.join('\n')}`);
133
163
  return changedFiles;
134
164
  } catch (error) {
135
165
  console.error('Error getting changed files:', error.message || error);
@@ -137,14 +167,22 @@ export function getChangedFiles(BASE_BRANCH) {
137
167
  }
138
168
  }
139
169
 
140
- function runJest(command) {
141
- console.log(` Jest command: ${command}`);
170
+ let testsFailed = false;
171
+
172
+ function runJest(jestArgs) {
173
+ console.log(` Jest command: npx jest ${jestArgs.join(' ')}`);
142
174
 
175
+ // The locally installed Jest entry point is invoked directly (no shell,
176
+ // no npx), with an argument array, so file paths with spaces or special
177
+ // characters can't break the invocation.
143
178
  try {
144
- execSync(command, { stdio: 'inherit' });
179
+ const jestBin = path.resolve('node_modules', 'jest', 'bin', 'jest.js');
180
+ execFileSync(process.execPath, [jestBin, ...jestArgs], { stdio: 'inherit' });
145
181
  } catch (err) {
182
+ // Log and continue so the coverage report still runs and CI can
183
+ // surface it. `main` exits non-zero at the end when this happened.
184
+ testsFailed = true;
146
185
  console.error('❌ Tests failed:', err.message || err);
147
- exit(1);
148
186
  }
149
187
  }
150
188
 
@@ -186,7 +224,7 @@ function runRelatedTests(files, mode, depth = 2) {
186
224
  console.log(' Files passed to Jest:');
187
225
  jestTargets.forEach(file => console.log(` - ${file}`));
188
226
 
189
- runJest(`npx jest --findRelatedTests --passWithNoTests --coverage ${jestTargets.join(' ')}`);
227
+ runJest(['--findRelatedTests', '--passWithNoTests', '--coverage', ...jestTargets]);
190
228
  return;
191
229
  }
192
230
 
@@ -243,11 +281,61 @@ function runRelatedTests(files, mode, depth = 2) {
243
281
  console.log(` Source files detected: ${sourceFiles.length}`);
244
282
  }
245
283
 
246
- runJest(`npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`);
284
+ runJest(['--passWithNoTests', '--coverage', ...finalTestFiles]);
285
+ }
286
+
287
+ /**
288
+ * Dry run: only resolve the test files that the selected mode would run,
289
+ * then print one path per line and exit without running Jest or checking
290
+ * coverage. The stdout is clean enough for another tool to consume:
291
+ * node index.js --dry-run true --files src/a.js --base origin/main
292
+ * Errors still go to stderr via the catch in main().
293
+ *
294
+ * @param {string[]} files - Changed source and test files (repo-relative)
295
+ * @param {string} mode - Execution mode (fast, smart, or full)
296
+ * @param {number} depth - Max reverse-dependency depth for smart mode
297
+ */
298
+ export function dryRun(files, mode, depth = 2) {
299
+ if (files.length === 0) {
300
+ // Keep stdout a clean file list; informational messages go to stderr.
301
+ console.error('✅ No changed source files found.');
302
+ exit(0);
303
+ }
304
+
305
+ const { sourceFiles, testFiles } = separateSourceAndTestFiles(files);
306
+
307
+ // Full mode delegates discovery to Jest; without running it, the only
308
+ // guaranteed output is the changed files themselves.
309
+ if (mode === 'full') {
310
+ // Keep stdout clean (one path per line) for other tools; warn on stderr.
311
+ console.error('⚠️ full mode relies on Jest --findRelatedTests; --dry-run prints only the changed test files.');
312
+ testFiles.forEach(file => console.log(file));
313
+ exit(0);
314
+ }
315
+
316
+ const testFilesToRun = new Set(testFiles);
317
+
318
+ sourceFiles.forEach(sourceFile => {
319
+ // Same matching rules as the real run (see runRelatedTests), just no Jest.
320
+ const relatedTests = mode === 'smart'
321
+ ? findRelatedTestFilesBySource(sourceFile, { maxDepth: depth })
322
+ : findTestFilesForSource(sourceFile);
323
+
324
+ if (mode === 'fast' && relatedTests.length === 0) {
325
+ relatedTests.push(...findTestFilesByImport(sourceFile));
326
+ }
327
+
328
+ relatedTests.forEach(test => testFilesToRun.add(test));
329
+ });
330
+
331
+ Array.from(testFilesToRun).sort().forEach(file => console.log(file));
332
+ exit(0);
247
333
  }
248
334
 
249
335
  function getChangedLines(filePath, BASE_BRANCH) {
250
- const diff = execSync(`git diff -U0 ${BASE_BRANCH} -- ${filePath}`).toString();
336
+ // Argument array + `--` separator keeps file paths (and the ref, already
337
+ // validated in verifyBaseBranchExists) out of any shell interpretation.
338
+ const diff = execFileSync('git', ['diff', '-U0', BASE_BRANCH, '--', filePath], { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
251
339
  const lines = [];
252
340
 
253
341
  const hunkRegex = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;
@@ -335,6 +423,42 @@ export function summarizeCoverageResult(totalChanged, totalNotCovered, coverageL
335
423
  };
336
424
  }
337
425
 
426
+ export function buildMarkdownCoverageReport(rows, { overallCoverage, changedLinesLimit, totalChanged, totalNotCovered }) {
427
+ const lines = [
428
+ '# mo3ta-coverage report',
429
+ '',
430
+ '| Status | File | Changed coverable lines | Covered | Uncovered | Coverage |',
431
+ '| --- | --- | ---: | ---: | ---: | ---: |'
432
+ ];
433
+
434
+ rows.forEach(({ filePath, covered, uncovered, trackedChangedLines, fileCoverage, status }) => {
435
+ lines.push(
436
+ `| ${status} | \`${filePath}\` | ${trackedChangedLines} | ${covered} | ${uncovered} | ${fileCoverage} |`
437
+ );
438
+ });
439
+
440
+ if (totalChanged > 0) {
441
+ lines.push(
442
+ `| **Overall** | — | ${totalChanged} | ${totalChanged - totalNotCovered} | ${totalNotCovered} | ${overallCoverage}% |`
443
+ );
444
+ lines.push('');
445
+ lines.push(
446
+ `Overall coverage: **${overallCoverage}%** (limit: ${changedLinesLimit}%) — ` +
447
+ `${totalChanged - totalNotCovered}/${totalChanged} changed lines covered, ${totalNotCovered} uncovered.`
448
+ );
449
+ } else {
450
+ lines.push('');
451
+ lines.push('**No coverable changed lines found.**');
452
+ }
453
+
454
+ return lines.join('\n');
455
+ }
456
+
457
+ export function writeMarkdownReport(markdown, reportPath) {
458
+ fs.mkdirSync(path.dirname(reportPath), { recursive: true });
459
+ fs.writeFileSync(reportPath, markdown + '\n', 'utf8');
460
+ }
461
+
338
462
  export function formatMissedLinesSummary(uncoveredByFile) {
339
463
  if (uncoveredByFile.length === 0) {
340
464
  return [];
@@ -351,40 +475,53 @@ export function formatMissedLinesSummary(uncoveredByFile) {
351
475
  ];
352
476
  }
353
477
 
354
- function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED) {
478
+ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED, CI = false, CI_REPORT_PATH) {
355
479
  if (!fs.existsSync(LCOV_PATH)) {
356
480
  console.error('❌ lcov.info not found. Make sure coverage ran correctly.');
357
481
  process.exit(1);
358
482
  }
359
483
 
360
- const coverageByFile = parseLcov(LCOV_PATH);
484
+ if (CI) {
485
+ // In CI mode keep the console output clean: results go in the markdown
486
+ // table below and are also saved to a file for CI to read.
487
+ console.error(`ℹ️ CI mode enabled. Coverage table will be saved to: ${CI_REPORT_PATH}`);
488
+ } else {
489
+ console.log(`\n🔍 Checking coverage of changed lines vs branch: ${BASE_BRANCH}\n`);
490
+ }
361
491
 
362
- console.log(`\n🔍 Checking coverage of changed lines vs branch: ${BASE_BRANCH}\n`);
492
+ const coverageByFile = parseLcov(LCOV_PATH);
363
493
 
364
494
  changedFiles = getJsOnlyFiles(changedFiles);
365
495
 
366
496
  if (changedFiles.length === 0) {
367
- console.log('✅ No relevant files found for coverage check.');
497
+ if (!CI) {
498
+ console.log('✅ No relevant files found for coverage check.');
499
+ }
368
500
  return;
369
501
  }
370
502
 
371
- console.log('Files with changed lines:', changedFiles.join('\n'));
503
+ if (!CI) {
504
+ console.log('Files with changed lines:', changedFiles.join('\n'));
505
+ }
372
506
 
373
507
  let totalChanged = 0;
374
508
  let totalNotCovered = 0;
375
509
  const uncoveredByFile = [];
510
+ const rows = [];
376
511
 
377
512
  changedFiles.forEach(relPath => {
378
513
  const absPath = path.resolve(relPath);
379
514
  const addedLines = getChangedLines(relPath, BASE_BRANCH);
380
515
 
381
516
  if (addedLines.length === 0) {
382
- console.log(`ℹ️ ${absPath} - No changed lines detected.`);
517
+ if (!CI) {
518
+ console.log(`ℹ️ ${absPath} - No changed lines detected.`);
519
+ }
383
520
  return;
384
521
  }
385
522
 
386
523
  const fileCoverage = coverageByFile[absPath];
387
- if (!fileCoverage) {
524
+ if (!fileCoverage && !CI) {
388
525
  console.log(`⚠️ No coverage info for: ${absPath}`);
389
526
  }
390
527
 
@@ -404,29 +541,60 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
404
541
  });
405
542
  }
406
543
 
407
- if (uncoveredLines.length > 0) {
408
- console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredLines.join(', ')}]`);
409
- } else if (trackedChangedLines > 0) {
410
- console.log(`✅ ${absPath} - All changed lines are covered`);
411
- }
544
+ rows.push({
545
+ filePath: relPath,
546
+ covered: coveredLines.length,
547
+ uncovered: uncoveredLines.length,
548
+ trackedChangedLines,
549
+ fileCoverage: trackedChangedLines > 0
550
+ ? `${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`
551
+ : '-',
552
+ status: uncoveredLines.length > 0 ? '🚨' : trackedChangedLines > 0 ? '✅' : 'ℹ️'
553
+ });
554
+
555
+ if (!CI) {
556
+ if (uncoveredLines.length > 0) {
557
+ console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredLines.join(', ')}]`);
558
+ } else if (trackedChangedLines > 0) {
559
+ console.log(`✅ ${absPath} - All changed lines are covered`);
560
+ }
412
561
 
413
- console.log(` Total coverable changed lines: ${trackedChangedLines}, Covered: ${coveredLines.length}, Uncovered: ${uncoveredLines.length}`)
414
- if (SHOW_COVERED && coveredLines.length > 0) {
415
- console.log(` Covered lines: [${coveredLines.join(', ')}]`);
416
- }
417
- if (trackedChangedLines > 0) {
418
- console.log(` Coverage for changed lines: ${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`);
419
- } else {
420
- console.log(` No coverable lines in this file's changed lines (e.g., imports, comments).`);
562
+ console.log(` Total coverable changed lines: ${trackedChangedLines}, Covered: ${coveredLines.length}, Uncovered: ${uncoveredLines.length}`)
563
+ if (SHOW_COVERED && coveredLines.length > 0) {
564
+ console.log(` Covered lines: [${coveredLines.join(', ')}]`);
565
+ }
566
+ if (trackedChangedLines > 0) {
567
+ console.log(` Coverage for changed lines: ${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`);
568
+ } else {
569
+ console.log(` No coverable lines in this file's changed lines (e.g., imports, comments).`);
570
+ }
421
571
  }
422
572
  });
423
573
 
424
574
  // Cumulative coverage check
575
+ const { overallCoverage, passed, icon } = totalChanged > 0
576
+ ? summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT)
577
+ : { overallCoverage: null, passed: true, icon: '✅' };
578
+
579
+ if (CI) {
580
+ const report = buildMarkdownCoverageReport(rows, {
581
+ overallCoverage: overallCoverage === null ? null : overallCoverage.toFixed(2),
582
+ changedLinesLimit: COVERAGE_LIMIT,
583
+ totalChanged,
584
+ totalNotCovered
585
+ });
586
+
587
+ writeMarkdownReport(report, CI_REPORT_PATH);
588
+ console.log(report);
589
+ console.error(`📄 Coverage table saved to: ${CI_REPORT_PATH}`);
590
+ }
591
+
425
592
  if (totalChanged > 0) {
426
- const { overallCoverage, passed, icon } = summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT);
427
- console.log(`\n${icon} Overall coverage for all changed lines: ${overallCoverage.toFixed(2)}% (limit: ${COVERAGE_LIMIT}%)`);
428
- console.log(`Not covered lines: ${totalNotCovered} out of ${totalChanged} changed lines`);
429
- formatMissedLinesSummary(uncoveredByFile).forEach(line => console.log(line));
593
+ if (!CI) {
594
+ console.log(`\n${icon} Overall coverage for all changed lines: ${overallCoverage.toFixed(2)}% (limit: ${COVERAGE_LIMIT}%)`);
595
+ console.log(`Not covered lines: ${totalNotCovered} out of ${totalChanged} changed lines`);
596
+ formatMissedLinesSummary(uncoveredByFile).forEach(line => console.log(line));
597
+ }
430
598
 
431
599
  if (!passed) {
432
600
  process.exit(1);
package/src/cli.test.js CHANGED
@@ -3,14 +3,17 @@ import os from 'os';
3
3
  import path from 'path';
4
4
  import { execSync } from 'child_process';
5
5
  import {
6
+ buildMarkdownCoverageReport,
6
7
  classifyChangedLineCoverage,
8
+ dryRun,
7
9
  formatMissedLinesSummary,
8
10
  getChangedFiles,
9
11
  getExplicitFiles,
10
12
  normalizeExplicitFiles,
11
13
  parseLcov,
12
14
  readExplicitFilesFromFile,
13
- summarizeCoverageResult
15
+ summarizeCoverageResult,
16
+ writeMarkdownReport
14
17
  } from './cli.js';
15
18
 
16
19
  function writeLcovFixture(records) {
@@ -117,6 +120,49 @@ describe('formatMissedLinesSummary', () => {
117
120
  });
118
121
  });
119
122
 
123
+ describe('buildMarkdownCoverageReport', () => {
124
+ it('renders a markdown table with per-file rows and an overall line', () => {
125
+ const report = buildMarkdownCoverageReport(
126
+ [
127
+ { filePath: 'src/a.js', covered: 4, uncovered: 1, trackedChangedLines: 5, fileCoverage: '80.00%', status: '🚨' },
128
+ { filePath: 'src/b.js', covered: 3, uncovered: 0, trackedChangedLines: 3, fileCoverage: '100.00%', status: '✅' }
129
+ ],
130
+ { overallCoverage: '87.50', changedLinesLimit: 80, totalChanged: 8, totalNotCovered: 1 }
131
+ );
132
+
133
+ expect(report).toContain('| Status | File | Changed coverable lines | Covered | Uncovered | Coverage |');
134
+ expect(report).toContain('| --- | --- | ---: | ---: | ---: | ---: |');
135
+ expect(report).toContain('| 🚨 | `src/a.js` | 5 | 4 | 1 | 80.00% |');
136
+ expect(report).toContain('| ✅ | `src/b.js` | 3 | 3 | 0 | 100.00% |');
137
+ expect(report).toContain('| **Overall** | — | 8 | 7 | 1 | 87.50% |');
138
+ expect(report).toContain('Overall coverage: **87.50%** (limit: 80%) — 7/8 changed lines covered, 1 uncovered.');
139
+ });
140
+
141
+ it('notes when there are no coverable changed lines', () => {
142
+ const report = buildMarkdownCoverageReport([], {
143
+ overallCoverage: null,
144
+ changedLinesLimit: 80,
145
+ totalChanged: 0,
146
+ totalNotCovered: 0
147
+ });
148
+
149
+ expect(report).toContain('**No coverable changed lines found.**');
150
+ });
151
+ });
152
+
153
+ describe('writeMarkdownReport', () => {
154
+ it('creates parent directories and writes the report file', () => {
155
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-report-'));
156
+ const reportPath = path.join(tempDir, 'nested', 'report.md');
157
+
158
+ writeMarkdownReport('# report\n', reportPath);
159
+
160
+ expect(fs.readFileSync(reportPath, 'utf8')).toBe('# report\n\n');
161
+
162
+ fs.rmSync(tempDir, { recursive: true, force: true });
163
+ });
164
+ });
165
+
120
166
  describe('normalizeExplicitFiles', () => {
121
167
  it('accepts a comma-separated string', () => {
122
168
  expect(normalizeExplicitFiles('src/a.js,src/b.ts')).toEqual([
@@ -238,3 +284,101 @@ describe('getChangedFiles', () => {
238
284
  expect(result).toEqual(['base.js', 'staged.js']);
239
285
  });
240
286
  });
287
+
288
+ describe('dryRun', () => {
289
+ let tempDir;
290
+ let originalCwd;
291
+ let originalLog;
292
+ let originalError;
293
+ let exitSpy;
294
+ let stdoutLines;
295
+ let stderrLines;
296
+
297
+ beforeEach(() => {
298
+ originalCwd = process.cwd();
299
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-dry-run-'));
300
+
301
+ fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
302
+ fs.writeFileSync(path.join(tempDir, 'src', 'example.js'), 'export const example = 1;\n');
303
+ fs.writeFileSync(
304
+ path.join(tempDir, 'src', 'example.test.js'),
305
+ "import { example } from './example';\n\ntest('naming match', () => expect(example).toBe(1));\n"
306
+ );
307
+ fs.mkdirSync(path.join(tempDir, 'specs'), { recursive: true });
308
+ fs.writeFileSync(
309
+ path.join(tempDir, 'specs', 'custom-name.spec.js'),
310
+ "import { example } from '../src/example';\n\ntest('import match', () => expect(example).toBe(1));\n"
311
+ );
312
+
313
+ // A source file with no naming-convention match: only reachable by import.
314
+ fs.writeFileSync(path.join(tempDir, 'src', 'bare.js'), 'export const bare = 1;\n');
315
+ fs.writeFileSync(
316
+ path.join(tempDir, 'specs', 'custom-name-bare.spec.js'),
317
+ "import { bare } from '../src/bare';\n\ntest('bare import match', () => expect(bare).toBe(1));\n"
318
+ );
319
+
320
+ process.chdir(tempDir);
321
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
322
+ throw new Error(`exit:${code}`);
323
+ });
324
+
325
+ stdoutLines = [];
326
+ stderrLines = [];
327
+ originalLog = console.log;
328
+ originalError = console.error;
329
+ console.log = (...args) => stdoutLines.push(args.join(' '));
330
+ console.error = (...args) => stderrLines.push(args.join(' '));
331
+ });
332
+
333
+ function runDryRun(files, mode = 'smart', depth = 2) {
334
+ expect(() => dryRun(files, mode, depth)).toThrow(/^exit:/);
335
+ }
336
+
337
+ afterEach(() => {
338
+ console.log = originalLog;
339
+ console.error = originalError;
340
+ exitSpy.mockRestore();
341
+ process.chdir(originalCwd);
342
+ fs.rmSync(tempDir, { recursive: true, force: true });
343
+ });
344
+
345
+ it('prints one matched test path per line (naming + depth-1 import match)', () => {
346
+ runDryRun(['src/example.js'], 'smart');
347
+
348
+ expect(stdoutLines).toEqual(['specs/custom-name.spec.js', 'src/example.test.js']);
349
+ expect(exitSpy).toHaveBeenCalledWith(0);
350
+ });
351
+
352
+ it('honors the depth limit (depth 0 = naming matches only)', () => {
353
+ runDryRun(['src/example.js'], 'smart', 0);
354
+
355
+ expect(stdoutLines).toEqual(['src/example.test.js']);
356
+ });
357
+
358
+ it('uses the import-scan fallback in fast mode when no naming match exists', () => {
359
+ runDryRun(['src/bare.js'], 'fast');
360
+
361
+ expect(stdoutLines).toEqual(['specs/custom-name-bare.spec.js']);
362
+ });
363
+
364
+ it('prints the changed test files themselves', () => {
365
+ runDryRun(['src/example.test.js']);
366
+
367
+ expect(stdoutLines).toEqual(['src/example.test.js']);
368
+ });
369
+
370
+ it('prints no paths and exits when there are no changed files', () => {
371
+ runDryRun([]);
372
+
373
+ expect(stdoutLines).toEqual([]);
374
+ expect(stderrLines.some(line => line.includes('No changed source files'))).toBe(true);
375
+ expect(exitSpy).toHaveBeenCalledWith(0);
376
+ });
377
+
378
+ it('full mode warns on stderr and prints only the changed test files', () => {
379
+ runDryRun(['src/example.js', 'src/example.test.js'], 'full');
380
+
381
+ expect(stdoutLines).toEqual(['src/example.test.js']);
382
+ expect(stderrLines.some(line => line.includes('--findRelatedTests'))).toBe(true);
383
+ });
384
+ });
package/src/gitUtils.js CHANGED
@@ -1,9 +1,9 @@
1
- import { execSync } from 'child_process';
1
+ import { execFileSync } from 'child_process';
2
2
  import { exit } from 'process';
3
3
 
4
4
  export function verifyGitRepoExists() {
5
5
  try {
6
- execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
6
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { stdio: 'ignore' });
7
7
  } catch (err) {
8
8
  console.error(`❌ Not a git repository. Please run this tool inside a git repo. ${err.message}`);
9
9
  exit(1);
@@ -12,7 +12,11 @@ export function verifyGitRepoExists() {
12
12
 
13
13
  export function verifyBaseBranchExists(BASE_BRANCH) {
14
14
  try {
15
- execSync(`git rev-parse --verify ${BASE_BRANCH}`, { stdio: 'ignore' });
15
+ // Accept any valid git ref (branch, tag, or revision like origin/main, HEAD~1).
16
+ // Git is invoked with an argument array (never through a shell) and the value
17
+ // is checked with --verify, so a hostile value such as `--upload-pack=cmd`
18
+ // or `a; rm -rf ~` is rejected by git as an invalid ref instead of running.
19
+ execFileSync('git', ['rev-parse', '--verify', '--quiet', `${BASE_BRANCH}^{commit}`], { stdio: 'ignore' });
16
20
  } catch (err) {
17
21
  console.error(`❌ Base branch "${BASE_BRANCH}" does not exist or is invalid. try git fetch to update your local branches.`);
18
22
  exit(1);
package/docs/poster.png DELETED
Binary file
package/docs/poster.svg DELETED
@@ -1,131 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="1600" height="900" viewBox="0 0 1600 900" role="img" aria-labelledby="title desc">
2
- <title id="title">mo3ta-coverage — modes and features</title>
3
- <desc id="desc">Poster listing the fast, smart, and full execution modes and the main features of mo3ta-coverage.</desc>
4
-
5
- <defs>
6
- <linearGradient id="bgGlow" x1="0" y1="0" x2="0" y2="1">
7
- <stop offset="0%" stop-color="#10131a"/>
8
- <stop offset="100%" stop-color="#0f1115"/>
9
- </linearGradient>
10
- <radialGradient id="topGlow" cx="50%" cy="0%" r="70%">
11
- <stop offset="0%" stop-color="#60a5fa" stop-opacity="0.20"/>
12
- <stop offset="100%" stop-color="#60a5fa" stop-opacity="0"/>
13
- </radialGradient>
14
- <radialGradient id="greenGlow" cx="100%" cy="100%" r="60%">
15
- <stop offset="0%" stop-color="#22c55e" stop-opacity="0.10"/>
16
- <stop offset="100%" stop-color="#22c55e" stop-opacity="0"/>
17
- </radialGradient>
18
- <pattern id="grid" width="52" height="52" patternUnits="userSpaceOnUse">
19
- <path d="M52 0H0V52" fill="none" stroke="#ffffff" stroke-opacity="0.035" stroke-width="1"/>
20
- </pattern>
21
- <filter id="cardShadow" x="-20%" y="-20%" width="140%" height="160%">
22
- <feDropShadow dx="0" dy="18" stdDeviation="24" flood-color="#000000" flood-opacity="0.45"/>
23
- </filter>
24
- <style>
25
- .sans { font-family: Inter, -apple-system, "Helvetica Neue", Arial, sans-serif; }
26
- .mono { font-family: "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace; }
27
- .muted { fill: #9aa0a6; }
28
- .bright { fill: #f4f7fb; }
29
- .accent { fill: #60a5fa; }
30
- </style>
31
- </defs>
32
-
33
- <!-- background -->
34
- <rect width="1600" height="900" fill="url(#bgGlow)"/>
35
- <rect width="1600" height="900" fill="url(#grid)"/>
36
- <rect width="1600" height="900" fill="url(#topGlow)"/>
37
- <rect width="1600" height="900" fill="url(#greenGlow)"/>
38
-
39
- <!-- header -->
40
- <g class="sans">
41
- <g transform="translate(72, 78)">
42
- <rect x="0" y="-26" width="286" height="46" rx="23" fill="#60a5fa" fill-opacity="0.09" stroke="#60a5fa" stroke-opacity="0.42"/>
43
- <circle cx="28" cy="-3" r="5" fill="#22c55e"/>
44
- <text x="46" y="4" class="mono" font-size="15" letter-spacing="3.2" fill="#60a5fa">PR COVERAGE · SMART MODE</text>
45
- </g>
46
-
47
- <text x="72" y="188" class="bright" font-size="76" font-weight="800" letter-spacing="-3.2">mo3ta-coverage</text>
48
- <text x="74" y="238" class="muted" font-size="28" letter-spacing="-0.4">Changed code. Related specs. Real coverage.</text>
49
- </g>
50
-
51
- <!-- modes -->
52
- <g class="sans">
53
- <text x="72" y="308" class="mono" font-size="15" letter-spacing="3.4" fill="#60a5fa">MODES</text>
54
-
55
- <!-- fast -->
56
- <g filter="url(#cardShadow)">
57
- <rect x="72" y="330" width="460" height="196" rx="18" fill="#1a1c22" stroke="#2a2d35"/>
58
- </g>
59
- <text x="102" y="382" class="mono" font-size="15" letter-spacing="2.4" fill="#38bdf8">FAST</text>
60
- <text x="102" y="425" class="bright" font-size="26" font-weight="700">Direct mapped tests</text>
61
- <text x="102" y="461" class="muted" font-size="18">Naming convention + direct import scan.</text>
62
- <text x="102" y="489" class="muted" font-size="18">No dependency traversal.</text>
63
- <text x="102" y="518" class="mono" font-size="15" fill="#7dd3fc">--mode fast</text>
64
-
65
- <!-- smart -->
66
- <g filter="url(#cardShadow)">
67
- <rect x="562" y="330" width="460" height="196" rx="18" fill="#1a1c22" stroke="#60a5fa" stroke-opacity="0.85"/>
68
- </g>
69
- <rect x="878" y="352" width="118" height="30" rx="15" fill="#60a5fa" fill-opacity="0.14" stroke="#60a5fa" stroke-opacity="0.45"/>
70
- <text x="895" y="372" class="mono" font-size="12" letter-spacing="1.6" fill="#60a5fa">DEFAULT</text>
71
- <text x="592" y="382" class="mono" font-size="15" letter-spacing="2.4" fill="#60a5fa">SMART</text>
72
- <text x="592" y="425" class="bright" font-size="26" font-weight="700">Naming + reverse imports</text>
73
- <text x="592" y="461" class="muted" font-size="18">Finds specs through barrels and wrappers.</text>
74
- <text x="592" y="489" class="muted" font-size="18">Depth-limited by --depth (default 2).</text>
75
- <text x="592" y="518" class="mono" font-size="15" fill="#93c5fd">--mode smart --depth 2</text>
76
-
77
- <!-- full -->
78
- <g filter="url(#cardShadow)">
79
- <rect x="1052" y="330" width="460" height="196" rx="18" fill="#1a1c22" stroke="#2a2d35"/>
80
- </g>
81
- <text x="1082" y="382" class="mono" font-size="15" letter-spacing="2.4" fill="#a78bfa">FULL</text>
82
- <text x="1082" y="425" class="bright" font-size="26" font-weight="700">Jest finds related tests</text>
83
- <text x="1082" y="461" class="muted" font-size="18">Passes changed files to Jest directly.</text>
84
- <text x="1082" y="489" class="muted" font-size="18">Unbounded --findRelatedTests walk.</text>
85
- <text x="1082" y="518" class="mono" font-size="15" fill="#c4b5fd">--mode full</text>
86
- </g>
87
-
88
- <!-- features -->
89
- <g class="sans">
90
- <text x="72" y="598" class="mono" font-size="15" letter-spacing="3.4" fill="#60a5fa">FEATURES</text>
91
-
92
- <!-- column 1 -->
93
- <g transform="translate(72, 638)">
94
- <circle cx="6" cy="-6" r="4" fill="#22c55e"/>
95
- <text x="26" y="0" font-size="21" class="bright">Detects changed JS/TS files for all authors</text>
96
-
97
- <circle cx="6" cy="42" r="4" fill="#22c55e"/>
98
- <text x="26" y="48" font-size="21" class="bright">Runs only the tests related to the change</text>
99
-
100
- <circle cx="6" cy="90" r="4" fill="#22c55e"/>
101
- <text x="26" y="96" font-size="21" class="bright">Maps specs by name and by import graph</text>
102
-
103
- <circle cx="6" cy="138" r="4" fill="#22c55e"/>
104
- <text x="26" y="144" font-size="21" class="bright">Scans selected files with --files</text>
105
- </g>
106
-
107
- <!-- column 2 -->
108
- <g transform="translate(876, 638)">
109
- <circle cx="6" cy="-6" r="4" fill="#22c55e"/>
110
- <text x="26" y="0" font-size="21" class="bright">Checks changed-line coverage from lcov.info</text>
111
-
112
- <circle cx="6" cy="42" r="4" fill="#22c55e"/>
113
- <text x="26" y="48" font-size="21" class="bright">Fails below the --limit threshold</text>
114
-
115
- <circle cx="6" cy="90" r="4" fill="#22c55e"/>
116
- <text x="26" y="96" font-size="21" class="bright">Reports every uncovered changed line</text>
117
-
118
- <circle cx="6" cy="138" r="4" fill="#22c55e"/>
119
- <text x="26" y="144" font-size="21" class="bright">Works locally and in CI</text>
120
- </g>
121
- </g>
122
-
123
- <!-- footer command -->
124
- <rect x="72" y="790" width="1456" height="62" rx="14" fill="#14161c" stroke="#2a2d35"/>
125
- <text x="102" y="829" class="mono" font-size="19" fill="#9aa0a6">$</text>
126
- <text x="124" y="829" class="mono" font-size="19" fill="#e6e6e6">npx mo3ta-coverage</text>
127
- <text x="334" y="829" class="mono" font-size="19" fill="#60a5fa">--mode smart</text>
128
- <text x="482" y="829" class="mono" font-size="19" fill="#9aa0a6">--base origin/main</text>
129
- <text x="706" y="829" class="mono" font-size="19" fill="#9aa0a6">--limit 80</text>
130
- <text x="1476" y="829" class="mono" font-size="14" fill="#22c55e" text-anchor="end">changed lines only</text>
131
- </svg>