Skip to content

Commit

Permalink
refactor: use Cobra print functions where possible (#608)
Browse files Browse the repository at this point in the history
This change makes it possible to easily change which stream command
outputs are printed to. This is in preparation for the resource creation
JSON output feature (as described in #470)
  • Loading branch information
phm07 authored Nov 9, 2023
1 parent a77e553 commit 765bc3f
Show file tree
Hide file tree
Showing 104 changed files with 583 additions and 591 deletions.
2 changes: 2 additions & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"os"
"time"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -62,5 +63,6 @@ func NewRootCommand(state *state.State, client hcapi2.Client) *cobra.Command {
primaryip.NewCommand(state, client),
)
cmd.PersistentFlags().Duration("poll-interval", 500*time.Millisecond, "Interval at which to poll information, for example action progress")
cmd.SetOut(os.Stdout)
return cmd
}
7 changes: 3 additions & 4 deletions internal/cmd/all/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package all
import (
"context"
"encoding/json"
"fmt"
"strings"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -158,7 +157,7 @@ Listed resources are:
if err != nil {
return err
}
fmt.Printf("%s\n", jsonBytes)
cmd.Printf("%s\n", jsonBytes)
return nil
}

Expand All @@ -171,14 +170,14 @@ Listed resources are:
continue
}

fmt.Print(strings.ToUpper(lc.ResourceNamePlural) + "\n---\n")
cmd.Print(strings.ToUpper(lc.ResourceNamePlural) + "\n---\n")
for _, resource := range resources[i] {
table.Write(cols, resource)
}
if err := table.Flush(); err != nil {
return err
}
fmt.Println()
cmd.Println()
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/base/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ func (dc *DeleteCmd) Run(ctx context.Context, client hcapi2.Client, actionWaiter
if err := dc.Delete(ctx, client, actionWaiter, cmd, resource); err != nil {
return fmt.Errorf("deleting %s %s failed: %s", dc.ResourceNameSingular, idOrName, err)
}
fmt.Printf("%s %v deleted\n", dc.ResourceNameSingular, idOrName)
cmd.Printf("%s %v deleted\n", dc.ResourceNameSingular, idOrName)
return nil
}
6 changes: 3 additions & 3 deletions internal/cmd/base/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func (lc *LabelCmds) RunAdd(ctx context.Context, client hcapi2.Client, cmd *cobr
return err
}

fmt.Printf("Label %s added to %s %d\n", key, lc.ResourceNameSingular, id)
cmd.Printf("Label %s added to %s %d\n", key, lc.ResourceNameSingular, id)
return nil
}

Expand Down Expand Up @@ -137,9 +137,9 @@ func (lc *LabelCmds) RunRemove(ctx context.Context, client hcapi2.Client, cmd *c
}

if all {
fmt.Printf("All labels removed from %s %d\n", lc.ResourceNameSingular, id)
cmd.Printf("All labels removed from %s %d\n", lc.ResourceNameSingular, id)
} else {
fmt.Printf("Label %s removed from %s %d\n", args[1], lc.ResourceNameSingular, id)
cmd.Printf("Label %s removed from %s %d\n", args[1], lc.ResourceNameSingular, id)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/base/set_rdns.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (rc *SetRdnsCmd) Run(ctx context.Context, client hcapi2.Client, cmd *cobra.
return err
}

fmt.Printf("Reverse DNS of %s %s changed\n", rc.ResourceNameSingular, idOrName)
cmd.Printf("Reverse DNS of %s %s changed\n", rc.ResourceNameSingular, idOrName)

return nil
}
2 changes: 1 addition & 1 deletion internal/cmd/base/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,6 @@ func (uc *UpdateCmd) Run(ctx context.Context, client hcapi2.Client, cmd *cobra.C
return fmt.Errorf("updating %s %s failed: %s", uc.ResourceNameSingular, idOrName, err)
}

