mo3ta-coverage 1.0.7 โ†’ 1.0.9

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.
@@ -0,0 +1,4 @@
1
+ {
2
+ "shallowTests": false,
3
+ "base": "origin/dev"
4
+ }
package/README.md CHANGED
@@ -36,40 +36,55 @@ mo3ta-coverage --base origin/master --lcov coverage/lcov.info --limit 80 --showC
36
36
  5. **Report**: Prints uncovered changed lines, optionally covered lines, and overall coverage ([`src/cli.js`](src/cli.js)).
37
37
  6. **Enforce limit**: Exits with error if coverage is below the specified threshold.
38
38
 
39
- ## Architecture Diagram
40
-
41
- ```mermaid
42
- flowchart TD
43
- A[User runs mo3ta-coverage] --> B[Parse CLI options in index.js]
44
- B --> C[Get changed files via git diff in cli.js]
45
- C --> D[Run related Jest tests in cli.js]
46
- D --> E[Parse lcov.info for coverage in cli.js]
47
- E --> F[Report uncovered & covered changed lines in cli.js]
48
- F --> G[Check overall coverage vs limit in cli.js]
39
+
40
+ # mo3ta-coverage
41
+
42
+ Run tests and report uncovered changed lines in a PR. Checks cumulative coverage for all changed lines against a specified limit. Useful for CI and code review workflows.
43
+
44
+ ## Installation
45
+
46
+ ```sh
47
+ npm install -g mo3ta-coverage
49
48
  ```
50
49
 
51
- ## Example Output
50
+ ## Usage
52
51
 
52
+ ```sh
53
+ mo3ta-coverage --base origin/main --lcov coverage/lcov.info --limit 80 --showCovered --shallowTests
53
54
  ```
54
- Options:
55
- Base Branch: origin/main
56
- LCOV Path: coverage/lcov.info
57
- Coverage Limit: 80
58
- Show Covered Lines: true
59
- ๐Ÿงช Running tests related to the changed files:
60
- src/foo.js
61
- src/bar.js
62
- ๐Ÿšจ /abs/path/src/foo.js - Uncovered changed lines: [12, 15]
63
- Total changed lines: 5, Covered: 3, Uncovered: 2
64
- Covered lines: [10, 11, 13]
65
- Coverage for changed lines: 60.00%
66
- โœ… /abs/path/src/bar.js - All changed lines are covered
67
- Total changed lines: 4, Covered: 4, Uncovered: 0
68
- Covered lines: [20, 21, 22, 23]
69
- Coverage for changed lines: 100.00%
70
- ๐Ÿ”ข Overall coverage for all changed lines: 80.00% limit is 80%
55
+
56
+ ### Options
57
+ - `--base <branch>`: Base branch to compare against (default: origin/main or config value)
58
+ - `--lcov <path>`: Path to lcov.info file generated by test coverage tools (default: coverage/lcov.info)
59
+ - `--limit <percent>`: Minimum required coverage percentage for all changed lines (default: 80)
60
+ - `--showCovered`: Show covered changed lines in the output
61
+ - `--shallowTests`: Run test files only without deep in tests tree
62
+
63
+ ## Configuration
64
+
65
+ You can persist default options using the config command:
66
+
67
+ ```sh
68
+ mo3ta-coverage config --base origin/dev --shallowTests false
71
69
  ```
72
70
 
73
- ## License
71
+ This will save your preferences in `.mo3ta-coverage.json` in your project root. The CLI will use these values unless overridden by command-line options.
72
+
73
+ ## Development
74
74
 
75
+ 1. Clone the repository
76
+ 2. Install dependencies:
77
+ ```sh
78
+ npm install
79
+ ```
80
+ 3. Run tests:
81
+ ```sh
82
+ npm test
83
+ ```
84
+ 4. Run tests with coverage:
85
+ ```sh
86
+ npm run test:coverage
87
+ ```
88
+
89
+ ## License
75
90
  MIT
package/index.js CHANGED
@@ -1,19 +1,94 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+
3
4
  import { Command } from 'commander';
4
5
  import { main } from './src/cli.js';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { verifyBaseBranchExists } from './src/gitUtils.js';
9
+
10
+ const CONFIG_PATH = path.resolve(process.cwd(), '.mo3ta-coverage.json');
11
+
12
+ function readConfig() {
13
+ console.log(`Reading config from: ${CONFIG_PATH}`);
14
+
15
+ if (fs.existsSync(CONFIG_PATH)) {
16
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
17
+ }
18
+ return {};
19
+ }
20
+
21
+ function writeConfig(config) {
22
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
23
+ console.log(`Updated config: ${JSON.stringify(config, null, 2)}`);
24
+ }
5
25
 
6
26
  const program = new Command();
27
+
7
28
  program
8
29
  .name('mo3ta-coverage')
9
- .description('Run tests and report uncovered changed lines in a PR. Checks cumulative coverage for all changed lines against a specified limit. Useful for CI and code review workflows.')
10
- .option('--base <branch>', 'Base branch to compare against (e.g., origin/main)', 'origin/main')
30
+ .description('Run tests and report uncovered changed lines in a PR. Checks cumulative coverage for all changed lines against a specified limit. Useful for CI and code review workflows.');
31
+
32
+ program
33
+ .option('--base <branch>', 'Base branch to compare against (e.g., origin/main)')
11
34
  .option('--lcov <path>', 'Path to lcov.info file generated by test coverage tools', 'coverage/lcov.info')
12
35
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
13
- .option('--showCovered', 'Show covered changed lines in the output', false)
14
- .option('--shallowTests', 'Run test files only without deep in tests tree', true);
36
+ .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
37
+ .option('--shallow <bool>', 'Run test files only without deep in tests tree', true)
38
+ .enablePositionalOptions(); // used to allow using same options in subcommands
39
+
40
+
41
+ program
42
+ .command('config')
43
+ .description('Set or get configuration options')
44
+ .option('--base <branch>', 'Set default base branch')
45
+ .option('--shallow <bool>', 'Set default shallow value (true/false)')
46
+ .action((opts) => {
47
+ let config = readConfig();
48
+
49
+ let updated = false;
50
+
51
+ if (opts.base) {
52
+ verifyBaseBranchExists(opts.base);
53
+
54
+ config.base = opts.base;
55
+ updated = true;
56
+ console.log(`Default base branch set to: ${opts.base}`);
57
+ }
58
+
59
+ if (typeof opts.shallow !== 'undefined') {
60
+ config.shallow = opts.shallow === 'true' || opts.shallow === true;
61
+ updated = true;
62
+ console.log(`Default shallow set to: ${config.shallow}`);
63
+ }
64
+ if (updated) {
65
+ writeConfig(config);
66
+ } else {
67
+ console.log('Current config:', config);
68
+ }
69
+ process.exit(0);
70
+ })
71
+ .enablePositionalOptions()
72
+
73
+
74
+ program.action((opts) => {
75
+ const config = readConfig();
76
+ const options = program.opts();
77
+
78
+ // Use config base if not provided in CLI
79
+ if (!options.base && config.base) {
80
+ options.base = config.base;
81
+ } else if (!options.base) {
82
+ options.base = 'origin/main';
83
+ }
84
+ // Use config shallow if not provided in CLI
85
+ console.log(`Using shallow: ${options.shallow} ${config.shallow}`);
86
+
87
+ options.shallow = config.shallow ?? options.shallow;
88
+
89
+ console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
15
90
 
16
- program.parse(process.argv);
17
- const options = program.opts();
91
+ main(options);
92
+ });
18
93
 
19
- main(options);
94
+ await program.parseAsync(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "main": "index.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -2,44 +2,52 @@ import { execSync } from 'child_process';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { exit } from 'process';
5
+ import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
6
+ import { getJsOnlyFiles } from './fileUtils.js';
5
7
 
6
8
  export function main(options) {
7
- // Check if current directory is a git repository
8
9
  try {
9
- execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
10
- } catch (err) {
11
- console.error(`โŒ Not a git repository. Please run this tool inside a git repo. ${err.message}`);
12
-
10
+ // Check if current directory is a git repository
11
+ verifyGitRepoExists();
12
+
13
+ const BASE_BRANCH = options.base;
14
+ const LCOV_PATH = options.lcov;
15
+ const COVERAGE_LIMIT = parseFloat(options.limit);
16
+ const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
17
+ const SHALLOW_TESTS = options.shallow === true || options.shallow === 'true';
18
+
19
+ console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nShallow Tests: ${SHALLOW_TESTS}`);
20
+
21
+ const changedFiles = getChangedFiles(BASE_BRANCH);
22
+ runRelatedTests(changedFiles, SHALLOW_TESTS);
23
+ reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
24
+ } catch (error) {
25
+ console.error('โŒ An unexpected error occurred:', error.message || error);
13
26
  exit(1);
14
27
  }
