/
repository.go
88 lines (73 loc) · 2.14 KB
/
repository.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
package repository
import (
"fmt"
"strings"
"github.com/devon-mar/regexupdater/utils/envtag"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
)
const (
configStructTag = "cfg"
)
type Repository interface {
GetFile(path string) (File, error)
FindPR(string) (PullRequest, error)
UpdateFilePR(path string, oldSHA string, newContent []byte, commitMsg string, newBranch string, prTitle string, prBody string) (prID string, err error)
// Implementations can assume that pr is their own PR type.
ClosePR(pr PullRequest) error
AddPRComment(pr PullRequest, body string) error
RebasePR(pr PullRequest, path string, oldSHA string, newContent []byte, commitMsg string) error
// Return the name of the deleted branch.
DeletePRBranch(prID string) (string, error)
}
type File interface {
// May return nil.
Content() []byte
Path() string
SHA() string
}
type PullRequest interface {
ID() string
Body() string
IsOpen() bool
IsMergeable() bool
}
func NewRepository(typ string, cfg map[string]interface{}) (Repository, error) {
r, err := getRepository(typ, cfg)
if err != nil {
return nil, err
}
if v, ok := r.(interface{ init() error }); ok {
if err := v.init(); err != nil {
return nil, fmt.Errorf("error initializing repository: %w", err)
}
}
return r, nil
}
func Validate(typ string, cfg map[string]interface{}) error {
_, err := getRepository(typ, cfg)
return err
}
func getRepository(typ string, cfg map[string]interface{}) (Repository, error) {
var r Repository
switch typ {
case typeGitHub:
r = &GitHub{}
case typeGitea:
r = &Gitea{}
default:
return nil, fmt.Errorf("unsupported repository type %q", typ)
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{Result: r, ErrorUnused: true, TagName: configStructTag})
if err != nil {
return nil, fmt.Errorf("error initializing config decoder: %w", err)
}
if err = decoder.Decode(cfg); err != nil {
return nil, err
}
envtag.Unmarshal("cfg", "REPOSITORY_"+strings.ToUpper(typ)+"_", r)
if err := validator.New().Struct(r); err != nil {
return nil, fmt.Errorf("error validating %s repository config: %w", typ, err)
}
return r, nil
}