eslint-plugin-ft-flow
Version:
Flowtype linting rules for ESLint by flow-typed
70 lines (59 loc) • 1.77 kB
Flow
const looksLikeFlowFileAnnotation = (comment) => /^\s*.*@(?:no)?flow(.|\s)*/u.test(comment);
const schema = [
{
enum: ['always', 'always-windows', 'never'],
type: 'string',
},
];
const create = (context) => {
const mode = context.options[0];
const never = mode === 'never';
const newline = mode === 'always-windows' ? '\r\n' : '\n';
return {
Program(node) {
const sourceCode = context.getSourceCode();
const potentialFlowFileAnnotation = sourceCode.getAllComments().find(
(comment) => looksLikeFlowFileAnnotation(comment.value),
);
if (potentialFlowFileAnnotation) {
const { line } = potentialFlowFileAnnotation.loc.end;
const nextLineIsEmpty = sourceCode.lines[line] === '';
if (!never && !nextLineIsEmpty) {
context.report({
fix: (fixer) => fixer.insertTextAfter(
potentialFlowFileAnnotation,
newline,
),
message: 'Expected newline after flow annotation',
node,
});
}
if (never && nextLineIsEmpty) {
context.report({
fix: (fixer) => {
const lineBreak = sourceCode.text[potentialFlowFileAnnotation.range[1]];
return fixer.replaceTextRange(
[
potentialFlowFileAnnotation.range[1],
potentialFlowFileAnnotation.range[1] + (
lineBreak === '\r' ? 2 : 1
),
],
'',
);
},
message: 'Expected no newline after flow annotation',
node,
});
}
}
},
};
};
export default {
create,
meta: {
fixable: 'code',
schema,
},
};