cfssl-newkey.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "github.com/cloudflare/cfssl/cli"
  7. "github.com/cloudflare/cfssl/cli/genkey"
  8. "github.com/cloudflare/cfssl/config"
  9. )
  10. // main defines the newkey usage and registers all defined commands and flags.
  11. func main() {
  12. var newkeyFlagSet = flag.NewFlagSet("newkey", flag.ExitOnError)
  13. var c cli.Config
  14. var usageText = `cfssl-newkey -- generate a new key and CSR
  15. Usage of genkey:
  16. newkey CSRJSON
  17. Arguments:
  18. CSRJSON: JSON file containing the request, use '-' for reading JSON from stdin
  19. Flags:
  20. `
  21. registerFlags(&c, newkeyFlagSet)
  22. newkeyFlagSet.Usage = func() {
  23. fmt.Fprintf(os.Stderr, "\t%s", usageText)
  24. for _, name := range genkey.Command.Flags {
  25. if f := newkeyFlagSet.Lookup(name); f != nil {
  26. printDefaultValue(f)
  27. }
  28. }
  29. }
  30. args := os.Args[1:]
  31. newkeyFlagSet.Parse(args)
  32. args = newkeyFlagSet.Args()
  33. var err error
  34. c.CFG, err = config.LoadFile(c.ConfigFile)
  35. if c.ConfigFile != "" && err != nil {
  36. fmt.Fprintf(os.Stderr, "Failed to load config file: %v", err)
  37. }
  38. if err := genkey.Command.Main(args, c); err != nil {
  39. fmt.Fprintln(os.Stderr, err)
  40. }
  41. }
  42. // printDefaultValue is a helper function to print out a user friendly
  43. // usage message of a flag. It's useful since we want to write customized
  44. // usage message on selected subsets of the global flag set. It is
  45. // borrowed from standard library source code. Since flag value type is
  46. // not exported, default string flag values are printed without
  47. // quotes. The only exception is the empty string, which is printed as "".
  48. func printDefaultValue(f *flag.Flag) {
  49. format := " -%s=%s: %s\n"
  50. if f.DefValue == "" {
  51. format = " -%s=%q: %s\n"
  52. }
  53. fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage)
  54. }
  55. // registerFlags defines all cfssl command flags and associates their values with variables.
  56. func registerFlags(c *cli.Config, f *flag.FlagSet) {
  57. f.BoolVar(&c.IsCA, "initca", false, "initialise new CA")
  58. f.StringVar(&c.ConfigFile, "config", "", "path to configuration file")
  59. }