location.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package detect
  2. // Location represents a location in a file
  3. type Location struct {
  4. startLine int
  5. endLine int
  6. startColumn int
  7. endColumn int
  8. startLineIndex int
  9. endLineIndex int
  10. }
  11. func location(fragment Fragment, matchIndex []int) Location {
  12. var (
  13. prevNewLine int
  14. location Location
  15. lineSet bool
  16. _lineNum int
  17. )
  18. start := matchIndex[0]
  19. end := matchIndex[1]
  20. // default startLineIndex to 0
  21. location.startLineIndex = 0
  22. for lineNum, pair := range fragment.newlineIndices {
  23. _lineNum = lineNum
  24. newLineByteIndex := pair[0]
  25. if prevNewLine <= start && start < newLineByteIndex {
  26. lineSet = true
  27. location.startLine = lineNum
  28. location.endLine = lineNum
  29. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  30. location.startLineIndex = prevNewLine
  31. location.endLineIndex = newLineByteIndex
  32. }
  33. if prevNewLine < end && end <= newLineByteIndex {
  34. location.endLine = lineNum
  35. location.endColumn = (end - prevNewLine)
  36. location.endLineIndex = newLineByteIndex
  37. }
  38. prevNewLine = pair[0]
  39. }
  40. if !lineSet {
  41. // if lines never get set then that means the secret is most likely
  42. // on the last line of the diff output and the diff output does not have
  43. // a newline
  44. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  45. location.endColumn = (end - prevNewLine)
  46. location.startLine = _lineNum + 1
  47. location.endLine = _lineNum + 1
  48. // search for new line byte index
  49. i := 0
  50. for end+i < len(fragment.Raw) {
  51. if fragment.Raw[end+i] == '\n' {
  52. break
  53. }
  54. if fragment.Raw[end+i] == '\r' {
  55. break
  56. }
  57. i++
  58. }
  59. location.endLineIndex = end + i
  60. }
  61. return location
  62. }