Makefile 的目标可以在 Linux 上完成,但 AFAICS,不能在 Mac OS (10.8.5) 上使用。
是否可以使用此操作系统完成工作?
最佳答案
这似乎在 El Capitan 上为我实现了简单的 bash 完成:
# .bashrc
function _makefile_targets {
local curr_arg;
local targets;
# Find makefile targets available in the current directory
targets=''
if [[ -e "$(pwd)/Makefile" ]]; then
targets=$( \
grep -oE '^[a-zA-Z0-9_-]+:' Makefile \
| sed 's/://' \
| tr '\n' ' ' \
)
fi
# Filter targets based on user input to the bash completion
curr_arg=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -W "${targets[@]}" -- $curr_arg ) );
}
complete -F _makefile_targets make
其工作原理如下:
complete -F [函数名称] [命令名称] -- 这个 bash 内置函数为由 bash 函数 [函数名称] 生成的 [命令名称] 注册一个新的完成。因此,在上面的代码中,如果您在 shell 中输入
<make [TAB][TAB]
,您将触发_makefile_targets()
函数。if [[ -e "$(pwd)/Makefile"]]; then -- 确保当前目录中有 Makefile,否则不要尝试 bash 补全。
grep -oE '^[a-zA-Z0-9_-]+:' Makefile -- 使用目标名称的正则表达式过滤 Makefile 的每一行,例如“test: ”。
-o
表示仅返回行中匹配的部分。例如,给定像“test: build package”这样的 Makefile 目标,只会返回“test:”| sed 's/://' -- 获取 grep 结果,从行尾删除冒号
| tr '\n' ' ' -- 将所有目标平滑到一行,用一个空格分隔
在 bash 补全函数中,complete
会为您设置几个环境变量。 COMP_WORDS
是基于用户输入内容的可用 bash 补全选项列表的数组。 COMP_CWORD
是当前所选单词的索引。
另一个非常神奇的内置compgen
将获取一个空格分隔的字符串列表,并使用当前选定的单词过滤它们。我完全不清楚它是如何工作的。
所以,底线是函数中的最后两行过滤我们的 makefile 目标列表(存储在 $targets
内)并将它们插入数组 COMPREPLY
。 bash 完成读取并显示 COMPREPLY
作为 shell 中的选项。
灵感来源:
关于macos - Mac 上的 Makefile 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33760647/