github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/pkg/projectfile/projectfield.go (about) 1 package projectfile 2 3 import ( 4 "fmt" 5 "net/url" 6 "os" 7 "regexp" 8 "strings" 9 10 "github.com/ActiveState/cli/internal/errs" 11 "github.com/ActiveState/cli/internal/locale" 12 ) 13 14 var projectFieldRE = regexp.MustCompile(`(?m:^project:["' ]*(https?:\/\/.*?)["' ]*$)`) 15 16 type projectField struct { 17 url *url.URL 18 } 19 20 func NewProjectField() *projectField { 21 return &projectField{} 22 } 23 24 func (p *projectField) LoadProject(rawProjectValue string) error { 25 pv := rawProjectValue 26 u, err := url.Parse(pv) 27 if err != nil { 28 return locale.NewInputError("err_project_url", "Invalid format for project field: {{.V0}}.", pv) 29 } 30 p.url = u 31 32 return nil 33 } 34 35 func (p *projectField) String() string { 36 return p.url.String() 37 } 38 39 func (p *projectField) SetNamespace(owner, name string) { 40 p.setPath(fmt.Sprintf("%s/%s", owner, name)) 41 } 42 43 func (p *projectField) SetBranch(branch string) { 44 p.setQuery("branch", branch) 45 } 46 47 func (p *projectField) SetLegacyCommitID(commitID string) { 48 p.setQuery("commitID", commitID) 49 } 50 51 func (p *projectField) setPath(path string) { 52 p.url.Path = path 53 p.url.RawPath = p.url.EscapedPath() 54 } 55 56 func (p *projectField) setQuery(key, value string) { 57 q := p.url.Query() 58 q.Set(key, value) 59 p.url.RawQuery = q.Encode() 60 } 61 62 func (p *projectField) Marshal() string { 63 return p.url.String() 64 } 65 66 func (p *projectField) Save(path string) error { 67 data, err := os.ReadFile(path) 68 if err != nil { 69 return errs.Wrap(err, "os.ReadFile %s failed", path) 70 } 71 72 projectValue := p.url.String() 73 out := projectFieldRE.ReplaceAll(data, []byte("project: "+projectValue)) 74 if !strings.Contains(string(out), projectValue) { 75 return locale.NewInputError("err_set_project") 76 } 77 78 if err := os.WriteFile(path, out, 0664); err != nil { 79 return errs.Wrap(err, "os.WriteFile %s failed", path) 80 } 81 82 return nil 83 }