Skip to content

Commit

Permalink
Keygen command using cobra
Browse files Browse the repository at this point in the history
  • Loading branch information
Victor Castell committed Aug 24, 2018
1 parent 3ace66d commit 22aefab
Showing 1 changed file with 23 additions and 36 deletions.
59 changes: 23 additions & 36 deletions cmd/keygen.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,34 @@ package cmd
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"strings"

"github.com/mitchellh/cli"
"github.com/spf13/cobra"
)

// KeygenCommand is a Command implementation that generates an encryption
// key for use in `dkron agent`.
type KeygenCommand struct {
Ui cli.Ui
}

// Run is the main entrypoint for the keygen command
func (c *KeygenCommand) Run(_ []string) int {
key := make([]byte, 16)
n, err := rand.Reader.Read(key)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error reading random data: %s", err))
return 1
}
if n != 16 {
c.Ui.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!"))
return 1
}

c.Ui.Output(base64.StdEncoding.EncodeToString(key))
return 0
}
// versionCmd represents the version command
var keygenCmd = &cobra.Command{
Use: "keygen",
Short: "Generates a new encryption key",
Long: `Generates a new encryption key that can be used to configure the
agent to encrypt traffic. The output of this command is already
in the proper format that the agent expects.`,
RunE: func(cmd *cobra.Command, args []string) error {
key := make([]byte, 16)
n, err := rand.Reader.Read(key)
if err != nil {
return fmt.Errorf("Error reading random data: %s", err)
}
if n != 16 {
return errors.New("Couldn't read enough entropy. Generate more entropy")
}

// Synopsis returns the purpose fo the KeygenCommand for the CLI help text.
func (c *KeygenCommand) Synopsis() string {
return "Generates a new encryption key"
fmt.Println(base64.StdEncoding.EncodeToString(key))
return nil
},
}

// Help returns the usage text for the CLI.
func (c *KeygenCommand) Help() string {
helpText := `
Usage: dkron keygen
Generates a new encryption key that can be used to configure the
agent to encrypt traffic. The output of this command is already
in the proper format that the agent expects.
`
return strings.TrimSpace(helpText)
func init() {
dkronCmd.AddCommand(keygenCmd)
}

0 comments on commit 22aefab

Please sign in to comment.