-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
156 lines (138 loc) · 4.33 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
package main
import (
"bytes"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
)
type appConfig struct {
IncludeExtensions []string
ExcludeExtensions []string
IgnoreDirs []string
OutputFile string
}
func main() {
config := appConfig{
IncludeExtensions: []string{".go", ".js", ".jsx", ".ts", ".tsx", ".py", ".rb", ".php", ".swift", ".c", ".cpp", ".h", ".hpp", ".java", ".rs", ".kt", ".scala", ".m"},
ExcludeExtensions: []string{".log", ".tmp", ".bak", ".o", ".obj", ".class", ".exe", ".dll", ".so", ".a", ".lib", ".pyc", ".jar"},
IgnoreDirs: []string{".git", ".idea", ".vscode", "node_modules", "vendor", "build", "dist", "bin", "obj"},
OutputFile: "output.txt",
}
var rootCmd = &cobra.Command{
Use: "code2text",
Short: "Collects code files and outputs them into a single text document.",
Long: `A fast and flexible utility to collect code files from a directory tree
and consolidate them into a single text document for analysis.`,
Run: func(cmd *cobra.Command, args []string) {
start := time.Now()
if err := processFiles(".", &config); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
duration := time.Since(start)
fmt.Printf("Processing completed in %v\n", duration)
},
}
rootCmd.PersistentFlags().StringVarP(&config.OutputFile, "output", "o", config.OutputFile, "Output file name")
rootCmd.PersistentFlags().StringSliceVarP(&config.IncludeExtensions, "include", "i", config.IncludeExtensions, "File extensions to include")
rootCmd.PersistentFlags().StringSliceVarP(&config.ExcludeExtensions, "exclude", "e", config.ExcludeExtensions, "File extensions to exclude")
rootCmd.PersistentFlags().StringSliceVarP(&config.IgnoreDirs, "ignore", "g", config.IgnoreDirs, "Directories to ignore")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func processFiles(startDir string, config *appConfig) error {
var buffer bytes.Buffer
// Directory structure output
dirStructure, err := generateDirStructure(startDir, config.IgnoreDirs)
if err != nil {
return err
}
buffer.WriteString(dirStructure)
var totalLines int
var totalSize int64
fileCount := 0
err = filepath.WalkDir(startDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if contains(config.IgnoreDirs, d.Name()) {
return fs.SkipDir
}
return nil
}
ext := filepath.Ext(path)
if contains(config.IncludeExtensions, ext) && !contains(config.ExcludeExtensions, ext) {
data, err := os.ReadFile(path)
if err != nil {
return err
}
lines := bytes.Count(data, []byte("\n"))
totalLines += lines
totalSize += int64(len(data))
fileCount++
buffer.WriteString(fmt.Sprintf("File: %s\n", path))
buffer.WriteString(fmt.Sprintf("Lines: %d\n", lines))
buffer.WriteString(fmt.Sprintf("-----BEGIN %s-----\n", path))
buffer.Write(data)
buffer.WriteString(fmt.Sprintf("\n-----END %s-----\n\n", path))
}
return nil
})
if err != nil {
return err
}
if err := os.WriteFile(config.OutputFile, buffer.Bytes(), 0644); err != nil {
return err
}
fmt.Printf("Total files processed: %d\n", fileCount)
fmt.Printf("Total lines: %d\n", totalLines)
fmt.Printf("Total size of data: %d bytes\n", totalSize)
return nil
}
func generateDirStructure(startDir string, ignoreDirs []string) (string, error) {
cmd := exec.Command("tree", startDir)
if output, err := cmd.CombinedOutput(); err == nil {
return string(output), nil
}
return customTree(startDir, "", ignoreDirs)
}
func customTree(dir, prefix string, ignoreDirs []string) (string, error) {
var result strings.Builder
files, err := os.ReadDir(dir)
if err != nil {
return "", err
}
for _, file := range files {
if contains(ignoreDirs, file.Name()) {
continue
}
if file.IsDir() {
result.WriteString(fmt.Sprintf("%s├── %s\n", prefix, file.Name()))
newPrefix := prefix + "│ "
subTree, err := customTree(filepath.Join(dir, file.Name()), newPrefix, ignoreDirs)
if err != nil {
return "", err
}
result.WriteString(subTree)
} else {
result.WriteString(fmt.Sprintf("%s├── %s\n", prefix, file.Name()))
}
}
return result.String(), nil
}
func contains(slice []string, item string) bool {
for _, s := range slice {
if s == item {
return true
}
}
return false
}