Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added --output=json flag to epinio namespace [list|show] #2547

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions acceptance/namespaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
package acceptance_test

import (
"encoding/json"

"github.com/epinio/epinio/acceptance/helpers/catalog"
"github.com/epinio/epinio/pkg/api/core/v1/models"

. "github.com/epinio/epinio/acceptance/helpers/matchers"
. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -100,6 +103,16 @@ var _ = Describe("Namespaces", LNamespace, func() {
),
)
})

It("lists namespaces in JSON format", func() {
out, err := env.Epinio("", "namespace", "list", namespaceName, "--output", "json")
Expect(err).ToNot(HaveOccurred(), out)

namespaces := models.NamespaceList{}
err = json.Unmarshal([]byte(out), &namespaces)
Expect(err).ToNot(HaveOccurred(), out)
Expect(namespaces).ToNot(BeEmpty())
})
})

Describe("namespace show", func() {
Expand Down Expand Up @@ -175,6 +188,16 @@ var _ = Describe("Namespaces", LNamespace, func() {
),
)
})

It("shows a namespace in JSON format", func() {
out, err := env.Epinio("", "namespace", "show", namespaceName, "--output", "json")
Expect(err).ToNot(HaveOccurred(), out)

namespace := models.Namespace{}
err = json.Unmarshal([]byte(out), &namespace)
Expect(err).ToNot(HaveOccurred(), out)
Expect(namespace.Meta.Name).To(Equal(namespaceName))
})
})
})

Expand Down
16 changes: 16 additions & 0 deletions internal/cli/commons.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,19 @@

return filteredMatches
}

type flagCompletionFunc func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

func newStaticFlagsCompletionFunc(allowedValues []string) flagCompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
matches := []string{}

for _, allowed := range allowedValues {
if strings.HasPrefix(allowed, toComplete) {
matches = append(matches, allowed)
}

Check warning on line 216 in internal/cli/commons.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/commons.go#L211-L216

Added lines #L211 - L216 were not covered by tests
}

return matches, cobra.ShellCompDirectiveNoFileComp

Check warning on line 219 in internal/cli/commons.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/commons.go#L219

Added line #L219 was not covered by tests
}
}
59 changes: 59 additions & 0 deletions internal/cli/enum_flag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2021 - 2023 SUSE LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cli

import (
"fmt"
"strings"
)

// enumValue implements the Value interface
// It can be used to define a flag with a set of allowed values
// Ref:
// - https://github.com/spf13/pflag/blob/2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab/flag.go#L185-L191
// - https://github.com/spf13/pflag/issues/236#issuecomment-931600452
type enumValue struct {
Allowed []string
Value string
}

// newEnumValue give a list of allowed flag parameters, where the second argument is the default
func newEnumValue(allowed []string, d string) *enumValue {
return &enumValue{
Allowed: allowed,
Value: d,
}
}

func (a enumValue) String() string {
return a.Value
}

func (a *enumValue) Set(p string) error {
isIncluded := func(opts []string, val string) bool {
for _, opt := range opts {
if val == opt {
return true
}
}
return false

Check warning on line 48 in internal/cli/enum_flag.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/enum_flag.go#L48

Added line #L48 was not covered by tests
}
if !isIncluded(a.Allowed, p) {
return fmt.Errorf("%s is not included in %s", p, strings.Join(a.Allowed, ","))
}

Check warning on line 52 in internal/cli/enum_flag.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/enum_flag.go#L51-L52

Added lines #L51 - L52 were not covered by tests
a.Value = p
return nil
}

func (a *enumValue) Type() string {
return "string"

Check warning on line 58 in internal/cli/enum_flag.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/enum_flag.go#L57-L58

Added lines #L57 - L58 were not covered by tests
}
11 changes: 11 additions & 0 deletions internal/cli/namespaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (

"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
Expand Down Expand Up @@ -47,6 +48,16 @@ func init() {
flags.BoolVarP(&gNamespaceForceFlag, "force", "f", false, "force namespace deletion")
flags.BoolVar(&gNamespaceAllFlag, "all", false, "delete all namespaces")

flagOutput = newEnumValue([]string{"text", "json"}, "text")

CmdNamespaceList.Flags().VarP(flagOutput, "output", "o", "sets output format [text|json]")
checkErr(viper.BindPFlag("output", CmdNamespaceList.Flags().Lookup("output")))
checkErr(CmdNamespaceList.RegisterFlagCompletionFunc("output", newStaticFlagsCompletionFunc(flagOutput.Allowed)))

CmdNamespaceShow.Flags().VarP(flagOutput, "output", "o", "sets output format [text|json]")
checkErr(viper.BindPFlag("output", CmdNamespaceShow.Flags().Lookup("output")))
checkErr(CmdNamespaceShow.RegisterFlagCompletionFunc("output", newStaticFlagsCompletionFunc(flagOutput.Allowed)))

CmdNamespace.AddCommand(CmdNamespaceCreate)
CmdNamespace.AddCommand(CmdNamespaceList)
CmdNamespace.AddCommand(CmdNamespaceDelete)
Expand Down
6 changes: 6 additions & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var (

flagSettingsFile string
flagHeaders []string
flagOutput *enumValue
)

// NewRootCmd returns the rootCmd, that is the main `epinio` cli.
Expand All @@ -64,6 +65,11 @@ func NewRootCmd() (*cobra.Command, error) {
return errors.Wrap(err, "initializing client")
}

if flagOutput.String() == "json" {
client.UI().EnableJSON()
client.API.DisableVersionWarning()
}

for _, header := range flagHeaders {
headerKeyValue := strings.SplitN(header, ":", 2)

Expand Down
22 changes: 20 additions & 2 deletions internal/cli/termui/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -53,8 +54,9 @@
// UI contains functionality for dealing with the user
// on the CLI
type UI struct {
output io.Writer
verbosity int // Verbosity level for user messages.
output io.Writer
verbosity int // Verbosity level for user messages.
jsonEnabled bool
}

// Message represents a piece of information we want displayed to the user
Expand Down Expand Up @@ -96,6 +98,22 @@
}
}

func (u *UI) EnableJSON() {
u.verbosity = -1
u.jsonEnabled = true
}

func (u *UI) DisableJSON() {
u.verbosity = verbosity()
u.jsonEnabled = false

Check warning on line 108 in internal/cli/termui/ui.go

View check run for this annotation

Codecov / codecov/patch

internal/cli/termui/ui.go#L106-L108

Added lines #L106 - L108 were not covered by tests
}

func (u *UI) JSON(value any) {
if u.jsonEnabled {
_ = json.NewEncoder(u.output).Encode(value)
}
}

func (u *UI) Raw(message string) {
fmt.Fprintf(u.output, "%s", message)
}
Expand Down
4 changes: 4 additions & 0 deletions internal/cli/usercmd/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ func (c *EpinioClient) Namespaces() error {

msg.Msg("Epinio Namespaces:")

c.ui.JSON(namespaces)

return nil
}

Expand Down Expand Up @@ -252,6 +254,8 @@ func (c *EpinioClient) ShowNamespace(namespace string) error {

msg.Msg("Details:")

c.ui.JSON(space)

return nil
}

Expand Down
Loading