テキストファイルとバイナリファイルのテスト
このステップでは、Git がテキストファイルとバイナリファイルの変更をどのように扱うかを見ていきます。これにより、Git の差分表示機能が主にテキストを対象として設計されている理由が明らかになります。
まず、プロジェクトディレクトリにいることを確認しましょう。
cd ~/project/my-time-machine
既に message.txt
(テキストファイル)と binary_file
があります。message.txt
にさらに変更を加えましょう。
echo "Another line for the future" >> message.txt
次に、両方のファイルをステージングエリアに追加してコミットしましょう。まず、ファイルを追加します。
git add message.txt binary_file
状態を確認して、両方のファイルがステージングされていることを確認しましょう。
git status
「Changes to be committed」の下に両方のファイルがリストされているはずです。
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: message.txt
new file: binary_file
次に、これらの変更をコミットしましょう。
git commit -m "Add binary file and update message"
コミットが確認される出力が表示され、両方のファイルの変更が含まれます。
[master ...] Add binary file and update message
2 files changed, 2 insertions(+)
create mode 100644 binary_file
次に、binary_file
に小さな変更を加えましょう。1 バイトを追加することができます。
echo -n "a" >> binary_file
-n
フラグは、echo
が改行文字を追加しないようにします。
再度状態を確認しましょう。
git status
Git は、binary_file
が変更されたことを表示します。
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: binary_file
no changes added to commit but untracked files present (use "git add" to track)
次に、git diff
を使って差分を見てみましょう。
git diff
行単位の変更を表示する代わりに、Git はバイナリファイルが異なることを示すでしょう。
warning: LF will be replaced by CRLF in binary_file.
The file has no newline at the end of the file.
diff --git a/binary_file b/binary_file
index ... ...
Binary files a/binary_file and b/binary_file differ
この出力は、Git がバイナリファイル内の詳細な変更を表示しようとしないことを明確に示しています。単にファイルが異なると述べているだけです。これは、Git がテキストファイルとバイナリファイルを扱う方法の重要な違いです。テキストファイルの場合、Git はどの行が追加、削除、または変更されたかを正確に表示できます。バイナリファイルの場合、変更があったことだけを知らせることができます。
このステップは、Git の強力な差分表示とマージツールが、ソースコードや設定ファイルなどのテキストベースのコンテンツで最も効果的である理由を示しています。