-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
315 lines (276 loc) · 7.4 KB
/
main.go
File metadata and controls
315 lines (276 loc) · 7.4 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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/JordanCoin/docmap/parser"
"github.com/JordanCoin/docmap/render"
)
// JSON output structures
type JSONOutput struct {
Root string `json:"root"`
TotalTokens int `json:"total_tokens"`
TotalDocs int `json:"total_docs"`
Documents []JSONDocument `json:"documents"`
}
type JSONDocument struct {
Filename string `json:"filename"`
Tokens int `json:"tokens"`
Sections []JSONSection `json:"sections"`
References []JSONRef `json:"references,omitempty"`
}
type JSONSection struct {
Level int `json:"level"`
Title string `json:"title"`
Tokens int `json:"tokens"`
KeyTerms []string `json:"key_terms,omitempty"`
Children []JSONSection `json:"children,omitempty"`
}
type JSONRef struct {
Text string `json:"text"`
Target string `json:"target"`
Line int `json:"line"`
}
var version = "dev"
func main() {
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
// Check for help/version flags first
for _, arg := range os.Args[1:] {
switch arg {
case "--help", "-h":
printUsage()
return
case "--version", "-v":
fmt.Printf("docmap %s\n", version)
return
}
}
target := os.Args[1]
// Parse flags
var sectionFilter string
var expandSection string
var searchQuery string
var showRefs bool
var jsonMode bool
for i := 2; i < len(os.Args); i++ {
switch os.Args[i] {
case "--section", "-s":
if i+1 < len(os.Args) {
sectionFilter = os.Args[i+1]
i++
}
case "--expand", "-e":
if i+1 < len(os.Args) {
expandSection = os.Args[i+1]
i++
}
case "--search":
if i+1 < len(os.Args) {
searchQuery = os.Args[i+1]
i++
}
case "--refs", "-r":
showRefs = true
case "--json", "-j":
jsonMode = true
}
}
// Check if target is a directory
info, err := os.Stat(target)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if info.IsDir() {
// Multi-file mode: find all .md files
docs := parseDirectory(target)
if len(docs) == 0 {
fmt.Println("No markdown, PDF, or YAML files found")
os.Exit(1)
}
if jsonMode {
absPath, _ := filepath.Abs(target)
outputJSON(docs, absPath)
} else if searchQuery != "" {
render.SearchResults(docs, searchQuery)
} else if showRefs {
render.RefsTree(docs, target)
} else {
render.MultiTree(docs, target)
}
} else {
// Single file mode
var doc *parser.Document
lower := strings.ToLower(target)
if strings.HasSuffix(lower, ".pdf") {
// PDF file
var err error
doc, err = parser.ParsePDF(target)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing PDF: %v\n", err)
os.Exit(1)
}
} else if strings.HasSuffix(lower, ".yaml") || strings.HasSuffix(lower, ".yml") {
// YAML file
content, err := os.ReadFile(target)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file: %v\n", err)
os.Exit(1)
}
doc, err = parser.ParseYAML(string(content))
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing YAML: %v\n", err)
os.Exit(1)
}
} else {
// Markdown file
content, err := os.ReadFile(target)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file: %v\n", err)
os.Exit(1)
}
doc = parser.Parse(string(content))
}
parts := strings.Split(target, "/")
doc.Filename = parts[len(parts)-1]
if jsonMode {
absPath, _ := filepath.Abs(target)
outputJSON([]*parser.Document{doc}, absPath)
} else if searchQuery != "" {
render.SearchResults([]*parser.Document{doc}, searchQuery)
} else if expandSection != "" {
render.ExpandSection(doc, expandSection)
} else if sectionFilter != "" {
render.FilteredTree(doc, sectionFilter)
} else {
render.Tree(doc)
}
}
}
func parseDirectory(dir string) []*parser.Document {
var docs []*parser.Document
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() {
return nil
}
lowerPath := strings.ToLower(path)
isMd := strings.HasSuffix(lowerPath, ".md")
isPdf := strings.HasSuffix(lowerPath, ".pdf")
isYaml := strings.HasSuffix(lowerPath, ".yaml") || strings.HasSuffix(lowerPath, ".yml")
if !isMd && !isPdf && !isYaml {
return nil
}
// Skip hidden files
base := filepath.Base(path)
if strings.HasPrefix(base, ".") {
return nil
}
var doc *parser.Document
if isPdf {
var err error
doc, err = parser.ParsePDF(path)
if err != nil {
// Skip PDFs that can't be parsed
return nil
}
} else if isYaml {
content, err := os.ReadFile(path)
if err != nil {
return nil
}
doc, err = parser.ParseYAML(string(content))
if err != nil {
// Skip YAML files that can't be parsed
return nil
}
} else {
content, err := os.ReadFile(path)
if err != nil {
return nil
}
doc = parser.Parse(string(content))
}
// Get relative path from dir
relPath, _ := filepath.Rel(dir, path)
doc.Filename = relPath
docs = append(docs, doc)
return nil
})
return docs
}
func outputJSON(docs []*parser.Document, root string) {
output := JSONOutput{
Root: root,
TotalDocs: len(docs),
}
for _, doc := range docs {
jsonDoc := JSONDocument{
Filename: doc.Filename,
Tokens: doc.TotalTokens,
Sections: convertSections(doc.Sections),
}
// Add references
for _, ref := range doc.References {
jsonDoc.References = append(jsonDoc.References, JSONRef{
Text: ref.Text,
Target: ref.Target,
Line: ref.Line,
})
}
output.Documents = append(output.Documents, jsonDoc)
output.TotalTokens += doc.TotalTokens
}
json.NewEncoder(os.Stdout).Encode(output)
}
func convertSections(sections []*parser.Section) []JSONSection {
var result []JSONSection
for _, s := range sections {
js := JSONSection{
Level: s.Level,
Title: s.Title,
Tokens: s.Tokens,
KeyTerms: s.KeyTerms,
Children: convertSections(s.Children),
}
result = append(result, js)
}
return result
}
func printUsage() {
fmt.Println(`docmap - instant documentation structure for LLMs and humans
Usage:
docmap <file.md|file.pdf|file.yaml|dir> [flags]
Examples:
docmap . # All markdown, PDF, and YAML files
docmap README.md # Single markdown file deep dive
docmap report.pdf # Single PDF file structure
docmap config.yaml # Single YAML file structure
docmap docs/ # Specific folder
docmap README.md --section "API" # Filter to section
docmap README.md --expand "API" # Show section content
docmap . --refs # Show cross-references between docs
docmap docs/ --search "auth" # Search across all files
Flags:
--search <query> Search sections across all files
-s, --section <name> Filter to a specific section
-e, --expand <name> Show full content of a section
-r, --refs Show cross-references between markdown files
-j, --json Output JSON format
-v, --version Print version
-h, --help Show this help
PDF Support:
PDFs with outlines show document structure; tokens are estimated.
PDFs without outlines fall back to page-by-page structure.
YAML Support:
Maps keys to sections with nested children. Sequences use name/id/title
fields for titles when available, falling back to key: value or [N].
More info: https://github.com/JordanCoin/docmap`)
}