【问题标题】:Removing text from the middle of a string when fixing a tslint rule修复 tslint 规则时从字符串中间删除文本
【发布时间】:2019-01-15 04:08:46
【问题描述】:

我正在尝试创建一个 tslint 规则,该规则将阻止我们的测试人员提交包含 .only 的夹具/测试。

因此,如果他们尝试提交包含 fixture.onlytest.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


    【解决方案1】:

    此规则已作为 mocha-avoid-only 存在于 tslint-microsoft-contrib 中。万岁!

    您正在调用node.getStart(),其中nodeCallExpression,所以您得到的是describe.only(...) 的开头。

    • node.expressiondescribe
    • node.nameonly

    您想从node.expression 的末尾删除(所以它包括.,即使那里有空格)node.name 的末尾。比如:

    Lint.Replacement.deleteFromTo(node.name.end, node.expression.end);
    

    【讨论】:

    • 感谢您的回答,但是...... mocha tslint 规则对我没有帮助,因为我正在寻找不同的语法(需要夹具和测试。不描述)并且我不想删除从头开始,因为它可能会链接其他功能:test.only(“my test”).before().blabla
    【解决方案2】:

    解决方案可能是将您当前的 tslint.json 复制到(例如)tslint-no-only.json

    tslint-no-only.json 中修改rules 部分:

    "rules": {
            ...
            "ban": [
                true,
                "eval",
                {
                    "name": ["test", "only"],
                    "message": "do not commit with test.only"
                },
                {
                    "name": ["fixture", "only"],
                    "message": "do not commit with fixture.only"
                }
            ]
        }
    

    只需在 Husky 配置中引用这个新的 tslint 文件即可。

    【讨论】:

    • 我不明白为什么在尝试为当前规则创建新规则时需要复制 tslint
    • @doron,是的,您是对的,如果您在启动 TestCafe 之前不使用tsc 作为预检查,则无需复制。
    猜你喜欢
    • 2020-03-01
    • 2019-03-26
    • 2016-08-10
    • 2022-01-16
    • 1970-01-01
    • 2017-05-17
    • 2019-04-19
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多