bonzai/bonzai.go

78 lines
1.9 KiB
Go
Raw Normal View History

2022-02-20 00:22:03 +00:00
// Copyright 2022 Robert S. Muhlestein.
// SPDX-License-Identifier: Apache-2.0
2022-02-17 22:47:28 +00:00
2022-02-17 04:31:12 +00:00
package bonzai
import (
"fmt"
"log"
"os"
"strings"
)
// Method defines the main code to execute for a command (Cmd). By
2022-02-24 13:06:10 +00:00
// convention the parameter list should be named "args" if there are
// args expected and underscore (_) if not. Methods must never write
// error output to anything but standard error and should almost always
// use the log package to do so.
2022-02-24 12:33:54 +00:00
type Method func(caller *Cmd, args ...string) error
2022-02-17 04:31:12 +00:00
// ----------------------- errors, exit, debug -----------------------
2022-02-17 23:03:19 +00:00
// DoNotExit effectively disables Exit and ExitError allowing the
// program to continue running, usually for test evaluation.
2022-02-17 04:31:12 +00:00
var DoNotExit bool
// ExitOff sets DoNotExit to false.
func ExitOff() { DoNotExit = true }
// ExitOn sets DoNotExit to true.
func ExitOn() { DoNotExit = false }
2022-02-17 23:05:23 +00:00
// Exit calls os.Exit(0) unless DoNotExit has been set to true. Cmds
// should never call Exit themselves returning a nil error from their
// Methods instead.
2022-02-17 04:31:12 +00:00
func Exit() {
if !DoNotExit {
os.Exit(0)
}
}
// ExitError prints err and exits with 1 return value unless DoNotExit
2022-02-17 23:05:23 +00:00
// has been set to true. Commands should usually never call ExitError
// themselves returning an error from their Method instead.
2022-02-17 04:31:12 +00:00
func ExitError(err ...interface{}) {
switch e := err[0].(type) {
case string:
if len(e) > 1 {
2022-02-18 03:06:48 +00:00
log.Printf(e+"\n", err[1:]...)
} else {
log.Println(e)
2022-02-17 04:31:12 +00:00
}
case error:
out := fmt.Sprintf("%v", e)
if len(out) > 0 {
log.Println(out)
}
}
if !DoNotExit {
os.Exit(1)
}
}
2022-02-17 23:05:23 +00:00
// ArgsFrom returns a list of field strings split on space with an extra
2022-02-17 04:31:12 +00:00
// trailing special space item appended if the line has any trailing
// spaces at all signifying a definite word boundary and not a potential
// prefix.
func ArgsFrom(line string) []string {
args := []string{}
if line == "" {
return args
}
args = strings.Fields(line)
if line[len(line)-1] == ' ' {
args = append(args, "")
2022-02-17 04:31:12 +00:00
}
return args
}