-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitignore.go
More file actions
110 lines (96 loc) · 2.17 KB
/
Copy pathgitignore.go
File metadata and controls
110 lines (96 loc) · 2.17 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package contexting
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
var starterGitignoreEntries = []string{
// Version control
".git",
".svn",
".hg",
// Virtual environments / caches
".venv",
".cache",
".pytest_cache",
"site-packages",
"__pycache__",
// Dependencies
"node_modules",
"vendor",
// Build outputs
"dist",
"build",
"out",
"tmp",
"temp",
// IDE / editor
".vscode",
".idea",
"*.swp",
"*.swo",
// Secrets / env
".env",
".env.local",
".env.*.local",
// OS junk
".DS_Store",
"Thumbs.db",
// Logs
"*.log",
}
func EnsureAndLoadGitignore(root string) ([]string, error) {
gitignorePath := filepath.Join(root, ".gitignore")
if _, err := os.Stat(gitignorePath); err != nil {
if os.IsNotExist(err) {
if err := createStarterGitignore(gitignorePath); err != nil {
return nil, err
}
LogInfof("Created starter .gitignore at %s", gitignorePath)
} else {
return nil, fmt.Errorf("stat .gitignore: %w", err)
}
}
patterns, err := LoadGitignorePatterns(gitignorePath)
if err != nil {
return nil, err
}
return patterns, nil
}
func createStarterGitignore(path string) error {
lines := []string{"# Contexting starter .gitignore"}
lines = append(lines, starterGitignoreEntries...)
content := strings.Join(lines, "\n") + "\n"
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return fmt.Errorf("create .gitignore directory: %w", err)
}
return writeFileAtomic(path, []byte(content), 0o644)
}
func LoadGitignorePatterns(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open .gitignore: %w", err)
}
defer file.Close()
patterns := make([]string, 0, 32)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "!") {
continue
}
line = strings.TrimPrefix(line, "./")
line = strings.TrimPrefix(line, "/")
line = strings.TrimSuffix(line, "/")
if line == "" {
continue
}
patterns = append(patterns, line)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("read .gitignore: %w", err)
}
return dedupeStrings(patterns), nil
}