git pre-commit钩子格式代码 - Intellij / Android Studio [英] git pre-commit hook format code - Intellij/Android Studio

查看:893
本文介绍了git pre-commit钩子格式代码 - Intellij / Android Studio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个要点展示了如何在预提交时使用Eclipse格式化程序自动格式化Java代码。

This gist shows how to auto-format Java code using the Eclipse formatter at pre-commit.

来源: https://gist.github.com/ktoso/708972

代码:

#!/bin/sh
#
# This hook will run the eclipse code formatter before any commit
# to make the source look as it's supposed to look like in the repo.

ECLIPSE_HOME=$HOME/eclipse
STYLE_FILE=$HOME/org.eclipse.jdt.core.prefs
echo "Running pre-commit hook: run-eclipse-formatter---------------------"
echo "Will run eclipse formatter, using: $STYLE_FILE"
echo "Listing folders to run formatter on… "
code_dirs=`find . -maxdepth 3 | grep 'src/'`
for dir in $code_dirs; do
   echo $dir;
done;

echo "Launching eclipse code formatter…    "
exec $ECLIPSE_HOME/eclipse \
                    -nosplash \
                    -application org.eclipse.jdt.core.JavaCodeFormatter \
                    -verbose \
                    -config $STYLE_FILE \
                    $code_dirs

echo "done---------------------------------------------------------------"

我想用IntelliJ和Android Studio实现这一目标。那么脚本会是什么样子?

I'd like to achieve this with IntelliJ and Android Studio. How would the script look like then?

另外我想最好只在更改的文件上运行格式化程序。也许这很有用:

Also I guess it would be best to only run the formatter on changed files. Maybe this is useful:

changedJavaFiles=$(git diff --cached --name-only --diff-filter=ACM | grep '.java$')

ACM代表已添加,已复制,已修改。来源: http://git-scm.com/docs/git-diff

ACM stands for Added, Copied, Modified. Source: http://git-scm.com/docs/git-diff

如果有任何不清楚的地方请评论。

Please comment if anything is unclear.

更新

我的设置是Windows 10,我想使用命令行工具MINGW32(Git Bash)。 Git版本是1.9.5 msysgit.1

My setup is Windows 10 and I'd like to use the command line tool MINGW32(Git Bash). Git version is 1.9.5 msysgit.1

推荐答案

你可以使用 IntelliJ命令行源代码格式化程序,自版本2016.3以来在IntelliJ中可用。例如(对于Git Bash):

You can use the IntelliJ command-line source code formatter available in IntelliJ since version 2016.3. For example (for Git Bash):

CHANGED_JAVA_SRC_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '.java$')
$INTELLIJ_DIR/bin/format $CHANGED_JAVA_SRC_FILES



<虽然Android Studio基于IntelliJ,但在IDE打开时似乎不支持这一点,请参阅下面的评论。

Although Android Studio is based on IntelliJ, it seems not to support this when the IDE is open, see comment below.

更高级的预提交钩子示例是可在 git-hooks-code-autoformat项目中找到GitHub

A more advanced pre-commit hook example is available in the git-hooks-code-autoformat project in GitHub.

这篇关于git pre-commit钩子格式代码 - Intellij / Android Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