5119
Lh
lazy-history / files
lazy-history / main.go
2.1 KB
1package main 2 3import ( 4 "bufio" 5 "log" 6 "os" 7 "os/exec" 8 "path/filepath" 9 "strings" 10 11 tea "github.com/charmbracelet/bubbletea" 12 "github.com/sacenox/lazy-history/internal/debug" 13 internal_list "github.com/sacenox/lazy-history/internal/list" 14 "github.com/sacenox/lazy-history/internal/search" 15) 16 17func main() { 18 if debug.IsDebug { 19 // Clear the debug.log file 20 os.Truncate("debug.log", 0) 21 22 // Log to the debug.log file 23 f, err := tea.LogToFile("debug.log", "debug") 24 if err != nil { 25 log.Fatalf("Failed to log to file: %v", err) 26 } 27 defer f.Close() 28 } 29 30 // Get the output of `history` 31 history := []string{} // one cmd per entry 32 33 historyFilePaths := []string{ 34 filepath.Join(os.Getenv("HOME"), ".history"), 35 filepath.Join(os.Getenv("HOME"), ".zsh_history"), 36 filepath.Join(os.Getenv("HOME"), ".bash_history"), 37 } 38 39 // TODO: This is not working, we need to do it in an interactive shell owner by the user. 40 // Run `history -a` to append the history to the files 41 exec.Command("history", "-a").Run() 42 43 // Read the history files 44 for _, historyFilePath := range historyFilePaths { 45 if _, err := os.Stat(historyFilePath); os.IsNotExist(err) { 46 continue 47 } 48 49 historyFile, err := os.Open(historyFilePath) 50 if err != nil { 51 log.Fatalf("Failed to open history file: %v", err) 52 } 53 54 scanner := bufio.NewScanner(historyFile) 55 // Read each line from the history file 56 for scanner.Scan() { 57 line := scanner.Text() 58 history = append(history, line) 59 } 60 61 // Check for scanner errors 62 if err := scanner.Err(); err != nil { 63 log.Fatalf("Error reading history file %s: %v", historyFilePath, err) 64 } 65 66 historyFile.Close() 67 } 68 69 debug.Debugf("History length: %d", len(history)) 70 71 // Join all args into a single string 72 query := strings.Join(os.Args[1:], " ") 73 74 debug.Debugf("Searching for %s", query) 75 76 // Search the history output for the query 77 results := search.Search(history, query) 78 79 debug.Debugf("Found %d results", len(results)) 80 debug.Debugf("Results: %v", results) 81 82 ui := internal_list.New(results) 83 84 if _, err := tea.NewProgram(ui).Run(); err != nil { 85 log.Fatal("Error running program: ", err) 86 } 87}