Skip to content

Commit

Permalink
support output flag
Browse files Browse the repository at this point in the history
  • Loading branch information
AdheipSingh committed Nov 4, 2024
1 parent a9b11d3 commit f95926c
Show file tree
Hide file tree
Showing 3 changed files with 197 additions and 199 deletions.
39 changes: 39 additions & 0 deletions cmd/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package cmd

import (
"encoding/json"
"errors"
"fmt"
"net/url"
Expand Down Expand Up @@ -54,6 +55,29 @@ func (item *ProfileListItem) Render(highlight bool) string {
return ItemOuter.Render(render)
}

// Add an output flag to specify the output format.
var outputFormat string

// Initialize flags
func init() {
AddProfileCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Output format (text|json)")
RemoveProfileCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Output format (text|json)")
DefaultProfileCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Output format (text|json)")
ListProfileCmd.Flags().StringVarP(&outputFormat, "output", "o", "text", "Output format (text|json)")
}
func outputResult(v interface{}) error {
if outputFormat == "json" {
jsonData, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonData))
} else {
fmt.Println(v)
}
return nil
}

var AddProfileCmd = &cobra.Command{
Use: "add profile-name url <username?> <password?>",
Example: " pb profile add local_parseable http://0.0.0.0:8000 admin admin",
Expand Down Expand Up @@ -116,6 +140,11 @@ var AddProfileCmd = &cobra.Command{
}
config.WriteConfigToFile(fileConfig)

if outputFormat == "json" {
return outputResult(profile)
}
fmt.Printf("Profile %s added successfully\n", name)

return nil
},
}
Expand All @@ -140,6 +169,9 @@ var RemoveProfileCmd = &cobra.Command{
fileConfig.DefaultProfile = ""
}
config.WriteConfigToFile(fileConfig)
if outputFormat == "json" {
return outputResult(fmt.Sprintf("Deleted profile %s", name))
}
fmt.Printf("Deleted profile %s\n", StyleBold.Render(name))
} else {
fmt.Printf("No profile found with the name: %s", StyleBold.Render(name))
Expand Down Expand Up @@ -190,6 +222,9 @@ var DefaultProfileCmd = &cobra.Command{
}

config.WriteConfigToFile(fileConfig)
if outputFormat == "json" {
return outputResult(fmt.Sprintf("%s is now set as default profile", name))
}
fmt.Printf("%s is now set as default profile\n", StyleBold.Render(name))
return nil
},
Expand All @@ -209,6 +244,10 @@ var ListProfileCmd = &cobra.Command{
println()
}

if outputFormat == "json" {
return outputResult(fileConfig.Profiles)
}

row := 0
for key, value := range fileConfig.Profiles {
item := ProfileListItem{key, value.URL, value.Username}
Expand Down
Loading

0 comments on commit f95926c

Please sign in to comment.