英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论