-
Notifications
You must be signed in to change notification settings - Fork 13
/
projectfield.go
83 lines (65 loc) · 1.73 KB
/
projectfield.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
package projectfile
import (
"fmt"
"net/url"
"os"
"regexp"
"strings"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/locale"
)
var projectFieldRE = regexp.MustCompile(`(?m:^project:["' ]*(https?:\/\/.*?)["' ]*$)`)
type projectField struct {
url *url.URL
}
func NewProjectField() *projectField {
return &projectField{}
}
func (p *projectField) LoadProject(rawProjectValue string) error {
pv := rawProjectValue
u, err := url.Parse(pv)
if err != nil {
return locale.NewInputError("err_project_url", "Invalid format for project field: {{.V0}}.", pv)
}
p.url = u
return nil
}
func (p *projectField) String() string {
return p.url.String()
}
func (p *projectField) SetNamespace(owner, name string) {
p.setPath(fmt.Sprintf("%s/%s", owner, name))
}
func (p *projectField) SetBranch(branch string) {
p.setQuery("branch", branch)
}
func (p *projectField) SetLegacyCommitID(commitID string) {
p.setQuery("commitID", commitID)
}
func (p *projectField) setPath(path string) {
p.url.Path = path
p.url.RawPath = p.url.EscapedPath()
}
func (p *projectField) setQuery(key, value string) {
q := p.url.Query()
q.Set(key, value)
p.url.RawQuery = q.Encode()
}
func (p *projectField) Marshal() string {
return p.url.String()
}
func (p *projectField) Save(path string) error {
data, err := os.ReadFile(path)
if err != nil {
return errs.Wrap(err, "os.ReadFile %s failed", path)
}
projectValue := p.url.String()
out := projectFieldRE.ReplaceAll(data, []byte("project: "+projectValue))
if !strings.Contains(string(out), projectValue) {
return locale.NewInputError("err_set_project")
}
if err := os.WriteFile(path, out, 0664); err != nil {
return errs.Wrap(err, "os.WriteFile %s failed", path)
}
return nil
}