1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

「diffコマンド」と「Gitのdiff」は何が違うのか調査してみた

Last updated at Posted at 2022-10-12

以下の2つのテキストファイルがあるとする

A.txt
apple
banana
chocolate
B.txt
apple
blueberry
chocolate

A. Linuxのdiffコマンドで比較

diff A.txt B.txt

オプション無しの場合、normal形式のdiffが出力される

2c2
< banana
---
> blueberry

normal形式では、変更行の前後は出力されない

B. Linuxのdiffコマンドで比較(Gitのdiff風になるようにオプションを付与)

diff -u A.txt B.txt

unified形式のdiffが出力される
Gitのdiffにかなり近い形式

--- A.txt       2022-10-12 17:24:12.165288000 +0900
+++ B.txt       2022-10-12 17:26:09.695288000 +0900
@@ -1,3 +1,3 @@
 apple
-banana
+blueberry
 chocolate

ただ、これだと出力文字列に色が付かない...
diffを色付きで見たい場合、

diff -u A.txt B.txt > sabun.diff

という風に一旦ファイルに出力し、
それをVimやVSCodeなどのリッチなエディタで開いてシンタックスハイライトを表示させるという方法があるが、
「直で色付きで出力させたい!」というせっかちな人には、後述の方法を紹介する

C. colordiffコマンドを使用

sudo apt install colordiff
colordiff -u A.txt B.txt

色付きのdiffが出力されて、見やすくなった!

--- A.txt       2022-10-12 17:24:12.165288000 +0900
+++ B.txt       2022-10-12 17:26:09.695288000 +0900
@@ -1,3 +1,3 @@
 apple
-banana
+blueberry
 chocolate

D. Gitのdiff

  1. 空のディレクトリを作成し、git init でGitリポジトリを作成
  2. 変更前のファイルをコミット
  3. 変更後のファイルに置き換えてコミット

という手順でdiffを作成(面倒...)
見慣れた形式のdiffが出力される

diff --git a/test.txt b/test.txt
index 684da80..6e73a9c 100644
--- a/test.txt
+++ b/test.txt
@@ -1,3 +1,3 @@
 apple
-banana
+blueberry
 chocolate

ところで、Gitはどうやって差分を取得している?

# テキストファイルのハッシュ値を計算
cat test.txt | git hash-object -w --stdin

6e73a9cea3235240ff29f184e0427d47b09f8801

diffを表示した際に出力された index 684da80..6e73a9c6e73a9c は、ファイルの中身をハッシュ化した際の値の先頭7桁と一致!
Gitはハッシュ関数を利用することで、ファイルの中身が一致しているかどうかをチェックしているというわけなのだ

ちなみに、ハッシュ値の先頭2桁はディレクトリ名、残りの38桁はファイル名として .git/objects の下に保存される
git_object.png

cat-file コマンドを使うことで中身を取り出すこともできる

git cat-file -p 6e73a9cea3235240ff29f184e0427d47b09f8801

apple
blueberry
chocolate

Gitが高速な動作をする背景には、こういった優れた仕組みがあったのだ
リーナス様に感謝🙇‍♂️

参考サイト

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?