应用 libcst codemod 并跳过测试文件。

huangapple go评论58阅读模式
英文:

Apply libcst codemod and skip test files

问题

我正在编写一个使用libcst代码修改器(codemod),它继承自VisitorBasedCodemodCommand。它运行得很好,但速度较慢。一个简单的技巧是按照约定跳过所有以test_开头的测试文件。然而,我还没有找到在我的代码修改器中添加这样的逻辑的位置。

我看到了SkipFile异常,但我不知道从哪里触发它。

我该如何忽略我的测试文件?

英文:

I am writing a codemod with libcst which inherits from VisitorBasedCodemodCommand. It works fine but is rather slow. One simple trick would be to skip all test files which start with test_ by convention. However I haven't been able to find a place to add such logic in my codemod.

I saw a SkipFile exception but I don't know from where I could trigger it.

How can I ignore my test files?

答案1

得分: 1

您可以在检测到当前文件无法被代码修改时,随时在codemod中引发SkipFile。由于您事先知道要完全跳过测试文件,因此可以在模块节点访问时立即退出,例如:

import pathlib
import libcst as cst
from libcst.codemod import VisitorBasedCodemodCommand, SkipFile

class SkipTests(VisitorBasedCodemodCommand):
    def visit_Module(self, mod: cst.Module) -> bool | None:
        if pathlib.Path(self.context.filename).name.startswith("test_"):
            raise SkipFile("not touching any tests")
        return True

现在,当您使用codemod调用libcst.tool时,您应该会看到每个跳过的文件的日志行:

$ python -m libcst.tool codemod so.SkipTests .
Calculating full-repo metadata...
Executing codemod...
Codemodding /path/to/example/test_mod.py
Skipped codemodding /path/to/example/test_mod.py: not touching any tests

Finished codemodding 8 files!
 - Transformed 7 files successfully.
 - Skipped 1 files.
 - Failed to codemod 0 files.
 - 0 warnings were generated.
英文:

You can raise SkipFile anywhere in the codemod when you detect that the current file can not be modified by the codemod. Since you know upfront you want to skip the test files completely, you can bail out on module node visit already, for example:

import pathlib
import libcst as cst
from libcst.codemod import VisitorBasedCodemodCommand, SkipFile


class SkipTests(VisitorBasedCodemodCommand):
    def visit_Module(self, mod: cst.Module) -> bool | None:
        if pathlib.Path(self.context.filename).name.startswith("test_"):
            raise SkipFile("not touching any tests")
        return True

Now, when you invoke libcst.tool with the codemod, you should see a log line for each skipped file:

$ python -m libcst.tool codemod so.SkipTests .
Calculating full-repo metadata...
Executing codemod...
Codemodding /path/to/example/test_mod.py
Skipped codemodding /path/to/example/test_mod.py: not touching any tests

Finished codemodding 8 files!
 - Transformed 7 files successfully.
 - Skipped 1 files.
 - Failed to codemod 0 files.
 - 0 warnings were generated.

huangapple
  • 本文由 发表于 2023年6月1日 21:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定