code

Git 후크가 커밋에 파일을 자동으로 추가 할 수 있습니까?

codestyles 2020. 12. 24. 23:45
반응형

Git 후크가 커밋에 파일을 자동으로 추가 할 수 있습니까?


해당 커밋에서 수정 된 파일에 따라 Git의 사전 또는 사후 커밋 후크를 사용하여 자동 생성 된 파일을 동일한 커밋에 추가하고 싶습니다. 어떻게해야합니까?

나는 이것을 사전 커밋 후크로 시도했지만 운이 없습니다.

#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
  echo "Creating files"
  exec bundle exec create_my_files
  exec git add my_files
  exec git commit --amend -C HEAD
fi

이렇게하면 저장소에 성공적으로 추가되지만 커밋에는 추가되지 않습니다. 또한 커밋 전 검사와 함께 커밋 후 후크에서 마지막 두 개의 exec 줄을 사용해 보았지만 좋지 않았습니다.


git add도 사전 커밋에서 작동하지 않았기 때문에 .commit 파일을 사용하고 프로세스를 사전 및 사후 커밋으로 분할하는 mark의 아이디어를 따랐습니다.

이해하기 쉬운 코드가 있습니다.

사전 커밋에서 :

  • 파일 .commit 등을 터치합니다. (이것을 .gitignore에 추가하십시오)
#!/bin/sh 
echo 
touch .commit 
exit

커밋 후 :

.commit이 있으면 커밋이 방금 발생했지만 사후 커밋이 아직 실행되지 않았 음을 알 수 있습니다. 따라서 여기에서 코드 생성을 수행 할 수 있습니다. 또한 .commit을 테스트하고 존재하는지 테스트하십시오.

  • 파일 추가
  • commit --amend -C HEAD --no-verify (루핑 방지)
  • .commit 파일 삭제
#!/bin/sh
echo
if [ -a .commit ]
    then
    rm .commit
    git add yourfile
    git commit --amend -C HEAD --no-verify
fi
exit

이것이 bash 지식이 거의없는 사람들이 mark의 아이디어를 쉽게 따를 수 있기를 바랍니다.


사전 커밋 후크를 사용하여 원하는 작업을 수행 할 수 있습니다. heroku 배포에 대해서도 비슷한 작업을 수행합니다 (coffeescript를 javascript로 컴파일). 스크립트가 작동하지 않는 이유는 exec명령을 부적절하게 사용했기 때문 입니다.

로부터 man 페이지 :

exec 내장은 현재 실행중인 쉘 프로세스 이미지를 새 명령으로 대체하는 데 사용됩니다. 성공적으로 완료되면 exec는 반환되지 않습니다. exec는 파이프 라인 내에서 사용할 수 없습니다.

첫 번째 exec 명령 만 실행 중입니다. 그 후 스크립트는 기본적으로 종료됩니다.

다음과 같이 시도해보십시오 (사전 커밋 후크로).

#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
  echo "Creating files"
  bundle exec create_my_files
  git add my_files
fi

사전 및 사후 커밋 스크립트의 조합을 사용할 수 있습니다.

사전 커밋에서 :

  • 파일 .commit 등을 터치합니다. (이것을 .gitignore에 추가하십시오)

커밋 후 :

.commit이 있으면 커밋이 방금 발생했지만 사후 커밋이 아직 실행되지 않았 음을 알 수 있습니다. 따라서 여기에서 코드 생성을 수행 할 수 있습니다. 또한 .commit을 테스트하고 존재하는지 테스트하십시오.

  • 파일 추가
  • commit --ammend -C HEAD --no-verify (루핑 방지)
  • .commit 파일 삭제

이것은 메타 스토어에서 생성 된 저장소에 .metadata 파일을 저장하는 데 사용하는 대략적인 프로세스입니다.

누구든지 더 나은 방법을 알고 있다면 나는 모두 귀이지만 지금은 작동하는 것 같습니다.


#!/bin/sh
#
#  .git/hooks/pre-commit
#

git add file.xyz

이것은 나를 위해 잘 작동했습니다. 현재 커밋의 일부가됩니다.

git version 1.7.12.4 (Apple Git-37)


다음을 사용할 수 있습니다 update-index.

git update-index --add my_files


If the files are automatically generated, and they can be generated anywhere (implicit in your desire to build them in the Git pre-commit hook) then you shouldn't be putting them under source control in the first place. You should only control source files -- generated files should be generated as part of the build scripts.

The only reason to put a generated file under source control is when it requires unique/privileged resources to generate (such as a licensed program) or it requires a significant amount of time to generate.

Added

From http://git-scm.com/docs/githooks :

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

The default pre-commit hook, when enabled, catches introduction of lines with trailing whitespaces and aborts the commit when such a line is found.

All the git commit hooks are invoked with the environment variable GIT_EDITOR=: if the command will not bring up an editor to modify the commit message.

The intent of the pre-commit hook is to be a pass-fail check on the state of the workspace and the contents of the commit, prior to making the commit. Attempting to change the contents of the commit won't work.

My recommendation would be add two steps to your build scripts: (1) a step that will build all of the out-of-date files that needs to be generated (and adds them to the workspace), and (2) a step that will check to ensure that all of the generated files are up-to-date, and return a non-zero status code. Your Git pre-commit hook should run the second step. Your developers should be trained to run the first step as necessary.


How about writing a post-commit script instead which generates your files, and then have that do (something along the lines of) git add my_files; git commit --amend.


I had the same need and this approach worked pretty well for me:

#!/bin/sh
files='git diff --cached --name-only'
re="<files of importance>"
if [[ $files =~ $re ]]
then
   echo "Creating files"
   create_my_files && git add my_files
fi

where "create_my_files" should be executable, for example if it is a python file you could execute it as "python create_my_files && git add my_files"

and is true you don't need a pre-commit to commit again (that would create a infinite nasty loop :p)


Yes, you can add generated files automatically on the commit using git hooks! But it requires a tricky script.

Here you can find the problem solved. There, it is updating the file version on every commit, adding a new modified file and amending the commit as you need it to. It is fully working: https://github.com/evandrocoan/.versioning

Then you just replace the 'Version File Replacement' algorithm on the file 'updateVersion.sh', by your algorithm. Maybe you need to change a few things like, remove the branch limitation, because there, the script only runs if you are on the 'develop' branch.

Also, it will only change the specified file, if is staged. If the file is not staged, then it will do nothing than the normal/usual commit. More precisely, it print out what it is doing on every step.

I am going to explain, that trick. It is quite tricky. On the prepare-commit-msg-hook, it detects whether the desired file is being staged and committed. After that, it creates a flag file, and stops the prepare-commit-msg-hook. Later on the post-commit-hook, it checks whether the flag file exists. If yes, it amends the files on the commit.

Attention, it would create a infinity loop because it would call again the prepare-commit-msg-hook (as we are amending). But it does not happen because of the flag file. When the prepare-commit-msg-hook runs and find the flag file, it "knows" what is happening. Then is just deletes the flag file and do not create it again. Doing it, it will block the post-commit-hook from amending again the commits, allowing the commit to finish for good.


I was facing same problem in pre-commit hook also. I was modifying one file and committing but it was taking previous file not updated file so by adding git command(as below) in pre-commit hook, it solved.

git add $file

note: $file is your file to be added.

Thanks,

ReferenceURL : https://stackoverflow.com/questions/3284292/can-a-git-hook-automatically-add-files-to-the-commit

반응형