git 使用高级技巧(待补充)

git 问题列表

  1. 在提交前删除尾随空格

1 在提交前删除尾随空格

问题描述:
修改完代码,通过git diff命令查看差异时,发现一些文件有多余的空格,在git上显示特别丑,在提交前需要将这些空格去掉。

如果多余的空格有很多,手动清除工作量很大时,可选择如下几种方式:

方法1: 用第三方工具

工具 使用
linux/scripts/cleanfile (linux 源码的scripts目录,perl脚本) cleanfile file
astyle 、clang-format 等 用法可自行搜索

方法2: git

1 简单但不健全的解决方案

修复以当前目录为根的子树(但如果索引不为空,则重置索引)

(export GIT_EDITOR=: && git -c apply.whitespace=fix add -ue .) && git checkout . && git reset

修复并保留索引(但如果树是脏的或索引为空则失败)

git commit -m TEMP && git rebase --whitespace=fix HEAD~ && git reset --soft HEAD~

修复树和索引(但如果索引不为空,则重置索引)

git add -u :/ && git commit -m TEMP && git rebase --whitespace=fix HEAD~ && git reset HEAD~

2 使用钩子

补充一下git hook的知识

Git Hook纯属于本地的操作,不会被push到远程仓库上。

git 提供的hooks及其执行的时间如下图所示:

所以我们可以修改pre-commit脚本:

 cd .git/hooks/
 mv pre-commit.sample pre-commit  # git提供了10个hook用例,只要把.sample的后缀去掉,那么这个hook脚本就能生效。

修改pre-commit,退出时chmod a+x 给予权限。

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   against=HEAD
else
   # Initial commit: diff against an empty tree object
   against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
   # Fix them!
   sed -i 's/[[:space:]]*$//' "$FILE"
   git add "$FILE"
done
exit

这样在git commit时会自动触发此脚本执行,注意有些文件(如.md文件)不希望去掉空格,可选择不运行pre-commit钩子:

- 暂时: git commit --no-verify
- 永久性: cd .git/hooks/; chmod -x pre-commit

参考:

  1. 在提交之前让git自动删除尾随空格
  2. https://www.r2coding.com/#/
  3. √了没?—— 介绍Git Hooks
posted @ 2022-07-06 23:49  sureZ_ok  阅读(260)  评论(0编辑  收藏  举报