From 0a2388168b1357187c45b6f3ae531a9e0ba0d67f Mon Sep 17 00:00:00 2001 From: baz Date: Thu, 27 Sep 2018 16:51:36 +0200 Subject: [PATCH] Same things, more cleanup explicit support for subcommands, separate backend library --- .gitignore | 3 +- cmd/panelcli/cli.go | 68 +++++++++++++++++++++++++++++++++++++++++++++ main.go => db/db.go | 19 +------------ go.mod | 2 +- 4 files changed, 72 insertions(+), 20 deletions(-) create mode 100644 cmd/panelcli/cli.go rename main.go => db/db.go (78%) diff --git a/.gitignore b/.gitignore index 152a7d0..e67274b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ vendor -panel +panelcli +go.sum diff --git a/cmd/panelcli/cli.go b/cmd/panelcli/cli.go new file mode 100644 index 0000000..8762a4b --- /dev/null +++ b/cmd/panelcli/cli.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" + "io" + "os" + + "git.lattuga.net/boyska/feedpanel/db" + "github.com/go-pg/pg" +) + +func getDB() paneldb.DB { + pgdb := pg.Connect(&pg.Options{ + User: "panel", + Password: "panelpass", + Database: "feeds", + }) + db := paneldb.DB{PgDB: pgdb} + return db +} + +type commandFunc func() error + +func cmdSetup() error { + db := getDB() + err := db.Setup() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Println("All done") + os.Exit(0) + return nil +} + +var cmdMap map[string]commandFunc = map[string]commandFunc{ + "setup": cmdSetup, +} + +func usage(w io.Writer) { + fmt.Fprintf(w, "Usage: %s SUBCOMMAND [command args...]\n", os.Args[0]) + fmt.Fprintln(w, "\nSubcommands:") + for cmdName, _ := range cmdMap { + fmt.Fprintln(w, " -", cmdName) + } +} + +func main() { + if len(os.Args) < 2 { + fmt.Fprintln(os.Stderr, "Not enough arguments!") + usage(os.Stderr) + os.Exit(2) + } + cmdName := os.Args[1] + cmdFunc, ok := cmdMap[cmdName] + if !ok { + fmt.Fprintln(os.Stderr, "Invalid command") + usage(os.Stderr) + os.Exit(2) + } + err := cmdFunc() + if err != nil { + fmt.Fprintln(os.Stderr, "Error") + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) +} diff --git a/main.go b/db/db.go similarity index 78% rename from main.go rename to db/db.go index f44a9e6..b6ce65c 100644 --- a/main.go +++ b/db/db.go @@ -1,8 +1,7 @@ -package main +package paneldb import ( "fmt" - "os" "github.com/go-pg/pg" "github.com/pkg/errors" @@ -44,19 +43,3 @@ func (db *DB) UserAdd(username, email, pwhash string) error { } return nil } - -func main() { - pgdb := pg.Connect(&pg.Options{ - User: "panel", - Password: "panelpass", - Database: "feeds", - }) - db := DB{PgDB: pgdb} - err := db.Setup() - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - fmt.Println("All done") - os.Exit(0) -} diff --git a/go.mod b/go.mod index e9ef530..0e23214 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module panel +module git.lattuga.net/boyska/feedpanel require ( github.com/go-pg/pg v6.15.0+incompatible