aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/email/patch.go
blob: c77d19bed7ab6e9ea54b828cec4f3f5d22b03d6f (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
49
50
51
52
53
54
55
56
// Copyright 2017 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 email

import (
	"bufio"
	"bytes"
	"regexp"
	"strings"
)

func ParsePatch(message []byte) (diff string) {
	s := bufio.NewScanner(bytes.NewReader(message))
	diffStarted := false
	for s.Scan() {
		ln := s.Text()
		if lineMatchesDiffStart(ln) {
			diffStarted = true
			diff += ln + "\n"
			continue
		}
		if diffStarted {
			if ln == "" || ln == "--" || ln == "-- " || ln[0] == '>' {
				diffStarted = false
				continue
			}
			if strings.HasPrefix(ln, " ") || strings.HasPrefix(ln, "+") ||
				strings.HasPrefix(ln, "-") || strings.HasPrefix(ln, "@") ||
				strings.HasPrefix(ln, "================") {
				diff += ln + "\n"
				continue
			}
		}
	}
	if err := s.Err(); err != nil {
		panic("error while scanning from memory: " + err.Error())
	}
	return
}

func lineMatchesDiffStart(ln string) bool {
	diffRegexps := []*regexp.Regexp{
		regexp.MustCompile(`^(---|\+\+\+) [^\s]`),
		regexp.MustCompile(`^diff --git`),
		regexp.MustCompile(`^index [0-9a-f]+\.\.[0-9a-f]+`),
		regexp.MustCompile(`^new file mode [0-9]+`),
		regexp.MustCompile(`^Index: [^\s]`),
	}
	for _, re := range diffRegexps {
		if re.MatchString(ln) {
			return true
		}
	}
	return false
}