-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathprojectfile.go
More file actions
1426 lines (1198 loc) · 40.6 KB
/
projectfile.go
File metadata and controls
1426 lines (1198 loc) · 40.6 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package projectfile
import (
"errors"
"fmt"
"net/url"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/ActiveState/cli/internal/assets"
"github.com/ActiveState/cli/internal/condition"
"github.com/ActiveState/cli/internal/config"
"github.com/ActiveState/cli/internal/constants"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/fileutils"
"github.com/ActiveState/cli/internal/hash"
"github.com/ActiveState/cli/internal/language"
"github.com/ActiveState/cli/internal/locale"
"github.com/ActiveState/cli/internal/logging"
"github.com/ActiveState/cli/internal/multilog"
"github.com/ActiveState/cli/internal/osutils"
"github.com/ActiveState/cli/internal/profile"
"github.com/ActiveState/cli/internal/rollbar"
"github.com/ActiveState/cli/internal/rtutils"
"github.com/ActiveState/cli/internal/sliceutils"
"github.com/ActiveState/cli/internal/strutils"
"github.com/ActiveState/cli/pkg/sysinfo"
"github.com/google/uuid"
"github.com/imdario/mergo"
"github.com/spf13/cast"
"github.com/thoas/go-funk"
"gopkg.in/yaml.v2"
)
var (
urlProjectRegexStr = `https:\/\/[\w\.]+\/([\w_.-]*)\/([\w_.-]*)(?:\?commitID=)*([^&]*)(?:\&branch=)*(.*)`
urlCommitRegexStr = `https:\/\/[\w\.]+\/commit\/(.*)`
// ProjectURLRe Regex used to validate project fields /orgname/projectname[?commitID=someUUID]
ProjectURLRe = regexp.MustCompile(urlProjectRegexStr)
// CommitURLRe Regex used to validate commit info /commit/someUUID
CommitURLRe = regexp.MustCompile(urlCommitRegexStr)
// deprecatedRegex covers the deprecated fields in the project file
deprecatedRegex = regexp.MustCompile(`(?m)^\s*(?:constraints|platforms|languages):`)
// nonAlphanumericRegex covers all non alphanumeric characters
nonAlphanumericRegex = regexp.MustCompile(`[^a-zA-Z0-9 ]+`)
)
const ConfigVersion = 1
type MigratorFunc func(project *Project, configVersion int) (int, error)
var migrationRunning bool
var migrator MigratorFunc
func RegisterMigrator(m MigratorFunc) {
migrator = m
}
type ErrorParseProject struct{ *locale.LocalizedError }
type ErrorNoProject struct{ *locale.LocalizedError }
type ErrorNoProjectFromEnv struct{ *locale.LocalizedError }
type ErrorNoDefaultProject struct{ *locale.LocalizedError }
// projectURL comprises all fields of a parsed project URL
type projectURL struct {
Owner string
Name string
LegacyCommitID string
BranchName string
}
const LocalProjectsConfigKey = "projects"
// VersionInfo is used in cases where we only care about parsing the version and channel fields.
// In all other cases the version is parsed via the Project struct
type VersionInfo struct {
Channel string `yaml:"branch"` // branch for backward compatibility
Version string
Lock string `yaml:"lock"`
}
// ProjectSimple reflects a bare basic project structure
type ProjectSimple struct {
Project string `yaml:"project"`
}
// Project covers the top level project structure of our yaml
type Project struct {
Project string `yaml:"project"`
ConfigVersion int `yaml:"config_version"`
Lock string `yaml:"lock,omitempty"`
Environments string `yaml:"environments,omitempty"`
Constants Constants `yaml:"constants,omitempty"`
Secrets *SecretScopes `yaml:"secrets,omitempty"`
Events Events `yaml:"events,omitempty"`
Scripts Scripts `yaml:"scripts,omitempty"`
Jobs Jobs `yaml:"jobs,omitempty"`
Private bool `yaml:"private,omitempty"`
Cache string `yaml:"cache,omitempty"`
Portable bool `yaml:"portable,omitempty"`
path string // "private"
parsedURL projectURL // parsed url data
parsedChannel string
parsedVersion string
}
// Build covers the build map, which can go under languages or packages
// Build can hold variable keys, so we cannot predict what they are, hence why it is a map
type Build map[string]string
// ConstantFields are the common fields for the Constant type. This is required
// for type composition related to its yaml.Unmarshaler implementation.
type ConstantFields struct {
Conditional Conditional `yaml:"if,omitempty"`
}
// Constant covers the constant structure, which goes under Project
type Constant struct {
NameVal `yaml:",inline"`
ConstantFields `yaml:",inline"`
}
func (c *Constant) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&c.NameVal); err != nil {
return err
}
if err := unmarshal(&c.ConstantFields); err != nil {
return err
}
return nil
}
var _ ConstrainedEntity = &Constant{}
// ID returns the constant name
func (c *Constant) ID() string {
return c.Name
}
func (c *Constant) ConditionalFilter() Conditional {
return c.Conditional
}
// Constants is a slice of constant values
type Constants []*Constant
// AsConstrainedEntities boxes constants as a slice ConstrainedEntities
func (constants Constants) AsConstrainedEntities() (items []ConstrainedEntity) {
for _, c := range constants {
items = append(items, c)
}
return items
}
// MakeConstantsFromConstrainedEntities unboxes ConstraintedEntities as Constants
func MakeConstantsFromConstrainedEntities(items []ConstrainedEntity) (constants []*Constant) {
constants = make([]*Constant, 0, len(items))
for _, v := range items {
if o, ok := v.(*Constant); ok {
constants = append(constants, o)
}
}
return constants
}
// SecretScopes holds secret scopes, scopes define what the secrets belong to
type SecretScopes struct {
User Secrets `yaml:"user,omitempty"`
Project Secrets `yaml:"project,omitempty"`
}
// Secret covers the variable structure, which goes under Project
type Secret struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Conditional Conditional `yaml:"if,omitempty"`
}
var _ ConstrainedEntity = &Secret{}
// ID returns the secret name
func (s *Secret) ID() string {
return s.Name
}
func (s *Secret) ConditionalFilter() Conditional {
return s.Conditional
}
// Secrets is a slice of Secret definitions
type Secrets []*Secret
// AsConstrainedEntities box Secrets as a slice of ConstrainedEntities
func (secrets Secrets) AsConstrainedEntities() (items []ConstrainedEntity) {
for _, s := range secrets {
items = append(items, s)
}
return items
}
// MakeSecretsFromConstrainedEntities unboxes ConstraintedEntities as Secrets
func MakeSecretsFromConstrainedEntities(items []ConstrainedEntity) (secrets []*Secret) {
secrets = make([]*Secret, 0, len(items))
for _, v := range items {
if o, ok := v.(*Secret); ok {
secrets = append(secrets, o)
}
}
return secrets
}
// Conditional is an `if` conditional that when evalutes to true enables the entity its under
// it is meant to replace Constraints
type Conditional string
// ConstrainedEntity is an entity in a project file that can be filtered with constraints
type ConstrainedEntity interface {
// ID returns the name of the entity
ID() string
ConditionalFilter() Conditional
}
// Package covers the package structure, which goes under the language struct
type Package struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
Conditional Conditional `yaml:"if,omitempty"`
Build Build `yaml:"build,omitempty"`
}
var _ ConstrainedEntity = Package{}
// ID returns the package name
func (p Package) ID() string {
return p.Name
}
func (p Package) ConditionalFilter() Conditional {
return p.Conditional
}
// Packages is a slice of Package configurations
type Packages []Package
// AsConstrainedEntities boxes Packages as a slice of ConstrainedEntities
func (packages Packages) AsConstrainedEntities() (items []ConstrainedEntity) {
for i := range packages {
items = append(items, &packages[i])
}
return items
}
// MakePackagesFromConstrainedEntities unboxes ConstraintedEntities as Packages
func MakePackagesFromConstrainedEntities(items []ConstrainedEntity) (packages []*Package) {
packages = make([]*Package, 0, len(items))
for _, v := range items {
if o, ok := v.(*Package); ok {
packages = append(packages, o)
}
}
return packages
}
// EventFields are the common fields for the Event type. This is required
// for type composition related to its yaml.Unmarshaler implementation.
type EventFields struct {
Scope []string `yaml:"scope"`
Conditional Conditional `yaml:"if,omitempty"`
id string
}
// Event covers the event structure, which goes under Project
type Event struct {
NameVal `yaml:",inline"`
EventFields `yaml:",inline"`
}
func (e *Event) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&e.NameVal); err != nil {
return err
}
if err := unmarshal(&e.EventFields); err != nil {
return err
}
return nil
}
var _ ConstrainedEntity = Event{}
// ID returns the event name
func (e Event) ID() string {
if e.id == "" {
id, err := uuid.NewUUID()
if err != nil {
multilog.Error("UUID generation failed, defaulting to serialization")
e.id = hash.ShortHash(e.Name, e.Value, strings.Join(e.Scope, ""))
} else {
e.id = id.String()
}
}
return e.id
}
func (e Event) ConditionalFilter() Conditional {
return e.Conditional
}
// Events is a slice of Event definitions
type Events []Event
// AsConstrainedEntities boxes events as a slice of ConstrainedEntities
func (events Events) AsConstrainedEntities() (items []ConstrainedEntity) {
for i := range events {
items = append(items, &events[i])
}
return items
}
// MakeEventsFromConstrainedEntities unboxes ConstraintedEntities as Events
func MakeEventsFromConstrainedEntities(items []ConstrainedEntity) (events []*Event) {
events = make([]*Event, 0, len(items))
for _, v := range items {
if o, ok := v.(*Event); ok {
events = append(events, o)
}
}
return events
}
// ScriptFields are the common fields for the Script type. This is required
// for type composition related to its yaml.Unmarshaler implementation.
type ScriptFields struct {
Description string `yaml:"description,omitempty"`
Filename string `yaml:"filename,omitempty"`
Standalone bool `yaml:"standalone,omitempty"`
Language string `yaml:"language,omitempty"`
Conditional Conditional `yaml:"if,omitempty"`
}
// Script covers the script structure, which goes under Project
type Script struct {
NameVal `yaml:",inline"`
ScriptFields `yaml:",inline"`
}
func (s *Script) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&s.NameVal); err != nil {
return err
}
if err := unmarshal(&s.ScriptFields); err != nil {
return err
}
return nil
}
var _ ConstrainedEntity = Script{}
// ID returns the script name
func (s Script) ID() string {
return s.Name
}
func (s Script) ConditionalFilter() Conditional {
return s.Conditional
}
// Scripts is a slice of scripts
type Scripts []Script
// AsConstrainedEntities boxes scripts as a slice of ConstrainedEntities
func (scripts Scripts) AsConstrainedEntities() (items []ConstrainedEntity) {
for i := range scripts {
items = append(items, &scripts[i])
}
return items
}
// MakeScriptsFromConstrainedEntities unboxes ConstraintedEntities as Scripts
func MakeScriptsFromConstrainedEntities(items []ConstrainedEntity) (scripts []*Script) {
scripts = make([]*Script, 0, len(items))
for _, v := range items {
if o, ok := v.(*Script); ok {
scripts = append(scripts, o)
}
}
return scripts
}
// Job covers the job structure, which goes under Project
type Job struct {
Name string `yaml:"name"`
Constants []string `yaml:"constants"`
Scripts []string `yaml:"scripts"`
}
// Jobs is a slice of jobs
type Jobs []Job
// Parse the given filepath, which should be the full path to an activestate.yaml file
func Parse(configFilepath string) (_ *Project, rerr error) {
projectDir := filepath.Dir(configFilepath)
files, err := os.ReadDir(projectDir)
if err != nil {
return nil, locale.WrapError(err, "err_project_readdir", "Could not read project directory: {{.V0}}.", projectDir)
}
project, err := parse(configFilepath)
if err != nil {
return nil, err
}
re, _ := regexp.Compile(`activestate[._-](\w+)\.yaml`)
for _, file := range files {
match := re.FindStringSubmatch(file.Name())
if len(match) == 0 {
continue
}
// If an OS keyword was used ensure it matches our runtime
l := strings.ToLower
keyword := l(match[1])
if (keyword == l(sysinfo.Linux.String()) || keyword == l(sysinfo.Mac.String()) || keyword == l(sysinfo.Windows.String())) &&
keyword != l(sysinfo.OS().String()) {
continue
}
secondaryProject, err := parse(filepath.Join(projectDir, file.Name()))
if err != nil {
return nil, err
}
if err := mergo.Merge(secondaryProject, *project, mergo.WithAppendSlice); err != nil {
return nil, errs.Wrap(err, "Could not merge %s into your activestate.yaml", file.Name())
}
secondaryProject.path = project.path // keep original project path, not secondary path
project = secondaryProject
}
if err = project.Init(); err != nil {
return nil, errs.Wrap(err, "project.Init failed")
}
cfg, err := config.New()
if err != nil {
return nil, errs.Wrap(err, "Could not read configuration required by projectfile parser.")
}
defer rtutils.Closer(cfg.Close, &rerr)
namespace := fmt.Sprintf("%s/%s", project.parsedURL.Owner, project.parsedURL.Name)
StoreProjectMapping(cfg, namespace, filepath.Dir(project.Path()))
// Migrate project file if needed
if !migrationRunning && project.ConfigVersion != ConfigVersion && migrator != nil {
// Migrations may themselves utilize the projectfile package, so we have to ensure we don't start an infinite loop
migrationRunning = true
defer func() { migrationRunning = false }()
if project.ConfigVersion > ConfigVersion {
return nil, locale.NewInputError("err_projectfile_version_too_high")
}
updatedConfigVersion, errMigrate := migrator(project, ConfigVersion)
// Ensure we update the config version regardless of any error that occurred, because we don't want to repeat
// the same version migrations
project.ConfigVersion = updatedConfigVersion
if err := NewYamlField("config_version", ConfigVersion).Save(project.Path()); err != nil {
return nil, errs.Pack(errMigrate, errs.Wrap(err, "Could not save config_version"))
}
if errMigrate != nil {
return nil, errs.Wrap(errMigrate, "Migrator failed")
}
}
return project, nil
}
// Init initializes the parsedURL field from the project url string
func (p *Project) Init() error {
parsedURL, err := p.parseURL()
if err != nil {
return locale.WrapInputError(err, "parse_project_file_url_err", "Could not parse project url: {{.V0}}.", p.Project)
}
p.parsedURL = parsedURL
// Ensure branch name is set
if p.parsedURL.Owner != "" && p.parsedURL.BranchName == "" {
logging.Debug("Appending default branch as none is set")
if err := p.SetBranch(constants.DefaultBranchName); err != nil {
return locale.WrapError(err, "err_set_default_branch", "", constants.DefaultBranchName)
}
}
if p.Lock != "" {
parsedLock, err := ParseLock(p.Lock)
if err != nil {
return errs.Wrap(err, "ParseLock %s failed", p.Lock)
}
p.parsedChannel = parsedLock.Channel
p.parsedVersion = parsedLock.Version
}
return nil
}
func parse(configFilepath string) (*Project, error) {
if !fileutils.FileExists(configFilepath) {
return nil, &ErrorNoProject{locale.NewInputError("err_no_projectfile")}
}
dat, err := os.ReadFile(configFilepath)
if err != nil {
return nil, errs.Wrap(err, "os.ReadFile %s failure", configFilepath)
}
return parseData(dat, configFilepath)
}
func parseData(dat []byte, configFilepath string) (*Project, error) {
if err := detectDeprecations(dat, configFilepath); err != nil {
return nil, errs.Wrap(err, "deprecations found")
}
project := Project{}
err2 := yaml.Unmarshal(dat, &project)
project.path = configFilepath
if err2 != nil {
return nil, &ErrorParseProject{locale.NewExternalError(
"err_project_parsed",
"Project file `{{.V1}}` could not be parsed. The parser produced the following error: {{.V0}}", err2.Error(), configFilepath),
}
}
return &project, nil
}
func detectDeprecations(dat []byte, configFilepath string) error {
deprecations := deprecatedRegex.FindAllIndex(dat, -1)
if len(deprecations) == 0 {
return nil
}
deplist := []string{}
for _, depIdxs := range deprecations {
dep := strings.TrimSpace(strings.TrimSuffix(string(dat[depIdxs[0]:depIdxs[1]]), ":"))
deplist = append(deplist, locale.Tr("pjfile_deprecation_entry", dep, strconv.Itoa(depIdxs[0])))
}
return &ErrorParseProject{locale.NewExternalError(
"pjfile_deprecation_msg",
"", configFilepath, strings.Join(deplist, "\n"), constants.DocumentationURL+"config/#deprecation"),
}
}
// URL returns the project namespace's string URL from activestate.yaml.
func (p *Project) URL() string {
return p.Project
}
// Owner returns the project namespace's organization
func (p *Project) Owner() string {
return p.parsedURL.Owner
}
// Name returns the project namespace's name
func (p *Project) Name() string {
return p.parsedURL.Name
}
// BranchName returns the branch name specified in the project
func (p *Project) BranchName() string {
return p.parsedURL.BranchName
}
// Path returns the project's activestate.yaml file path.
func (p *Project) Path() string {
return p.path
}
// LegacyCommitID is for use by legacy mechanics ONLY
// It returns a pre-migrated project's commit ID from activestate.yaml.
func (p *Project) LegacyCommitID() string {
return p.parsedURL.LegacyCommitID
}
// SetLegacyCommit sets the commit id within the current project file. This is done
// in-place so that line order is preserved.
func (p *Project) SetLegacyCommit(commitID string) error {
pf := NewProjectField()
if err := pf.LoadProject(p.Project); err != nil {
return errs.Wrap(err, "Could not load activestate.yaml")
}
pf.SetLegacyCommitID(commitID)
if err := pf.Save(p.path); err != nil {
return errs.Wrap(err, "Could not save activestate.yaml")
}
p.parsedURL.LegacyCommitID = commitID
p.Project = pf.String()
return nil
}
func (p *Project) Dir() string {
return filepath.Dir(p.path)
}
// SetPath sets the path of the project file and should generally only be used by tests
func (p *Project) SetPath(path string) {
p.path = path
}
// Channel returns the channel as it was interpreted from the lock
func (p *Project) Channel() string {
return p.parsedChannel
}
// Version returns the version as it was interpreted from the lock
func (p *Project) Version() string {
return p.parsedVersion
}
// ValidateProjectURL validates the configured project URL
func ValidateProjectURL(url string) error {
// Note: This line also matches headless commit URLs: match == {'commit', '<commit_id>'}
match := ProjectURLRe.FindStringSubmatch(url)
if len(match) < 3 {
return &ErrorParseProject{locale.NewError("err_bad_project_url")}
}
return nil
}
// Reload the project file from disk
func (p *Project) Reload() error {
pj, err := Parse(p.path)
if err != nil {
return err
}
*p = *pj
return nil
}
// Save the project to its activestate.yaml file
func (p *Project) Save(cfg ConfigGetter) error {
return p.save(cfg, p.Path())
}
// parseURL returns the parsed fields of a Project URL
func (p *Project) parseURL() (projectURL, error) {
return parseURL(p.Project)
}
func parseURL(rawURL string) (projectURL, error) {
p := projectURL{}
err := ValidateProjectURL(rawURL)
if err != nil {
return p, err
}
u, err := url.Parse(rawURL)
if err != nil {
return p, errs.Wrap(err, "Could not parse URL")
}
path := strings.Split(u.Path, "/")
if len(path) > 2 {
if path[1] == "commit" {
p.LegacyCommitID = path[2]
} else {
p.Owner = path[1]
p.Name = path[2]
}
}
q := u.Query()
if c := q.Get("commitID"); c != "" {
p.LegacyCommitID = c
}
if b := q.Get("branch"); b != "" {
p.BranchName = b
}
return p, nil
}
// Save the project to its activestate.yaml file
func (p *Project) save(cfg ConfigGetter, path string) error {
dat, err := yaml.Marshal(p)
if err != nil {
return errs.Wrap(err, "yaml.Marshal failed")
}
err = ValidateProjectURL(p.Project)
if err != nil {
return errs.Wrap(err, "ValidateProjectURL failed")
}
logging.Debug("Saving %s", path)
f, err := os.Create(path)
if err != nil {
return errs.Wrap(err, "os.Create %s failed", path)
}
defer f.Close()
_, err = f.Write([]byte(dat))
if err != nil {
return errs.Wrap(err, "f.Write %s failed", path)
}
if cfg != nil {
StoreProjectMapping(cfg, fmt.Sprintf("%s/%s", p.parsedURL.Owner, p.parsedURL.Name), filepath.Dir(p.Path()))
}
return nil
}
// SetNamespace updates the namespace in the project file
func (p *Project) SetNamespace(owner, project string) error {
pf := NewProjectField()
if err := pf.LoadProject(p.Project); err != nil {
return errs.Wrap(err, "Could not load activestate.yaml")
}
pf.SetNamespace(owner, project)
if err := pf.Save(p.path); err != nil {
return errs.Wrap(err, "Could not save activestate.yaml")
}
// keep parsed url components in sync
p.parsedURL.Owner = owner
p.parsedURL.Name = project
p.Project = pf.String()
return nil
}
// SetBranch sets the branch within the current project file. This is done
// in-place so that line order is preserved.
func (p *Project) SetBranch(branch string) error {
pf := NewProjectField()
if err := pf.LoadProject(p.Project); err != nil {
return errs.Wrap(err, "Could not load activestate.yaml")
}
pf.SetBranch(branch)
if !condition.InUnitTest() || p.path != "" {
if err := pf.Save(p.path); err != nil {
return errs.Wrap(err, "Could not save activestate.yaml")
}
}
p.parsedURL.BranchName = branch
p.Project = pf.String()
return nil
}
// GetProjectFilePath returns the path to the project activestate.yaml
// It considers projects in the following order:
// 1. Environment variable (e.g. `state shell` sets one)
// 2. Working directory (i.e. walk up directory tree looking for activestate.yaml)
// 3. Fall back on default project
func GetProjectFilePath() (string, error) {
defer profile.Measure("GetProjectFilePath", time.Now())
lookup := []func() (string, error){
getProjectFilePathFromEnv,
getProjectFilePathFromWd,
getProjectFilePathFromDefault,
}
for _, getProjectFilePath := range lookup {
path, err := getProjectFilePath()
if err != nil {
return "", errs.Wrap(err, "getProjectFilePath failed")
}
if path != "" {
return path, nil
}
}
return "", &ErrorNoProject{locale.NewInputError("err_no_projectfile")}
}
func getProjectFilePathFromEnv() (string, error) {
var projectFilePath string
if activatedProjectDirPath := os.Getenv(constants.ActivatedStateEnvVarName); activatedProjectDirPath != "" {
projectFilePath = filepath.Join(activatedProjectDirPath, constants.ConfigFileName)
}
if projectFilePath != "" {
if fileutils.FileExists(projectFilePath) {
return projectFilePath, nil
}
return "", &ErrorNoProjectFromEnv{locale.NewInputError("err_project_env_file_not_exist", "", projectFilePath)}
}
return "", nil
}
func getProjectFilePathFromWd() (string, error) {
root, err := osutils.Getwd()
if err != nil {
return "", errs.Wrap(err, "osutils.Getwd failed")
}
path, err := fileutils.FindFileInPath(root, constants.ConfigFileName)
if err != nil && !errors.Is(err, fileutils.ErrorFileNotFound) {
return "", errs.Wrap(err, "fileutils.FindFileInPath %s failed", root)
}
return path, nil
}
func getProjectFilePathFromDefault() (_ string, rerr error) {
cfg, err := config.New()
if err != nil {
return "", errs.Wrap(err, "Could not read configuration required to determine which project to use")
}
defer rtutils.Closer(cfg.Close, &rerr)
defaultProjectPath := cfg.GetString(constants.GlobalDefaultPrefname)
if defaultProjectPath == "" {
return "", nil
}
path, err := fileutils.FindFileInPath(defaultProjectPath, constants.ConfigFileName)
if err != nil {
if !errors.Is(err, fileutils.ErrorFileNotFound) {
return "", errs.Wrap(err, "fileutils.FindFileInPath %s failed", defaultProjectPath)
}
return "", &ErrorNoDefaultProject{locale.NewInputError("err_no_default_project", "Could not find your project at: [ACTIONABLE]{{.V0}}[/RESET]", defaultProjectPath)}
}
return path, nil
}
// FromEnv returns the project configuration based on environment information (env vars, cwd, etc)
func FromEnv() (*Project, error) {
// we do not want to use a path provided by state if we're running tests
projectFilePath, err := GetProjectFilePath()
if err != nil {
if errors.Is(err, fileutils.ErrorFileNotFound) {
return nil, &ErrorNoProject{locale.WrapError(err, "err_project_file_notfound", "Could not detect project file path.")}
}
return nil, err
}
project, err := Parse(projectFilePath)
if err != nil {
return nil, errs.Wrap(err, "Could not parse projectfile")
}
return project, nil
}
// FromPath will return the projectfile that's located at the given path (this will walk up the directory tree until it finds the project)
func FromPath(path string) (*Project, error) {
defer profile.Measure("projectfile:FromPath", time.Now())
// we do not want to use a path provided by state if we're running tests
projectFilePath, err := fileutils.FindFileInPath(path, constants.ConfigFileName)
if err != nil {
return nil, &ErrorNoProject{locale.WrapInputError(err, "err_project_not_found", "", path)}
}
_, err = os.ReadFile(projectFilePath)
if err != nil {
logging.Warning("Cannot load config file: %v", err)
return nil, &ErrorNoProject{locale.WrapInputError(err, "err_no_projectfile")}
}
project, err := Parse(projectFilePath)
if err != nil {
return nil, errs.Wrap(err, "Could not parse projectfile")
}
return project, nil
}
// FromExactPath will return the projectfile that's located at the given path without walking up the directory tree
func FromExactPath(path string) (*Project, error) {
// we do not want to use a path provided by state if we're running tests
projectFilePath := filepath.Join(path, constants.ConfigFileName)
if !fileutils.FileExists(projectFilePath) {
return nil, &ErrorNoProject{locale.NewInputError("err_no_projectfile")}
}
_, err := os.ReadFile(projectFilePath)
if err != nil {
logging.Warning("Cannot load config file: %v", err)
return nil, &ErrorNoProject{locale.WrapInputError(err, "err_no_projectfile")}
}
project, err := Parse(projectFilePath)
if err != nil {
return nil, errs.Wrap(err, "Could not parse projectfile")
}
return project, nil
}
// CreateParams are parameters that we create a custom activestate.yaml file from
type CreateParams struct {
Owner string
Project string
BranchName string
Directory string
Content string
Language string
Private bool
path string
ProjectURL string
Cache string
Portable bool
Host string
}
// Create will create a new activestate.yaml with a projectURL for the given details
func Create(params *CreateParams) (*Project, error) {
lang := language.MakeByName(params.Language)
err := validateCreateParams(params)
if err != nil {
return nil, err
}
return createCustom(params, lang)
}
func createCustom(params *CreateParams, lang language.Language) (*Project, error) {
err := fileutils.MkdirUnlessExists(params.Directory)
if err != nil {
return nil, err
}
if params.ProjectURL == "" {
// Note: cannot use api.GetPlatformURL() due to import cycle.
host := params.Host
if host == "" {
host = constants.DefaultAPIHost
}
u, err := url.Parse(fmt.Sprintf("https://%s/%s/%s", host, params.Owner, params.Project))
if err != nil {
return nil, errs.Wrap(err, "url parse new project url failed")
}
q := u.Query()
if params.BranchName != "" {
q.Set("branch", params.BranchName)
}
u.RawQuery = q.Encode()
params.ProjectURL = u.String()
}
params.path = filepath.Join(params.Directory, constants.ConfigFileName)
if fileutils.FileExists(params.path) {
return nil, locale.NewInputError("err_projectfile_exists")
}
err = ValidateProjectURL(params.ProjectURL)
if err != nil {
return nil, err
}
match := ProjectURLRe.FindStringSubmatch(params.ProjectURL)
if len(match) < 3 {
return nil, locale.NewInputError("err_projectfile_invalid_url")
}
owner, project := match[1], match[2]
shell := "bash"
if runtime.GOOS == "windows" {
shell = "batch"
}
languageDisabled := os.Getenv(constants.DisableLanguageTemplates) == "true"
content := params.Content
if !languageDisabled && content == "" && lang != language.Unset && lang != language.Unknown {
tplName := "activestate.yaml." + strings.TrimRight(lang.String(), "23") + ".tpl"
template, err := assets.ReadFileBytes(tplName)
if err != nil {
return nil, errs.Wrap(err, "Could not read asset")
}
content, err = strutils.ParseTemplate(
string(template),
map[string]interface{}{"Owner": owner, "Project": project, "Shell": shell, "Language": lang.String(), "LangExe": lang.Executable().Filename()},
nil)
if err != nil {
return nil, errs.Wrap(err, "Could not parse %s", tplName)
}
}