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

refactor: make command definition consistent #585

Merged
merged 1 commit into from
Oct 26, 2023
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
12 changes: 6 additions & 6 deletions internal/cmd/certificate/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ func NewCommand(cli *state.State, client hcapi2.Client) *cobra.Command {
}
cmd.AddCommand(
ListCmd.CobraCommand(cli.Context, client, cli),
newCreateCommand(cli),
updateCmd.CobraCommand(cli.Context, client, cli),
labelCmds.AddCobraCommand(cli.Context, client, cli),
labelCmds.RemoveCobraCommand(cli.Context, client, cli),
deleteCmd.CobraCommand(cli.Context, client, cli, cli),
describeCmd.CobraCommand(cli.Context, client, cli),
CreateCmd.CobraCommand(cli.Context, client, cli, cli),
UpdateCmd.CobraCommand(cli.Context, client, cli),
LabelCmds.AddCobraCommand(cli.Context, client, cli),
LabelCmds.RemoveCobraCommand(cli.Context, client, cli),
DeleteCmd.CobraCommand(cli.Context, client, cli, cli),
DescribeCmd.CobraCommand(cli.Context, client, cli),
)

return cmd
Expand Down
105 changes: 52 additions & 53 deletions internal/cmd/certificate/create.go
Original file line number Diff line number Diff line change
@@ -1,66 +1,65 @@
package certificate

import (
"context"
"fmt"
"io/ioutil"
"os"

"github.com/spf13/cobra"

"github.com/hetznercloud/cli/internal/cmd/base"
"github.com/hetznercloud/cli/internal/cmd/cmpl"
"github.com/hetznercloud/cli/internal/cmd/util"
"github.com/hetznercloud/cli/internal/hcapi2"
"github.com/hetznercloud/cli/internal/state"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

func newCreateCommand(cli *state.State) *cobra.Command {
cmd := &cobra.Command{
Use: "create [FLAGS]",
Short: "Create or upload a Certificate",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: cli.EnsureToken,
RunE: cli.Wrap(runCreate),
}

cmd.Flags().String("name", "", "Certificate name (required)")
cmd.MarkFlagRequired("name")

cmd.Flags().StringP("type", "t", string(hcloud.CertificateTypeUploaded),
fmt.Sprintf("Type of certificate to create. Valid choices: %v, %v",
hcloud.CertificateTypeUploaded, hcloud.CertificateTypeManaged))
cmd.RegisterFlagCompletionFunc(
"type",
cmpl.SuggestCandidates(string(hcloud.CertificateTypeUploaded), string(hcloud.CertificateTypeManaged)),
)

cmd.Flags().String("cert-file", "", "File containing the PEM encoded certificate (required if type is uploaded)")
cmd.Flags().String("key-file", "",
"File containing the PEM encoded private key for the certificate (required if type is uploaded)")
cmd.Flags().StringSlice("domain", nil, "One or more domains the certificate is valid for.")

return cmd
var CreateCmd = base.Cmd{
BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "create [FLAGS]",
Short: "Create or upload a Certificate",
Args: cobra.ExactArgs(0),
}

cmd.Flags().String("name", "", "Certificate name (required)")
cmd.MarkFlagRequired("name")

cmd.Flags().StringP("type", "t", string(hcloud.CertificateTypeUploaded),
fmt.Sprintf("Type of certificate to create. Valid choices: %v, %v",
hcloud.CertificateTypeUploaded, hcloud.CertificateTypeManaged))
cmd.RegisterFlagCompletionFunc(
"type",
cmpl.SuggestCandidates(string(hcloud.CertificateTypeUploaded), string(hcloud.CertificateTypeManaged)),
)

cmd.Flags().String("cert-file", "", "File containing the PEM encoded certificate (required if type is uploaded)")
cmd.Flags().String("key-file", "",
"File containing the PEM encoded private key for the certificate (required if type is uploaded)")
cmd.Flags().StringSlice("domain", nil, "One or more domains the certificate is valid for.")

return cmd
},
Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, strings []string) error {
certType, err := cmd.Flags().GetString("type")
if err != nil {
return err
}
switch hcloud.CertificateType(certType) {
case hcloud.CertificateTypeUploaded:
return createUploaded(ctx, client, cmd)
case hcloud.CertificateTypeManaged:
return createManaged(ctx, client, waiter, cmd)
default:
return createUploaded(ctx, client, cmd)
}
},
}

