added an history for future features...

This commit is contained in:
Alexandre 2025-01-30 20:39:57 +01:00
parent 4ee0f33170
commit ce9340a570
2 changed files with 35 additions and 30 deletions

26
conf.go
View File

@ -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()
}

39
main.go
View File

@ -27,16 +27,18 @@ func main() {
} }
func execInput(input string) error { func execInput(input string) error {
// Remove the newline caracter. // Remove the newline character.
input = strings.TrimSuffix(input, "\n") input = strings.TrimSuffix(input, "\n")
// Split the input to separate the command and the arguments. // Split the input to separate the command and the arguments.
args := strings.Split(input, " ") args := strings.Split(input, " ")
// Sauvegarde l'historique avant de traiter la commande
checkHistoryAndWrite(input)
// Check for built-in commands. // Check for built-in commands.
switch args[0] { switch args[0] {
case "cd": case "cd":
// Change to ~ with an empty PATH is not supported
if len(args) < 2 || args[1] == "" { if len(args) < 2 || args[1] == "" {
homeDir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {
@ -44,12 +46,12 @@ func execInput(input string) error {
} }
return os.Chdir(homeDir) return os.Chdir(homeDir)
} }
// Change the dir and return the error.
return os.Chdir(args[1]) return os.Chdir(args[1])
case "exit": case "exit":
os.Exit(0) os.Exit(0)
case "version": case "version":
println("GoShell Version 0.0.1") println("GoShell Version 0.2.0")
return nil
} }
// Pass the program and the arguments separately. // Pass the program and the arguments separately.
@ -62,3 +64,32 @@ func execInput(input string) error {
// Execute the command and return the error. // Execute the command and return the error.
return cmd.Run() 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
}