From 48c8baed56fc5e72e62c59db63aee29865646688 Mon Sep 17 00:00:00 2001 From: Hedzr Yeh Date: Tue, 22 Oct 2024 09:41:12 +0800 Subject: [PATCH] improved ParsedState interface - added `Translate()` to convert the placeholders in given text pattern - processing the placeholders, such as `AppName`, `AppVersion`, `CommandsText`, `DadCommandsText`, ... --- cli/config.go | 5 ++++ cli/worker/parse_ctx.go | 52 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/cli/config.go b/cli/config.go index 0119089..ab1e791 100644 --- a/cli/config.go +++ b/cli/config.go @@ -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 { diff --git a/cli/worker/parse_ctx.go b/cli/worker/parse_ctx.go index c7aca94..c2bc42b 100644 --- a/cli/worker/parse_ctx.go +++ b/cli/worker/parse_ctx.go @@ -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" @@ -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