|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/user" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/nohns/nohns-cli/flag" |
| 10 | + "github.com/nohns/nohns-cli/subcmd" |
| 11 | + "github.com/urfave/cli/v2" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + confDirName = ".nohns" |
| 16 | +) |
| 17 | + |
| 18 | +func main() { |
| 19 | + |
| 20 | + // Depedencies |
| 21 | + nvf := subcmd.NewNginxVhostFactory() |
| 22 | + |
| 23 | + app := cli.App{ |
| 24 | + Name: "nohns", |
| 25 | + Usage: "A simple CLI for automating repetivite tasks", |
| 26 | + EnableBashCompletion: true, |
| 27 | + Before: func(c *cli.Context) error { |
| 28 | + // Set home directory on context |
| 29 | + usr, err := user.Current() |
| 30 | + if err != nil { |
| 31 | + return fmt.Errorf("could not get current user: %s", err) |
| 32 | + } |
| 33 | + if err := c.Set(flag.NameHomeDir, usr.HomeDir); err != nil { |
| 34 | + return fmt.Errorf("could not set home directory on CLI context: %s", err) |
| 35 | + } |
| 36 | + |
| 37 | + // Make sure config directory exists |
| 38 | + if err := ensureConfDirIn(usr.HomeDir); err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + |
| 42 | + return nil |
| 43 | + }, |
| 44 | + Flags: []cli.Flag{ |
| 45 | + &cli.StringFlag{ |
| 46 | + Name: flag.NameHomeDir, |
| 47 | + Usage: "The home directory of the current user", |
| 48 | + }, |
| 49 | + }, |
| 50 | + Commands: []*cli.Command{ |
| 51 | + { |
| 52 | + Name: "cp-pubkey", |
| 53 | + Aliases: []string{"pk"}, |
| 54 | + Usage: "Copies public key to clipboard", |
| 55 | + Action: subcmd.ActionCopyPubSSHKey, |
| 56 | + Flags: []cli.Flag{ |
| 57 | + &cli.StringFlag{ |
| 58 | + Name: flag.NameSSHKey, |
| 59 | + Usage: "The name of the public key file", |
| 60 | + Value: flag.DefaultSSHKey, |
| 61 | + }, |
| 62 | + }, |
| 63 | + }, |
| 64 | + { |
| 65 | + Name: "nginx", |
| 66 | + Aliases: []string{"i"}, |
| 67 | + Usage: "Run nginx related tasks", |
| 68 | + Subcommands: subcmd.NginxSubcommands(nvf), |
| 69 | + }, |
| 70 | + }, |
| 71 | + } |
| 72 | + |
| 73 | + // Run cli |
| 74 | + if err := app.Run(os.Args); err != nil { |
| 75 | + fmt.Printf("\nerror: %s\n", err) |
| 76 | + os.Exit(1) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +// Ensures that a config directory exists |
| 81 | +func ensureConfDirIn(basepath string) error { |
| 82 | + p := filepath.Join(basepath, confDirName) |
| 83 | + fi, err := os.Stat(p) |
| 84 | + if os.IsNotExist(err) { |
| 85 | + if err := os.Mkdir(p, 0700); err != nil { |
| 86 | + return fmt.Errorf("could not create %s: %s", p, err) |
| 87 | + } |
| 88 | + |
| 89 | + return nil |
| 90 | + } |
| 91 | + if err != nil { |
| 92 | + return fmt.Errorf("could not create %s: %s", p, err) |
| 93 | + } |
| 94 | + if !fi.IsDir() { |
| 95 | + return fmt.Errorf("%s is not a directory. please remove it and try running the cli again.", p) |
| 96 | + } |
| 97 | + |
| 98 | + return nil |
| 99 | +} |
0 commit comments