Basic working utility. Needs refinement

master
Bryan 2023-09-11 09:22:28 -06:00
parent c3b483e47d
commit 3704ed9985
3 changed files with 103 additions and 8 deletions

View File

@ -1,9 +1,76 @@
package main 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 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 return
} }

2
go.mod
View File

@ -1,3 +1,3 @@
module projects/cdhist-v2 module projects/cdhist
go 1.20 go 1.20

38
main.go
View File

@ -2,14 +2,42 @@ package main
import ( import (
"os" "os"
// "os/exec"
"log"
"path"
// "syscall"
"fmt"
) )
func main(){ var (
if len(os.Args) > 1 && os.Args[1] == "add" { histFile string = ".cd_history"
histAdd() )
return
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 return
} }