15
-
16
-
17
- const BASE_BRANCH = options.base;
18
- const LCOV_PATH = options.lcov;
19
- const COVERAGE_LIMIT = parseFloat(options.limit);
20
- const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
21
- const RUN_TESTS_ONLY = options.shallowTests === true || options.shallowTests === 'true';
22
-
23
- console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nRun Tests Only: ${RUN_TESTS_ONLY}`);
24
-
25
- const changedFiles = getChangedFiles(BASE_BRANCH);
26
- runRelatedTests(changedFiles, RUN_TESTS_ONLY);
27
- reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
28
-
29
28
  }
30
29
 
30
+
31
31
  function getChangedFiles(BASE_BRANCH) {
32
+ // Check if BASE_BRANCH exists
33
+ verifyBaseBranchExists(BASE_BRANCH);
34
+
32
35
  const command = `(
33
36
  git log --pretty=format: --name-only --diff-filter=AM --author="$(git config user.name)" $(git merge-base HEAD ${BASE_BRANCH})..HEAD
34
37
  git diff --name-only --diff-filter=AM
35
38
  git diff --cached --name-only --diff-filter=AM
36
39
  ) | sort -u`;
37
40
 
38
- const output = execSync(command).toString();
39
-
40
- return output
41
- .split('\n')
42
- .filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/));
41
+ try {
42
+ const output = execSync(command).toString();
43
+ console.log(`Changed files:\n${output}`);
44
+ return output
45
+ .split('\n')
46
+ .filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/));
47
+ } catch (error) {
48
+ console.error('Error getting changed files:', error.message || error);
49
+ return [];
50
+ }
43
51
  }
44
52
 
45
53
  function runRelatedTests(files, runTestsOnly) {
@@ -66,7 +74,7 @@ function runRelatedTests(files, runTestsOnly) {
66
74
  }
67
75
 
68
76
  // log files to be tested
69
- console.log('\nFiles to be tested:', files.join('\n'));
77
+ console.log('\nFiles to be tested:\n', files.join('\n'));
70
78
 
71
79
  const command = `npx jest ${runRelatedFilesArgs} --passWithNoTests --coverage ${files.join(' ')}`;
72
80
  try {
@@ -77,22 +85,6 @@ function runRelatedTests(files, runTestsOnly) {
77
85
  }
78
86
  }
79
87
 
80
- function getJsOnlyFiles(files, runTestsOnly) {
81
- // Only include source code files, exclude test, config, and json files
82
- return files.filter(f => {
83
- // Exclude test files
84
- if (f.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) return false;
85
- // skip non test files when running only test files
86
- if (runTestsOnly) return false;
87
- // Exclude config files
88
- if (f.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/)) return false;
89
- // Exclude json files
90
- if (f.endsWith('.json')) return false;
91
- // Only include code files
92
- return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.jsx') || f.endsWith('.tsx');
93
- });
94
- }
95
-
96
88
  function getChangedLines(filePath, BASE_BRANCH) {
97
89
  const diff = execSync(`git diff -U0 ${BASE_BRANCH} -- ${filePath}`).toString();
98
90
  const lines = [];
@@ -190,6 +182,8 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
190
182
  // Cumulative coverage check
191
183
  if (totalChanged > 0) {
192
184
  const overallCoverage = (((totalChanged - totalUncovered) / totalChanged) * 100).toFixed(2);
193
- console.log(`\n๐Ÿ”ข Overall coverage for all changed lines: ${overallCoverage}% limit is ${COVERAGE_LIMIT}% with Uncovered: ${totalUncovered} (${totalChanged})`);
185
+ console.log(`\n๐Ÿ”ข Overall coverage for all changed lines: ${overallCoverage}% >>> ${COVERAGE_LIMIT}% `);
186
+ console.log(`Uncovered Lines: ${totalUncovered} out of ${totalChanged} changed lines`);
187
+
194
188
  }
195
189
  }
@@ -0,0 +1,15 @@
1
+ export function getJsOnlyFiles(files, runTestsOnly) {
2
+ // Only include source code files, exclude test, config, and json files
3
+ return files.filter(f => {
4
+ // Exclude test files
5
+ if (f.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) return false || runTestsOnly;
6
+ // skip non test files when running only test files
7
+ if (runTestsOnly) return false;
8
+ // Exclude config files and files with .config. in their name
9
+ if (f.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/) || f.includes('.config.')) return false;
10
+ // Exclude json files
11
+ if (f.endsWith('.json')) return false;
12
+ // Only include code files
13
+ return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.jsx') || f.endsWith('.tsx');
14
+ });
15
+ }
@@ -0,0 +1,84 @@
1
+ import { getJsOnlyFiles } from './fileUtils';
2
+
3
+ describe('getJsOnlyFiles', () => {
4
+ const files = [
5
+ 'src/app.js',
6
+ 'src/utils.ts',
7
+ 'src/component.jsx',
8
+ 'src/page.tsx',
9
+ 'src/app.test.js',
10
+ 'src/utils.spec.ts',
11
+ 'src/config/jest.config.js',
12
+ 'src/config/babel.config.js',
13
+ 'src/config/webpack.config.js',
14
+ 'src/config/tsconfig.json',
15
+ 'src/config/eslint.config.js',
16
+ 'src/config/prettier.config.js',
17
+ 'src/config/rollup.config.js',
18
+ 'src/config/vite.config.js',
19
+ 'src/package.json',
20
+ 'src/data.json',
21
+ 'README.md',
22
+ 'src/styles.css'
23
+ ];
24
+
25
+ it('should include only source code files and exclude test, config, and json files', () => {
26
+ const result = getJsOnlyFiles(files, false);
27
+ expect(result).toEqual([
28
+ 'src/app.js',
29
+ 'src/utils.ts',
30
+ 'src/component.jsx',
31
+ 'src/page.tsx'
32
+ ]);
33
+ });
34
+
35
+ it('should exclude all files except test files when runTestsOnly is true', () => {
36
+ const result = getJsOnlyFiles(files, true);
37
+ expect(result).toEqual([
38
+ 'src/app.test.js',
39
+ 'src/utils.spec.ts',
40
+ ]);
41
+ });
42
+
43
+ it('should return empty array if no files match', () => {
44
+ const result = getJsOnlyFiles(['README.md', 'src/styles.css'], false);
45
+ expect(result).toEqual([]);
46
+ });
47
+
48
+ it('should exclude .json files', () => {
49
+ const result = getJsOnlyFiles(['src/data.json', 'src/app.js'], false);
50
+ expect(result).toEqual(['src/app.js']);
51
+ });
52
+
53
+ it('should exclude config files', () => {
54
+ const configFiles = [
55
+ 'jest.config.js',
56
+ 'babel.config.js',
57
+ 'webpack.config.js',
58
+ 'tsconfig.json',
59
+ 'eslint.config.js',
60
+ 'prettier.config.js',
61
+ 'rollup.config.js',
62
+ 'vite.config.js',
63
+ 'package.json'
64
+ ];
65
+ const result = getJsOnlyFiles(configFiles, false);
66
+ expect(result).toEqual([]);
67
+ });
68
+
69
+ it('should include only .js, .ts, .jsx, .tsx files', () => {
70
+ const result = getJsOnlyFiles([
71
+ 'src/app.js',
72
+ 'src/utils.ts',
73
+ 'src/component.jsx',
74
+ 'src/page.tsx',
75
+ 'src/other.txt'
76
+ ], false);
77
+ expect(result).toEqual([
78
+ 'src/app.js',
79
+ 'src/utils.ts',
80
+ 'src/component.jsx',
81
+ 'src/page.tsx'
82
+ ]);
83
+ });
84
+ });
@@ -0,0 +1,20 @@
1
+ import { execSync } from 'child_process';
2
+ import { exit } from 'process';
3
+
4
+ export function verifyGitRepoExists() {
5
+ try {
6
+ execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
7
+ } catch (err) {
8
+ console.error(`โŒ Not a git repository. Please run this tool inside a git repo. ${err.message}`);
9
+ exit(1);
10
+ }
11
+ }
12
+
13
+ export function verifyBaseBranchExists(BASE_BRANCH) {
14
+ try {
15
+ execSync(`git rev-parse --verify ${BASE_BRANCH}`, { stdio: 'ignore' });
16
+ } catch (err) {
17
+ console.error(`โŒ Base branch "${BASE_BRANCH}" does not exist or is invalid. try git fetch to update your local branches.`);
18
+ exit(1);
19
+ }
20
+ }
package/src/cli.test.js DELETED
@@ -1,79 +0,0 @@
1
- import { main } from './cli';
2
- import * as child_process from 'child_process';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
5
-
6
-
7
- jest.mock('child_process');
8
- jest.mock('fs');
9
- jest.mock('path');
10
-
11
- describe('main', () => {
12
- let originalExit;
13
- let exitMock;
14
- let consoleLogSpy;
15
- let consoleErrorSpy;
16
-
17
- beforeEach(() => {
18
- // Mock process.exit
19
- originalExit = process.exit;
20
- exitMock = jest.fn();
21
- process.exit = exitMock;
22
-
23
- // Mock console
24
- consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
25
- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
26
-
27
- // Reset mocks
28
- jest.clearAllMocks();
29
- });
30
-
31
- afterEach(() => {
32
- process.exit = originalExit;
33
- consoleLogSpy.mockRestore();
34
- consoleErrorSpy.mockRestore();
35
- });
36
-
37
- it('should log options and call getChangedFiles, runRelatedTests, and reportUncoveredChangedLines', () => {
38
- // Mock git check
39
- child_process.execSync.mockImplementationOnce(() => 'true');
40
- // Mock getChangedFiles
41
- const fakeFiles = ['src/foo.js', 'src/bar.ts'];
42
- // Mock execSync for getChangedFiles
43
- child_process.execSync.mockImplementationOnce(() => fakeFiles.join('\n'));
44
- // Mock execSync for runRelatedTests (jest run)
45
- child_process.execSync.mockImplementationOnce(() => {});
46
- // Mock fs.existsSync for lcov
47
- fs.existsSync.mockReturnValue(true);
48
- // Mock fs.readFileSync for lcov parsing
49
- fs.readFileSync.mockReturnValue(
50
- 'SF:/abs/path/src/foo.js\nDA:1,0\nDA:2,1\nend_of_record\nSF:/abs/path/src/bar.ts\nDA:3,0\nend_of_record\n'
51
- );
52
- // Mock path.resolve to identity for simplicity
53
- path.resolve.mockImplementation(x => '/abs/path/' + x);
54
-
55
- // Mock getChangedLines to return some lines
56
- jest.spyOn(child_process, 'execSync').mockImplementation((cmd) => {
57
- if (cmd.includes('git diff')) {
58
- return Buffer.from('@@ -0,0 +1,2 @@\n+foo\n+bar\n');
59
- }
60
- if (cmd.includes('git rev-parse')) {
61
- return Buffer.from('true');
62
- }
63
- if (cmd.includes('git log') || cmd.includes('git diff --name-only')) {
64
- return Buffer.from(fakeFiles.join('\n'));
65
- }
66
- return Buffer.from('');
67
- });
68
-
69
- main({ base: 'main', lcov: 'lcov.info', limit: '80', showCovered: true });
70
-
71
- expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Options:'));
72
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Base Branch: main'));
73
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('LCOV Path: lcov.info'));
74
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Coverage Limit: 80'));
75
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Show Covered Lines: true'));
76
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Files with changed lines:'));
77
- // expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Overall coverage for all changed lines:'));
78
- });
79
- });