gitstack

grindlemire/go-tui code browser

4.3 KB Go 191 lines 2026-06-03 · d15bb9f raw
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
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

	"github.com/grindlemire/go-tui/internal/tuigen"
)

// runGenerate implements the generate subcommand.
// It processes .gsx files and generates corresponding Go source files.
func runGenerate(args []string) error {
	verbose := false
	var paths []string

	// Parse arguments
	for _, arg := range args {
		if arg == "-v" || arg == "--verbose" {
			verbose = true
		} else {
			paths = append(paths, arg)
		}
	}

	// Default to current directory if no paths specified
	if len(paths) == 0 {
		paths = []string{"."}
	}

	// Collect all .gsx files
	files, err := collectGsxFiles(paths)
	if err != nil {
		return err
	}

	if len(files) == 0 {
		return fmt.Errorf("no .gsx files found")
	}

	if verbose {
		fmt.Printf("Found %d .gsx file(s)\n", len(files))
	}

	// Process each file
	var errorCount int
	for _, inputPath := range files {
		outputPath := outputFileName(inputPath)

		if verbose {
			fmt.Printf("Processing %s -> %s\n", inputPath, outputPath)
		}

		if err := generateFile(inputPath, outputPath); err != nil {
			fmt.Fprintf(os.Stderr, "%s: %v\n", inputPath, err)
			errorCount++
			continue
		}
	}

	if errorCount > 0 {
		return fmt.Errorf("%d file(s) had errors", errorCount)
	}

	if verbose {
		fmt.Printf("Successfully generated %d file(s)\n", len(files))
	}

	return nil
}

// collectGsxFiles finds all .gsx files from the given paths.
// Supports:
//   - Direct file paths: "header.gsx"
//   - Directory paths: "./components"
//   - Recursive pattern: "./..."
func collectGsxFiles(paths []string) ([]string, error) {
	var files []string

	for _, path := range paths {
		// Handle ./... recursive pattern
		if before, ok := strings.CutSuffix(path, "/..."); ok {
			root := before
			if root == "." || root == "" {
				root = "."
			}

			err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
				if err != nil {
					return err
				}
				if !d.IsDir() && strings.HasSuffix(p, ".gsx") {
					files = append(files, p)
				}
				return nil
			})
			if err != nil {
				return nil, fmt.Errorf("walking %s: %w", root, err)
			}
			continue
		}

		// Check if path exists
		info, err := os.Stat(path)
		if err != nil {
			return nil, fmt.Errorf("stat %s: %w", path, err)
		}

		if info.IsDir() {
			// Collect all .gsx files in directory (non-recursive)
			entries, err := os.ReadDir(path)
			if err != nil {
				return nil, fmt.Errorf("reading directory %s: %w", path, err)
			}
			for _, entry := range entries {
				if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".gsx") {
					files = append(files, filepath.Join(path, entry.Name()))
				}
			}
		} else if strings.HasSuffix(path, ".gsx") {
			files = append(files, path)
		}
	}

	return files, nil
}

// outputFileName converts a .gsx filename to its output .go filename.
// Examples:
//
//	header.gsx     -> header_gsx.go
//	my-app.gsx     -> my_app_gsx.go
//	components.gsx -> components_gsx.go
func outputFileName(inputPath string) string {
	dir := filepath.Dir(inputPath)
	base := filepath.Base(inputPath)

	// Remove .gsx extension
	name := strings.TrimSuffix(base, ".gsx")

	// Replace hyphens with underscores (Go doesn't like hyphens in filenames)
	name = strings.ReplaceAll(name, "-", "_")

	// Add _gsx.go suffix
	output := name + "_gsx.go"

	return filepath.Join(dir, output)
}

// generateFile parses a .gsx file and generates the corresponding Go file.
func generateFile(inputPath, outputPath string) error {
	// Read source file
	source, err := os.ReadFile(inputPath)
	if err != nil {
		return fmt.Errorf("reading file: %w", err)
	}

	// Get just the filename for error messages and header comment
	filename := filepath.Base(inputPath)

	// Parse source
	lexer := tuigen.NewLexer(filename, string(source))
	parser := tuigen.NewParser(lexer)

	file, err := parser.ParseFile()
	if err != nil {
		return err
	}

	// Analyze (validates and adds missing imports)
	analyzer := tuigen.NewAnalyzer()
	if err := analyzer.Analyze(file); err != nil {
		return err
	}

	// Generate Go code
	generator := tuigen.NewGenerator()
	output, err := generator.Generate(file, filename)
	if err != nil {
		return fmt.Errorf("generating code: %w", err)
	}

	// Write output file
	if err := os.WriteFile(outputPath, output, 0o644); err != nil {
		return fmt.Errorf("writing file: %w", err)
	}

	return nil
}