From 6906153e5d4884737a509c7bc98f03a007703729 Mon Sep 17 00:00:00 2001 From: Marc O'Morain Date: Thu, 21 Jun 2018 22:39:00 +0100 Subject: [PATCH] Add orb command --- cmd/orb.go | 66 ++++++++++++++++++++++++++++++++++++++++++++ cmd/root.go | 1 + settings/settings.go | 16 +++++++---- 3 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 cmd/orb.go diff --git a/cmd/orb.go b/cmd/orb.go new file mode 100644 index 000000000..17206254e --- /dev/null +++ b/cmd/orb.go @@ -0,0 +1,66 @@ +package cmd + +import ( + "context" + "fmt" + + "github.com/pkg/errors" + + "github.com/machinebox/graphql" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func newOrbCommand() *cobra.Command { + + orbListCommand := &cobra.Command{ + Use: "list", + Short: "List orbs", + RunE: listOrbs, + } + + orbCommand := &cobra.Command{ + Use: "orb", + Short: "Operate on orbs", + } + + orbCommand.AddCommand(orbListCommand) + + return orbCommand +} + +func listOrbs(cmd *cobra.Command, args []string) error { + + ctx := context.Background() + + // Define a structure that matches the result of the GQL + // query, so that we can use mapstructure to convert from + // nested maps to a strongly typed struct. + type orbList struct { + ListOrbs struct { + TotalCount int + } + } + + request := graphql.NewRequest(` + query ListOrbs { + orbs(first: 20, after: "") { + totalCount + } + } + `) + + client := graphql.NewClient(viper.GetString("endpoint")) + + var result orbList + + err := client.Run(ctx, request, &result) + + if err != nil { + return errors.Wrap(err, "GraphQL query failed") + } + + fmt.Printf("Total Number Of Orbs: %d\n", result.ListOrbs.TotalCount) + return nil + +} diff --git a/cmd/root.go b/cmd/root.go index eaf11bb32..630171b85 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -37,6 +37,7 @@ func addCommands() { rootCmd.AddCommand(collapseCommand) rootCmd.AddCommand(configureCommand) rootCmd.AddCommand(configCmd) + rootCmd.AddCommand(newOrbCommand()) // Cobra has a peculiar default behaviour: // https://github.com/spf13/cobra/issues/340 diff --git a/settings/settings.go b/settings/settings.go index 9dae7e143..2fbf453d6 100644 --- a/settings/settings.go +++ b/settings/settings.go @@ -21,19 +21,25 @@ func UserHomeDir() string { // EnsureSettingsFileExists does just that. func EnsureSettingsFileExists(filepath, filename string) error { // TODO - handle invalid YAML config files. - _, err := os.Stat(filepath) - if !os.IsNotExist(err) { + fullPath := path.Join(filepath, filename) + + _, err := os.Stat(fullPath) + + if err == nil { return nil } - if err = os.MkdirAll(filepath, 0700); err != nil { + if !os.IsNotExist(err) { + // Filesystem error return err } - if _, err = os.Create(path.Join(filepath, filename)); err != nil { + // Create folder + if err = os.MkdirAll(filepath, 0700); err != nil { return err } - return nil + _, err = os.Create(fullPath) + return err }