-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
template.go
112 lines (93 loc) · 2.29 KB
/
template.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
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
package template
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/fatih/color"
"github.com/mitchellh/go-homedir"
"github.com/sammcj/ingest/utils"
)
func SetupTemplate(templatePath string) (*template.Template, error) {
var templateContent string
var err error
if templatePath != "" {
templateContent, err = readTemplateFile(templatePath)
} else {
templateContent, err = getDefaultTemplate()
}
if err != nil {
return nil, fmt.Errorf("failed to read template: %w", err)
}
tmpl, err := template.New("default").Parse(templateContent)
if err != nil {
return nil, fmt.Errorf("failed to parse template: %w", err)
}
return tmpl, nil
}
func readTemplateFile(path string) (string, error) {
content, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(content), nil
}
func getDefaultTemplate() (string, error) {
// Check for user-specific template
home, err := homedir.Dir()
if err == nil {
userTemplateDir := filepath.Join(home, ".config", "ingest", "patterns", "templates")
userDefaultTemplate := filepath.Join(userTemplateDir, "default.tmpl")
if _, err := os.Stat(userDefaultTemplate); err == nil {
return readTemplateFile(userDefaultTemplate)
}
}
// If no user-specific template, use built-in template
return readEmbeddedTemplate()
}
func readEmbeddedTemplate() (string, error) {
return `
Source Trees:
{{.source_trees}}
{{range .files}}
{{if .Code}}
` + "`{{.Path}}:`" + `
{{.Code}}
{{end}}
{{end}}
{{range .git_data}}
{{if or .GitDiff .GitDiffBranch .GitLogBranch}}
Git Information for {{.Path}}:
{{if .GitDiff}}
Git Diff:
{{.GitDiff}}
{{end}}
{{if .GitDiffBranch}}
Git Diff Between Branches:
{{.GitDiffBranch}}
{{end}}
{{if .GitLogBranch}}
Git Log Between Branches:
{{.GitLogBranch}}
{{end}}
{{end}}
{{end}}
`, nil
}
func RenderTemplate(tmpl *template.Template, data map[string]interface{}) (string, error) {
var output strings.Builder
err := tmpl.Execute(&output, data)
if err != nil {
return "", fmt.Errorf("failed to render template: %w", err)
}
return output.String(), nil
}
func PrintDefaultTemplate() {
defaultTemplate, err := readEmbeddedTemplate()
if err != nil {
utils.PrintColouredMessage("!", fmt.Sprintf("Failed to get default template: %v", err), color.FgRed)
os.Exit(1)
}
fmt.Println(defaultTemplate)
}