-
Notifications
You must be signed in to change notification settings - Fork 83
/
template.go
98 lines (83 loc) · 2.39 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
package generate
import (
"bytes"
"embed"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
type langOpts struct {
detectionFile string
}
// I hate this part of the code so much.. but we are waiting for UBI images
// having >1.6 golang for integrated templates.
var languageDetection = map[string]langOpts{
"go": {
detectionFile: "go.mod",
},
"python": {
detectionFile: "setup.py",
},
"nodejs": {
detectionFile: "package.json",
},
"java": {
detectionFile: "pom.xml",
},
"generic": {},
}
//go:embed templates
var resource embed.FS
func (o *Opts) detectLanguage() (string, error) {
if o.language != "" {
if _, ok := languageDetection[o.language]; !ok {
return "", fmt.Errorf("no template available for %s", o.language)
}
return o.language, nil
}
cs := o.IOStreams.ColorScheme()
for t, v := range languageDetection {
if v.detectionFile == "" {
continue
}
fpath := filepath.Join(o.GitInfo.TopLevelPath, v.detectionFile)
if _, err := os.Stat(fpath); !os.IsNotExist(err) {
fmt.Fprintf(o.IOStreams.Out, "%s We have detected your repository using the programming language %s.\n",
cs.SuccessIcon(),
cs.Bold(cases.Title(language.Und, cases.NoLower).String(t)),
)
return t, nil
}
}
return "generic", nil
}
func (o *Opts) genTmpl() (*bytes.Buffer, error) {
lang, err := o.detectLanguage()
if err != nil {
return nil, err
}
embedfile, err := resource.Open(fmt.Sprintf("templates/%s.yaml", lang))
if err != nil {
log.Fatal(err)
}
defer embedfile.Close()
tmplB, _ := io.ReadAll(embedfile)
prName := filepath.Base(o.GitInfo.URL)
// if eventType has both the events [push, pull_request] then skip
// adding it to pipelinerun name
if !strings.Contains(o.Event.EventType, ",") {
prName = prName + "-" + strings.ReplaceAll(o.Event.EventType, "_", "-")
}
tmplB = bytes.ReplaceAll(tmplB, []byte("pipelinesascode.tekton.dev/on-event: \"pull_request\""),
[]byte(fmt.Sprintf("pipelinesascode.tekton.dev/on-event: \"[%s]\"", o.Event.EventType)))
tmplB = bytes.ReplaceAll(tmplB, []byte("pipelinesascode.tekton.dev/on-target-branch: \"main\""),
[]byte(fmt.Sprintf("pipelinesascode.tekton.dev/on-target-branch: \"[%s]\"", o.Event.BaseBranch)))
tmplB = bytes.ReplaceAll(tmplB, []byte(fmt.Sprintf("name: pipelinerun-%s", lang)),
[]byte(fmt.Sprintf("name: %s", prName)))
return bytes.NewBuffer(tmplB), nil
}