package cmd import ( "errors" "fmt" "os" "os/exec" "strings" "github.com/spf13/cobra" "tangled.org/matilde.at/km/internal/config" "tangled.org/matilde.at/km/internal/render" ) // isBuiltin reports whether name is a command (or command alias) of root. func isBuiltin(root *cobra.Command, name string) bool { if name == "help" || name == "completion" { return true } for _, c := range root.Commands() { if c.Name() == name || c.HasAlias(name) { return true } } return false } type aliasEntry struct { Name string `json:"name"` Expansion string `json:"expansion"` } var aliasFields = []string{"name", "expansion"} func newAliasCmd(f *Factory) *cobra.Command { c := &cobra.Command{ Use: "alias ", Short: "Create command shortcuts", Long: `Create, list and delete aliases for km commands. An alias expands to a km command line. $1, $2 and so on are replaced by the positional arguments; arguments not used by a placeholder are appended. An expansion starting with "!" (or set with --shell) is run through sh.`, } c.AddCommand(newAliasSetCmd(f), newAliasListCmd(f), newAliasDeleteCmd(f)) return c } func newAliasSetCmd(f *Factory) *cobra.Command { var shell, clobber bool c := &cobra.Command{ Use: "set ", Short: "Create a shortcut for a km command", Example: ` $ km alias set unread 'mail list --unread' $ km alias set view 'mail view $1' $ km alias set --shell count 'km mail list --json id | jq length'`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { return runAliasSet(f, cmd.Root(), args[0], args[1], shell, clobber) }, } c.Flags().BoolVarP(&shell, "shell", "s", false, "Declare an alias to be passed through a shell interpreter") c.Flags().BoolVar(&clobber, "clobber", false, "Overwrite existing aliases of the same name") return c } func runAliasSet(f *Factory, root *cobra.Command, name, expansion string, shell, clobber bool) error { if name == "" || strings.ContainsAny(name, " \t\n") || strings.HasPrefix(name, "-") { return usagef("invalid alias name %q", name) } if isBuiltin(root, name) { return usagef("could not create alias: %q is already a km command", name) } if shell && !config.IsShellAlias(expansion) { expansion = "!" + expansion } if !config.IsShellAlias(expansion) { words, err := config.SplitArgs(expansion) if err != nil { return usagef("invalid expansion: %v", err) } if len(words) == 0 { return usagef("expansion is empty") } if !isBuiltin(root, words[0]) { return usagef("could not create alias: %q does not correspond to a km command", words[0]) } } if _, exists := f.Config.Aliases[name]; exists && !clobber { return usagef("could not create alias: %q already exists (use --clobber to overwrite)", name) } if f.Config.Aliases == nil { f.Config.Aliases = map[string]string{} } f.Config.Aliases[name] = expansion if err := f.Config.Save(); err != nil { return err } if f.IO.StdoutTTY { fmt.Fprintf(f.IO.ErrOut, "Added alias %s\n", name) } return nil } func newAliasListCmd(f *Factory) *cobra.Command { c := &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "List your aliases", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { p, err := f.Printer(cmd) if err != nil { return err } entries := []aliasEntry{} for _, n := range f.Config.AliasNames() { entries = append(entries, aliasEntry{n, f.Config.Aliases[n]}) } return p.Emit(entries, func() error { rows := make([][]string, 0, len(entries)) for _, e := range entries { rows = append(rows, []string{e.Name, e.Expansion}) } p.Table(nil, rows) return nil }) }, } render.AddOutputFlags(c, aliasFields) return c } func newAliasDeleteCmd(f *Factory) *cobra.Command { return &cobra.Command{ Use: "delete ", Short: "Delete an alias", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if _, ok := f.Config.Aliases[args[0]]; !ok { return fmt.Errorf("no such alias %q", args[0]) } delete(f.Config.Aliases, args[0]) if err := f.Config.Save(); err != nil { return err } if f.IO.StdoutTTY { fmt.Fprintf(f.IO.ErrOut, "Deleted alias %s\n", args[0]) } return nil }, } } // expandAlias rewrites args (without the program name) using the configured // aliases. When the alias is a shell alias ("!cmd"), shell is true and // expanded holds the shell command line followed by the remaining args. // Built-in commands are never shadowed by aliases. func expandAlias(f *Factory, root *cobra.Command, args []string) (expanded []string, shell bool, err error) { if len(args) == 0 || strings.HasPrefix(args[0], "-") || isBuiltin(root, args[0]) { return args, false, nil } exp, ok := f.Config.Aliases[args[0]] if !ok { return args, false, nil } rest := args[1:] if config.IsShellAlias(exp) { return append([]string{strings.TrimPrefix(exp, "!")}, rest...), true, nil } out, err := config.ExpandAlias(exp, rest) if err != nil { return nil, false, usagef("alias %q: %v", args[0], err) } return out, false, nil } // runShellAlias runs a shell alias produced by expandAlias. func runShellAlias(f *Factory, expanded []string) (int, error) { if len(expanded) == 0 { return ExitError, errors.New("empty shell alias") } c := exec.Command("sh", append([]string{"-c", expanded[0], "--"}, expanded[1:]...)...) c.Stdin, c.Stdout, c.Stderr = f.IO.In, f.IO.Out, f.IO.ErrOut c.Env = append(os.Environ(), "KM_HOST="+f.Host()) return runExternal(c) } // runExternal runs c and maps its result to an exit code. func runExternal(c *exec.Cmd) (int, error) { err := c.Run() if err == nil { return ExitOK, nil } var ee *exec.ExitError if errors.As(err, &ee) { return ee.ExitCode(), nil } return ExitError, err }