func runCreate(cli *state.State, cmd *cobra.Command, args []string) error {
certType, err := cmd.Flags().GetString("type")
if err != nil {
return err
}
switch hcloud.CertificateType(certType) {
case hcloud.CertificateTypeUploaded:
return createUploaded(cli, cmd, args)
case hcloud.CertificateTypeManaged:
return createManaged(cli, cmd, args)
default:
return createUploaded(cli, cmd, args)
}
}

func createUploaded(cli *state.State, cmd *cobra.Command, args []string) error {
func createUploaded(ctx context.Context, client hcapi2.Client, cmd *cobra.Command) error {
var (
name string

name string
certFile, keyFile string
certPEM, keyPEM []byte
cert *hcloud.Certificate
Expand All @@ -81,10 +80,10 @@ func createUploaded(cli *state.State, cmd *cobra.Command, args []string) error {
return err
}

if certPEM, err = ioutil.ReadFile(certFile); err != nil {
if certPEM, err = os.ReadFile(certFile); err != nil {
return err
}
if keyPEM, err = ioutil.ReadFile(keyFile); err != nil {
if keyPEM, err = os.ReadFile(keyFile); err != nil {
return err
}

Expand All @@ -94,14 +93,14 @@ func createUploaded(cli *state.State, cmd *cobra.Command, args []string) error {
Certificate: string(certPEM),
PrivateKey: string(keyPEM),
}
if cert, _, err = cli.Client().Certificate.Create(cli.Context, createOpts); err != nil {
if cert, _, err = client.Certificate().Create(ctx, createOpts); err != nil {
return err
}
fmt.Printf("Certificate %d created\n", cert.ID)
return nil
}

func createManaged(cli *state.State, cmd *cobra.Command, args []string) error {
func createManaged(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command) error {
var (
name string
domains []string
Expand All @@ -124,10 +123,10 @@ func createManaged(cli *state.State, cmd *cobra.Command, args []string) error {
Type: hcloud.CertificateTypeManaged,
DomainNames: domains,
}
if res, _, err = cli.Client().Certificate.CreateCertificate(cli.Context, createOpts); err != nil {
if res, _, err = client.Certificate().CreateCertificate(ctx, createOpts); err != nil {
return err
}
if err := cli.ActionProgress(cli.Context, res.Action); err != nil {
if err := waiter.ActionProgress(ctx, res.Action); err != nil {
return err
}
fmt.Printf("Certificate %d created\n", res.Certificate.ID)
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/certificate/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var deleteCmd = base.DeleteCmd{
var DeleteCmd = base.DeleteCmd{
ResourceNameSingular: "certificate",
ShortDescription: "Delete a certificate",
NameSuggestions: func(c hcapi2.Client) func() []string { return c.Firewall().Names },
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/certificate/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var describeCmd = base.DescribeCmd{
var DescribeCmd = base.DescribeCmd{
ResourceNameSingular: "certificate",
ShortDescription: "Describe an certificate",
JSONKeyGetByID: "certificate",
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/certificate/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var labelCmds = base.LabelCmds{
var LabelCmds = base.LabelCmds{
ResourceNameSingular: "certificate",
ShortDescriptionAdd: "Add a label to an certificate",
ShortDescriptionRemove: "Remove a label from an certificate",
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/certificate/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var updateCmd = base.UpdateCmd{
var UpdateCmd = base.UpdateCmd{
ResourceNameSingular: "certificate",
ShortDescription: "Update a certificate",
NameSuggestions: func(c hcapi2.Client) func() []string { return c.Firewall().Names },
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/datacenter/datacenter.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func NewCommand(cli *state.State, client hcapi2.Client) *cobra.Command {
}
cmd.AddCommand(
ListCmd.CobraCommand(cli.Context, client, cli),
describeCmd.CobraCommand(cli.Context, client, cli),
DescribeCmd.CobraCommand(cli.Context, client, cli),
)
return cmd
}
2 changes: 1 addition & 1 deletion internal/cmd/datacenter/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var describeCmd = base.DescribeCmd{
var DescribeCmd = base.DescribeCmd{
ResourceNameSingular: "datacenter",
ShortDescription: "Describe an datacenter",
JSONKeyGetByID: "datacenter",
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 @@ -14,7 +14,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var AddRuleCommand = base.Cmd{
var AddRuleCmd = base.Cmd{
BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "add-rule FIREWALL FLAGS",
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 @@ -13,7 +13,7 @@ import (
"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

var ApplyToResourceCommand = base.Cmd{
var ApplyToResourceCmd = base.Cmd{
BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "apply-to-resource FIREWALL FLAGS",
Expand Down
125 changes: 62 additions & 63 deletions internal/cmd/firewall/create.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package firewall

import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
Expand All @@ -9,83 +10,81 @@ import (

"github.com/spf13/cobra"

"github.com/hetznercloud/cli/internal/cmd/util"
"github.com/hetznercloud/cli/internal/cmd/base"
"github.com/hetznercloud/cli/internal/hcapi2"
"github.com/hetznercloud/cli/internal/state"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
"github.com/hetznercloud/hcloud-go/v2/hcloud/schema"
)

func newCreateCommand(cli *state.State) *cobra.Command {
cmd := &cobra.Command{
Use: "create FLAGS",
Short: "Create a Firewall",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: util.ChainRunE(cli.EnsureToken),
RunE: cli.Wrap(runFirewallCreate),
}
cmd.Flags().String("name", "", "Name")
cmd.MarkFlagRequired("name")

cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")
var CreateCmd = base.Cmd{
BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
cmd := &cobra.Command{
Use: "create FLAGS",
Short: "Create a Firewall",
Args: cobra.NoArgs,
}
cmd.Flags().String("name", "", "Name")
cmd.MarkFlagRequired("name")

cmd.Flags().String("rules-file", "", "JSON file containing your routes (use - to read from stdin). The structure of the file needs to be the same as within the API: https://docs.hetzner.cloud/#firewalls-get-a-firewall ")
return cmd
}
cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")

func runFirewallCreate(cli *state.State, cmd *cobra.Command, args []string) error {
name, _ := cmd.Flags().GetString("name")
labels, _ := cmd.Flags().GetStringToString("label")
cmd.Flags().String("rules-file", "", "JSON file containing your routes (use - to read from stdin). The structure of the file needs to be the same as within the API: https://docs.hetzner.cloud/#firewalls-get-a-firewall ")
return cmd
},
Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, strings []string) error {
name, _ := cmd.Flags().GetString("name")
labels, _ := cmd.Flags().GetStringToString("label")

opts := hcloud.FirewallCreateOpts{
Name: name,
Labels: labels,
}
opts := hcloud.FirewallCreateOpts{
Name: name,
Labels: labels,
}

rulesFile, _ := cmd.Flags().GetString("rules-file")
rulesFile, _ := cmd.Flags().GetString("rules-file")

if len(rulesFile) > 0 {
var data []byte
var err error
if rulesFile == "-" {
data, err = ioutil.ReadAll(os.Stdin)
} else {
data, err = ioutil.ReadFile(rulesFile)
}
if err != nil {
return err
}
var rules []schema.FirewallRule
err = json.Unmarshal(data, &rules)
if err != nil {
return err
}
for _, rule := range rules {
var sourceNets []net.IPNet
for i, sourceIP := range rule.SourceIPs {
_, sourceNet, err := net.ParseCIDR(sourceIP)
if err != nil {
return fmt.Errorf("invalid CIDR on index %d : %s", i, err)
if len(rulesFile) > 0 {
var data []byte
var err error
if rulesFile == "-" {
data, err = ioutil.ReadAll(os.Stdin)
} else {
data, err = ioutil.ReadFile(rulesFile)
}
if err != nil {
return err
}
var rules []schema.FirewallRule
err = json.Unmarshal(data, &rules)
if err != nil {
return err
}
for _, rule := range rules {
var sourceNets []net.IPNet
for i, sourceIP := range rule.SourceIPs {
_, sourceNet, err := net.ParseCIDR(sourceIP)
if err != nil {
return fmt.Errorf("invalid CIDR on index %d : %s", i, err)
}
sourceNets = append(sourceNets, *sourceNet)
}
sourceNets = append(sourceNets, *sourceNet)
opts.Rules = append(opts.Rules, hcloud.FirewallRule{
Direction: hcloud.FirewallRuleDirection(rule.Direction),
SourceIPs: sourceNets,
Protocol: hcloud.FirewallRuleProtocol(rule.Protocol),
Port: rule.Port,
Description: rule.Description,
})
}
opts.Rules = append(opts.Rules, hcloud.FirewallRule{
Direction: hcloud.FirewallRuleDirection(rule.Direction),
SourceIPs: sourceNets,
Protocol: hcloud.FirewallRuleProtocol(rule.Protocol),
Port: rule.Port,
Description: rule.Description,
})
}
}

result, _, err := cli.Client().Firewall.Create(cli.Context, opts)
if err != nil {
return err
}
result, _, err := client.Firewall().Create(ctx, opts)
if err != nil {
return err
}

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

return nil
return nil
},
}
Loading
Loading