add(): Pass HistoryEntry struct

This commit is contained in:
Albert S. 2021-04-05 13:00:27 +02:00
parent 88362e99a9
commit 250af52750

37
main.go
View File

@ -100,6 +100,23 @@ func setDBVersion(conn *sql.DB, ver int) {
} }
} }
func NewHistoryEntry(cmd string) HistoryEntry {
wd, err := os.Getwd()
if err != nil {
log.Panic(err)
}
hostname, err := os.Hostname()
if err != nil {
log.Panic(err)
}
return HistoryEntry{
user : os.Getenv("USER"),
hostname : hostname,
cmd : cmd,
cwd : wd,
}
}
func importFromStdin(conn *sql.DB) { func importFromStdin(conn *sql.DB) {
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -109,7 +126,9 @@ func importFromStdin(conn *sql.DB) {
} }
for scanner.Scan() { for scanner.Scan() {
add(conn, scanner.Text(), "") entry := NewHistoryEntry(scanner.Text())
entry.cwd = ""
add(conn, entry)
} }
_, err = conn.Exec("END;") _, err = conn.Exec("END;")
@ -148,19 +167,13 @@ func delete(conn *sql.DB, entryId uint32) {
} }
} }
func add(conn *sql.DB, cmd string, cwd string) { func add(conn *sql.DB, entry HistoryEntry ) {
user := os.Getenv("USER")
hostname, err := os.Hostname()
if err != nil {
log.Panic(err)
}
stmt, err := conn.Prepare("INSERT INTO history (user, command, hostname, workdir) VALUES (?, ?, ?, ?)") stmt, err := conn.Prepare("INSERT INTO history (user, command, hostname, workdir) VALUES (?, ?, ?, ?)")
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
_, err = stmt.Exec(user, cmd, hostname, cwd) _, err = stmt.Exec(entry.user, entry.cmd, entry.hostname, entry.cwd)
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
@ -240,11 +253,7 @@ func main() {
var rgx = regexp.MustCompile("\\s+\\d+\\s+(.*)") var rgx = regexp.MustCompile("\\s+\\d+\\s+(.*)")
rs := rgx.FindStringSubmatch(historycmd) rs := rgx.FindStringSubmatch(historycmd)
if len(rs) == 2 { if len(rs) == 2 {
wd, err := os.Getwd() add(conn, NewHistoryEntry(rs[1]))
if err != nil {
log.Panic(err)
}
add(conn, rs[1], wd)
} }
case "search": fallthrough; case "search": fallthrough;
case "delete": case "delete":