如何使用预提交钩子使用IntelliJ格式来格式化代码?

时间:2019-09-19 08:08:26

标签: intellij-idea pre-commit-hook

我正在尝试配置预提交挂钩,以使用IntelliJ代码格式化程序自动格式化代码。

实际上,IntelliJ允许使用IDE外部的命令行运行格式化程序:https://www.jetbrains.com/help/idea/command-line-formatter.html

所以我创建了我的预提交文件:

 git diff --name-only --cached --diff-filter=ACM | xargs -L 1 format

因此,要在每个暂存的文件上运行format。问题是当我尝试执行此命令时,IDE会显示错误消息:

Only one instance of IDEA can be run at a time.

消息:一次只能运行一个IDEA实例。

您是否有一个想法,即使在未打开IDE的情况下也可以在IDE外部运行format

1 个答案:

答案 0 :(得分:0)

您可以自动化所需的说明以允许运行单独的实例:

cat >/tmp/format.properties <<EOF
idea.config.path=\${user.home}/.IntelliJIdea/format/config
idea.system.path=\${user.home}/.IntelliJIdea/format/system
EOF

git diff --name-only --cached --diff-filter=ACM | xargs env IDEA_PROPERTIES=/tmp/format.properties format

/tmp/format.properties:每次IntelliJ升级后idea.properties的位置都会更改。

就我而言,我还从format.sh命令中检索了idea的位置:

format_command=$(grep idea.sh $(which idea)|sed "s,idea.sh,format.sh,")
eval "env IDEA_PROPERTIES=/tmp/format.properties $format_command $(git diff --name-only --cached --diff-filter=ACM|xargs)"
相关问题