Add Cmd.Branch to help with unique ids for branch

pull/53/head v0.0.26
rwxrob 2 years ago
parent 27523c3526
commit cb47d20264
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77

@ -56,7 +56,7 @@ func init() {
var ExePath string
// ExeName holds just the base name of the executable without any suffix
// (ex: .exe).
// (ex: .exe) and is set at init() time (see ExePath).
var ExeName string
// ReplaceSelf replaces the current running executable at its current

@ -6,9 +6,11 @@ package bonzai
import (
"fmt"
"os"
"strings"
"github.com/rwxrob/bonzai/comp"
"github.com/rwxrob/fn/each"
"github.com/rwxrob/structs/qstack"
)
// Cmd is a struct the easier to use and read when creating
@ -205,6 +207,21 @@ func (x *Cmd) Seek(args []string) (*Cmd, []string) {
return cur, args[n:]
}
// Branch returns the dotted path to this command location within the
// parent tree. This is useful for associating configuration and other
// data specifically with this command. The branch path is determined by
// walking backward from current Caller up rather than depending on
// anything from the command line used to invoke the composing binary.
func (x *Cmd) Branch() string {
callers := qstack.New[string]()
callers.Unshift(x.Name)
for p := x.Caller; p != nil; p = p.Caller {
callers.Unshift(p.Name)
}
callers.Shift()
return strings.Join(callers.Items(), ".")
}
// ---------------------- comp.Command interface ----------------------
// mostly to overcome cyclical imports

@ -5,6 +5,7 @@ package bonzai_test
import (
"fmt"
"os"
"github.com/rwxrob/bonzai"
"github.com/rwxrob/bonzai/inc/help"
@ -40,7 +41,7 @@ func ExampleCmd_Seek() {
yo := &bonzai.Cmd{
Name: `yo`,
Call: func(_ *bonzai.Cmd, args ...string) error {
Call: func(x *bonzai.Cmd, args ...string) error {
fmt.Println("yo")
return nil
},
@ -120,3 +121,28 @@ func ExampleCmd_GetParams() {
// Output:
// [box bing and]
}
func ExampleCmd_Branch() {
bonzai.ExitOff()
z := new(bonzai.Cmd)
c := z.Add("some")
//fmt.Print(z.Commands[0].Name)
c = c.Add("thing")
//fmt.Print(z.Commands[0].Commands[0].Name)
c = c.Add("deep")
//fmt.Print(z.Commands[0].Commands[0].Commands[0].Name)
c.Call = func(x *bonzai.Cmd, _ ...string) error {
fmt.Println(x.Branch())
return nil
}
defer func() { args := os.Args; os.Args = args }()
os.Args = []string{"z", "some", "thing", "deep"}
z.Run()
// Output:
// some.thing.deep
}

Loading…
Cancel
Save