如何用Make递归获取目录及子目录下的指定测试文件?
解决Makefile递归匹配测试文件的问题
方法1:启用bash的globstar特性
Make默认使用/bin/sh,而bash的globstar选项能让**匹配任意层级的子目录(包括当前目录本身)。修改Makefile如下:
# 指定用bash作为shell,开启globstar特性 SHELL := /bin/bash .SHELLFLAGS := -O globstar -c TESTS = dir_1/**/test_*.py dir_2/**/test_*.py check_tests: set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;
这样dir_1/**/test_*.py会匹配dir_1下所有层级(包括dir_1根目录)的test_*.py文件,dir_2同理,一次就能覆盖所有符合条件的文件。
方法2:用find命令生成文件列表
如果不想依赖bash特性,用find命令是更通用的跨环境方案:
# 递归查找指定目录下所有符合命名规则的测试文件 TESTS := $(shell find dir_1 dir_2 -name 'test_*.py') check_tests: set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;
find dir_1 dir_2 -name 'test_*.py'会自动遍历两个目录的所有子层级,把所有匹配的文件路径收集起来赋值给TESTS,兼容性拉满。
额外提示
如果需要排除某些特定子目录,给find加过滤参数就行,比如:
TESTS := $(shell find dir_1 dir_2 -name 'test_*.py' -not -path '*/temp_dir/*')
内容的提问来源于stack exchange,提问作者Ibolit
相关产品推荐
相关产品推荐

