aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/covermerger/lines_matcher.go
blob: 0f3d33fc71fe222f4f4631e9e680e41d5ee33f0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2024 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package covermerger

import (
	"strings"

	dmp "github.com/sergi/go-diff/diffmatchpatch"
)

func makeLineToLineMatcher(textFrom, textTo string) *LineToLineMatcher {
	diffMatcher := dmp.New()
	diffMatcher.DiffTimeout = 0
	diffs := diffMatcher.DiffMain(textFrom, textTo, false)
	curToLinePos := 0
	textDestPosToLine := map[int]int{}
	for iLine, line := range strings.Split(textTo, "\n") {
		textDestPosToLine[curToLinePos] = iLine
		curToLinePos += len(line) + len("\n")
	}

	toLines := strings.Split(textTo, "\n")
	curFromLinePos := 0
	lineToLine := []int{}
	for _, line := range strings.Split(textFrom, "\n") {
		toLinePos := diffMatcher.DiffXIndex(diffs, curFromLinePos)
		toLine := -1
		if bestMatchDestLine, ok := textDestPosToLine[toLinePos]; ok {
			if toLines[bestMatchDestLine] == line {
				toLine = bestMatchDestLine
			}
		}
		lineToLine = append(lineToLine, toLine)
		curFromLinePos += len(line) + len("\n")
	}
	return &LineToLineMatcher{
		lineToLine: lineToLine,
	}
}

type LineToLineMatcher struct {
	lineToLine []int
}

func (lm *LineToLineMatcher) SameLinePos(line int) int {
	return lm.lineToLine[line]
}