fix: alias argument expansion with flags and spaces
Fixes an issue where alias arguments containing spaces or flags were being split incorrectly by using strings.Fields on the substituted command string. Instead, the command string is tokenized first and then substitution happens on each token. Also disables Cobra flag parsing for aliases dynamically so that arguments and flags correctly cascade down to the target command instead of throwing unknown flag errors.
This commit is contained in:
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
@@ -155,11 +156,30 @@ func (c *fileConfig) Save() error {
|
||||
func ExpandAlias(alias *Alias, args []string, currentUser string) []string {
|
||||
cmd := alias.Command
|
||||
cmd = strings.ReplaceAll(cmd, "$me", currentUser)
|
||||
if len(args) > 0 {
|
||||
cmd = strings.ReplaceAll(cmd, "$@", strings.Join(args, " "))
|
||||
|
||||
parts := strings.Fields(cmd)
|
||||
var result []string
|
||||
|
||||
for _, part := range parts {
|
||||
if part == "$@" {
|
||||
result = append(result, args...)
|
||||
continue
|
||||
}
|
||||
|
||||
hasCatchAll := strings.Contains(part, "$@")
|
||||
replaced := part
|
||||
|
||||
if hasCatchAll {
|
||||
replaced = strings.ReplaceAll(replaced, "$@", strings.Join(args, " "))
|
||||
}
|
||||
|
||||
for i := len(args) - 1; i >= 0; i-- {
|
||||
placeholder := fmt.Sprintf("$%d", i+1)
|
||||
replaced = strings.ReplaceAll(replaced, placeholder, args[i])
|
||||
}
|
||||
|
||||
result = append(result, replaced)
|
||||
}
|
||||
for i, arg := range args {
|
||||
cmd = strings.ReplaceAll(cmd, "$"+string(rune('1'+i)), arg)
|
||||
}
|
||||
return strings.Fields(cmd)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user