~mil/mobroute

419d2138c67dbfdcf7c3e9ff2a2344d9a9053204 — Miles Alan 2 months ago e9cdd77
Further cleanup cli; break mobsql subcommand out; move helpers to sepearte file
2 files changed, 72 insertions(+), 94 deletions(-)

A cli/helper.go
M cli/mobroutecli.go
A cli/helper.go => cli/helper.go +44 -0
@@ 0,0 1,44 @@
package main

import (
	"log"
	"os"
	"runtime/pprof"
	"strings"

	"git.sr.ht/~mil/mobroute/util/utillog"
)

func errorDie(subcmd, req string, err error) {
	if err != nil {
		log.Printf("Request failed (use 'mobroute %s -h' for proper usage)", subcmd)
		log.Printf("Failed JSON request buffer: %s", req)
		log.Fatal(err)
	}
	os.Exit(1)
}

func globalsSetup(debugCategories, debugProfile string) func() {
	// Setup debug categories
	if strings.Contains(debugCategories, "i") {
		utillog.LogInfo = true
	}
	if strings.Contains(debugCategories, "w") {
		utillog.LogWarn = true
	}
	if strings.Contains(debugCategories, "d") {
		utillog.LogDebug = true
	}

	// Setup pprof debugging
	if debugProfile != "" {
		if f, err := os.Create(debugProfile); err != nil {
			log.Fatal(err)
		} else {
			pprof.StartCPUProfile(f)
			return pprof.StopCPUProfile
		}
	}

	return func() {}
}

M cli/mobroutecli.go => cli/mobroutecli.go +28 -94
@@ 6,23 6,14 @@ import (
	"encoding/json"
	"flag"
	"fmt"

	"log"
	"os"
	"runtime/pprof"
	"strings"

	"git.sr.ht/~mil/mobroute"

	"git.sr.ht/~mil/mobroute/util/utilfuncs"
	"git.sr.ht/~mil/mobroute/util/utillog"
)

