diff --git a/go.mod b/go.mod index d7bae00..90ff0e2 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,10 @@ go 1.25.5 require github.com/fatih/color v1.18.0 require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/spf13/cobra v1.10.2 // indirect + github.com/spf13/pflag v1.0.9 // indirect golang.org/x/sys v0.25.0 // indirect ) diff --git a/go.sum b/go.sum index 33148a4..d39b047 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,21 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/main.go b/main.go index f306c2b..9ec8697 100644 --- a/main.go +++ b/main.go @@ -2,12 +2,13 @@ package main import ( "fmt" - "github.com/fatih/color" "os" "os/exec" "runtime" "github.com/d3uceY/Ya-CLI/utils" + "github.com/fatih/color" + "github.com/spf13/cobra" ) func main() { @@ -16,174 +17,225 @@ func main() { green := color.New(color.FgGreen).SprintFunc() yellow := color.New(color.FgYellow).SprintFunc() - shortcuts, err := utils.LoadShortcuts() + // root command — handles running shortcuts directly via `ya [args...]` + var rootCmd = &cobra.Command{ + Use: "ya", + Short: "Ya - a CLI shortcut runner", + // DisableFlagParsing allows extra args like -m to be passed through to the shortcut command + DisableFlagParsing: true, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + shortcut := args[0] + + shortcuts, err := utils.LoadShortcuts() + if err != nil { + color.Red("Error loading shortcuts: %v", err) + os.Exit(1) + } - if err != nil { - color.Red("Error loading shortcuts:", err) - os.Exit(1) - } + command, exists := shortcuts[shortcut] - if len(os.Args) < 2 { - color.Red("Usage: ya \n for shortcuts use: ya help") - os.Exit(1) - } + if !exists { + fmt.Printf("Unknown shortcut: %s\n to add a new shortcut use: ya add ''", yellow(shortcut)) + os.Exit(1) + } + + // i added this because i was wondering how i would have been using this + // this allows arguments passing the shortcut commands to also pass messages like git commit -m 'message' + if len(args) > 1 { + for index, value := range args { + if index >= 1 { + if value != "-m" { + if args[index-1] == "-m" { + command += " " + fmt.Sprintf("'%s'", value) + } else { + command += " " + value + } + } + } + } + } - shortcut := os.Args[1] + // if we are here, detect if it is windows, you get? + var execCmd *exec.Cmd + if runtime.GOOS == "windows" { + execCmd = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", command) + } else { + // for linux and macOS typeshit + execCmd = exec.Command("bash", "-c", command) + } - switch shortcut { - // Version command - case "version", "-v": - if len(os.Args) > 2 { - color.Red("usage: ya version") - os.Exit(1) - } - version := utils.GetAppVersion() - color.Green("Ya version: %s", version) - return + execCmd.Stdout = os.Stdout + execCmd.Stderr = os.Stderr + execCmd.Stdin = os.Stdin - // list command - case "list", "-l", "--list": - if len(os.Args) > 2 { - color.Red("usage: ya list") - os.Exit(1) - } - color.Green("Available shortcuts:") - for key, cmd := range shortcuts { - fmt.Printf("- %s : %s\n", yellow(key), green(cmd)) - } - return - // Help command - case "help", "--help", "-h": - if len(os.Args) > 2 { - color.Red("usage: ya help") - os.Exit(1) - } + cmdError := execCmd.Run() + if cmdError != nil { + color.Red("Command failed: %v", cmdError) + os.Exit(1) + } + }, + } - fmt.Println("\n--- Ya Usage ---") + // Version command + var versionCmd = &cobra.Command{ + Use: "version", + Short: "Show the current Ya version", + Aliases: []string{"-v", "--version"}, + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + version := utils.GetAppVersion() + color.Green("Ya version: %s", version) + }, + } - fmt.Printf("%s %s\n", yellow("To add a new shortcut use:"), green("ya add ")) - fmt.Printf("%s %s\n", yellow("To remove a shortcut use:"), green("ya remove ")) - fmt.Printf("%s %s\n", yellow("To list all shortcuts:"), green("ya list")) - fmt.Printf("%s %s\n", yellow("To show version:"), green("ya version")) - fmt.Printf("%s %s\n", yellow("To import shortcuts use:"), green("ya import ")) - fmt.Printf("%s %s\n", yellow("To search shortcuts use:"), green("ya search ")) - fmt.Printf("%s %s\n", yellow("To show shortcuts use:"), green("ya show ")) + // list command + var listCmd = &cobra.Command{ + Use: "list", + Short: "List all available shortcuts", + Aliases: []string{"-l", "--list"}, + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + shortcuts, err := utils.LoadShortcuts() + if err != nil { + color.Red("Error loading shortcuts: %v", err) + os.Exit(1) + } + color.Green("Available shortcuts:") + for key, command := range shortcuts { + fmt.Printf("- %s : %s\n", yellow(key), green(command)) + } + }, + } - fmt.Println() - return + // Help command + var helpCmd = &cobra.Command{ + Use: "help", + Short: "Show usage information", + Aliases: []string{"--help", "-h"}, + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("\n--- Ya Usage ---") + + fmt.Printf("%s %s\n", yellow("To add a new shortcut use:"), green("ya add ")) + fmt.Printf("%s %s\n", yellow("To remove a shortcut use:"), green("ya remove ")) + fmt.Printf("%s %s\n", yellow("To list all shortcuts:"), green("ya list")) + fmt.Printf("%s %s\n", yellow("To show version:"), green("ya version")) + fmt.Printf("%s %s\n", yellow("To import shortcuts use:"), green("ya import ")) + fmt.Printf("%s %s\n", yellow("To search shortcuts use:"), green("ya search ")) + fmt.Printf("%s %s\n", yellow("To show shortcuts use:"), green("ya show ")) + + fmt.Println() + }, + } // Search command - case "search", "--search": - if len(os.Args) > 3 { - color.Red("usage: ya search ") - os.Exit(1) - } - shortcuts, err := utils.SearchShortcut(os.Args[2]) - if err != nil { - color.Red(err.Error()) - } - if !(len(shortcuts) >= 1) { - color.Red("Shortcuts with `%s` not found", os.Args[2]) - } - color.Green("Search results:") - for key, cmd := range shortcuts { - color.Yellow(" - %s :", key) - color.Green(" %s", cmd) - } - return + var searchCmd = &cobra.Command{ + Use: "search ", + Short: "Search for shortcuts by name or command", + Aliases: []string{"--search"}, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + shortcuts, err := utils.SearchShortcut(args[0]) + if err != nil { + color.Red(err.Error()) + } + if !(len(shortcuts) >= 1) { + color.Red("Shortcuts with `%s` not found", args[0]) + } + color.Green("Search results:") + for key, command := range shortcuts { + color.Yellow(" - %s :", key) + color.Green(" %s", command) + } + }, + } // Show command - case "show": - if len(os.Args) > 3 || len(os.Args) < 3 { - color.Red("usage: ya show ") - os.Exit(1) - } - command, err := utils.GetShortcut(os.Args[2]) - if err != nil { - color.Red(err.Error()) - os.Exit(1) - } - fmt.Printf("Shortcut `%s` maps to command: %s\n", yellow(os.Args[2]), green(command)) - return + var showCmd = &cobra.Command{ + Use: "show ", + Short: "Show the command mapped to a shortcut", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + command, err := utils.GetShortcut(args[0]) + if err != nil { + color.Red(err.Error()) + os.Exit(1) + } + fmt.Printf("Shortcut `%s` maps to command: %s\n", yellow(args[0]), green(command)) + }, + } // Add command - case "add": - if len(os.Args) < 4 { - color.Red("Usage: ya add ''") - os.Exit(1) - } - shortcutName := os.Args[2] - command := os.Args[3] - if utils.IsInvalidString(shortcutName) || utils.IsInvalidString(command) { - color.Red("Usage: ya add ''") - os.Exit(1) - } - utils.AddShortcut(shortcutName, command) - return - - // import shortcuts - case "import": - if len(os.Args) < 3 { - color.Red("Usage: ya import ''") - os.Exit(1) - } - - err := utils.ImportShortcuts(os.Args[2]) - if err != nil { - color.Red(err.Error()) - os.Exit(1) - } - color.Green("Shortcut Imported `%s`", os.Args[2]) - return - // Remove command - case "remove": - if len(os.Args) < 3 { - color.Red("Usage: ya remove ") - os.Exit(1) - } - utils.RemoveShortcut(os.Args[2]) - return + var addCmd = &cobra.Command{ + Use: "add ", + Short: "Add a new shortcut", + Args: cobra.ExactArgs(2), + Run: func(cmd *cobra.Command, args []string) { + shortcutName := args[0] + command := args[1] + if utils.IsInvalidString(shortcutName) || utils.IsInvalidString(command) { + color.Red("Usage: ya add ''") + os.Exit(1) + } + utils.AddShortcut(shortcutName, command) + }, } - command, exists := shortcuts[shortcut] - - // i added this because i was wondering how i would have been using this - // this allows arguments passing the shortcut commands to also pass messages like git commit -m 'message' - if len(os.Args) > 2 { - for index, value := range os.Args { - if !(index <= 1) { - if value != "-m" { - if os.Args[index-1] == "-m" { - command += " " + fmt.Sprintf("'%s'", value) - } else { - command += " " + value - } - } + // import shortcuts + var importCmd = &cobra.Command{ + Use: "import ", + Short: "Import shortcuts from a JSON file", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + err := utils.ImportShortcuts(args[0]) + if err != nil { + color.Red(err.Error()) + os.Exit(1) } - } + color.Green("Shortcut Imported `%s`", args[0]) + }, } - if !exists { - fmt.Printf("Unknown shortcut: %s\n to add a new shortcut use: ya add ''", yellow(shortcut)) - os.Exit(1) + // export shortcuts + // usage: ya export [--name ] + // if --name is not provided, defaults to shortcuts.json + var exportName string + var exportCmd = &cobra.Command{ + Use: "export ", + Short: "Export shortcuts to a JSON file in the given directory", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + filePath := args[0] + "/" + exportName + err := utils.ExportShortcuts(filePath) + if err != nil { + color.Red(err.Error()) + os.Exit(1) + } + color.Green("Shortcuts exported to `%s`", filePath) + }, } + // --name flag to set the output filename, defaults to shortcuts.json + exportCmd.Flags().StringVarP(&exportName, "name", "n", "shortcuts.json", "Name of the exported file") - // if we are here, detect if it is windows, you get? - var cmd *exec.Cmd - if runtime.GOOS == "windows" { - cmd = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", command) - } else { - // for linux and macOS typeshit - cmd = exec.Command("bash", "-c", command) + // Remove command + var removeCmd = &cobra.Command{ + Use: "remove ", + Short: "Remove an existing shortcut", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + utils.RemoveShortcut(args[0]) + }, } - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - cmd.Stdin = os.Stdin + // register all subcommands onto the root + rootCmd.AddCommand(versionCmd, listCmd, helpCmd, searchCmd, showCmd, addCmd, importCmd, exportCmd, removeCmd) + + // disable cobra's default help/completion so our custom help command takes over cleanly + rootCmd.SetHelpCommand(helpCmd) + rootCmd.CompletionOptions.DisableDefaultCmd = true - cmdError := cmd.Run() - if cmdError != nil { - color.Red("Command failed: %v", cmdError) + if err := rootCmd.Execute(); err != nil { os.Exit(1) } } diff --git a/utils/utilities.go b/utils/utilities.go index 2020132..53d1027 100644 --- a/utils/utilities.go +++ b/utils/utilities.go @@ -221,3 +221,24 @@ func ImportShortcuts(path string) error { // this permission param lowkey threw me off ngl return os.WriteFile(shortCutpath, data, 0644) } + +// exports the shortcut and takes the concatenated file path as a param +func ExportShortcuts(filepath string) error { + shortcuts, err := LoadShortcuts() + + if err != nil { + return fmt.Errorf("Could not load Shortcuts for exports %v", err) + } + + data, err := json.MarshalIndent(shortcuts, "", " ") + if err != nil { + return err + } + + err = os.WriteFile(filepath, data, 0644) + + if err != nil { + return err + } + return nil +}