From a4d7e6640b7f14d2407ed28e5357b61e9b003ecc Mon Sep 17 00:00:00 2001 From: boyska Date: Sat, 29 Sep 2018 21:48:10 +0200 Subject: [PATCH] run batch commands this is useful for initialization scripts or the like. the parser is very basic, but should still be useful --- cmd/panelcli/cli.go | 49 +++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/cmd/panelcli/cli.go b/cmd/panelcli/cli.go index 0459c7e..afde88a 100644 --- a/cmd/panelcli/cli.go +++ b/cmd/panelcli/cli.go @@ -1,10 +1,12 @@ package main import ( + "bufio" "flag" "fmt" "io" "os" + "strings" paneldb "git.lattuga.net/boyska/feedpanel/db" "github.com/go-pg/pg" @@ -22,6 +24,7 @@ var cmdMap map[string]commandFunc func init() { cmdMap = map[string]commandFunc{ + "batch": cmdBatch, "setup": cmdSetup, "adduser": cmdAddUser, "listusers": cmdListUsers, @@ -160,6 +163,37 @@ func usage(w io.Writer) { } } +func runLine(args []string) { + cmdName := args[0] + cmdFunc, ok := cmdMap[cmdName] + if !ok { + fmt.Fprintf(os.Stderr, "Invalid command `%s`\n", cmdName) + usage(os.Stderr) + os.Exit(2) + } + err := cmdFunc(args) + if err != nil { + fmt.Fprintln(os.Stderr, "Error") + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func cmdBatch(args []string) error { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + line := scanner.Text() + runLine(strings.Split(line, " ")) + } + + if scanner.Err() != nil { + fmt.Fprintln(os.Stderr, "Error reading stdin:", scanner.Err()) + os.Exit(1) + } + os.Exit(0) + return nil +} + func main() { flag.StringVar(&globalOptions.pgOptions.User, "db-user", "panel", "The user to connect to database to") flag.StringVar(&globalOptions.pgOptions.Password, "db-pass", "", "database password") @@ -167,23 +201,12 @@ func main() { flag.StringVar(&globalOptions.pgOptions.Addr, "db-addr", "127.0.0.1:5432", "database network address") flag.BoolVar(&globalOptions.verbose, "verbose", false, "verbose output") flag.Parse() + if len(flag.Args()) < 1 { fmt.Fprintln(os.Stderr, "Not enough arguments!") usage(os.Stderr) os.Exit(2) } - cmdName := flag.Args()[0] - cmdFunc, ok := cmdMap[cmdName] - if !ok { - fmt.Fprintf(os.Stderr, "Invalid command `%s`\n", cmdName) - usage(os.Stderr) - os.Exit(2) - } - err := cmdFunc(flag.Args()) - if err != nil { - fmt.Fprintln(os.Stderr, "Error") - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } + runLine(flag.Args()) os.Exit(0) }