func main() {
	var (
		jsonBytes                                     []byte
		commandData                                   any
		err                                           error
		flagBaseDebugCategories, flagBaseDebugProfile string
		flagMobsqlSet                                 = flag.NewFlagSet("mobsql", flag.ExitOnError)
		flagMobsqlParams                              = flagMobsqlSet.String("mp", "", subcmdMobsqlDoc)


@@ 30,113 21,56 @@ func main() {
		flagRouteParams                               = flagRouteSet.String("rp", "", subcmdRouteDoc)
	)

	validSubcommands := []string{
		"version", "route", "mobsql_status", "mobsql_load", "mobsql_compute",
		"mobsql_purgeall", "mobsql_purgegtfs", "mobsql_purgecomputed",
	}

	if len(os.Args) < 2 || !utilfuncs.StringInArray(validSubcommands, os.Args[1]) {
		fmt.Println("Provide valid subcommand as first arg, valid subcommands:", validSubcommands)
		os.Exit(1)
	}

	// Debug Same usage for all subcommands
	for _, f := range []*flag.FlagSet{flagRouteSet} {
	for _, f := range []*flag.FlagSet{flagRouteSet, flagMobsqlSet} {
		f.StringVar(&flagBaseDebugCategories, "d", "i", "Verbose debug categories: (i) Information (w) Warn (d) Debug")
		f.StringVar(&flagBaseDebugProfile, "dprof", "", "Write debug pprof CPU profile to file")
	}
	globalDeferedFn := globalsSetup(flagBaseDebugCategories, flagBaseDebugProfile)
	defer globalDeferedFn()

	// Route subcommand
	if os.Args[1] == "route" {
		cmdRoute(flagRouteSet, *flagRouteParams)
	}

	// Mobsql_* subcommand
	if utilfuncs.ItemInArray(os.Args[1], []string{
		"mobsql_load", "mobsql_status", "mobsql_compute",
		"mobsql_purgegtfs", "mobsql_purgecomputed", "mobsql_purgeall",
	}) {
		var jsonBuffer string
		if *flagMobsqlParams == "" {
			flagMobsqlSet.Usage()
			return
		} else {
			flagMobsqlSet.Parse(os.Args[2:])
			jsonBuffer = *flagMobsqlParams
			if commandData, err = cmdMobsql(*flagMobsqlParams); err != nil {
				errorDie(os.Args[1], jsonBuffer, err)
			} else if jsonBytes, err = json.MarshalIndent(commandData, "", "  "); err != nil {
				errorDie(os.Args[1], jsonBuffer, err)
			} else {
				fmt.Println(string(jsonBytes))
			}
		}
	}

	// Version subcommand
	if os.Args[1] == "version" {
	// Run command
	validSubcommands := []string{"version", "route", "mobsql"}
	if len(os.Args) < 2 || !utilfuncs.StringInArray(validSubcommands, os.Args[1]) {
		fmt.Println("Provide valid subcommand as first arg, valid subcommands:", validSubcommands)
		os.Exit(1)
	} else if os.Args[1] == "route" {
		cmdRoute(flagRouteSet, flagRouteParams)
	} else if os.Args[1] == "mobsql" {
		cmdMobsql(flagMobsqlSet, flagMobsqlParams)
	} else if os.Args[1] == "version" {
		fmt.Println("v0.5.0")
	}
}

func cmdRoute(flagRouteSet *flag.FlagSet, flagRouteParams string) {
func cmdRoute(flagRouteSet *flag.FlagSet, flagRouteParams *string) {
	var routeParams mobroute.OneshotRouteRequest
	flagRouteSet.Parse(os.Args[2:])
	if flagRouteParams == "" {
	if *flagRouteParams == "" {
		flagRouteSet.Usage()
	} else if err := json.Unmarshal([]byte(flagRouteParams), &routeParams); err != nil {
		errorDie(os.Args[1], flagRouteParams, err)
	} else if err := json.Unmarshal([]byte(*flagRouteParams), &routeParams); err != nil {
		errorDie(os.Args[1], *flagRouteParams, err)
	} else if commandData, err := mobroute.OneshotRoute(&routeParams); err != nil {
		errorDie(os.Args[1], flagRouteParams, err)
		errorDie(os.Args[1], *flagRouteParams, err)
	} else if jsonBytes, err := json.MarshalIndent(commandData, "", "  "); err != nil {
		errorDie(os.Args[1], flagRouteParams, err)
		errorDie(os.Args[1], *flagRouteParams, err)
	} else {
		fmt.Println(string(jsonBytes))
	}
}

func cmdMobsql(paramsJSON string) (any, error) {
func cmdMobsql(flagMobsqlSet *flag.FlagSet, flagMobsqlParams *string) {
	var mobsqlParams mobroute.OneshotMobsqlRequest

	if err := json.Unmarshal([]byte(paramsJSON), &mobsqlParams); err != nil {
		return nil, fmt.Errorf("Error demarshalling YML %s: %v", paramsJSON, err)
	flagMobsqlSet.Parse(os.Args[2:])
	if *flagMobsqlParams == "" {
		flagMobsqlSet.Usage()
	} else if err := json.Unmarshal([]byte(*flagMobsqlParams), &mobsqlParams); err != nil {
		errorDie(os.Args[1], *flagMobsqlParams, err)
	} else if commandData, err := mobroute.OneshotMobsql(&mobsqlParams); err != nil {
		errorDie(os.Args[1], *flagMobsqlParams, err)
	} else if jsonBytes, err := json.MarshalIndent(commandData, "", "  "); err != nil {
		errorDie(os.Args[1], *flagMobsqlParams, err)
	} else {
		return mobroute.OneshotMobsql(&mobsqlParams)
	}
}

func errorDie(subcmd, req string, err error) {
	if err != nil {
		log.Printf("Request failed (use 'mobroute %s -h' for proper usage)", subcmd)
		log.Printf("Failed JSON request buffer: %s", req)
		log.Fatal(err)
	}
	os.Exit(1)
}

func globalsSetup(debugCategories, debugProfile string) func() {
	// Setup debug categories
	if strings.Contains(debugCategories, "i") {
		utillog.LogInfo = true
	}
	if strings.Contains(debugCategories, "w") {
		utillog.LogWarn = true
	}
	if strings.Contains(debugCategories, "d") {
		utillog.LogDebug = true
	}

	// Setup pprof debugging
	if debugProfile != "" {
		if f, err := os.Create(debugProfile); err != nil {
			log.Fatal(err)
		} else {
			pprof.StartCPUProfile(f)
			return pprof.StopCPUProfile
		}
		fmt.Println(string(jsonBytes))
	}

	return func() {}
}