1package cmd
2
3import (
4	"fmt"
5	"os"
6	"strings"
7
8	"github.com/fatih/color"
9	"github.com/knqyf263/pet/config"
10	"github.com/spf13/cobra"
11	"gopkg.in/alessio/shellescape.v1"
12)
13
14// execCmd represents the exec command
15var execCmd = &cobra.Command{
16	Use:   "exec",
17	Short: "Run the selected commands",
18	Long:  `Run the selected commands directly`,
19	RunE:  execute,
20}
21
22func execute(cmd *cobra.Command, args []string) (err error) {
23	flag := config.Flag
24
25	var options []string
26	if flag.Query != "" {
27		options = append(options, fmt.Sprintf("--query %s", shellescape.Quote(flag.Query)))
28	}
29
30	commands, err := filter(options, flag.FilterTag)
31	if err != nil {
32		return err
33	}
34	command := strings.Join(commands, "; ")
35	if config.Flag.Debug {
36		fmt.Printf("Command: %s\n", command)
37	}
38	if config.Flag.Command {
39		fmt.Printf("%s: %s\n", color.YellowString("Command"), command)
40	}
41	return run(command, os.Stdin, os.Stdout)
42}
43
44func init() {
45	RootCmd.AddCommand(execCmd)
46	execCmd.Flags().BoolVarP(&config.Flag.Color, "color", "", false,
47		`Enable colorized output (only fzf)`)
48	execCmd.Flags().StringVarP(&config.Flag.Query, "query", "q", "",
49		`Initial value for query`)
50	execCmd.Flags().StringVarP(&config.Flag.FilterTag, "tag", "t", "",
51		`Filter tag`)
52	execCmd.Flags().BoolVarP(&config.Flag.Command, "command", "c", false,
53		`Show the command with the plain text before executing`)
54}
55