/
parameter_git.go
100 lines (78 loc) · 1.92 KB
/
parameter_git.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
package config
import (
"context"
"errors"
"fmt"
"github.com/9seconds/chore/internal/git"
)
const ParameterGit = "git"
var ErrGitIncorrectRefType = errors.New("value does not conform an expected reference type")
type parameterGit struct {
baseParameter
repo *git.Repo
refTypes []git.RefType
}
func (p parameterGit) Type() string {
return ParameterGit
}
func (p parameterGit) Validate(_ context.Context, value string) error { //nolint: cyclop
refTypes := p.refTypes
if len(p.refTypes) == 0 {
if ok, err := p.repo.HasRevision(value); err != nil || ok {
return err
}
return ErrGitIncorrectRefType
}
for _, refType := range refTypes {
var validate func(string) (bool, error)
switch refType {
case git.RefTypeTag:
validate = p.repo.HasTag
case git.RefTypeBranch:
validate = p.repo.HasBranch
case git.RefTypeRemote:
validate = p.repo.HasRemote
case git.RefTypeNote:
validate = p.repo.HasNote
case git.RefTypeCommit:
validate = p.repo.HasCommit
default:
panic(fmt.Sprintf("unexpected reference type %v", refType))
}
if ok, err := validate(value); err != nil || ok {
return err
}
}
return ErrGitIncorrectRefType
}
func NewGit(
description string,
required bool,
spec map[string]string,
createRepo func() (*git.Repo, error),
) (Parameter, error) {
param := parameterGit{
baseParameter: baseParameter{
required: required,
description: description,
specification: spec,
},
}
refTypes := make(map[git.RefType]bool)
for _, value := range parseCSV(spec["type"]) {
refType, err := git.GetRefType(value)
if err != nil {
return nil, fmt.Errorf("incorrect value %s for 'type': %w", refType, err)
}
refTypes[refType] = true
}
for k := range refTypes {
param.refTypes = append(param.refTypes, k)
}
repo, err := createRepo()
if err != nil {
return nil, fmt.Errorf("cannot initialize repo: %w", err)
}
param.repo = repo
return param, nil
}