bonzai/bonzai.go

91 lines
2.4 KiB
Go
Raw Normal View History

2022-02-17 22:47:28 +00:00
/*
Copyright 2022 Robert S. Muhlestein.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
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
// convention the parameter list should be names "args" if there are
// args expected and "none" if not. Methods must never write error
// output to anything but standard error and should almost always use
// the log package to do so.
type Method func(args ...string) error
// ----------------------- 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, " ")
}
return args
}