mirror of
https://github.com/Alexandre1a/GoSH.git
synced 2026-03-09 19:19:46 +01:00
65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
reader := bufio.NewReader(os.Stdin)
|
|
for {
|
|
fmt.Print("> ")
|
|
// Read the keyboard input.
|
|
input, err := reader.ReadString('\n')
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
}
|
|
|
|
// Handle the execution of the input.
|
|
if err = execInput(input); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func execInput(input string) error {
|
|
// Remove the newline caracter.
|
|
input = strings.TrimSuffix(input, "\n")
|
|
|
|
// Split the input to separate the command and the arguments.
|
|
args := strings.Split(input, " ")
|
|
|
|
// Check for built-in commands.
|
|
switch args[0] {
|
|
case "cd":
|
|
// Change to ~ with an empty PATH is not supported
|
|
if len(args) < 2 || args[1] == "" {
|
|
homeDir, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return errors.New("Unable to get home directory")
|
|
}
|
|
return os.Chdir(homeDir)
|
|
}
|
|
// Change the dir and return the error.
|
|
return os.Chdir(args[1])
|
|
case "exit":
|
|
os.Exit(0)
|
|
case "version":
|
|
println("GoShell Version 0.0.1")
|
|
}
|
|
|
|
// Pass the program and the arguments separately.
|
|
cmd := exec.Command(args[0], args[1:]...)
|
|
|
|
// Set the correct output device.
|
|
cmd.Stderr = os.Stderr
|
|
cmd.Stdout = os.Stdout
|
|
|
|
// Execute the command and return the error.
|
|
return cmd.Run()
|
|
}
|