fmt.Printf("%s %v updated\n", uc.ResourceNameSingular, idOrName)
cmd.Printf("%s %v updated\n", uc.ResourceNameSingular, idOrName)
return nil
}
4 changes: 2 additions & 2 deletions internal/cmd/certificate/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func createUploaded(ctx context.Context, client hcapi2.Client, cmd *cobra.Comman
if cert, _, err = client.Certificate().Create(ctx, createOpts); err != nil {
return err
}
fmt.Printf("Certificate %d created\n", cert.ID)
cmd.Printf("Certificate %d created\n", cert.ID)
return nil
}

Expand Down Expand Up @@ -129,6 +129,6 @@ func createManaged(ctx context.Context, client hcapi2.Client, waiter state.Actio
if err := waiter.ActionProgress(ctx, res.Action); err != nil {
return err
}
fmt.Printf("Certificate %d created\n", res.Certificate.ID)
cmd.Printf("Certificate %d created\n", res.Certificate.ID)
return nil
}
43 changes: 21 additions & 22 deletions internal/cmd/certificate/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package certificate

import (
"context"
"fmt"

"github.com/dustin/go-humanize"
"github.com/spf13/cobra"
Expand All @@ -24,47 +23,47 @@ var DescribeCmd = base.DescribeCmd{
},
PrintText: func(_ context.Context, client hcapi2.Client, cmd *cobra.Command, resource interface{}) error {
cert := resource.(*hcloud.Certificate)
fmt.Printf("ID:\t\t\t%d\n", cert.ID)
fmt.Printf("Name:\t\t\t%s\n", cert.Name)
fmt.Printf("Type:\t\t\t%s\n", cert.Type)
fmt.Printf("Fingerprint:\t\t%s\n", cert.Fingerprint)
fmt.Printf("Created:\t\t%s (%s)\n", util.Datetime(cert.Created), humanize.Time(cert.Created))
fmt.Printf("Not valid before:\t%s (%s)\n", util.Datetime(cert.NotValidBefore), humanize.Time(cert.NotValidBefore))
fmt.Printf("Not valid after:\t%s (%s)\n", util.Datetime(cert.NotValidAfter), humanize.Time(cert.NotValidAfter))
cmd.Printf("ID:\t\t\t%d\n", cert.ID)
cmd.Printf("Name:\t\t\t%s\n", cert.Name)
cmd.Printf("Type:\t\t\t%s\n", cert.Type)
cmd.Printf("Fingerprint:\t\t%s\n", cert.Fingerprint)
cmd.Printf("Created:\t\t%s (%s)\n", util.Datetime(cert.Created), humanize.Time(cert.Created))
cmd.Printf("Not valid before:\t%s (%s)\n", util.Datetime(cert.NotValidBefore), humanize.Time(cert.NotValidBefore))
cmd.Printf("Not valid after:\t%s (%s)\n", util.Datetime(cert.NotValidAfter), humanize.Time(cert.NotValidAfter))
if cert.Status != nil {
fmt.Printf("Status:\n")
fmt.Printf(" Issuance:\t%s\n", cert.Status.Issuance)
fmt.Printf(" Renewal:\t%s\n", cert.Status.Renewal)
cmd.Printf("Status:\n")
cmd.Printf(" Issuance:\t%s\n", cert.Status.Issuance)
cmd.Printf(" Renewal:\t%s\n", cert.Status.Renewal)
if cert.Status.IsFailed() {
fmt.Printf(" Failure reason: %s\n", cert.Status.Error.Message)
cmd.Printf(" Failure reason: %s\n", cert.Status.Error.Message)
}
}
fmt.Printf("Domain names:\n")
cmd.Printf("Domain names:\n")
for _, domainName := range cert.DomainNames {
fmt.Printf(" - %s\n", domainName)
cmd.Printf(" - %s\n", domainName)
}
fmt.Print("Labels:\n")
cmd.Print("Labels:\n")
if len(cert.Labels) == 0 {
fmt.Print(" No labels\n")
cmd.Print(" No labels\n")
} else {
for key, value := range cert.Labels {
fmt.Printf(" %s:\t%s\n", key, value)
cmd.Printf(" %s:\t%s\n", key, value)
}
}
fmt.Println("Used By:")
cmd.Println("Used By:")
if len(cert.UsedBy) == 0 {
fmt.Println(" Certificate unused")
cmd.Println(" Certificate unused")
} else {
for _, ub := range cert.UsedBy {
fmt.Printf(" - Type: %s\n", ub.Type)
cmd.Printf(" - Type: %s\n", ub.Type)
// Currently certificates can be only attached to load balancers.
// If we ever get something that is not a load balancer fall back
// to printing the ID.
if ub.Type != hcloud.CertificateUsedByRefTypeLoadBalancer {
fmt.Printf(" - ID: %d\n", ub.ID)
cmd.Printf(" - ID: %d\n", ub.ID)
continue
}
fmt.Printf(" - Name: %s\n", client.LoadBalancer().LoadBalancerName(ub.ID))
cmd.Printf(" - Name: %s\n", client.LoadBalancer().LoadBalancerName(ub.ID))
}
}
return nil
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/context/active.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func runActive(cli *state.State, cmd *cobra.Command, args []string) error {
_, _ = fmt.Fprintln(os.Stderr, "Warning: HCLOUD_TOKEN is set. The active context will have no effect.")
}
if cli.Config.ActiveContext != nil {
fmt.Println(cli.Config.ActiveContext.Name)
cmd.Println(cli.Config.ActiveContext.Name)
}
return nil
}
15 changes: 7 additions & 8 deletions internal/cmd/context/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"strings"
"syscall"
Expand All @@ -27,7 +26,7 @@ func newCreateCommand(cli *state.State) *cobra.Command {
return cmd
}

func runCreate(cli *state.State, _ *cobra.Command, args []string) error {
func runCreate(cli *state.State, cmd *cobra.Command, args []string) error {
if !state.StdoutIsTerminal() {
return errors.New("context create is an interactive command")
}
Expand All @@ -47,9 +46,9 @@ func runCreate(cli *state.State, _ *cobra.Command, args []string) error {
envToken := os.Getenv("HCLOUD_TOKEN")
if envToken != "" {
if len(envToken) != 64 {
fmt.Println("Warning: HCLOUD_TOKEN is set, but token is invalid (must be exactly 64 characters long)")
cmd.Println("Warning: HCLOUD_TOKEN is set, but token is invalid (must be exactly 64 characters long)")
} else {
fmt.Print("The HCLOUD_TOKEN environment variable is set. Do you want to use the token from HCLOUD_TOKEN for the new context? (Y/n): ")
cmd.Print("The HCLOUD_TOKEN environment variable is set. Do you want to use the token from HCLOUD_TOKEN for the new context? (Y/n): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
if s := strings.ToLower(scanner.Text()); s == "" || s == "y" || s == "yes" {
Expand All @@ -60,11 +59,11 @@ func runCreate(cli *state.State, _ *cobra.Command, args []string) error {

if token == "" {
for {
fmt.Printf("Token: ")
cmd.Printf("Token: ")
// Conversion needed for compilation on Windows
// vvv
btoken, err := term.ReadPassword(int(syscall.Stdin))
fmt.Print("\n")
cmd.Print("\n")
if err != nil {
return err
}
Expand All @@ -73,7 +72,7 @@ func runCreate(cli *state.State, _ *cobra.Command, args []string) error {
continue
}
if len(token) != 64 {
fmt.Print("Entered token is invalid (must be exactly 64 characters long)\n")
cmd.Print("Entered token is invalid (must be exactly 64 characters long)\n")
continue
}
break
Expand All @@ -89,7 +88,7 @@ func runCreate(cli *state.State, _ *cobra.Command, args []string) error {
return err
}

fmt.Printf("Context %s created and activated\n", name)
cmd.Printf("Context %s created and activated\n", name)

return nil
}
37 changes: 18 additions & 19 deletions internal/cmd/datacenter/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package datacenter

import (
"context"
"fmt"

"github.com/spf13/cobra"

Expand All @@ -23,37 +22,37 @@ var DescribeCmd = base.DescribeCmd{
PrintText: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, resource interface{}) error {
datacenter := resource.(*hcloud.Datacenter)

fmt.Printf("ID:\t\t%d\n", datacenter.ID)
fmt.Printf("Name:\t\t%s\n", datacenter.Name)
fmt.Printf("Description:\t%s\n", datacenter.Description)
fmt.Printf("Location:\n")
fmt.Printf(" Name:\t\t%s\n", datacenter.Location.Name)
fmt.Printf(" Description:\t%s\n", datacenter.Location.Description)
fmt.Printf(" Country:\t%s\n", datacenter.Location.Country)
fmt.Printf(" City:\t\t%s\n", datacenter.Location.City)
fmt.Printf(" Latitude:\t%f\n", datacenter.Location.Latitude)
fmt.Printf(" Longitude:\t%f\n", datacenter.Location.Longitude)
fmt.Printf("Server Types:\n")
cmd.Printf("ID:\t\t%d\n", datacenter.ID)
cmd.Printf("Name:\t\t%s\n", datacenter.Name)
cmd.Printf("Description:\t%s\n", datacenter.Description)
cmd.Printf("Location:\n")
cmd.Printf(" Name:\t\t%s\n", datacenter.Location.Name)
cmd.Printf(" Description:\t%s\n", datacenter.Location.Description)
cmd.Printf(" Country:\t%s\n", datacenter.Location.Country)
cmd.Printf(" City:\t\t%s\n", datacenter.Location.City)
cmd.Printf(" Latitude:\t%f\n", datacenter.Location.Latitude)
cmd.Printf(" Longitude:\t%f\n", datacenter.Location.Longitude)
cmd.Printf("Server Types:\n")

printServerTypes := func(list []*hcloud.ServerType) {
for _, t := range list {
fmt.Printf(" - ID:\t\t %d\n", t.ID)
fmt.Printf(" Name:\t %s\n", client.ServerType().ServerTypeName(t.ID))
fmt.Printf(" Description: %s\n", client.ServerType().ServerTypeDescription(t.ID))
cmd.Printf(" - ID:\t\t %d\n", t.ID)
cmd.Printf(" Name:\t %s\n", client.ServerType().ServerTypeName(t.ID))
cmd.Printf(" Description: %s\n", client.ServerType().ServerTypeDescription(t.ID))
}
}

fmt.Printf(" Available:\n")
cmd.Printf(" Available:\n")
if len(datacenter.ServerTypes.Available) > 0 {
printServerTypes(datacenter.ServerTypes.Available)
} else {
fmt.Printf(" No available server types\n")
cmd.Printf(" No available server types\n")
}
fmt.Printf(" Supported:\n")
cmd.Printf(" Supported:\n")
if len(datacenter.ServerTypes.Supported) > 0 {
printServerTypes(datacenter.ServerTypes.Supported)
} else {
fmt.Printf(" No supported server types\n")
cmd.Printf(" No supported server types\n")
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/firewall/add_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ var AddRuleCmd = base.Cmd{
return err
}

fmt.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)
cmd.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)

return nil
},
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/firewall/apply_to_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ var ApplyToResourceCmd = base.Cmd{
if err := waiter.WaitForActions(ctx, actions); err != nil {
return err
}
fmt.Printf("Firewall %d applied\n", firewall.ID)
cmd.Printf("Firewall %d applied\n", firewall.ID)

return nil
},
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/firewall/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ var CreateCmd = base.Cmd{
return err
}

fmt.Printf("Firewall %d created\n", result.Firewall.ID)
cmd.Printf("Firewall %d created\n", result.Firewall.ID)

return nil
},
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/firewall/delete_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ var DeleteRuleCmd = base.Cmd{
if err := waiter.WaitForActions(ctx, actions); err != nil {
return err
}
fmt.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)
cmd.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)

return nil
},
Expand Down
Loading

0 comments on commit 765bc3f

Please sign in to comment.