Git が一部のファイルの変更を元に戻す [重複] 質問する

Git が一部のファイルの変更を元に戻す [重複] 質問する

コーディング中に、何が起こっているかを追跡するために、いくつかのファイルに print ステートメントを追加しました。

作業が完了したら、一部のファイルの変更を元に戻し、実際に作業したファイルをコミットすることは可能ですか?

たとえば、ファイル に print を追加したAが、ファイル を変更したとしますBBをコミットし、 をA古い状態に戻したいとします。

ベストアンサー1

ファイル A への変更内容に応じて、これを行う基本的な方法は 3 つあります。変更内容をまだインデックスに追加していない、またはコミットしていない場合は、チェックアウト コマンドを使用するだけです。これにより、作業コピーの状態がリポジトリと一致するように変更されます。

git checkout A

すでにインデックスに追加している場合は、リセットを使用します。

git reset A

コミットした場合は、revert コマンドを使用します。

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

一方、コミットしたが、そのコミットに、元に戻したくないファイルが多数含まれていた場合、上記の方法では、多数の「リセット B」コマンドが必要になる可能性があります。この場合、次の方法を使用するとよいでしょう。

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

もう 1 つの方法では、rebase -i コマンドを使用する必要があります。これは、編集するコミットが複数ある場合に便利です。

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue

おすすめ記事