@tisankan/slop-check 0.0.0-stage → 1.1.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 +21 -0
- package/README.md +223 -2
- package/action.yml +29 -0
- package/bin/slop-check.js +147 -0
- package/package.json +44 -4
- package/src/action-main.js +9 -0
- package/src/action.js +203 -0
- package/src/check.js +136 -0
- package/src/comments.js +53 -0
- package/src/config.js +133 -0
- package/src/diff.js +65 -0
- package/src/git.js +166 -0
- package/src/languages.js +54 -0
- package/src/report.js +105 -0
- package/src/rules.js +417 -0
- package/src/run.js +64 -0
- package/src/score.js +40 -0
package/src/check.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Runs the enabled rules over one file's added lines.
|
|
2
|
+
|
|
3
|
+
import { getComment } from './comments.js';
|
|
4
|
+
import { getExtension, getLanguage, isExampleFile, isTestFile } from './languages.js';
|
|
5
|
+
import { RULES } from './rules.js';
|
|
6
|
+
|
|
7
|
+
// Very long lines are almost always minified or generated code.
|
|
8
|
+
export const MAX_LINE_LENGTH = 1000;
|
|
9
|
+
const IGNORE_MARKER = 'slop-check-ignore';
|
|
10
|
+
|
|
11
|
+
function commentOf(text, style) {
|
|
12
|
+
return style === 'text' ? null : getComment(text, style);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function cleanBlockLine(text) {
|
|
16
|
+
return text.trim().replace(/^\/?\*+/, '').replace(/\*\/\s*$/, '').trim();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Works out which lines are comments, following /* ... */ blocks across lines so
|
|
20
|
+
// code examples inside doc comments are not read as code.
|
|
21
|
+
function readComments(lines, style) {
|
|
22
|
+
const result = [];
|
|
23
|
+
let inBlock = false;
|
|
24
|
+
let previousNumber = null;
|
|
25
|
+
|
|
26
|
+
for (const line of lines) {
|
|
27
|
+
if (previousNumber !== null && line.number !== previousNumber + 1) {
|
|
28
|
+
inBlock = false;
|
|
29
|
+
}
|
|
30
|
+
previousNumber = line.number;
|
|
31
|
+
const trimmed = line.text.trim();
|
|
32
|
+
|
|
33
|
+
if (inBlock) {
|
|
34
|
+
result.push({ comment: cleanBlockLine(line.text), isCommentLine: true });
|
|
35
|
+
inBlock = !trimmed.includes('*/');
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (style === 'slash' && trimmed.startsWith('/*')) {
|
|
39
|
+
inBlock = !trimmed.slice(2).includes('*/');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const comment = commentOf(line.text, style);
|
|
43
|
+
const markers = { slash: ['//', '/*', '*'], hash: ['#'], dash: ['--'], text: [] }[style];
|
|
44
|
+
const startsWithMarker = markers.some((marker) => trimmed.startsWith(marker));
|
|
45
|
+
result.push({ comment, isCommentLine: comment !== null && startsWithMarker });
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Rules that read a block (a Ruby rescue with blank lines in it) need more than one
|
|
51
|
+
// line below. Only lines this change also added, in an unbroken run, are returned.
|
|
52
|
+
const LOOKAHEAD_LINES = 4;
|
|
53
|
+
|
|
54
|
+
function readLookahead(lines, comments, index) {
|
|
55
|
+
const result = [];
|
|
56
|
+
let expected = lines[index].number + 1;
|
|
57
|
+
for (let i = index + 1; i < lines.length && result.length < LOOKAHEAD_LINES; i += 1) {
|
|
58
|
+
if (lines[i].number !== expected) {
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
result.push({ number: lines[i].number, text: lines[i].text, ...comments[i] });
|
|
62
|
+
expected += 1;
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function checkFile(file, enabled) {
|
|
68
|
+
const language = getLanguage(file.path);
|
|
69
|
+
if (!language) {
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const info = {
|
|
74
|
+
path: file.path,
|
|
75
|
+
style: language.style,
|
|
76
|
+
extension: getExtension(file.path),
|
|
77
|
+
isTest: isTestFile(file.path),
|
|
78
|
+
isExample: isExampleFile(file.path),
|
|
79
|
+
};
|
|
80
|
+
const rules = RULES.filter((rule) => rule.scope === 'line' && enabled.has(rule.id) && rule.appliesTo(info));
|
|
81
|
+
const comments = readComments(file.lines, info.style);
|
|
82
|
+
const findings = [];
|
|
83
|
+
|
|
84
|
+
for (let i = 0; i < file.lines.length; i += 1) {
|
|
85
|
+
const line = file.lines[i];
|
|
86
|
+
if (line.text.length > MAX_LINE_LENGTH || line.text.includes(IGNORE_MARKER)) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// A rule may only look ahead at a line this change also added, right below.
|
|
91
|
+
const following = file.lines[i + 1];
|
|
92
|
+
let next = null;
|
|
93
|
+
if (following && following.number === line.number + 1) {
|
|
94
|
+
next = { number: following.number, text: following.text, ...comments[i + 1] };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const previous = file.lines[i - 1];
|
|
98
|
+
const previousIsComment = Boolean(previous && previous.number === line.number - 1 && comments[i - 1].isCommentLine);
|
|
99
|
+
const ctx = { text: line.text, ...comments[i], previousIsComment, next, lookahead: readLookahead(file.lines, comments, i), file: info };
|
|
100
|
+
for (const rule of rules) {
|
|
101
|
+
if (rule.check(ctx)) {
|
|
102
|
+
findings.push({ rule: rule.id, weight: rule.weight, message: rule.message, file: file.path, line: line.number });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return findings;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Commit messages are plain text, so only rules that also read markdown apply,
|
|
111
|
+
// plus the commit-only rules.
|
|
112
|
+
const COMMIT_TEXT = { path: '', style: 'text', extension: '', isTest: false, isExample: false };
|
|
113
|
+
|
|
114
|
+
export function checkCommit(commit, enabled) {
|
|
115
|
+
const rules = RULES.filter((rule) => {
|
|
116
|
+
if (!enabled.has(rule.id)) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
return rule.scope === 'commit' || rule.appliesTo(COMMIT_TEXT);
|
|
120
|
+
});
|
|
121
|
+
const findings = [];
|
|
122
|
+
|
|
123
|
+
for (const text of commit.message.split('\n')) {
|
|
124
|
+
if (text.includes(IGNORE_MARKER)) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const ctx = { text, comment: null, isCommentLine: false, previousIsComment: false, next: null, file: COMMIT_TEXT };
|
|
128
|
+
for (const rule of rules) {
|
|
129
|
+
if (rule.check(ctx)) {
|
|
130
|
+
findings.push({ rule: rule.id, weight: rule.weight, message: rule.message, commit: commit.sha.slice(0, 7) });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return findings;
|
|
136
|
+
}
|
package/src/comments.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Finds the comment part of one line of code, without understanding the language.
|
|
2
|
+
// A marker counts only outside quotes and at the line start or after whitespace,
|
|
3
|
+
// so "https://x.io" and color: "#fff" are not comments.
|
|
4
|
+
|
|
5
|
+
const MARKERS = { slash: '//', hash: '#', dash: '--' };
|
|
6
|
+
const QUOTES = ['"', "'", '`'];
|
|
7
|
+
|
|
8
|
+
function cleanBlockComment(text) {
|
|
9
|
+
return text.replace(/^\/\*+/, '').replace(/^\*+/, '').replace(/\*\/\s*$/, '').trim();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function findInlineMarker(text, marker) {
|
|
13
|
+
let quote = null;
|
|
14
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
15
|
+
const char = text[i];
|
|
16
|
+
if (quote) {
|
|
17
|
+
if (char === '\\') {
|
|
18
|
+
i += 1;
|
|
19
|
+
} else if (char === quote) {
|
|
20
|
+
quote = null;
|
|
21
|
+
}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (QUOTES.includes(char)) {
|
|
25
|
+
quote = char;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const startsHere = text.startsWith(marker, i);
|
|
29
|
+
const afterSpace = i === 0 || text[i - 1] === ' ' || text[i - 1] === '\t';
|
|
30
|
+
if (startsHere && afterSpace) {
|
|
31
|
+
return i;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return -1;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function getComment(text, style) {
|
|
38
|
+
const trimmed = text.trimStart();
|
|
39
|
+
|
|
40
|
+
if (style === 'slash' && (trimmed.startsWith('/*') || trimmed.startsWith('*'))) {
|
|
41
|
+
return cleanBlockComment(trimmed);
|
|
42
|
+
}
|
|
43
|
+
if (style === 'hash' && trimmed.startsWith('#!')) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const marker = MARKERS[style];
|
|
48
|
+
const index = findInlineMarker(trimmed, marker);
|
|
49
|
+
if (index === -1) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
return trimmed.slice(index + marker.length).replace(/^[/#-]+/, '').trim();
|
|
53
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Reads the optional .slopcheckrc.json and decides which files and rules are used.
|
|
2
|
+
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { RULES } from './rules.js';
|
|
6
|
+
|
|
7
|
+
const CONFIG_FILE = '.slopcheckrc.json';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_IGNORE = [
|
|
10
|
+
'**/node_modules/**',
|
|
11
|
+
'**/vendor/**',
|
|
12
|
+
'**/dist/**',
|
|
13
|
+
'**/build/**',
|
|
14
|
+
'**/out/**',
|
|
15
|
+
'**/coverage/**',
|
|
16
|
+
'package-lock.json',
|
|
17
|
+
'yarn.lock',
|
|
18
|
+
'pnpm-lock.yaml',
|
|
19
|
+
'*.lock',
|
|
20
|
+
'*.min.js',
|
|
21
|
+
'*.map',
|
|
22
|
+
'*.snap',
|
|
23
|
+
'*.gen.*',
|
|
24
|
+
'*.generated.*',
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
function globToRegExp(pattern) {
|
|
28
|
+
let source = '';
|
|
29
|
+
let i = 0;
|
|
30
|
+
while (i < pattern.length) {
|
|
31
|
+
if (pattern.startsWith('**/', i)) {
|
|
32
|
+
source += '(?:.*/)?';
|
|
33
|
+
i += 3;
|
|
34
|
+
} else if (pattern.startsWith('**', i)) {
|
|
35
|
+
source += '.*';
|
|
36
|
+
i += 2;
|
|
37
|
+
} else if (pattern[i] === '*') {
|
|
38
|
+
source += '[^/]*';
|
|
39
|
+
i += 1;
|
|
40
|
+
} else if (pattern[i] === '?') {
|
|
41
|
+
source += '[^/]';
|
|
42
|
+
i += 1;
|
|
43
|
+
} else {
|
|
44
|
+
source += pattern[i].replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
45
|
+
i += 1;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return new RegExp(`^${source}$`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function matchGlob(pattern, path) {
|
|
52
|
+
const fullPattern = pattern.includes('/') ? pattern : `**/${pattern}`;
|
|
53
|
+
return globToRegExp(fullPattern).test(path);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isPlainObject(value) {
|
|
57
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function loadConfig(rootDir) {
|
|
61
|
+
const config = { rules: {}, ignore: [], maxScore: null, warnings: [] };
|
|
62
|
+
const path = join(rootDir, CONFIG_FILE);
|
|
63
|
+
if (!existsSync(path)) {
|
|
64
|
+
return config;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let raw;
|
|
68
|
+
try {
|
|
69
|
+
raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
70
|
+
} catch (error) {
|
|
71
|
+
config.warnings.push(`could not read ${CONFIG_FILE}: ${error.message}`);
|
|
72
|
+
return config;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (!isPlainObject(raw)) {
|
|
76
|
+
config.warnings.push(`${CONFIG_FILE} must hold a JSON object`);
|
|
77
|
+
return config;
|
|
78
|
+
}
|
|
79
|
+
if (raw.rules !== undefined && !isPlainObject(raw.rules)) {
|
|
80
|
+
config.warnings.push(`"rules" in ${CONFIG_FILE} must be an object such as { "em-dash": "on" }`);
|
|
81
|
+
raw.rules = {};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const knownIds = RULES.map((rule) => rule.id);
|
|
85
|
+
for (const [id, value] of Object.entries(raw.rules || {})) {
|
|
86
|
+
if (!knownIds.includes(id)) {
|
|
87
|
+
config.warnings.push(`unknown rule "${id}" in ${CONFIG_FILE}`);
|
|
88
|
+
} else if (value !== 'on' && value !== 'off') {
|
|
89
|
+
config.warnings.push(`rule "${id}" in ${CONFIG_FILE} must be "on" or "off"`);
|
|
90
|
+
} else {
|
|
91
|
+
config.rules[id] = value;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (raw.ignore !== undefined) {
|
|
96
|
+
const isList = Array.isArray(raw.ignore) && raw.ignore.every((item) => typeof item === 'string');
|
|
97
|
+
if (isList) {
|
|
98
|
+
config.ignore = raw.ignore;
|
|
99
|
+
} else {
|
|
100
|
+
config.warnings.push(`"ignore" in ${CONFIG_FILE} must be a list of patterns`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (raw.maxScore !== undefined) {
|
|
105
|
+
if (Number.isInteger(raw.maxScore) && raw.maxScore >= 0 && raw.maxScore <= 100) {
|
|
106
|
+
config.maxScore = raw.maxScore;
|
|
107
|
+
} else {
|
|
108
|
+
config.warnings.push(`"maxScore" in ${CONFIG_FILE} must be a whole number from 0 to 100`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return config;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function enabledRules(config) {
|
|
116
|
+
const enabled = new Set();
|
|
117
|
+
for (const rule of RULES) {
|
|
118
|
+
const setting = config.rules[rule.id];
|
|
119
|
+
if (setting === 'on' || (setting === undefined && rule.defaultOn)) {
|
|
120
|
+
enabled.add(rule.id);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return enabled;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function isIgnored(path, config) {
|
|
127
|
+
for (const pattern of [...DEFAULT_IGNORE, ...config.ignore]) {
|
|
128
|
+
if (matchGlob(pattern, path)) {
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Turns `git diff` output into the lines each file added, with their new line numbers.
|
|
2
|
+
|
|
3
|
+
const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
|
|
4
|
+
|
|
5
|
+
function readPath(headerLine) {
|
|
6
|
+
let path = headerLine.slice(4).replace(/\t$/, '');
|
|
7
|
+
if (path === '/dev/null') {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
if (path.startsWith('"') && path.endsWith('"')) {
|
|
11
|
+
path = path.slice(1, -1).replace(/\\(.)/g, (match, char) => (char === 't' ? '\t' : char));
|
|
12
|
+
}
|
|
13
|
+
return path.startsWith('b/') ? path.slice(2) : path;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseDiff(text) {
|
|
17
|
+
const files = [];
|
|
18
|
+
let current = null;
|
|
19
|
+
let newLine = 0;
|
|
20
|
+
let oldLeft = 0;
|
|
21
|
+
let newLeft = 0;
|
|
22
|
+
|
|
23
|
+
for (const rawLine of text.split('\n')) {
|
|
24
|
+
const line = rawLine.replace(/\r$/, '');
|
|
25
|
+
|
|
26
|
+
// Inside a hunk the header counts tell us how many lines belong to it,
|
|
27
|
+
// so a content line such as "+++x" is never mistaken for a file header.
|
|
28
|
+
if (oldLeft > 0 || newLeft > 0) {
|
|
29
|
+
const marker = line[0];
|
|
30
|
+
if (marker === '+') {
|
|
31
|
+
if (current) {
|
|
32
|
+
current.lines.push({ number: newLine, text: line.slice(1) });
|
|
33
|
+
}
|
|
34
|
+
newLine += 1;
|
|
35
|
+
newLeft -= 1;
|
|
36
|
+
} else if (marker === '-') {
|
|
37
|
+
oldLeft -= 1;
|
|
38
|
+
} else if (marker === ' ' || line === '') {
|
|
39
|
+
newLine += 1;
|
|
40
|
+
newLeft -= 1;
|
|
41
|
+
oldLeft -= 1;
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (line.startsWith('diff --git ')) {
|
|
47
|
+
current = null;
|
|
48
|
+
} else if (line.startsWith('+++ ')) {
|
|
49
|
+
const path = readPath(line);
|
|
50
|
+
current = path ? { path, lines: [] } : null;
|
|
51
|
+
if (current) {
|
|
52
|
+
files.push(current);
|
|
53
|
+
}
|
|
54
|
+
} else {
|
|
55
|
+
const hunk = HUNK_HEADER.exec(line);
|
|
56
|
+
if (hunk) {
|
|
57
|
+
oldLeft = hunk[1] === undefined ? 1 : Number(hunk[1]);
|
|
58
|
+
newLine = Number(hunk[2]);
|
|
59
|
+
newLeft = hunk[3] === undefined ? 1 : Number(hunk[3]);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return files.filter((file) => file.lines.length > 0);
|
|
65
|
+
}
|
package/src/git.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Everything slop-check asks git: where the repo is, what the base is, what changed.
|
|
2
|
+
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
const BASE_CANDIDATES = ['origin/main', 'origin/master', 'main', 'master'];
|
|
8
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
9
|
+
|
|
10
|
+
// The exact diff format slop-check parses, whatever the user's git config says.
|
|
11
|
+
const DIFF_OPTIONS = [
|
|
12
|
+
'--unified=0', '--no-color', '--no-ext-diff', '--no-textconv', '--find-renames', '--src-prefix=a/', '--dst-prefix=b/',
|
|
13
|
+
];
|
|
14
|
+
const SHALLOW_HINT = 'this is a shallow clone, so the base commit is missing. Use actions/checkout with fetch-depth: 0, or run git fetch --unshallow.';
|
|
15
|
+
|
|
16
|
+
export class SlopCheckError extends Error {}
|
|
17
|
+
|
|
18
|
+
export function git(args, cwd) {
|
|
19
|
+
try {
|
|
20
|
+
return execFileSync('git', ['-c', 'core.quotePath=false', ...args], {
|
|
21
|
+
cwd,
|
|
22
|
+
encoding: 'utf8',
|
|
23
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
24
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
25
|
+
});
|
|
26
|
+
} catch (error) {
|
|
27
|
+
const stderr = String(error.stderr || error.message);
|
|
28
|
+
if (stderr.includes('not a git repository')) {
|
|
29
|
+
throw new SlopCheckError('not inside a git repository');
|
|
30
|
+
}
|
|
31
|
+
throw new SlopCheckError(`git ${args[0]} failed: ${stderr.trim().split('\n')[0]}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function refExists(cwd, ref) {
|
|
36
|
+
try {
|
|
37
|
+
git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);
|
|
38
|
+
return true;
|
|
39
|
+
} catch {
|
|
40
|
+
// rev-parse exits non-zero for a missing ref; that is the answer, not an error.
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function findRepoRoot(cwd) {
|
|
46
|
+
return git(['rev-parse', '--show-toplevel'], cwd).trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function requireCommits(cwd) {
|
|
50
|
+
if (!refExists(cwd, 'HEAD')) {
|
|
51
|
+
throw new SlopCheckError('this repository has no commits yet');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function commitExists(cwd, sha) {
|
|
56
|
+
return refExists(cwd, sha);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// merge-base fails in a shallow clone when history stops before the fork point.
|
|
60
|
+
function mergeBase(cwd, ref) {
|
|
61
|
+
try {
|
|
62
|
+
return git(['merge-base', 'HEAD', ref], cwd).trim();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (git(['rev-parse', '--is-shallow-repository'], cwd).trim() === 'true') {
|
|
65
|
+
throw new SlopCheckError(SHALLOW_HINT);
|
|
66
|
+
}
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function defaultBaseRef(cwd) {
|
|
72
|
+
try {
|
|
73
|
+
const originHead = git(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], cwd).trim();
|
|
74
|
+
return originHead.replace('refs/remotes/', '');
|
|
75
|
+
} catch {
|
|
76
|
+
// No origin/HEAD is normal for local-only repos; fall through to the usual names.
|
|
77
|
+
}
|
|
78
|
+
for (const candidate of BASE_CANDIDATES) {
|
|
79
|
+
if (refExists(cwd, candidate)) {
|
|
80
|
+
return candidate;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Returns { sha, name } for the merge base, or null when HEAD is the base itself.
|
|
87
|
+
export function findBase(cwd, ref) {
|
|
88
|
+
const name = ref || defaultBaseRef(cwd);
|
|
89
|
+
if (!name) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (!refExists(cwd, name)) {
|
|
93
|
+
throw new SlopCheckError(`unknown base "${name}"`);
|
|
94
|
+
}
|
|
95
|
+
const sha = mergeBase(cwd, name);
|
|
96
|
+
const head = git(['rev-parse', 'HEAD'], cwd).trim();
|
|
97
|
+
if (sha === head) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return { sha, name };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function findBaseFromSha(cwd, baseSha) {
|
|
104
|
+
if (!refExists(cwd, baseSha)) {
|
|
105
|
+
throw new SlopCheckError(
|
|
106
|
+
`base commit ${baseSha.slice(0, 7)} is not in this clone. Use actions/checkout with fetch-depth: 0.`,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
const sha = mergeBase(cwd, baseSha);
|
|
110
|
+
return { sha, name: baseSha.slice(0, 7) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function getDiffText(cwd, options) {
|
|
114
|
+
if (options.mode === 'staged') {
|
|
115
|
+
return git(['diff', '--cached', ...DIFF_OPTIONS], cwd);
|
|
116
|
+
}
|
|
117
|
+
return git(['diff', options.base || 'HEAD', ...DIFF_OPTIONS], cwd);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function getCommits(cwd, base) {
|
|
121
|
+
if (!base) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
const output = git(['log', '--no-merges', '--format=%H%x00%B%x1e', `${base}..HEAD`], cwd);
|
|
125
|
+
const commits = [];
|
|
126
|
+
for (const entry of output.split('\x1e')) {
|
|
127
|
+
const [sha, message] = entry.trim().split('\x00');
|
|
128
|
+
if (sha) {
|
|
129
|
+
commits.push({ sha, message: (message || '').trim() });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return commits;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isBinary(buffer) {
|
|
136
|
+
return buffer.subarray(0, 8000).includes(0);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Reads tracked files from disk as if every line were added. `keep` filters paths first.
|
|
140
|
+
export function getAllFiles(cwd, keep) {
|
|
141
|
+
const paths = git(['ls-files', '-z'], cwd).split('\0').filter(Boolean);
|
|
142
|
+
const files = [];
|
|
143
|
+
for (const path of paths) {
|
|
144
|
+
if (!keep(path)) {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const fullPath = join(cwd, path);
|
|
148
|
+
let stats;
|
|
149
|
+
try {
|
|
150
|
+
stats = statSync(fullPath);
|
|
151
|
+
} catch {
|
|
152
|
+
// Tracked but deleted in the working tree: nothing to read.
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (!stats.isFile() || stats.size > MAX_FILE_BYTES) {
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const buffer = readFileSync(fullPath);
|
|
159
|
+
if (isBinary(buffer)) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const lines = buffer.toString('utf8').split('\n').map((text, index) => ({ number: index + 1, text: text.replace(/\r$/, '') }));
|
|
163
|
+
files.push({ path, lines });
|
|
164
|
+
}
|
|
165
|
+
return files;
|
|
166
|
+
}
|
package/src/languages.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Which comment style a file uses, decided by its extension or name.
|
|
2
|
+
|
|
3
|
+
const STYLE_BY_EXTENSION = {
|
|
4
|
+
slash: [
|
|
5
|
+
'js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts', 'java', 'kt', 'kts', 'scala',
|
|
6
|
+
'go', 'rs', 'swift', 'dart', 'c', 'h', 'cc', 'cpp', 'hpp', 'cs', 'php', 'groovy',
|
|
7
|
+
],
|
|
8
|
+
hash: [
|
|
9
|
+
'py', 'rb', 'sh', 'bash', 'zsh', 'yml', 'yaml', 'toml', 'tf', 'r', 'pl', 'ex', 'exs',
|
|
10
|
+
'dockerfile',
|
|
11
|
+
],
|
|
12
|
+
dash: ['sql', 'lua', 'hs'],
|
|
13
|
+
text: ['md', 'mdx', 'txt'],
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function baseName(path) {
|
|
17
|
+
return path.split('/').pop();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function getExtension(path) {
|
|
21
|
+
const name = baseName(path);
|
|
22
|
+
const dot = name.lastIndexOf('.');
|
|
23
|
+
return dot === -1 ? '' : name.slice(dot + 1).toLowerCase();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function getLanguage(path) {
|
|
27
|
+
if (baseName(path) === 'Dockerfile') {
|
|
28
|
+
return { style: 'hash' };
|
|
29
|
+
}
|
|
30
|
+
const extension = getExtension(path);
|
|
31
|
+
for (const style of Object.keys(STYLE_BY_EXTENSION)) {
|
|
32
|
+
if (STYLE_BY_EXTENSION[style].includes(extension)) {
|
|
33
|
+
return { style };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isTestFile(path) {
|
|
40
|
+
const name = baseName(path);
|
|
41
|
+
if (name.includes('.test.') || name.includes('.spec.')) {
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
if (/_test\.(?:go|py)$/.test(name) || /^test_.*\.py$/.test(name) || /_spec\.rb$/.test(name)) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
const folders = path.split('/').slice(0, -1);
|
|
48
|
+
return ['__tests__', 'test', 'tests', 'spec'].some((folder) => folders.includes(folder));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function isExampleFile(path) {
|
|
52
|
+
const parts = baseName(path).toLowerCase().split('.');
|
|
53
|
+
return parts.includes('example') || parts.includes('sample');
|
|
54
|
+
}
|