Skip to content

Commit

Permalink
improved ParsedState interface
Browse files Browse the repository at this point in the history
- added `Translate()` to convert the placeholders in given text pattern
- processing the placeholders, such as `AppName`, `AppVersion`, `CommandsText`, `DadCommandsText`, ...
  • Loading branch information
hedzr committed Oct 22, 2024
1 parent d09d50b commit 48c8bae
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
5 changes: 5 additions & 0 deletions cli/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ type ParsedState interface {

HasCmd(longTitle string, validator func(cc Cmd, state *MatchState) bool) (found bool)
HasFlag(longTitle string, validator func(ff *Flag, state *MatchState) bool) (found bool)

Translate(pattern string) (result string)

DadCommandsText() string
CommandsText() string
}

func WithForceDefaultAction(b bool) Opt {
Expand Down
52 changes: 52 additions & 0 deletions cli/worker/parse_ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package worker

import (
"context"
"strings"
"sync/atomic"
"text/template"

"github.com/hedzr/cmdr/v2/cli"
"github.com/hedzr/cmdr/v2/pkg/logz"
Expand Down Expand Up @@ -32,6 +34,56 @@ type parseCtx struct {
// helpScreen bool
}

func (s *parseCtx) Translate(pattern string) (result string) {
if tpl, err := template.New("cool").Parse(pattern); err != nil {
logz.Warn("given pattern cannot be transalted or expanded", "pattern", pattern, "err", err)
return
} else {
var sb strings.Builder
cmd := s.LastCmd()
if err = tpl.Execute(&sb, struct {
AppName string
AppVersion string
DadCommands string
Commands string
*parseCtx
}{
cmd.App().Name(),
cmd.App().Version(),
s.DadCommandsText(),
s.CommandsText(),
s,
}); err != nil {
logz.Warn("given pattern cannot be transalted", "pattern", pattern, "err", err)
return
}
result = sb.String()
}
return
}

func (s *parseCtx) DadCommandsText() (result string) {
if len(s.matchedCommands) > 1 {
var ss []string
for _, z := range s.matchedCommands[:len(s.matchedCommands)-1] {
ss = append(ss, z.Name())
}
result = strings.Join(ss, " ")
}
return
}

func (s *parseCtx) CommandsText() (result string) {
if len(s.matchedCommands) > 0 {
var ss []string
for _, z := range s.matchedCommands {
ss = append(ss, z.Name())
}
result = strings.Join(ss, " ")
}
return
}

func (s *parseCtx) CommandMatchedState(c cli.Cmd) (ms *cli.MatchState) {
if m, ok := s.matchedCommandsStates[c]; ok {
return m
Expand Down

0 comments on commit 48c8bae

Please sign in to comment.