cdhist/main.go

89 lines
2.2 KiB
Go

package main
import (
"os"
"flag"
"log"
"path"
"fmt"
// "cdhist/dir"
)
// must run the following to source the cd bash function:
// if type cdhist &>/dev/null; then . <(cdhist -i); fi
var (
histFile string = ".cd_history"
aliasFile string = ".cd_aliases"
outString string = ""
)
type BashFuncOpts struct {
Command string
FuncName string
}
func main() {
// cdableVars()
dir, err := os.UserHomeDir()
if err != nil {
log.Printf("Error reading cd history file: %v", err)
}
histFile = path.Join(dir, histFile)
aliasFile = path.Join(dir, aliasFile)
if len(os.Args) == 2 && os.Args[1] == "--" {
if err := histList(histFile); err != nil {
log.Printf("Error reading cd history file: %s", err)
}
os.Exit(1)
}
flagInit := flag.Bool("i", false, "Creates function to be sourced by bash")
flagList := flag.Bool("l", false, "List cd history without prompting")
flagL := flag.Bool("L", false, "Builtin cd option, passed to cd")
flagP := flag.Bool("P", false, "Builtin cd option, passed to cd")
flage := flag.Bool("e", false, "Builtin cd option, passed to cd")
flagAt := flag.Bool("@", false, "Builtin cd option, passed to cd")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [option] [dir]\n\n", os.Args[0])
fmt.Fprint(flag.CommandLine.Output(), "Change directory and save directory to history.\n")
fmt.Fprint(flag.CommandLine.Output(), "Or show directory history with or without prompt.\n\n")
fmt.Fprint(flag.CommandLine.Output(), " --\tShow history with prompt.\n")
flag.PrintDefaults()
os.Exit(1)
}
flag.Parse()
switch {
case *flagInit:
name := "cd"
if flag.Arg(0) != "" {
name = flag.Arg(0)
}
printBashFunc(BashFuncOpts{FuncName: name, Command: os.Args[0]})
os.Exit(1)
case *flagList:
if err := histListNoPrompt(histFile); err != nil {
log.Printf("Error reading cd history file: %s", err)
}
os.Exit(2)
case *flagL:
outString = fmt.Sprintf("%s -L", outString)
case *flagP:
outString = fmt.Sprintf("%s -P", outString)
case *flage:
outString = fmt.Sprintf("%s -e", outString)
case *flagAt:
outString = fmt.Sprintf("%s -@", outString)
}
path := flag.Arg(0)
cd(histFile, aliasFile, outString, path)
return
}