【发布时间】:2019-01-15 04:08:46
【问题描述】:
我正在尝试创建一个 tslint 规则,该规则将阻止我们的测试人员提交包含 .only 的夹具/测试。
因此,如果他们尝试提交包含 fixture.only 或 test.only 的文件,则提交将失败(我在提交时使用 Husky + git hooks 来执行 tslint 命令)。
我想出了如何创建规则(意味着提交失败),但最好也自动删除此代码(修复提交)。
有办法吗? 我找不到如何从节点中间删除文本,只能从头开始。
这是JS代码
import * as ts from 'typescript';
import * as Lint from 'tslint';
import { IOptions } from 'tslint';
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Something bad happened - you're not
following the rules";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new TestcafeNoOnly(sourceFile,
this.getOptions()));
}
}
// This worker visits every source file
class TestcafeNoOnly extends Lint.RuleWalker {
private readonly FAILURE_STRING = 'Testcafe no only';
private readonly PROHIBITED = ['fixture.only', 'test.only'];
private readonly REGEX = new RegExp('^(' + this.PROHIBITED.join('|') + ')$');
constructor(sourceFile: ts.SourceFile, options: IOptions) {
super(sourceFile, options);
}
public visitCallExpression(node: ts.CallExpression) {
const match =
node.expression.getText().replace(/(\r\n\t|\n|\r\t|\s)/gm, '').trim().match(this.REGEX);
if (match) {
const fix = Lint.Replacement.deleteText(node.getStart(), 5);
this.addFailureAt(node.getStart(), match[0].length, this.FAILURE_STRING, fix);
}
super.visitCallExpression(node);
}
}
【问题讨论】:
标签: typescript tslint