code.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package source
  2. import (
  3. "bufio"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "unicode"
  8. )
  9. type Edit struct {
  10. Location int
  11. Old string
  12. New string
  13. }
  14. func LineNumber(source string, head int) (int, int) {
  15. // Calculate the true line and column number for a query, ignoring spaces
  16. var comment bool
  17. var loc, line, col int
  18. for i, char := range source {
  19. loc += 1
  20. col += 1
  21. // TODO: Check bounds
  22. if char == '-' && source[i+1] == '-' {
  23. comment = true
  24. }
  25. if char == '\n' {
  26. comment = false
  27. line += 1
  28. col = 0
  29. }
  30. if loc <= head {
  31. continue
  32. }
  33. if unicode.IsSpace(char) {
  34. continue
  35. }
  36. if comment {
  37. continue
  38. }
  39. break
  40. }
  41. return line + 1, col
  42. }
  43. func Pluck(source string, location, length int) (string, error) {
  44. head := location
  45. tail := location + length
  46. return source[head:tail], nil
  47. }
  48. func Mutate(raw string, a []Edit) (string, error) {
  49. if len(a) == 0 {
  50. return raw, nil
  51. }
  52. sort.Slice(a, func(i, j int) bool { return a[i].Location > a[j].Location })
  53. s := raw
  54. for _, edit := range a {
  55. start := edit.Location
  56. if start > len(s) {
  57. return "", fmt.Errorf("edit start location is out of bounds")
  58. }
  59. if len(edit.New) <= 0 {
  60. return "", fmt.Errorf("empty edit contents")
  61. }
  62. if len(edit.Old) <= 0 {
  63. return "", fmt.Errorf("empty edit contents")
  64. }
  65. stop := edit.Location + len(edit.Old) - 1 // Assumes edit.New is non-empty
  66. if stop < len(s) {
  67. s = s[:start] + edit.New + s[stop+1:]
  68. } else {
  69. s = s[:start] + edit.New
  70. }
  71. }
  72. return s, nil
  73. }
  74. func StripComments(sql string) (string, []string, error) {
  75. s := bufio.NewScanner(strings.NewReader(strings.TrimSpace(sql)))
  76. var lines, comments []string
  77. for s.Scan() {
  78. t := s.Text()
  79. if strings.HasPrefix(t, "-- name:") {
  80. continue
  81. }
  82. if strings.HasPrefix(t, "/* name:") && strings.HasSuffix(t, "*/") {
  83. continue
  84. }
  85. if strings.HasPrefix(t, "--") {
  86. comments = append(comments, strings.TrimPrefix(t, "--"))
  87. continue
  88. }
  89. if strings.HasPrefix(t, "/*") && strings.HasSuffix(t, "*/") {
  90. t = strings.TrimPrefix(t, "/*")
  91. t = strings.TrimSuffix(t, "*/")
  92. comments = append(comments, t)
  93. continue
  94. }
  95. lines = append(lines, t)
  96. }
  97. return strings.Join(lines, "\n"), comments, s.Err()
  98. }