-
Notifications
You must be signed in to change notification settings - Fork 232
/
orb.go
1544 lines (1303 loc) · 42.5 KB
/
orb.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
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 cmd
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/CircleCI-Public/circleci-cli/api"
"github.com/CircleCI-Public/circleci-cli/api/graphql"
"github.com/CircleCI-Public/circleci-cli/filetree"
"github.com/CircleCI-Public/circleci-cli/process"
"github.com/CircleCI-Public/circleci-cli/prompt"
"github.com/CircleCI-Public/circleci-cli/references"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/version"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/AlecAivazis/survey/v2"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
)
type orbOptions struct {
cfg *settings.Config
cl *graphql.Client
args []string
listUncertified bool
listJSON bool
listDetails bool
private bool
sortBy string
// Allows user to skip y/n confirm when creating an orb
noPrompt bool
// This lets us pass in our own interface for testing
tty createOrbUserInterface
// Linked with --integration-testing flag for stubbing UI in gexec tests
integrationTesting bool
}
var orbAnnotations = map[string]string{
"<path>": "The path to your orb (use \"-\" for STDIN)",
"<namespace>": "The namespace used for the orb (i.e. circleci)",
"<orb>": "A fully-qualified reference to an orb. This takes the form namespace/orb@version",
}
type createOrbUserInterface interface {
askUserToConfirm(message string) bool
}
type createOrbInteractiveUI struct{}
func (createOrbInteractiveUI) askUserToConfirm(message string) bool {
return prompt.AskUserToConfirm(message)
}
type createOrbTestUI struct {
confirm bool
}
type orbProtectTemplateRelease struct {
ZipUrl string `json:"zipball_url"`
}
func (ui createOrbTestUI) askUserToConfirm(message string) bool {
fmt.Println(message)
return ui.confirm
}
func newOrbCommand(config *settings.Config) *cobra.Command {
opts := orbOptions{
cfg: config,
tty: createOrbInteractiveUI{},
}
listCommand := &cobra.Command{
Use: "list <namespace>",
Short: "List orbs",
Args: cobra.MaximumNArgs(1),
RunE: func(_ *cobra.Command, _ []string) error {
return listOrbs(opts)
},
Annotations: make(map[string]string),
}
listCommand.Annotations["<namespace>"] = orbAnnotations["<namespace>"] + " (Optional)"
listCommand.PersistentFlags().StringVar(&opts.sortBy, "sort", "", `one of "builds"|"projects"|"orgs"`)
listCommand.PersistentFlags().BoolVarP(&opts.listUncertified, "uncertified", "u", false, "include uncertified orbs")
listCommand.PersistentFlags().BoolVar(&opts.listJSON, "json", false, "print output as json instead of human-readable")
listCommand.PersistentFlags().BoolVarP(&opts.listDetails, "details", "d", false, "output all the commands, executors, and jobs, along with a tree of their parameters")
listCommand.PersistentFlags().BoolVarP(&opts.private, "private", "", false, "exclusively list private orbs within a namespace")
if err := listCommand.PersistentFlags().MarkHidden("json"); err != nil {
panic(err)
}
validateCommand := &cobra.Command{
Use: "validate <path>",
Short: "Validate an orb.yml",
RunE: func(_ *cobra.Command, _ []string) error {
return validateOrb(opts)
},
Args: cobra.ExactArgs(1),
Annotations: make(map[string]string),
}
validateCommand.Annotations["<path>"] = orbAnnotations["<path>"]
processCommand := &cobra.Command{
Use: "process <path>",
Short: "Validate an orb and print its form after all pre-registration processing",
Long: strings.Join([]string{
"Use `$ circleci orb process` to resolve an orb, and it's dependencies to see how it would be expanded when you publish it to the registry.",
"", // purposeful new-line
"This can be helpful for validating an orb and debugging the processed form before publishing.",
}, "\n"),
PreRun: func(cmd *cobra.Command, args []string) {
opts.args = args
opts.cl = graphql.NewClient(config.HTTPClient, config.Host, config.Endpoint, config.Token, config.Debug)
},
RunE: func(_ *cobra.Command, _ []string) error {
return processOrb(opts)
},
Args: cobra.ExactArgs(1),
Annotations: make(map[string]string),
}
processCommand.Example = ` circleci orb process src/my-orb/@orb.yml`
processCommand.Annotations["<path>"] = orbAnnotations["<path>"]
publishCommand := &cobra.Command{
Use: "publish <path> <orb>",
Short: "Publish an orb to the registry",
Long: `Publish an orb to the registry.
Please note that at this time all orbs published to the registry are world-readable.`,
RunE: func(_ *cobra.Command, _ []string) error {
return publishOrb(opts)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateToken(opts.cfg)
},
Args: cobra.ExactArgs(2),
Annotations: make(map[string]string),
}
publishCommand.Annotations["<orb>"] = orbAnnotations["<orb>"]
publishCommand.Annotations["<path>"] = orbAnnotations["<path>"]
promoteCommand := &cobra.Command{
Use: "promote <orb> <segment>",
Short: "Promote a development version of an orb to a semantic release",
Long: `Promote a development version of an orb to a semantic release.
Please note that at this time all orbs promoted within the registry are world-readable.
Example: 'circleci orb publish promote foo/bar@dev:master major' => foo/bar@1.0.0`,
RunE: func(_ *cobra.Command, _ []string) error {
return promoteOrb(opts)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateToken(opts.cfg)
},
Args: cobra.ExactArgs(2),
Annotations: make(map[string]string),
}
promoteCommand.Annotations["<orb>"] = orbAnnotations["<orb>"]
promoteCommand.Annotations["<segment>"] = `"major"|"minor"|"patch"`
incrementCommand := &cobra.Command{
Use: "increment <path> <namespace>/<orb> <segment>",
Short: "Increment a released version of an orb",
Long: `Increment a released version of an orb.
Please note that at this time all orbs incremented within the registry are world-readable.
Example: 'circleci orb publish increment foo/orb.yml foo/bar minor' => foo/bar@1.1.0`,
RunE: func(_ *cobra.Command, _ []string) error {
return incrementOrb(opts)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateToken(opts.cfg)
},
Args: cobra.ExactArgs(3),
Annotations: make(map[string]string),
Aliases: []string{"inc"},
}
incrementCommand.Annotations["<path>"] = orbAnnotations["<path>"]
incrementCommand.Annotations["<segment>"] = `"major"|"minor"|"patch"`
publishCommand.AddCommand(promoteCommand)
publishCommand.AddCommand(incrementCommand)
unlistCmd := &cobra.Command{
Use: "unlist <namespace>/<orb> <true|false>",
Short: "Disable or enable an orb's listing in the registry",
Long: `Disable or enable an orb's listing in the registry.
This only affects whether the orb is displayed in registry search results;
the orb remains world-readable as long as referenced with a valid name.
Example: Run 'circleci orb unlist foo/bar true' to disable the listing of the
orb in the registry and 'circleci orb unlist foo/bar false' to re-enable the
listing of the orb in the registry.`,
RunE: func(_ *cobra.Command, _ []string) error {
return setOrbListStatus(opts)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateToken(opts.cfg)
},
Args: cobra.ExactArgs(2),
}
sourceCommand := &cobra.Command{
Use: "source <orb>",
Short: "Show the source of an orb",
RunE: func(_ *cobra.Command, _ []string) error {
return showSource(opts)
},
Args: cobra.ExactArgs(1),
Annotations: make(map[string]string),
}
sourceCommand.Annotations["<orb>"] = orbAnnotations["<orb>"]
sourceCommand.Example = ` circleci orb source circleci/python@0.1.4 # grab the source at version 0.1.4
circleci orb source my-ns/foo-orb@dev:latest # grab the source of dev release "latest"`
orbInfoCmd := &cobra.Command{
Use: "info <orb>",
Short: "Show the meta-data of an orb",
RunE: func(_ *cobra.Command, _ []string) error {
return orbInfo(opts)
},
Args: cobra.ExactArgs(1),
Annotations: make(map[string]string),
}
orbInfoCmd.Annotations["<orb>"] = orbAnnotations["<orb>"]
orbInfoCmd.Example = ` circleci orb info circleci/python@0.1.4
circleci orb info my-ns/foo-orb@dev:latest`
orbCreate := &cobra.Command{
Use: "create <namespace>/<orb>",
Short: "Create an orb in the specified namespace",
Long: `Create an orb in the specified namespace
Please note that at this time all orbs created in the registry are world-readable unless set as private using the optional flag.`,
RunE: func(_ *cobra.Command, _ []string) error {
if opts.integrationTesting {
opts.tty = createOrbTestUI{
confirm: true,
}
}
return createOrb(opts)
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateToken(opts.cfg)
},
Args: cobra.ExactArgs(1),
}
orbCreate.PersistentFlags().BoolVarP(&opts.private, "private", "", false, "Specify that this orb is for private use within your org, unlisted from the public registry.")
orbPack := &cobra.Command{
Use: "pack <path>",
Short: "Pack an Orb with local scripts.",
Long: ``,
RunE: func(_ *cobra.Command, _ []string) error {
return packOrbCommand(opts)
},
Args: cobra.ExactArgs(1),
}
listCategoriesCommand := &cobra.Command{
Use: "list-categories",
Short: "List orb categories",
Args: cobra.ExactArgs(0),
RunE: func(_ *cobra.Command, _ []string) error {
return listOrbCategories(opts)
},
}
listCategoriesCommand.PersistentFlags().BoolVar(&opts.listJSON, "json", false, "print output as json instead of human-readable")
if err := listCategoriesCommand.PersistentFlags().MarkHidden("json"); err != nil {
panic(err)
}
addCategorizationToOrbCommand := &cobra.Command{
Use: "add-to-category <namespace>/<orb> \"<category-name>\"",
Short: "Add an orb to a category",
Args: cobra.ExactArgs(2),
RunE: func(_ *cobra.Command, _ []string) error {
return addOrRemoveOrbCategorization(opts, api.Add)
},
}
removeCategorizationFromOrbCommand := &cobra.Command{
Use: "remove-from-category <namespace>/<orb> \"<category-name>\"",
Short: "Remove an orb from a category",
Args: cobra.ExactArgs(2),
RunE: func(_ *cobra.Command, _ []string) error {
return addOrRemoveOrbCategorization(opts, api.Remove)
},
}
orbInit := &cobra.Command{
Use: "init <path>",
Short: "Initialize a new orb.",
Long: ``,
RunE: func(_ *cobra.Command, _ []string) error {
return initOrb(opts)
},
Args: cobra.ExactArgs(1),
}
orbInit.PersistentFlags().BoolVarP(&opts.private, "private", "", false, "initialize a private orb")
orbCreate.Flags().BoolVar(&opts.integrationTesting, "integration-testing", false, "Enable test mode to bypass interactive UI.")
if err := orbCreate.Flags().MarkHidden("integration-testing"); err != nil {
panic(err)
}
orbCreate.Flags().BoolVar(&opts.noPrompt, "no-prompt", false, "Disable prompt to bypass interactive UI.")
orbCommand := &cobra.Command{
Use: "orb",
Short: "Operate on orbs",
Long: orbHelpLong(config),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
opts.args = args
opts.cl = graphql.NewClient(config.HTTPClient, config.Host, config.Endpoint, config.Token, config.Debug)
// PersistentPreRunE overwrites the inherited persistent hook from rootCmd
// So we explicitly call it here to retain that behavior.
// As of writing this comment, that is only for daily update checks.
return rootCmdPreRun(rootOptions)
},
}
orbCommand.AddCommand(listCommand)
orbCommand.AddCommand(orbCreate)
orbCommand.AddCommand(validateCommand)
orbCommand.AddCommand(processCommand)
orbCommand.AddCommand(publishCommand)
orbCommand.AddCommand(unlistCmd)
orbCommand.AddCommand(sourceCommand)
orbCommand.AddCommand(orbInfoCmd)
orbCommand.AddCommand(orbPack)
orbCommand.AddCommand(addCategorizationToOrbCommand)
orbCommand.AddCommand(removeCategorizationFromOrbCommand)
orbCommand.AddCommand(listCategoriesCommand)
orbCommand.AddCommand(orbInit)
return orbCommand
}
func orbHelpLong(config *settings.Config) string {
// We should only print this for cloud users
if config.Host != defaultHost {
return ""
}
return fmt.Sprintf(`Operate on orbs
See a full explanation and documentation on orbs here: %s`, config.Data.Links.OrbDocs)
}
func parameterDefaultToString(parameter api.OrbElementParameter) string {
defaultValue := " (default: '"
// If there isn't a default or the default value is for a steps parameter
// then just ignore the value.
// It's possible to have a very large list of steps that pollutes the output.
if parameter.Default == nil || parameter.Type == "steps" {
return ""
}
switch parameter.Type {
case "enum":
defaultValue += parameter.Default.(string)
case "string":
defaultValue += parameter.Default.(string)
case "boolean":
defaultValue += fmt.Sprintf("%t", parameter.Default.(bool))
default:
defaultValue += ""
}
return defaultValue + "')"
}
// nolint: errcheck, gosec
func addOrbElementParametersToBuffer(buf *bytes.Buffer, orbElement api.OrbElement) {
keys := make([]string, 0, len(orbElement.Parameters))
for k := range orbElement.Parameters {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
parameterName := k
parameter := orbElement.Parameters[k]
defaultValueString := parameterDefaultToString(parameter)
_, _ = buf.WriteString(fmt.Sprintf(" - %s: %s%s\n", parameterName, parameter.Type, defaultValueString))
}
}
// nolint: errcheck, gosec
func addOrbElementsToBuffer(buf *bytes.Buffer, name string, namedOrbElements map[string]api.OrbElement) {
if len(namedOrbElements) > 0 {
keys := make([]string, 0, len(namedOrbElements))
for k := range namedOrbElements {
keys = append(keys, k)
}
sort.Strings(keys)
_, _ = buf.WriteString(fmt.Sprintf(" %s:\n", name))
for _, k := range keys {
elementName := k
orbElement := namedOrbElements[k]
parameterCount := len(orbElement.Parameters)
_, _ = buf.WriteString(fmt.Sprintf(" - %s: %d parameter(s)\n", elementName, parameterCount))
if parameterCount > 0 {
addOrbElementParametersToBuffer(buf, orbElement)
}
}
}
}
// nolint: unparam, errcheck, gosec
func addOrbStatisticsToBuffer(buf *bytes.Buffer, name string, stats api.OrbStatistics) {
var (
encoded []byte
data map[string]int
)
// Roundtrip the stats to JSON so we can iterate a map since we don't care about the fields
encoded, err := json.Marshal(stats)
if err != nil {
panic(err)
}
if err := json.Unmarshal(encoded, &data); err != nil {
panic(err)
}
_, _ = buf.WriteString(fmt.Sprintf(" %s:\n", name))
// Sort the keys so we always get the same results even after the round-trip
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
value := data[key]
_, _ = buf.WriteString(fmt.Sprintf(" - %s: %d\n", key, value))
}
}
func orbToDetailedString(orb api.OrbWithData) string {
buffer := bytes.NewBufferString(orbToSimpleString(orb))
addOrbElementsToBuffer(buffer, "Commands", orb.Commands)
addOrbElementsToBuffer(buffer, "Jobs", orb.Jobs)
addOrbElementsToBuffer(buffer, "Executors", orb.Executors)
addOrbStatisticsToBuffer(buffer, "Statistics", orb.Statistics)
return buffer.String()
}
func orbToSimpleString(orb api.OrbWithData) string {
var buffer bytes.Buffer
_, err := buffer.WriteString(fmt.Sprintln(orb.Name, "("+orb.HighestVersion+")"))
if err != nil {
// The WriteString docstring says that it will never return an error
panic(err)
}
return buffer.String()
}
func orbIsOpenSource(cl *graphql.Client, namespace string, orbName string) bool {
orbExists, orbIsPrivate, err := api.OrbExists(cl, namespace, orbName)
// we are don't want to output errors as they've already
// published a version of the orb successfully
if err != nil {
return false
}
// orbExists will also be false if it is a private orb
return orbExists && !orbIsPrivate
}
func formatListOrbsResult(list api.OrbsForListing, opts orbOptions) (string, error) {
if opts.listJSON {
orbJSON, err := json.MarshalIndent(list, "", " ")
if err != nil {
return "", errors.Wrapf(err, "Failed to convert to JSON")
}
return string(orbJSON), nil
}
// Construct messaging based on provided options.
var b strings.Builder
b.WriteString(fmt.Sprintf("Orbs found: %d. ", len(list.Orbs)))
switch {
case opts.private:
b.WriteString("Showing only private orbs.\n\n")
case opts.listUncertified:
b.WriteString("Includes all certified and uncertified orbs.\n\n")
default:
b.WriteString("Showing only certified orbs.\nAdd --uncertified for a list of all orbs.\n\n")
}
for _, o := range list.Orbs {
if opts.listDetails {
b.WriteString(orbToDetailedString(o))
} else {
b.WriteString(orbToSimpleString(o))
}
}
if !opts.private {
b.WriteString("\nIn order to see more details about each orb, type: `circleci orb info orb-namespace/orb-name`\n")
b.WriteString("\nSearch, filter, and view sources for all Orbs online at https://circleci.com/developer/orbs/")
}
return b.String(), nil
}
func logOrbs(orbCollection api.OrbsForListing, opts orbOptions) error {
result, err := formatListOrbsResult(orbCollection, opts)
if err != nil {
return err
}
fmt.Println(result)
return nil
}
func orbCategoryCollectionToString(orbCategoryCollection *api.OrbCategoriesForListing, opts orbOptions) (string, error) {
var result string
if opts.listJSON {
orbCategoriesJSON, err := json.MarshalIndent(orbCategoryCollection, "", " ")
if err != nil {
return "", errors.Wrapf(err, "Failed to convert to JSON")
}
result = string(orbCategoriesJSON)
} else {
var categories []string = make([]string, 0, len(orbCategoryCollection.OrbCategories))
for _, orbCategory := range orbCategoryCollection.OrbCategories {
categories = append(categories, orbCategory.Name)
}
result = strings.Join(categories, "\n")
}
return result, nil
}
func logOrbCategories(orbCategoryCollection *api.OrbCategoriesForListing, opts orbOptions) error {
result, err := orbCategoryCollectionToString(orbCategoryCollection, opts)
if err != nil {
return err
}
fmt.Println(result)
return nil
}
var validSortFlag = map[string]bool{
"builds": true,
"projects": true,
"orgs": true}
func validateSortFlag(sort string) error {
if _, valid := validSortFlag[sort]; valid {
return nil
}
// TODO(zzak): we could probably reuse the map above to print the valid values
return fmt.Errorf("expected `%s` to be one of \"builds\", \"projects\", or \"orgs\"", sort)
}
func listOrbs(opts orbOptions) error {
if opts.sortBy != "" {
if err := validateSortFlag(opts.sortBy); err != nil {
return err
}
}
if len(opts.args) != 0 {
return listNamespaceOrbs(opts)
}
if opts.private {
return errors.New("Namespace must be provided when listing private orbs")
}
orbs, err := api.ListOrbs(opts.cl, opts.listUncertified)
if err != nil {
return errors.Wrapf(err, "Failed to list orbs")
}
if opts.sortBy != "" {
orbs.SortBy(opts.sortBy)
}
return logOrbs(*orbs, opts)
}
func listNamespaceOrbs(opts orbOptions) error {
namespace := opts.args[0]
orbs, err := api.ListNamespaceOrbs(opts.cl, namespace, opts.private)
if err != nil {
return errors.Wrapf(err, "Failed to list orbs in namespace `%s`", namespace)
}
if opts.sortBy != "" {
orbs.SortBy(opts.sortBy)
}
return logOrbs(*orbs, opts)
}
func validateOrb(opts orbOptions) error {
_, err := api.OrbQuery(opts.cl, opts.args[0])
if err != nil {
return err
}
if opts.args[0] == "-" {
fmt.Println("Orb input is valid.")
} else {
fmt.Printf("Orb at `%s` is valid.\n", opts.args[0])
}
return nil
}
func processOrb(opts orbOptions) error {
response, err := api.OrbQuery(opts.cl, opts.args[0])
if err != nil {
return err
}
fmt.Println(response.OutputYaml)
return nil
}
func publishOrb(opts orbOptions) error {
path := opts.args[0]
ref := opts.args[1]
namespace, orb, version, err := references.SplitIntoOrbNamespaceAndVersion(ref)
if err != nil {
return err
}
_, err = api.OrbPublishByName(opts.cl, path, orb, namespace, version)
if err != nil {
return err
}
fmt.Printf("Orb `%s` was published.\n", ref)
if references.IsDevVersion(version) {
fmt.Printf("Note that your dev label `%s` can be overwritten by anyone in your organization.\n", version)
fmt.Printf("Your dev orb will expire in 90 days unless a new version is published on the label `%s`.\n", version)
}
if orbIsOpenSource(opts.cl, namespace, orb) {
fmt.Println("Please note that this is an open orb and is world-readable.")
}
return nil
}
func setOrbListStatus(opts orbOptions) error {
ref := opts.args[0]
unlistArg := opts.args[1]
var err error
namespace, orb, err := references.SplitIntoOrbAndNamespace(ref)
if err != nil {
return err
}
unlist, err := strconv.ParseBool(unlistArg)
if err != nil {
return fmt.Errorf("expected \"true\" or \"false\", got \"%s\"", unlistArg)
}
listed, err := api.OrbSetOrbListStatus(opts.cl, namespace, orb, !unlist)
if err != nil {
return err
}
if listed != nil {
displayedStatus := "enabled"
if !*listed {
displayedStatus = "disabled"
}
fmt.Printf("The listing of orb `%s` is now %s.\n"+
"Note: changes may not be immediately reflected in the registry.\n", ref, displayedStatus)
} else {
return fmt.Errorf("unexpected error in setting the list status of orb `%s`", ref)
}
return nil
}
var validSegments = map[string]bool{
"major": true,
"minor": true,
"patch": true}
func validateSegmentArg(label string) error {
if _, valid := validSegments[label]; valid {
return nil
}
return fmt.Errorf("expected `%s` to be one of \"major\", \"minor\", or \"patch\"", label)
}
func incrementOrb(opts orbOptions) error {
ref := opts.args[1]
segment := opts.args[2]
if err := validateSegmentArg(segment); err != nil {
return err
}
namespace, orb, err := references.SplitIntoOrbAndNamespace(ref)
if err != nil {
return err
}
response, err := api.OrbIncrementVersion(opts.cl, opts.args[0], namespace, orb, segment)
if err != nil {
return err
}
fmt.Printf("Orb `%s` has been incremented to `%s/%s@%s`.\n", ref, namespace, orb, response.HighestVersion)
if orbIsOpenSource(opts.cl, namespace, orb) {
fmt.Println("Please note that this is an open orb and is world-readable.")
}
return nil
}
func promoteOrb(opts orbOptions) error {
ref := opts.args[0]
segment := opts.args[1]
if err := validateSegmentArg(segment); err != nil {
return err
}
namespace, orb, version, err := references.SplitIntoOrbNamespaceAndVersion(ref)
if err != nil {
return err
}
if !references.IsDevVersion(version) {
return fmt.Errorf("The version '%s' must be a dev version (the string should begin `dev:`)", version)
}
response, err := api.OrbPromoteByName(opts.cl, namespace, orb, version, segment)
if err != nil {
return err
}
fmt.Printf("Orb `%s` was promoted to `%s/%s@%s`.\n", ref, namespace, orb, response.HighestVersion)
if orbIsOpenSource(opts.cl, namespace, orb) {
fmt.Println("Please note that this is an open orb and is world-readable.")
}
return nil
}
func createOrb(opts orbOptions) error {
var err error
namespace, orbName, err := references.SplitIntoOrbAndNamespace(opts.args[0])
if err != nil {
return err
}
if !opts.noPrompt {
fmt.Printf(`You are creating an orb called "%s/%s".
You will not be able to change the name of this orb.
If you change your mind about the name, you will have to create a new orb with the new name.
`, namespace, orbName)
}
confirm := fmt.Sprintf("Are you sure you wish to create the orb: `%s/%s`", namespace, orbName)
if opts.noPrompt || opts.tty.askUserToConfirm(confirm) {
_, err = api.CreateOrb(opts.cl, namespace, orbName, opts.private)
if err != nil {
return err
}
confirmationString := "Please note that any versions you publish of this orb are world-readable."
if opts.private {
confirmationString = "This orb will not be listed on the registry and is usable only by org users."
}
fmt.Printf("Orb `%s` created.\n", opts.args[0])
fmt.Println(confirmationString)
fmt.Printf("You can now register versions of `%s` using `circleci orb publish`.\n", opts.args[0])
}
return nil
}
func showSource(opts orbOptions) error {
ref := opts.args[0]
source, err := api.OrbSource(opts.cl, ref)
if err != nil {
return errors.Wrapf(err, "Failed to get source for '%s'", ref)
}
fmt.Println(source)
return nil
}
func orbInfo(opts orbOptions) error {
ref := opts.args[0]
info, err := api.OrbInfo(opts.cl, ref)
if err != nil {
return errors.Wrapf(err, "Failed to get info for '%s'", ref)
}
fmt.Println("")
if len(info.Orb.Versions) > 0 {
fmt.Printf("Latest: %s@%s\n", info.Orb.Name, info.Orb.HighestVersion)
fmt.Printf("Last-updated: %s\n", info.Orb.Versions[0].CreatedAt)
fmt.Printf("Created: %s\n", info.Orb.CreatedAt)
fmt.Printf("Total-revisions: %d\n", len(info.Orb.Versions))
} else {
fmt.Println("This orb hasn't published any versions yet.")
}
fmt.Println("")
fmt.Printf("Total-commands: %d\n", len(info.Orb.Commands))
fmt.Printf("Total-executors: %d\n", len(info.Orb.Executors))
fmt.Printf("Total-jobs: %d\n", len(info.Orb.Jobs))
fmt.Println("")
fmt.Println("## Statistics (30 days):")
fmt.Printf("Builds: %d\n", info.Orb.Statistics.Last30DaysBuildCount)
fmt.Printf("Projects: %d\n", info.Orb.Statistics.Last30DaysProjectCount)
fmt.Printf("Orgs: %d\n", info.Orb.Statistics.Last30DaysOrganizationCount)
if len(info.Orb.Categories) > 0 {
fmt.Println("")
fmt.Println("## Categories:")
for _, category := range info.Orb.Categories {
fmt.Printf("%s\n", category.Name)
}
}
orbVersionSplit := strings.Split(ref, "@")
orbRef := orbVersionSplit[0]
fmt.Printf(`
Learn more about this orb online in the CircleCI Orb Registry:
https://circleci.com/developer/orbs/orb/%s
`, orbRef)
return nil
}
func listOrbCategories(opts orbOptions) error {
orbCategories, err := api.ListOrbCategories(opts.cl)
if err != nil {
return errors.Wrapf(err, "Failed to list orb categories")
}
return logOrbCategories(orbCategories, opts)
}
func addOrRemoveOrbCategorization(opts orbOptions, updateType api.UpdateOrbCategorizationRequestType) error {
var err error
namespace, orb, err := references.SplitIntoOrbAndNamespace(opts.args[0])
if err != nil {
return err
}
err = api.AddOrRemoveOrbCategorization(opts.cl, namespace, orb, opts.args[1], updateType)
if err != nil {
var errorString = "Failed to add orb %s to category %s"
if updateType == api.Remove {
errorString = "Failed to remove orb %s from category %s"
}
return errors.Wrapf(err, errorString, opts.args[0], opts.args[1])
}
var output = `%s is successfully added to the "%s" category.` + "\n"
if updateType == api.Remove {
output = `%s is successfully removed from the "%s" category.` + "\n"
}
fmt.Printf(output, opts.args[0], opts.args[1])
return nil
}
type OrbSchema struct {
Version float32 `yaml:"version,omitempty"`
Description string `yaml:"description,omitempty"`
Display yaml.Node `yaml:"display,omitempty"`
Orbs yaml.Node `yaml:"orbs,omitempty"`
Commands yaml.Node `yaml:"commands,omitempty"`
Executors yaml.Node `yaml:"executors,omitempty"`
Jobs yaml.Node `yaml:"jobs,omitempty"`
Examples map[string]ExampleSchema `yaml:"examples,omitempty"`
}
type ExampleUsageSchema struct {
Version string `yaml:"version,omitempty"`
Orbs interface{} `yaml:"orbs,omitempty"`
Jobs interface{} `yaml:"jobs,omitempty"`
Workflows interface{} `yaml:"workflows"`
}
type ExampleSchema struct {
Description string `yaml:"description,omitempty"`
Usage ExampleUsageSchema `yaml:"usage,omitempty"`
Result ExampleUsageSchema `yaml:"result,omitempty"`
}
func packOrbCommand(opts orbOptions) error {
result, err := packOrb(opts.args[0])
if err != nil {
return err
}
fmt.Println(result)
return nil
}
func packOrb(path string) (string, error) {
// Travel our Orb and build a tree from the YAML files.
// Non-YAML files will be ignored here.
_, err := os.Stat(filepath.Join(path, "@orb.yml"))
if err != nil {
return "", errors.New("@orb.yml file not found, are you sure this is the Orb root?")
}
tree, err := filetree.NewTree(path, "executors", "jobs", "commands", "examples")
if err != nil {
return "", errors.Wrap(err, "An unexpected error occurred")
}
y, err := yaml.Marshal(&tree)
if err != nil {
return "", errors.Wrap(err, "An unexpected error occurred")
}
var orbSchema OrbSchema
err = yaml.Unmarshal(y, &orbSchema)
if err != nil {
return "", errors.Wrap(err, "An unexpected error occurred")
}