| 1 | package review |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strconv" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | var hunkHeader = regexp.MustCompile(`^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@`) |
| 10 | |
| 11 | // DiffLines maps each file in a unified diff to the new-side line numbers its hunks show (added + context): the lines GitHub accepts inline comments on with side=RIGHT. |
| 12 | func DiffLines(diff string) map[string]map[int]bool { |
| 13 | files := map[string]map[int]bool{} |
| 14 | var cur map[int]bool // nil for deleted files |
| 15 | var line, oldLeft, newLeft int |
| 16 | for _, l := range strings.Split(diff, "\n") { |
| 17 | if oldLeft > 0 || newLeft > 0 { // inside a hunk; counts, not prefixes, mark its end |
| 18 | switch { |
| 19 | case strings.HasPrefix(l, "-"): |
| 20 | oldLeft-- |
| 21 | case strings.HasPrefix(l, "+"): |
| 22 | if cur != nil { |
| 23 | cur[line] = true |
| 24 | } |
| 25 | line++ |
| 26 | newLeft-- |
| 27 | case strings.HasPrefix(l, `\`): // "\ No newline at end of file" |
| 28 | default: // context; "" when trailing whitespace was stripped |
| 29 | if cur != nil { |
| 30 | cur[line] = true |
| 31 | } |
| 32 | line++ |
| 33 | oldLeft-- |
| 34 | newLeft-- |
| 35 | } |
| 36 | continue |
| 37 | } |
| 38 | switch { |
| 39 | case strings.HasPrefix(l, "diff --git "): |
| 40 | cur = nil |
| 41 | case strings.HasPrefix(l, "+++ "): |
| 42 | path := strings.TrimPrefix(l, "+++ ") |
| 43 | if path == "/dev/null" { |
| 44 | cur = nil |
| 45 | continue |
| 46 | } |
| 47 | if uq, err := strconv.Unquote(path); err == nil { |
| 48 | path = uq |
| 49 | } |
| 50 | cur = map[int]bool{} |
| 51 | files[strings.TrimPrefix(path, "b/")] = cur |
| 52 | default: |
| 53 | if m := hunkHeader.FindStringSubmatch(l); m != nil { |
| 54 | oldLeft, newLeft = hunkCount(m[1]), hunkCount(m[3]) |
| 55 | line, _ = strconv.Atoi(m[2]) |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | return files |
| 60 | } |
| 61 | |
| 62 | func hunkCount(s string) int { |
| 63 | if s == "" { |
| 64 | return 1 |
| 65 | } |
| 66 | n, _ := strconv.Atoi(s) |
| 67 | return n |
| 68 | } |
| 69 | |
| 70 | // diffPath resolves a finding's file to a key of lines, tolerating "./" and "b/" prefixes. |
| 71 | func diffPath(lines map[string]map[int]bool, file string) (string, bool) { |
| 72 | for _, p := range []string{file, strings.TrimPrefix(file, "./"), strings.TrimPrefix(file, "b/")} { |
| 73 | if _, ok := lines[p]; ok { |
| 74 | return p, true |
| 75 | } |
| 76 | } |
| 77 | return "", false |
| 78 | } |