-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
218 lines (181 loc) · 6.02 KB
/
main.go
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type ConnectorStyle struct {
Intermediate string
Last string
Prefix string
Branch string
}
func patternToRegex(pattern string) (string, error) {
regexPattern := regexp.QuoteMeta(pattern)
regexPattern = strings.ReplaceAll(regexPattern, `\*`, ".*")
regexPattern = strings.ReplaceAll(regexPattern, `\?`, ".")
regexPattern = "^" + regexPattern + "$"
_, err := regexp.Compile(regexPattern)
if err != nil {
return "", fmt.Errorf("error compiling regex pattern: %v", err)
}
return regexPattern, nil
}
func scanDirectory(root string, prefix string, ignoredDirs map[string]struct{}, style ConnectorStyle, excludePatterns []string, maxDepth, currentDepth int) (string, error) {
logrus.Debugf("Scanning directory: %s with prefix: %s", root, prefix)
var result strings.Builder
entries, err := os.ReadDir(root)
if err != nil {
return "", fmt.Errorf("error reading directory %s: %v", root, err)
}
filteredEntries := []os.DirEntry{}
for _, entry := range entries {
if _, ok := ignoredDirs[entry.Name()]; ok {
logrus.Debugf("Skipping ignored directory: %s", entry.Name())
continue
}
excluded := false
for _, pattern := range excludePatterns {
regexPattern, err := patternToRegex(pattern)
if err != nil {
return "", fmt.Errorf("error matching pattern %s: %v", pattern, err)
}
matched, err := regexp.MatchString(regexPattern, entry.Name())
if err != nil {
return "", fmt.Errorf("error matching pattern %s: %v", regexPattern, err)
}
if matched {
logrus.Debugf("Skipping excluded file/directory: %s", entry.Name())
excluded = true
break
}
}
if !excluded {
filteredEntries = append(filteredEntries, entry)
}
}
if maxDepth != -1 && currentDepth >= maxDepth {
return "", nil
}
for i, entry := range filteredEntries {
connector := style.Intermediate
newPrefix := prefix + style.Branch
if i == len(filteredEntries)-1 {
connector = style.Last
newPrefix = prefix + style.Prefix
}
result.WriteString(fmt.Sprintf("%s%s%s\n", prefix, connector, entry.Name()))
if entry.IsDir() {
subDir, err := scanDirectory(filepath.Join(root, entry.Name()), newPrefix, ignoredDirs, style, excludePatterns, maxDepth, currentDepth+1)
if err != nil {
return "", err
}
result.WriteString(subDir)
}
}
return result.String(), nil
}
func readDirIgnore(root string) (map[string]struct{}, error) {
ignoredDirs := make(map[string]struct{})
dirIgnorePath := filepath.Join(root, ".dirignore")
file, err := os.Open(dirIgnorePath)
if err != nil {
if os.IsNotExist(err) {
return ignoredDirs, nil
}
return nil, fmt.Errorf("error opening .dirignore file: %v", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
dir := strings.TrimSpace(scanner.Text())
if dir != "" {
ignoredDirs[dir] = struct{}{}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading .dirignore file: %v", err)
}
return ignoredDirs, nil
}
func generateMarkdown(dir string, structure string) string {
logrus.Debugf("Generating Markdown for directory: %s", dir)
return fmt.Sprintf("# Directory structure of %s\n\n```\n%s```\n", dir, structure)
}
func writeToFile(filename string, content string) error {
logrus.Debugf("Writing to file: %s", filename)
f, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file %s: %v", filename, err)
}
defer f.Close()
_, err = f.WriteString(content)
if err != nil {
return fmt.Errorf("error writing to file %s: %v", filename, err)
}
return nil
}
func ensureMdExtension(filename string) string {
if filepath.Ext(filename) != ".md" {
return filename + ".md"
}
return filename
}
func main() {
var (
intermediate string
last string
prefix string
branch string
exclude []string
maxDepth int
verbose bool
)
var rootCmd = &cobra.Command{
Use: "dirscanner <directory to scan> <output markdown file> [flags]",
Short: "A CLI tool to scan directories and generate a Markdown file with the structure",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
dir := args[0]
output := ensureMdExtension(args[1])
ignoredDirs, err := readDirIgnore(dir)
if err != nil {
return fmt.Errorf("error reading .dirignore file: %v", err)
}
style := ConnectorStyle{
Intermediate: intermediate,
Last: last,
Prefix: prefix,
Branch: branch,
}
if verbose {
logrus.SetLevel(logrus.DebugLevel)
}
structure, err := scanDirectory(dir, "", ignoredDirs, style, exclude, maxDepth, 0)
if err != nil {
return fmt.Errorf("error scanning directory: %v", err)
}
markdownContent := generateMarkdown(dir, structure)
if err := writeToFile(output, markdownContent); err != nil {
return fmt.Errorf("error writing to output file: %v", err)
}
fmt.Println("Markdown file created successfully.")
return nil
},
}
rootCmd.Flags().StringVar(&intermediate, "intermediate", "├── ", "Symbol for intermediate nodes")
rootCmd.Flags().StringVar(&last, "last", "└── ", "Symbol for the last node in a directory")
rootCmd.Flags().StringVar(&prefix, "prefix", " ", "Prefix for child nodes")
rootCmd.Flags().StringVar(&branch, "branch", "│ ", "Branch for intermediate nodes")
rootCmd.Flags().StringSliceVar(&exclude, "exclude", []string{}, "Exclude files or directories matching these patterns (e.g., '*.txt')")
rootCmd.Flags().IntVar(&maxDepth, "depth", -1, "Limit the depth of the directory traversal (-1 for no limit)")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Whether or not to show debug messages")
if err := rootCmd.Execute(); err != nil {
logrus.Fatal(err)
}
}