2013-05-30 8 views
16

私が持っているものの一つopen novel in GitHublist of wordsです。私は自動的に最初の行、つまり辞書の単語の数を設定したいと思います。私の最初の選択肢は、ファイルを読み込み、単語をカウントし、最初の行を書き換えて、それを再び書き戻す、事前コミットフックを書くことです。ここでは、コードgit commit中にファイルの内容を変更できますか?

PRE_COMMIT { 
    my ($git) = @_; 
    my $branch = $git->command(qw/rev-parse --abbrev-ref HEAD/); 
    say "Pre-commit hook in $branch"; 
    if ($branch =~ /master/) { 
    my $changed = $git->command(qw/show --name-status/); 
    my @changed_files = ($changed =~ /\s\w\s+(\S+)/g); 
    if ($words ~~ @changed_files) { 
     my @words_content = read_file($words); 
     say "I have $#words_content words"; 
     $words_content[0] = "$#words_content\n"; 
     write_file($words, @words_content); 
    } 
    } 
}; 

は、ファイルがすでに上演されているので、私はこのエラー

error: Your local changes to the following files would be overwritten by checkout: text/words.dic Please, commit your changes or stash them before you can switch branches. Aborting

が、コミット後のフックとしてそれを行うと、それがために変更した方が良いかもしれません得るのです次のコミット?あるいは、まったく別の何かをする?一般的な質問は、コミット中にファイルの内容を処理して変更したい場合は、それを行う正しい方法は何ですか?

答えて

15

実際にコミットされたのはgit commitです。プリコミット・フックが終了すると、インデックスには何かが入ります。これは、あなたがgit addである限り、のファイルをプリコミットフックで変更することを意味します。 (お使いの場合には適用されません)

$ git commit -m dink 
updated zorg to 3 
[master 76eeefc] dink 
1 file changed, 1 insertion(+), 1 deletion(-) 

しかし、マイナーな欠陥の点に注意してください。

#!/bin/sh 
# 
# An example hook script to verify what is about to be committed. 
# [snipped much of what used to be in it, added this -- 
# make sure you take out the exec of git diff-index!] 

num=$(cat zorg) 
num=$(expr 0$num + 1) 
echo $num > zorg 
git add zorg 
echo "updated zorg to $num" 
exit 0 

、その後:ここ

は私の例.sampleから変更されたフックを、事前にコミットします:

$ git commit 
git commit 
updated zorg to 4 
# On branch master 
# Untracked files: 
[snip] 
nothing added to commit but untracked files present (use "git add" to track) 
$ git commit 
updated zorg to 5 
# Please enter the commit message for your changes. Lines starting 
[snip - I quit editor without changing anything] 
Aborting commit due to empty commit message. 
$ git commit 
updated zorg to 6 
# Please enter the commit message for your changes. Lines starting 

事前コミットフックの更新とgit addのため、基本的に、ファイルが電子をインクリメントし続けます私は実際にコミットをしていませんが、ここでven。

+0

だから、基本的にそれはですハックの別の子供、そう?私のやり方では、ファイルは変更されますが、次のファイルにコミットされません。 – jjmerelo

+1

はい。いずれのアプローチでも私が本当に満足しているとは思えません。私はむしろ必要に応じて物事を更新するためのMakefileのようなものを用意しておきたい。しかし、それは動作するはずです。 – torek

+0

ポストコミットを行う方が正しいでしょうか? – jjmerelo

9

それはあなたが「フック」を実行することができ判明 - 彼らは実際には別のmecanismによって処理される - ファイル(git add時)ステージングとき:

https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#_keyword_expansion

を( "にビットをスクロールダウン汚れ/クリーン」の図)

ここでは、私が理解するものである:

  1. 編集.gitattributes、辞書更新トリガするファイルに対するルールの作成:「updateDict」フィルタが汚れ(gitのチェックアウト)とクリーンに何Gitのを教えてくれ、その後

    novel.txt updateDict

  2. を(gitの追加):

    $ git config --global filter.updateDict.clean countWords.script

    $ git config --global filter.updateDict.smudge cat

関連する問題