diff --git a/conf.go b/conf.go deleted file mode 100644 index 0340af8..0000000 --- a/conf.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "os" -) - -func main() { - homeDir, err := os.UserHomeDir() - if err != nil { - return - } - if fileExists(homeDir+"/.gosh_history") { - fmt.Println("GoSh History file exists") - } else { - fmt.Println("GoSh History file does not exist") - } -} - -func fileExists(filename string) bool { - info, err := os.Stat(filename) - if os.IsNotExist(err) { - return false - } - return !info.IsDir() -} diff --git a/main.go b/main.go index cd537e8..5f67638 100644 --- a/main.go +++ b/main.go @@ -27,16 +27,18 @@ func main() { } func execInput(input string) error { - // Remove the newline caracter. + // Remove the newline character. input = strings.TrimSuffix(input, "\n") // Split the input to separate the command and the arguments. args := strings.Split(input, " ") + // Sauvegarde l'historique avant de traiter la commande + checkHistoryAndWrite(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 { @@ -44,12 +46,12 @@ func execInput(input string) error { } 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") + println("GoShell Version 0.2.0") + return nil } // Pass the program and the arguments separately. @@ -62,3 +64,32 @@ func execInput(input string) error { // Execute the command and return the error. return cmd.Run() } + +func fileExists(filename string) bool { + info, err := os.Stat(filename) + if os.IsNotExist(err) { + return false + } + return !info.IsDir() +} + +func checkHistoryAndWrite(text string) error { + homeDir, err := os.UserHomeDir() + if err != nil { + return errors.New("Unable to get home directory") + } + filePath := homeDir + "/.gosh_history" + + // Ouvre le fichier en mode append et avec les bons droits + file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + return fmt.Errorf("Can't open history file: %v", err) + } + defer file.Close() + + _, err = file.WriteString(text + "\n") + if err != nil { + return fmt.Errorf("Can't write to history: %v", err) + } + return nil +}