Skip to content

Commit 5cd0c43

Browse files
authored
Merge pull request #58 from reeflective/dev
dev
2 parents b373c40 + 4aa2f9d commit 5cd0c43

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

commands/exit.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package commands
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"os"
7+
"strings"
8+
9+
"github.com/spf13/cobra"
10+
)
11+
12+
// Exit returns a command to exit the console application.
13+
// The command will prompt the user to confirm quitting.
14+
func Exit() *cobra.Command {
15+
exitCmd := &cobra.Command{
16+
Use: "exit",
17+
Short: "Exit the console application",
18+
GroupID: "core",
19+
Run: func(_ *cobra.Command, _ []string) {
20+
exitCtrlD()
21+
},
22+
}
23+
24+
return exitCmd
25+
}
26+
27+
// exitCtrlD is a custom interrupt handler to use when the shell
28+
// readline receives an io.EOF error, which is returned with CtrlD.
29+
func exitCtrlD() {
30+
reader := bufio.NewReader(os.Stdin)
31+
32+
fmt.Print("Confirm exit (Y/y): ")
33+
34+
text, _ := reader.ReadString('\n')
35+
answer := strings.TrimSpace(text)
36+
37+
if (answer == "Y") || (answer == "y") {
38+
os.Exit(0)
39+
}
40+
}

commands/shell.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package commands
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
"os/exec"
8+
9+
"github.com/spf13/cobra"
10+
)
11+
12+
// ExecuteShell returns a cobra command to execute a line through the system shell.
13+
// This uses the os/exec package to execute the command. The default command name is `!`.
14+
func ExecuteShell() *cobra.Command {
15+
shellCmd := &cobra.Command{
16+
Use: "!",
17+
Short: "Execute the remaining arguments with system shell",
18+
DisableFlagParsing: true,
19+
RunE: func(_ *cobra.Command, args []string) error {
20+
if len(args) == 0 {
21+
return errors.New("command requires one or more arguments")
22+
}
23+
24+
path, err := exec.LookPath(args[0])
25+
if err != nil {
26+
return err
27+
}
28+
29+
shellCmd := exec.Command(path, args[1:]...)
30+
31+
// Load OS environment
32+
shellCmd.Env = os.Environ()
33+
34+
out, err := shellCmd.CombinedOutput()
35+
if err != nil {
36+
return err
37+
}
38+
39+
fmt.Print(string(out))
40+
41+
return nil
42+
},
43+
}
44+
45+
return shellCmd
46+
}

0 commit comments

Comments
 (0)