Skip to content

Commit

Permalink
Merge pull request #58 from reeflective/dev
Browse files Browse the repository at this point in the history
dev
  • Loading branch information
maxlandon authored Nov 16, 2024
2 parents b373c40 + 4aa2f9d commit 5cd0c43
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
40 changes: 40 additions & 0 deletions commands/exit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package commands

import (
"bufio"
"fmt"
"os"
"strings"

"github.com/spf13/cobra"
)

// Exit returns a command to exit the console application.
// The command will prompt the user to confirm quitting.
func Exit() *cobra.Command {
exitCmd := &cobra.Command{
Use: "exit",
Short: "Exit the console application",
GroupID: "core",
Run: func(_ *cobra.Command, _ []string) {
exitCtrlD()
},
}

return exitCmd
}

// exitCtrlD is a custom interrupt handler to use when the shell
// readline receives an io.EOF error, which is returned with CtrlD.
func exitCtrlD() {
reader := bufio.NewReader(os.Stdin)

fmt.Print("Confirm exit (Y/y): ")

text, _ := reader.ReadString('\n')
answer := strings.TrimSpace(text)

if (answer == "Y") || (answer == "y") {
os.Exit(0)
}
}
46 changes: 46 additions & 0 deletions commands/shell.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package commands

import (
"errors"
"fmt"
"os"
"os/exec"

"github.com/spf13/cobra"
)

// ExecuteShell returns a cobra command to execute a line through the system shell.
// This uses the os/exec package to execute the command. The default command name is `!`.
func ExecuteShell() *cobra.Command {
shellCmd := &cobra.Command{
Use: "!",
Short: "Execute the remaining arguments with system shell",
DisableFlagParsing: true,
RunE: func(_ *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("command requires one or more arguments")
}

path, err := exec.LookPath(args[0])
if err != nil {
return err
}

shellCmd := exec.Command(path, args[1:]...)

// Load OS environment
shellCmd.Env = os.Environ()

out, err := shellCmd.CombinedOutput()
if err != nil {
return err
}

fmt.Print(string(out))

return nil
},
}

return shellCmd
}

0 comments on commit 5cd0c43

Please sign in to comment.