-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
612 lines (524 loc) · 16.7 KB
/
main.go
File metadata and controls
612 lines (524 loc) · 16.7 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"parsec/core"
"parsec/ui"
"parsec/utils"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/sahilm/fuzzy"
)
// UI dimension constants
const (
headerHeight = 1
footerHeight = 1
borderWidth = 2
borderHeight = 2
)
// Application model containing the main state
type model struct {
fileListModel ui.FileListModel
summaryModel ui.SummaryModel
summarizer *core.Summarizer
walker *utils.Walker
selectedPath string
width int
height int
basePath string
currentDir string // Current directory being browsed
// Search state
searchMode bool
searchQuery string
allFiles []utils.FileInfo // All files in current directory for filtering
filteredFiles []utils.FileInfo // Files after fuzzy search filter
}
// SummaryMsg is sent when a file summary is ready
type SummaryMsg struct {
summary core.FileSummary
path string // The relative path from base directory
selectedPath string // The path as selected in the file list
}
func (m model) Init() tea.Cmd {
return loadFilesCmd(m.walker, m.currentDir)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m = m.sizeComponents()
return m, nil
case LoadFilesMsg:
// Store all files and apply search filter if active
m.allFiles = msg.files
if m.searchMode && m.searchQuery != "" {
m.filteredFiles = m.fuzzyFilter(m.allFiles, m.searchQuery)
m.fileListModel.SetFiles(m.filteredFiles)
} else {
m.filteredFiles = m.allFiles
m.fileListModel.SetFiles(m.allFiles)
}
// Check if we have a new selection after loading files
var cmds []tea.Cmd
if selected := m.fileListModel.GetSelectedFile(); selected != nil && selected.Path != m.selectedPath {
m.selectedPath = selected.Path
if cmd := m.handleFileSelection(selected); cmd != nil {
cmds = append(cmds, cmd)
}
}
return m, tea.Batch(cmds...)
case SummaryMsg:
// Update summary when async summary is ready
if msg.selectedPath == m.selectedPath {
m.summaryModel.SetSummary(&msg.summary)
}
return m, nil
case DirectoryPreviewMsg:
// Update summary with directory preview
if selected := m.fileListModel.GetSelectedFile(); selected != nil && selected.Path == msg.dirName {
m.summaryModel.SetSummary(nil)
m.summaryModel.SetContent(msg.content)
}
return m, nil
case tea.KeyMsg:
// Handle search mode input
if m.searchMode {
// Check for escape key using key type for better reliability
if msg.Type == tea.KeyEscape {
// Exit search mode
m.searchMode = false
m.searchQuery = ""
m.fileListModel.SetFiles(m.allFiles)
return m, nil
}
// Handle other search mode keys
switch msg.Type {
case tea.KeyEnter:
// Exit search mode but keep filter
m.searchMode = false
return m, nil
case tea.KeyBackspace:
if len(m.searchQuery) > 0 {
m.searchQuery = m.searchQuery[:len(m.searchQuery)-1]
if m.searchQuery == "" {
m.filteredFiles = m.allFiles
m.fileListModel.SetFiles(m.allFiles)
} else {
m.filteredFiles = m.fuzzyFilter(m.allFiles, m.searchQuery)
m.fileListModel.SetFiles(m.filteredFiles)
}
}
return m, nil
default:
// Add character to search query
if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
m.searchQuery += msg.String()
m.filteredFiles = m.fuzzyFilter(m.allFiles, m.searchQuery)
m.fileListModel.SetFiles(m.filteredFiles)
}
return m, nil
}
}
// Normal mode keyboard handling
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "/":
// Enter search mode
m.searchMode = true
m.searchQuery = ""
return m, nil
case "r":
// Refresh file list
return m, loadFilesCmd(m.walker, m.currentDir)
case "pgup":
// Scroll summary up
m.summaryModel.Scroll(-5)
return m, nil
case "pgdown":
// Scroll summary down
m.summaryModel.Scroll(5)
return m, nil
case "enter":
// Navigate into directory or select file
if selected := m.fileListModel.GetSelectedFile(); selected != nil && selected.IsDir {
if selected.Path == ".." {
// Go up one directory
m.currentDir = filepath.Dir(m.currentDir)
} else {
// Go into the selected directory
m.currentDir = filepath.Join(m.currentDir, selected.Path)
}
// Load files from new directory
return m, loadFilesCmd(m.walker, m.currentDir)
}
return m, nil
default:
// Handle file list navigation
var cmd tea.Cmd
m.fileListModel, cmd = m.fileListModel.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
// Check if selection changed
if selected := m.fileListModel.GetSelectedFile(); selected != nil && selected.Path != m.selectedPath {
m.selectedPath = selected.Path
if cmd := m.handleFileSelection(selected); cmd != nil {
cmds = append(cmds, cmd)
}
}
}
}
return m, tea.Batch(cmds...)
}
// fuzzyFilter applies fuzzy search to filter files
func (m model) fuzzyFilter(files []utils.FileInfo, query string) []utils.FileInfo {
if query == "" {
return files
}
// Create a slice of file paths for fuzzy matching
var filePaths []string
for _, file := range files {
filePaths = append(filePaths, file.Path)
}
// Perform fuzzy search
matches := fuzzy.Find(query, filePaths)
// Convert matches back to FileInfo slice
var filtered []utils.FileInfo
for _, match := range matches {
for _, file := range files {
if file.Path == match.Str {
filtered = append(filtered, file)
break
}
}
}
return filtered
}
// DirectoryPreviewMsg is sent when directory preview is ready
type DirectoryPreviewMsg struct {
dirName string
content string
}
// showDirectoryPreview shows a preview of directory contents in the summary pane
func (m *model) showDirectoryPreview(dirName string) tea.Cmd {
return func() tea.Msg {
// Construct full path to the directory
dirPath := filepath.Join(m.currentDir, dirName)
// Get directory contents
files, err := m.walker.ListDirectory(dirPath)
if err != nil {
return DirectoryPreviewMsg{
dirName: dirName,
content: fmt.Sprintf("📁 Directory: %s\n\nError reading directory: %v", dirName, err),
}
}
// Format directory contents for display
content := m.formatDirectoryPreview(dirName, files, dirPath)
return DirectoryPreviewMsg{
dirName: dirName,
content: content,
}
}
}
// formatDirectoryPreview formats directory contents for display
func (m model) formatDirectoryPreview(dirName string, files []utils.FileInfo, dirPath string) string {
var result strings.Builder
// Get relative path for display
relDirPath, _ := filepath.Rel(m.basePath, dirPath)
if relDirPath == "." {
relDirPath = "/"
} else {
relDirPath = "/" + relDirPath
}
result.WriteString(fmt.Sprintf("📁 Directory: %s\n", dirName))
result.WriteString(fmt.Sprintf("Path: %s\n\n", relDirPath))
// Filter out ".." entry for preview since it's just navigation
var previewFiles []utils.FileInfo
for _, file := range files {
if file.Path != ".." {
previewFiles = append(previewFiles, file)
}
}
if len(previewFiles) == 0 {
result.WriteString("📭 This directory is empty.\n\nPress Enter to navigate into this directory.")
return result.String()
}
// Count files and directories
fileCount := 0
dirCount := 0
for _, file := range previewFiles {
if file.IsDir {
dirCount++
} else {
fileCount++
}
}
result.WriteString(fmt.Sprintf("Contains: %d files", fileCount))
if dirCount > 0 {
result.WriteString(fmt.Sprintf(", %d directories", dirCount))
}
result.WriteString("\n\n")
// Show first several items
maxItems := 20
if len(previewFiles) > maxItems {
result.WriteString(fmt.Sprintf("First %d items:\n", maxItems))
} else {
result.WriteString("Contents:\n")
}
for i, file := range previewFiles {
if i >= maxItems {
break
}
// Get file icon
var icon string
if file.IsDir {
icon = "📁"
} else {
// Get file icon based on extension
icon = utils.GetFileIcon(file.Extension)
}
result.WriteString(fmt.Sprintf(" %s %s", icon, file.Path))
if file.IsDir {
result.WriteString("/")
}
result.WriteString("\n")
}
if len(previewFiles) > maxItems {
result.WriteString(fmt.Sprintf(" ... and %d more items\n", len(previewFiles)-maxItems))
}
result.WriteString("\nPress Enter to navigate into this directory.")
return result.String()
}
// handleFileSelection processes file selection and starts summarization if appropriate
func (m *model) handleFileSelection(selected *utils.FileInfo) tea.Cmd {
if selected == nil {
m.summaryModel.SetSummary(nil)
return nil
}
// Handle directory selection - show directory contents preview
if selected.IsDir {
if selected.Path == ".." {
// Show parent directory info
parentPath := filepath.Dir(m.currentDir)
relParentPath, _ := filepath.Rel(m.basePath, parentPath)
if relParentPath == "." {
relParentPath = "/"
} else {
relParentPath = "/" + relParentPath
}
m.summaryModel.SetSummary(nil)
m.summaryModel.SetContent(fmt.Sprintf("📁 Parent Directory\n\nPath: %s\n\nPress Enter to navigate up to this directory.", relParentPath))
return nil
} else {
// Show directory contents preview
return m.showDirectoryPreview(selected.Path)
}
}
// Handle file selection
fullPath := filepath.Join(m.currentDir, selected.Path)
if utils.IsSourceFile(selected.Path) || utils.IsExecutableFile(fullPath) {
// Start loading summary for the new selection
m.summaryModel.SetLoading(true)
// Create relative path for summarization
relPath, _ := filepath.Rel(m.basePath, fullPath)
return summarizeFileCmd(m.summarizer, relPath, selected.Path)
} else {
// Show a simple message for unsupported files
m.summaryModel.SetSummary(nil)
m.summaryModel.SetContent(fmt.Sprintf("File: %s\n\nThis file type is not supported for summarization.", selected.Path))
return nil
}
}
// sizeComponents updates component dimensions based on current window size
func (m model) sizeComponents() model {
if m.width <= 0 || m.height <= 0 {
return m
}
// Calculate available space accounting for header, borders and footer
availableWidth := m.width
availableHeight := m.height - headerHeight - footerHeight
// Each pane gets half the width minus minimal border space
paneWidth := (availableWidth / 2) - borderWidth
paneHeight := availableHeight - borderHeight
// Ensure minimum sizes
if paneWidth < 10 {
paneWidth = 10
}
if paneHeight < 5 {
paneHeight = 5
}
m.fileListModel.SetDimensions(paneWidth, paneHeight)
m.summaryModel.SetDimensions(paneWidth, paneHeight)
return m
}
func (m model) View() string {
// If we don't have valid dimensions yet, return a simple message
if m.width <= 0 || m.height <= 0 {
return "Initializing..."
}
// Calculate available space accounting for header, borders and footer
availableWidth := m.width
availableHeight := m.height - headerHeight - footerHeight
paneWidth := (availableWidth / 2) - borderWidth
paneHeight := availableHeight - borderHeight
// Ensure minimum sizes
if paneWidth < 10 {
paneWidth = 10
}
if paneHeight < 5 {
paneHeight = 5
}
// Define styles for the split panes
leftPaneStyle := lipgloss.NewStyle().
Width(paneWidth).
Height(paneHeight).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("62"))
rightPaneStyle := lipgloss.NewStyle().
Width(paneWidth).
Height(paneHeight).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("62"))
// Render file list
fileListView := m.fileListModel.View()
leftPane := leftPaneStyle.Render(fileListView)
// Render summary
summaryView := m.summaryModel.View()
rightPane := rightPaneStyle.Render(summaryView)
// Join the panes horizontally
content := lipgloss.JoinHorizontal(lipgloss.Top, leftPane, rightPane)
// Add current directory header
relCurrentDir, _ := filepath.Rel(m.basePath, m.currentDir)
if relCurrentDir == "." {
relCurrentDir = "/"
} else {
relCurrentDir = "/" + relCurrentDir
}
header := lipgloss.NewStyle().
Foreground(lipgloss.Color("86")).
Bold(true).
Render(fmt.Sprintf("📁 %s", relCurrentDir))
// Add footer with help text or search input
var footer string
if m.searchMode {
// Show search input
searchStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("86")).
Bold(true)
cursor := ""
if len(m.searchQuery)%2 == 0 { // Simple blinking cursor simulation
cursor = "█"
}
footer = searchStyle.Render(fmt.Sprintf("Search: %s%s", m.searchQuery, cursor)) +
lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render(" (ESC to cancel, Enter to confirm)")
} else {
// Show regular help
footer = lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
Render("↑/↓ navigate • Enter to open • / search • PgUp/PgDn scroll • t toggle dirs • r refresh • q quit")
}
return lipgloss.JoinVertical(lipgloss.Left, header, content, footer)
}
func initialModel(basePath string) model {
m := model{
fileListModel: ui.NewFileListModel(),
summaryModel: ui.NewSummaryModel(),
summarizer: core.NewSummarizer(basePath),
walker: utils.NewWalker(basePath),
basePath: basePath,
currentDir: basePath, // Start in the base directory
selectedPath: "",
width: 80, // Set reasonable default dimensions
height: 24,
// Initialize search state
searchMode: false,
searchQuery: "",
allFiles: make([]utils.FileInfo, 0),
filteredFiles: make([]utils.FileInfo, 0),
}
return m.sizeComponents()
}
// LoadFilesMsg is sent when files are loaded from disk
type LoadFilesMsg struct {
files []utils.FileInfo
}
// loadFilesCmd loads files from the specified directory
func loadFilesCmd(walker *utils.Walker, dirPath string) tea.Cmd {
return func() tea.Msg {
files, err := walker.ListDirectory(dirPath)
if err != nil {
// Return empty list on error
files = make([]utils.FileInfo, 0)
}
return LoadFilesMsg{files: files}
}
}
// summarizeFileCmd creates a summary for the specified file
func summarizeFileCmd(summarizer *core.Summarizer, filePath string, selectedPath string) tea.Cmd {
return func() tea.Msg {
summary := summarizer.SummarizeFile(filePath)
return SummaryMsg{summary: summary, path: filePath, selectedPath: selectedPath}
}
}
func main() {
// Set custom usage function to show comprehensive help
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: parsec [directory]
Navigate and summarize files in a terminal-based interface.
Examples:
parsec # Scan current directory
parsec C:\Projects # Scan C:\Projects (Windows)
parsec /home/user/code # Scan /home/user/code (Unix)
parsec "C:\Program Files" # Use quotes for paths with spaces
Parsec is a terminal-based file summarizer that provides:
- Split-screen interface with file navigation
- Multi-language source code analysis
- Markdown rendering with syntax highlighting
- Configuration file parsing
- Directory navigation with live preview
- Smart directory content inspection
Keyboard Controls:
↑/↓ or k/j Navigate file list
Enter Enter directory or open file
/ Start fuzzy search
PgUp/PgDn Scroll summary content
Home/End Jump to first/last file
t Toggle directory visibility
r Refresh current directory
q or Ctrl+C Quit
Search Mode:
Type Add characters to search query
Backspace Remove last character
Enter Confirm search and stay filtered
ESC Cancel search and show all files
`)
}
flag.Parse()
// Get directory from positional argument or use current directory
basePath := "."
if flag.NArg() > 0 {
basePath = flag.Arg(0)
}
// Convert to absolute path
absPath, err := filepath.Abs(basePath)
if err != nil {
fmt.Printf("Error getting absolute path: %v\n", err)
os.Exit(1)
}
// Check if path exists
if _, err := os.Stat(absPath); os.IsNotExist(err) {
fmt.Printf("Directory does not exist: %s\n", absPath)
os.Exit(1)
}
p := tea.NewProgram(initialModel(absPath), tea.WithAltScreen())
if _, err := p.Run(); err != nil {
fmt.Printf("Error running program: %v\n", err)
os.Exit(1)
}
}