diff --git a/cdhist.go b/cdhist.go index bbe3404..dc956bf 100644 --- a/cdhist.go +++ b/cdhist.go @@ -1,9 +1,76 @@ package main -func histAdd() { +import ( + "fmt" + "log" + "os" + "io" + "bufio" +) + +func histAdd(histFile string, path string) (error) { + + data, err := ReadLines(histFile) + if err != nil { + if os.IsNotExist(err) != true { + log.Printf("Error reading cd history file: %v", err) + } + } + data = append(data, path) + file, err := os.OpenFile(histFile, os.O_RDWR|os.O_CREATE, 0660) + if err != nil { + return err + } + defer file.Close() + + for _, line := range data { + _, err := file.Write([]byte(fmt.Sprintf("%s\n", line))) + if err != nil { + log.Printf("Error writing cd history file: %v", err) + return err + } + } + return err +} + +func histList(histFile string) { + fmt.Println("List") + return } -func histList() { +func ReadLines(fileName string) (data []string, err error) { + file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0660) + if err != nil { + // log.Print(err) + return nil, err + } + defer file.Close() + + reader := bufio.NewReader(file) + var paths []string + for { + line, _, err := reader.ReadLine() + if err != nil { + if err == io.EOF { + err = nil + } + break + } + paths = append(paths, string(line)) + } + return paths, err +} + +// makeBashFunc prints the wrapper function to be sourced by bash +func makeBashFunc() { +// fmt.Printf("cdh() { local d; d=$(cdhist-v2 \"$@\"); if [ $? -ne 0 ]; then return 0; fi; builtin cd -- \"$d\"; }") + fmt.Printf(`cdh() { + local d + d=$(cdhist-v2 "$@") + if [ $? -ne 0 ]; then return 0 + fi + builtin cd -- "$d" + }`) return } diff --git a/go.mod b/go.mod index 5ffcf4d..ae48c2b 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module projects/cdhist-v2 +module projects/cdhist go 1.20 diff --git a/main.go b/main.go index 7b9c6c3..df9fbf2 100644 --- a/main.go +++ b/main.go @@ -2,14 +2,42 @@ package main import ( "os" + // "os/exec" + "log" + "path" + // "syscall" + "fmt" ) -func main(){ - if len(os.Args) > 1 && os.Args[1] == "add" { - histAdd() - return +var ( + histFile string = ".cd_history" +) + +func main() { + + histFileDir, err := os.UserHomeDir() + if err != nil { + log.Fatal(err, "Can't find home directory.") + } + histFile := path.Join(histFileDir, histFile) + + if len(os.Args) > 1 && os.Args[1] == "--" { + histList(histFile) + os.Exit(1) + } + + if len(os.Args) > 1 && os.Args[1] == "-i" { + makeBashFunc() + os.Exit(1) } - histList() + if len(os.Args) > 1 { + path := os.Args[1] + histAdd(histFile, path) + fmt.Printf("%s", path) + os.Exit(0) + } + + return }