29
25

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 5 years have passed since last update.

GolangのdiffMatchPatchライブラリで行単位diffをする

Posted at

diff-match-patch便利ですよね?

これで行単位のdiffを出そうと思ったんですが、APIのリストとにらめっこしてもわからなかったのですが、検索したら大本のGoogle謹製の方のWikiにあったので、実装のメモです。

import "github.com/sergi/go-diff/diffmatchpatch"

func lineDiff(src1, src2 string) []diffmatchpatch.Diff {
	dmp := diffmatchpatch.New()
	a, b, c := dmp.DiffLinesToChars(src1, src2)
	diffs := dmp.DiffMain(a, b, false)
	result := dmp.DiffCharsToLines(diffs, c)
	fmt.Println(result)
	return result
}

仮に、以下のテキストがあったとします。

abc
def
ghi
abc
go-
ghi

これのDiffをとると

{0 abc\n}
{-1 def\n}
{1 go-\n}
{0 ghi}

こんな感じのdiffになります。-1が削除(コード中はdiffmatchpatch.DiffDeleteを使ってね)、1が追加(diffmatchpatch.DiffInsert)、0が変更なし(diffmatchpatch.DiffEqual)で、各行の改行文字は各ブロックの末尾についてます。

29
25
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
29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?