-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
main.go
75 lines (68 loc) · 1.58 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
package fmtcmd
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"time"
"github.com/a-h/templ/cmd/templ/processor"
parser "github.com/a-h/templ/parser/v2"
"github.com/natefinch/atomic"
)
const workerCount = 4
func Run(args []string) (err error) {
if len(args) > 0 {
return formatDir(args[0])
}
return formatStdin()
}
func formatStdin() (err error) {
var bytes []byte
bytes, err = io.ReadAll(os.Stdin)
if err != nil {
return
}
t, err := parser.ParseString(string(bytes))
if err != nil {
return fmt.Errorf("parsing error: %w", err)
}
err = t.Write(os.Stdout)
if err != nil {
return fmt.Errorf("formatting error: %w", err)
}
return nil
}
func formatDir(dir string) (err error) {
start := time.Now()
results := make(chan processor.Result)
go processor.Process(dir, format, workerCount, results)
var successCount, errorCount int
for r := range results {
if r.Error != nil {
err = errors.Join(err, fmt.Errorf("%s: %w", r.FileName, r.Error))
errorCount++
continue
}
fmt.Printf("%s complete in %v\n", r.FileName, r.Duration)
successCount++
}
fmt.Printf("Formatted %d templates with %d errors in %s\n", successCount+errorCount, errorCount, time.Since(start))
return
}
func format(fileName string) (err error) {
t, err := parser.Parse(fileName)
if err != nil {
return fmt.Errorf("%s parsing error: %w", fileName, err)
}
w := new(bytes.Buffer)
err = t.Write(w)
if err != nil {
return fmt.Errorf("%s formatting error: %w", fileName, err)
}
err = atomic.WriteFile(fileName, w)
if err != nil {
return fmt.Errorf("%s file write error: %w", fileName, err)
}
return
}