排除一些被跟踪的文件被永久提交

Exclude some tracked files from being committed permanently

我正在做一个项目,我编辑了一些已被 Git跟踪 的文件。假设编辑的跟踪文件是:

files1.py
file2.py
file3.py

所有这些文件都存在于远程存储库中。但是,我编辑了其中一个文件(说 file2.py)以仅与我的机器兼容。所以在commit的时候,我不希望这个文件被commit(我希望这个文件的远程版本不变)。
我知道有这样的命令可以做到这一点:
来自这个 link

git add
git reset --file2.py

或从这个link:
git update-index --assume-unchanged "file2.py"

然而,我想要的是,如果没有 运行 上面的命令每次都将在以后的每次提交中忽略此文件。
有没有类似.gitignore的方法,让这个文件每次都自动忽略不被提交,始终保持远程版本不变?

你可以使用 pre-commit hook:

做你想做的事

pre-commit
This hook is invoked by git-commit, and can be bypassed with the --no-verify option. It takes no parameters, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit.

下面的简单代码在提交之前立即取消对 file2.py 的任何更改,并拒绝创建任何新的空提交——也就是说,如果唯一更改的文件是 file2.py.

#! /bin/bash

if ! git diff-index --quiet --cached HEAD -- file2.py; then
  echo Discarding file2.py changes from the index
  git reset HEAD -- file2.py

  if git diff-index --quiet --cached HEAD; then
    echo Aborting empty commit 1>&2
    exit 1
  fi
fi

既然已经回答了学术问题,我建议使用不同的方法,因为挂钩有意将控制 file2.py 的两种不同版本的版本的工作转嫁给人类用户。如果您想进行手动版本控制,为什么要使用 git?

相反,让 git 通过将您的更改放入单独的分支来完成它擅长的工作

git checkout --no-track -b feature/singrium origin/master

随着 master 的变化(你赶上 运行 git fetch

git checkout feature/singrium
git rebase origin/master

或者您定期合并来自 master 的更改。

git checkout feature/singrium
git merge origin/master

git rebasegit merge之间的区别在于它们各自产生的历史。如果您对 file2.py 的更改很小并且只局限于少量提交,则 rebase 方法会将这些提交作为补丁放在最新的 master 之上。如果你的历史比较笨重,合并可能会更容易,至少在短期内是这样。