ignore.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package git
  2. /*
  3. ignore.go
  4. Appending rules to a repository's .gitignore.
  5. This lives in Go rather than in the calling script so the file handling —
  6. locating the repository root, preserving whatever the user already wrote,
  7. getting the trailing newline right and never writing a duplicate rule — is
  8. covered by tests.
  9. */
  10. import (
  11. "errors"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. )
  16. // gitignoreName is the file rules are appended to, at the working tree root.
  17. const gitignoreName = ".gitignore"
  18. // ignoreHeader is written above the first block GitApp appends, so a user
  19. // reading their .gitignore later can tell where the lines came from.
  20. const ignoreHeader = "# Added by GitApp"
  21. // AddIgnoreRules appends the given patterns to the repository's .gitignore,
  22. // skipping any rule that is already there. The patterns actually written are
  23. // returned so the caller can report precisely what changed.
  24. func (m *Manager) AddIgnoreRules(realpath string, patterns []string) ([]string, error) {
  25. root, err := m.RepoRoot(realpath)
  26. if err != nil {
  27. return nil, err
  28. }
  29. wanted, err := normaliseIgnorePatterns(patterns)
  30. if err != nil {
  31. return nil, err
  32. }
  33. ignorePath := filepath.Join(root, gitignoreName)
  34. existing := ""
  35. if raw, rerr := os.ReadFile(ignorePath); rerr == nil {
  36. existing = string(raw)
  37. } else if !os.IsNotExist(rerr) {
  38. return nil, rerr
  39. }
  40. present := existingIgnoreRules(existing)
  41. added := []string{}
  42. for _, pattern := range wanted {
  43. if _, found := present[pattern]; found {
  44. continue
  45. }
  46. present[pattern] = struct{}{}
  47. added = append(added, pattern)
  48. }
  49. if len(added) == 0 {
  50. return added, nil
  51. }
  52. if err := os.WriteFile(ignorePath, []byte(appendIgnoreRules(existing, added)), 0664); err != nil {
  53. return nil, err
  54. }
  55. return added, nil
  56. }
  57. /*
  58. appendIgnoreRules produces the new .gitignore content.
  59. The existing content is never rewritten, only extended: the separating newlines
  60. are added as needed so appending to a file with or without a trailing newline
  61. both give a well formed result.
  62. */
  63. func appendIgnoreRules(existing string, added []string) string {
  64. builder := strings.Builder{}
  65. builder.WriteString(existing)
  66. //The header, and the blank line that sets it apart, belong to the first
  67. //block only. Later calls join the block that is already there — otherwise
  68. //ignoring several folders one at a time leaves a blank line between every
  69. //pair of rules.
  70. startingBlock := !strings.Contains(existing, ignoreHeader)
  71. if existing != "" && !strings.HasSuffix(existing, "\n") {
  72. builder.WriteString("\n")
  73. }
  74. if startingBlock {
  75. if existing != "" && !strings.HasSuffix(existing, "\n\n") {
  76. builder.WriteString("\n")
  77. }
  78. builder.WriteString(ignoreHeader)
  79. builder.WriteString("\n")
  80. }
  81. for _, pattern := range added {
  82. builder.WriteString(pattern)
  83. builder.WriteString("\n")
  84. }
  85. return builder.String()
  86. }
  87. // existingIgnoreRules indexes the rules already in a .gitignore. Comments and
  88. // blank lines are skipped so a rule that only appears inside a comment is not
  89. // mistaken for an active one.
  90. func existingIgnoreRules(content string) map[string]struct{} {
  91. rules := map[string]struct{}{}
  92. for _, line := range strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n") {
  93. trimmed := strings.TrimSpace(line)
  94. if trimmed == "" || strings.HasPrefix(trimmed, "#") {
  95. continue
  96. }
  97. rules[trimmed] = struct{}{}
  98. }
  99. return rules
  100. }
  101. // normaliseIgnorePatterns cleans the patterns coming from the browser and
  102. // rejects anything that cannot be a gitignore rule. Duplicates within one call
  103. // are collapsed so a single request never writes the same line twice.
  104. func normaliseIgnorePatterns(patterns []string) ([]string, error) {
  105. results := []string{}
  106. seen := map[string]struct{}{}
  107. for _, pattern := range patterns {
  108. cleaned := strings.TrimSpace(pattern)
  109. cleaned = strings.ReplaceAll(cleaned, "\\", "/")
  110. cleaned = strings.TrimPrefix(cleaned, "./")
  111. if cleaned == "" {
  112. continue
  113. }
  114. //A rule spanning lines would silently become several rules
  115. if strings.ContainsAny(cleaned, "\n\r") {
  116. return nil, errors.New("ignore rule cannot contain a line break: " + pattern)
  117. }
  118. if strings.HasPrefix(cleaned, "#") {
  119. return nil, errors.New("ignore rule cannot start with '#': " + pattern)
  120. }
  121. if _, duplicate := seen[cleaned]; duplicate {
  122. continue
  123. }
  124. seen[cleaned] = struct{}{}
  125. results = append(results, cleaned)
  126. }
  127. if len(results) == 0 {
  128. return nil, errors.New("no usable ignore rule was given")
  129. }
  130. return results, nil
  131. }