-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm.txt
More file actions
596 lines (470 loc) 路 12.7 KB
/
Copy pathllm.txt
File metadata and controls
596 lines (470 loc) 路 12.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
# Ason - Project Scaffolding Tool
Ason is a powerful, lightweight project scaffolding tool written in Go that transforms templates into fully-formed projects. It provides both a CLI tool and a library API for programmatic template generation.
## Quick Start
### Installation
```bash
# macOS (Homebrew)
brew tap madstone-tech/tap
brew install ason
# Linux
curl -sL https://github.com/madstone-tech/ason/releases/latest/download/ason_Linux_x86_64.tar.gz | tar xz
sudo mv ason /usr/local/bin/
# Go
go install github.com/madstone-tech/ason@latest
```
### Version
```bash
ason --version
```
## CLI Commands
### Create Projects
```bash
# From registered template
ason new <template-name> <output-directory>
ason new golang-service my-service
# From local directory
ason new ./my-template ./output
# With variables
ason new golang-service my-service --var name=MyService --var author=Alice
# Dry run (preview without writing)
ason new golang-service my-service --dry-run
```
### Template Registry Management
```bash
# Register a template
ason register <name> <path> [--description "Description"]
ason register golang-service ~/templates/golang-service
# List registered templates
ason list
# List in JSON format
ason list --format json
# Remove a template
ason remove <name>
ason remove golang-service
# Validate a template
ason validate <path>
ason validate ~/templates/golang-service
```
### Help
```bash
ason --help
ason new --help
ason register --help
```
## Using Ason as a Library
### Installation
```bash
go get github.com/madstone-tech/ason
```
Import in your code:
```go
import "github.com/madstone-tech/ason/pkg"
```
### Generator API
Generate projects programmatically with context support for cancellation and timeouts.
#### Create a Generator
```go
package main
import (
"context"
"log"
"time"
"github.com/madstone-tech/ason/pkg"
)
func main() {
// Create with default Pongo2 engine
engine := pkg.NewDefaultEngine()
gen, err := pkg.NewGenerator(engine)
if err != nil {
log.Fatal(err)
}
// Define template variables
variables := map[string]interface{}{
"project_name": "my-app",
"author": "Alice",
"version": "1.0.0",
}
// Generate project with 5 second timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = gen.Generate(ctx, "./template", variables, "./output")
if err != nil {
log.Fatal(err)
}
println("Project generated successfully")
}
```
#### Methods
- `NewGenerator(engine Engine) (*Generator, error)` - Create new generator
- `Generate(ctx context.Context, templatePath string, variables map[string]interface{}, outputPath string) error` - Generate project
- `GetEngine() Engine` - Get the configured engine
### Registry API
Manage template registry with XDG-compliant storage.
```go
package main
import (
"log"
"github.com/madstone-tech/ason/pkg"
)
func main() {
// Use default XDG location (~/.local/share/ason/registry.toml)
reg, err := pkg.NewRegistry()
if err != nil {
log.Fatal(err)
}
// Register a template (path must exist)
err = reg.Register("golang_service", "/path/to/template", "Go microservice")
if err != nil {
log.Fatal(err)
}
// List all templates (alphabetically sorted)
templates, err := reg.List()
if err != nil {
log.Fatal(err)
}
for _, t := range templates {
println(t.Name, t.Path, t.Description)
}
// Remove a template (safe to call multiple times)
err = reg.Remove("golang_service")
if err != nil {
log.Fatal(err)
}
}
```
#### Methods
- `NewRegistry() (*Registry, error)` - Use default XDG location
- `NewRegistryAt(path string) (*Registry, error)` - Custom registry location
- `Register(name, templatePath, description string) error` - Register template
- `List() ([]TemplateInfo, error)` - List all templates (sorted)
- `Remove(name string) error` - Remove template (idempotent)
#### Types
```go
type TemplateInfo struct {
Name string // Template name
Path string // Template path
Created time.Time // Registration time
Description string // Template description
}
```
### Engine API
Implement custom template engines or use the default Pongo2 engine.
#### Using Default Engine
```go
package main
import (
"context"
"log"
"time"
"github.com/madstone-tech/ason/pkg"
)
func main() {
engine := pkg.NewDefaultEngine()
// Render template string
output, err := engine.Render("Hello {{ name }}",
map[string]interface{}{"name": "World"})
if err != nil {
log.Fatal(err)
}
println(output) // "Hello World"
// Render template file
output, err = engine.RenderFile("/path/to/template.txt",
map[string]interface{}{"project": "MyApp"})
if err != nil {
log.Fatal(err)
}
println(output)
// With context (cancellation/timeout)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
output, err = pkg.RenderWithEngine(ctx, engine, "template", nil)
}
```
#### Engine Interface
```go
type Engine interface {
Render(template string, context map[string]interface{}) (string, error)
RenderFile(filePath string, context map[string]interface{}) (string, error)
}
func NewDefaultEngine() Engine
func RenderWithEngine(ctx context.Context, engine Engine,
template string, context map[string]interface{}) (string, error)
```
#### Implementing Custom Engine
```go
package main
import (
"fmt"
"strings"
"github.com/madstone-tech/ason/pkg"
"context"
)
// MyCustomEngine implements pkg.Engine
type MyCustomEngine struct{}
func (e *MyCustomEngine) Render(template string,
context map[string]interface{}) (string, error) {
// Your custom template rendering logic
// Must be thread-safe
return template, nil
}
func (e *MyCustomEngine) RenderFile(filePath string,
context map[string]interface{}) (string, error) {
// Your custom file rendering logic
// Must be thread-safe
return "", nil
}
// SimpleEngine example - basic variable replacement
type SimpleEngine struct{}
func (e *SimpleEngine) Render(template string,
context map[string]interface{}) (string, error) {
result := template
for key, value := range context {
placeholder := "{{" + key + "}}"
result = strings.ReplaceAll(result, placeholder,
fmt.Sprintf("%v", value))
}
return result, nil
}
func (e *SimpleEngine) RenderFile(filePath string,
context map[string]interface{}) (string, error) {
return "", nil
}
func main() {
engine := &MyCustomEngine{}
gen, _ := pkg.NewGenerator(engine)
gen.Generate(context.Background(), "./template", nil, "./output")
}
```
## Template Syntax (Pongo2)
Ason uses Pongo2, a Jinja2-like template engine.
### Variables
```
Hello {{ name }}
```
### Filters
```
{{ name|upper }}
{{ price|floatformat:2 }}
{{ date|date:"Y-m-d" }}
```
### Loops
```
{% for item in items %}
- {{ item }}
{% endfor %}
```
### Conditionals
```
{% if user.is_admin %}
Admin panel
{% else %}
User panel
{% endif %}
```
### Template Inheritance
```
{% extends "base.html" %}
{% block content %}
...
{% endblock %}
```
### Includes
```
{% include "header.html" %}
```
## Error Handling
The library exports specific error types:
```go
package main
import (
"errors"
"log"
"context"
"github.com/madstone-tech/ason/pkg"
)
func main() {
gen, err := pkg.NewGenerator(nil)
if err != nil {
log.Printf("Error: %v", err)
}
// Error type checking with errors.Is
if errors.Is(err, context.Canceled) {
log.Println("Generation was cancelled")
}
if errors.Is(err, context.DeadlineExceeded) {
log.Println("Generation timeout")
}
// Error unwrapping with errors.Unwrap
unwrapped := errors.Unwrap(err)
log.Printf("Underlying error: %v", unwrapped)
}
```
Error Types:
- `context.Canceled` - Operation was cancelled
- `context.DeadlineExceeded` - Context timeout
- `*InvalidArgumentError` - Invalid input (nil engine, bad variable names)
- `*InvalidPathError` - Path traversal or invalid path
- `*VariableValidationError` - Bad variable names/values
- `*GenerationError` - Template rendering failed
- `*EngineError` - Engine-specific failure
## Configuration
### Registry Location
- Default: `~/.local/share/ason/registry.toml`
- Custom: `NewRegistryAt("/custom/path")`
The registry stores:
- Template names (must be valid Go identifiers)
- Template paths (must exist on filesystem)
- Creation timestamps
- Descriptions
### Template Names
Must be valid Go identifiers:
- Valid: `my_template`, `golang_service`, `asonApp`
- Invalid: `my-template` (hyphens), `123app` (starts with number)
## Thread Safety
### Generator
- Thread-safe with RWMutex protection
- Multiple concurrent reads allowed
- Safe for concurrent goroutines
### Registry
- Multiple concurrent reads allowed
- Writes are serialized (mutex-protected)
- Safe for concurrent goroutines
### Engine
- Must be thread-safe (implementation dependent)
- Default Pongo2 engine is thread-safe
- Custom engines must implement thread safety
## Performance
- Lightweight with minimal dependencies
- Fast binary (~20MB)
- Supports large projects
- Efficient template rendering with Pongo2
- Atomic file operations for reliability
## Examples
### Example 1: CLI - Generate from Template
```bash
# Create a template
mkdir -p ~/templates/react-app
echo '# {{ project_name }}' > ~/templates/react-app/README.md.tmpl
echo 'Author: {{ author }}' >> ~/templates/react-app/README.md.tmpl
# Register template
ason register react_app ~/templates/react-app
# Generate project
ason new react_app my-app --var project_name=MyApp --var author=Alice
# View generated file
cat my-app/README.md
```
### Example 2: Library - Programmatic Generation
```go
package main
import (
"context"
"log"
"github.com/madstone-tech/ason/pkg"
)
func main() {
engine := pkg.NewDefaultEngine()
gen, _ := pkg.NewGenerator(engine)
variables := map[string]interface{}{
"project_name": "MyApp",
"author": "Alice",
"version": "1.0.0",
}
ctx := context.Background()
err := gen.Generate(ctx, "./template", variables, "./output")
if err != nil {
log.Fatal(err)
}
println("Generated successfully")
}
```
### Example 3: Registry Management
```go
package main
import (
"log"
"github.com/madstone-tech/ason/pkg"
)
func main() {
// Create registry at custom location
reg, _ := pkg.NewRegistryAt("/tmp/my-registry.toml")
// Register multiple templates
reg.Register("api_service", "/templates/api", "API service template")
reg.Register("web_app", "/templates/web", "Web app template")
// List templates
templates, _ := reg.List()
for _, t := range templates {
println(t.Name)
}
}
```
## Testing
### Run Official Tests
```bash
go test ./tests -v
```
### Run Demo Application
```bash
go run examples/test_library.go
```
### Run Race Detection
```bash
go test -race ./tests -v
```
## Documentation
- CLI Help: `ason --help`
- Testing Guide: `docs/TESTING_GUIDE.md`
- Engine Interface: `docs/api/engine_interface.md`
- Examples: `examples/test_library.go`
- Changelog: `CHANGELOG.md`
## Support
### Registry Issues
- Template names must be valid Go identifiers (no hyphens)
- Paths must exist on filesystem
- Default location: `~/.local/share/ason/registry.toml`
### Generation Issues
- Check template syntax with `ason validate <path>`
- Ensure variables match template placeholders
- Use `--dry-run` to preview without writing
### Context/Timeout Issues
- Use `context.WithTimeout()` for deadlines
- Use `context.WithCancel()` for manual cancellation
- Check `context.Canceled` and `context.DeadlineExceeded` errors
## Architecture
### CLI Tools
- `ason new` - Generate projects
- `ason register` - Register templates
- `ason list` - List registered templates
- `ason remove` - Remove templates
- `ason validate` - Validate templates
- `ason completion` - Shell autocompletion
### Library Components
- **Generator** (pkg/generator.go) - Project generation with context support
- **Registry** (pkg/registry.go) - XDG-compliant template management
- **Engine** (pkg/engine.go) - Pluggable template rendering interface
- **Error Types** - Comprehensive error handling with Unwrap support
- **Validation** - Input validation and security checks
### Internal Packages
- `internal/engine` - Pongo2 template engine implementation
- `internal/registry` - Registry persistence layer
- `internal/template` - Template configuration handling
- `internal/validation` - Input validation utilities
- `internal/security` - Path safety and traversal prevention
- `internal/xdg` - XDG Base Directory Specification support
## Requirements
- Go 1.21+
- Linux, macOS, or Windows
- No external CLI dependencies
## Compatibility
- Backward compatible with v0.2.x CLI
- Zero breaking changes in v0.3.0
- CLI tools unchanged and fully functional
- All existing templates continue to work
## Version
v0.3.0 - Library Export Release
## License
MIT
## Links
- Repository: https://github.com/madstone-tech/ason
- Releases: https://github.com/madstone-tech/ason/releases
- Issues: https://github.com/madstone-tech/ason/issues
- Changelog: CHANGELOG.md