run batch commands

this is useful for initialization scripts or the like.
the parser is very basic, but should still be useful
This commit is contained in:
boyska 2018-09-29 21:48:10 +02:00
parent a155818a36
commit a4d7e6640b

View file

@ -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)
}