我在GitHub上的开放小说中保存了一个单词列表,我希望自动设置第一行,即字典中的单词数。我的首选是编写一个pre-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 );
}
}
};
然而,由于文件已经被暂存,我遇到了这个错误:
错误:您对以下文件的本地更改将被检出覆盖:text/words.dic。请在切换分支之前提交您的更改或将它们隐藏起来。中止操作。
也许把它作为一个 post-commit 钩子,并在下一次提交时进行更改会更好?或者完全采取不同的方法?总的问题是:如果您想在提交过程中处理和更改文件内容,正确的方法是什么?