-
-
Notifications
You must be signed in to change notification settings - Fork 153
/
checkLineAlignment.js
307 lines (269 loc) · 8.19 KB
/
checkLineAlignment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import {
set,
} from 'lodash';
import iterateJsdoc from '../iterateJsdoc';
const applicableTags = ['param', 'arg', 'argument', 'property', 'prop', 'returns', 'return'];
/**
* Aux method until we consider the dev envs support `String.prototype.matchAll` (Node 12+).
*
* @param {string} string String that will be checked.
* @param {RegExp} regexp Regular expression to run.
* @param {Function} callback Function to be called each iteration.
* @param {int} limit Limit of matches that we want to exec.
*
* @todo [engine:node@>=12]: Remove function and use `String.prototype.matchAll` instead.
*/
const matchAll = (string, regexp, callback, limit) => {
let result;
let index = 0;
while ((result = regexp.exec(string)) && index <= limit - 1) {
// eslint-disable-next-line promise/prefer-await-to-callbacks
callback(result, index++);
}
};
/**
* Get the full description from a line.
*
* @param {string} lineString The line string.
*
* @returns {string} The full description.
*/
const getFullDescription = (lineString) => {
return /\S+\s+(?:{{.*?}}|{.*?})\s+\S+\s+(.*)/.exec(lineString)[1];
};
/**
* Get the expected positions for each part.
*
* @param {int[]} partsMaxLength Max length of each part.
* @param {int} indentLevel JSDoc indent level.
*
* @returns {int[]} Expected position for each part.
*/
const getExpectedPositions = (partsMaxLength, indentLevel) => {
// eslint-disable-next-line unicorn/no-reduce
return partsMaxLength.reduce(
(acc, cur, index) => {
return [...acc, cur + acc[index] + 1];
},
[indentLevel],
);
};
/**
* Check is not aligned.
*
* @param {int[]} expectedPositions Expected position for each part.
* @param {Array[]} partsMatrix Parts matrix.
*
* @returns {boolean}
*/
const isNotAligned = (expectedPositions, partsMatrix) => {
return partsMatrix.some((line) => {
return line.some(
({position}, partIndex) => {
return position !== expectedPositions[partIndex];
},
);
});
};
/**
* Fix function creator for the report. It creates a function which fix
* the JSDoc with the correct alignment.
*
* @param {object} comment Comment node.
* @param {int[]} expectedPositions Array with the expected positions.
* @param {Array[]} partsMatrix Parts matrix.
* @param {RegExp} lineRegExp Line regular expression.
* @param {string} tagIndentation Tag indentation.
*
* @returns {Function} Function which fixes the JSDoc alignment.
*/
const createFixer = (comment, expectedPositions, partsMatrix, lineRegExp, tagIndentation) => {
return (fixer) => {
let lineIndex = 0;
// Replace every line with the correct spacings.
const fixed = comment.value.replace(lineRegExp, () => {
// eslint-disable-next-line unicorn/no-reduce
return partsMatrix[lineIndex++].reduce(
(acc, {string}, index) => {
const spacings = ' '.repeat(expectedPositions[index] - acc.length);
return acc + (index === 0 ? tagIndentation : spacings) + string;
},
'',
);
});
return fixer.replaceText(comment, '/*' + fixed + '*/');
};
};
/**
* Check comment per tag.
*
* @param {object} comment Comment node.
* @param {string} tag Tag string.
* @param {string} tagIndentation Tag indentation.
* @param {Function} report Report function.
*/
const checkAlignedPerTag = (comment, tag, tagIndentation, report) => {
const lineRegExp = new RegExp(`.*@${tag}[\\s].*`, 'gm');
const lines = comment.value.match(lineRegExp);
if (!lines) {
return;
}
/**
* A matrix containing the current position and the string of each part for each line.
* 0 - Asterisk.
* 1 - Tag.
* 2 - Type.
* 3 - Variable name.
* 4 - Description (Optional).
*/
const partsMatrix = [];
/**
* The max length of each part, comparing all the lines.
*/
const partsMaxLength = [];
// Loop (lines x parts) to populate partsMatrix and partsMaxLength.
lines.forEach((lineString, lineIndex) => {
// All line parts until the first word of the description (if description exists).
matchAll(
lineString,
/{{.*?}}|{.*?}|\S+/g,
({0: match, index: position}, partIndex) => {
set(partsMatrix, [lineIndex, partIndex], {
position,
string: partIndex === 4 ? getFullDescription(lineString) : match,
});
const partLength = match.length;
const maxLength = partsMaxLength[partIndex];
partsMaxLength[partIndex] = maxLength > partLength ? maxLength : partLength;
},
5,
);
});
const expectedPositions = getExpectedPositions(partsMaxLength, tagIndentation.length);
if (isNotAligned(expectedPositions, partsMatrix)) {
report(
'Expected JSDoc block lines to be aligned.',
createFixer(
comment,
expectedPositions,
partsMatrix,
lineRegExp,
tagIndentation,
),
);
}
};
const checkNotAlignedPerTag = (utils, tag) => {
/*
start +
delimiter +
postDelimiter +
tag +
postTag +
type +
postType +
name +
postName +
description +
end
*/
let spacerProps;
let contentProps;
const isReturnTag = ['return', 'returns'].includes(tag.tag);
if (isReturnTag) {
spacerProps = ['postDelimiter', 'postTag', 'postType'];
contentProps = ['tag', 'type', 'description'];
} else {
spacerProps = ['postDelimiter', 'postTag', 'postType', 'postName'];
contentProps = ['tag', 'type', 'name', 'description'];
}
const {tokens} = tag.source[0];
const followedBySpace = (idx, callbck) => {
const nextIndex = idx + 1;
return spacerProps.slice(nextIndex).some((spacerProp, innerIdx) => {
const contentProp = contentProps[nextIndex + innerIdx];
const spacePropVal = tokens[spacerProp];
const ret = spacePropVal;
if (callbck) {
callbck(!ret, contentProp);
}
return ret;
});
};
// If checking alignment on multiple lines, need to check other `source`
// items
// Go through `post*` spacing properties and exit to indicate problem if
// extra spacing detected
const ok = !spacerProps.some((spacerProp, idx) => {
const contentProp = contentProps[idx];
const contentPropVal = tokens[contentProp];
const spacerPropVal = tokens[spacerProp];
// There will be extra alignment if...
// 1. There is extra whitespace within a single spacer segment OR
return spacerPropVal.length > 1 ||
// 2. There is a (single) space, no immediate content, and yet another
// space is found subsequently (not separated by intervening content)
spacerPropVal && !contentPropVal && followedBySpace(idx);
});
if (ok) {
return;
}
const fix = () => {
spacerProps.forEach((spacerProp, idx) => {
const contentProp = contentProps[idx];
const contentPropVal = tokens[contentProp];
if (contentPropVal) {
tokens[spacerProp] = ' ';
followedBySpace(idx, (hasSpace, contentPrp) => {
if (hasSpace) {
tokens[contentPrp] = '';
}
});
} else {
tokens[spacerProp] = '';
}
});
utils.setTag(tag, tokens);
};
utils.reportJSDoc('Expected JSDoc block lines to not be aligned.', tag, fix, true);
};
export default iterateJsdoc(({
jsdocNode,
report,
context,
indent,
utils,
}) => {
if (context.options[0] === 'always') {
// Skip if it contains only a single line.
if (!jsdocNode.value.includes('\n')) {
return;
}
// `indent` is whitespace from line 1 (`/**`), so slice and account for "/".
const tagIndentation = indent + ' ';
applicableTags.forEach((tag) => {
checkAlignedPerTag(jsdocNode, tag, tagIndentation, report);
});
return;
}
const foundTags = utils.getPresentTags(applicableTags);
foundTags.forEach((tag) => {
checkNotAlignedPerTag(utils, tag);
});
}, {
iterateAllJsdocs: true,
meta: {
docs: {
description: 'Reports invalid alignment of JSDoc block lines.',
url: 'https://github.com/gajus/eslint-plugin-jsdoc#eslint-plugin-jsdoc-rules-check-line-alignment',
},
fixable: 'whitespace',
schema: [
{
enum: ['always', 'never'],
type: 'string',
},
],
type: 'layout',
},
});