This repository has been archived by the owner on Oct 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
482 lines (412 loc) · 10.6 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package main
import (
"bufio"
"container/list"
"database/sql"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"hs9001/liner"
"github.com/tj/go-naturaldate"
_ "modernc.org/sqlite"
)
type HistoryEntry struct {
id uint32
cmd string
cwd string
hostname string
user string
retval int
timestamp time.Time
}
var GitTag string
var GitCommit string
func databaseLocation() string {
envOverride := os.Getenv("HS9001_DB_PATH")
if envOverride != "" {
return envOverride
}
return filepath.Join(xdgOrFallback("XDG_DATA_HOME", filepath.Join(os.Getenv("HOME"), ".local/share")), "hs9001/db.sqlite")
}
func createConnection() *sql.DB {
db, err := sql.Open("sqlite", databaseLocation())
if err != nil {
log.Panic(err)
}
return db
}
func initDatabase(conn *sql.DB) {
queryStmt := "CREATE TABLE history(id INTEGER PRIMARY KEY, command varchar(512), timestamp datetime DEFAULT current_timestamp, user varchar(25), hostname varchar(32));\n" +
"CREATE VIEW count_by_date AS SELECT COUNT(id), STRFTIME('%Y-%m-%d', timestamp) FROM history GROUP BY strftime('%Y-%m-%d', timestamp)"
_, err := conn.Exec(queryStmt)
if err != nil {
log.Panic(err)
}
}
func migrateDatabase(conn *sql.DB, currentVersion int) {
migrations := []string{
"ALTER TABLE history ADD COLUMN workdir varchar(4096) DEFAULT ''",
"ALTER TABLE history ADD COLUMN retval integer DEFAULT -9001",
"ALTER TABLE history ADD COLUMN unix_tmp integer",
"UPDATE history SET unix_tmp = strftime('%s', timestamp)",
"DROP VIEW count_by_date",
"ALTER TABLE history DROP COLUMN timestamp",
"ALTER TABLE history RENAME COLUMN unix_tmp TO timestamp",
}
if !(len(migrations) > currentVersion) {
return
}
_, err := conn.Exec("BEGIN;")
if err != nil {
log.Panic(err)
}
for _, m := range migrations[currentVersion:] {
_, err := conn.Exec(m)
if err != nil {
log.Panic(err)
}
}
setDBVersion(conn, len(migrations))
_, err = conn.Exec("END;")
if err != nil {
log.Panic(err)
}
}
func fetchDBVersion(conn *sql.DB) int {
rows, err := conn.Query("PRAGMA user_version;")
if err != nil {
log.Panic(err)
}
defer rows.Close()
rows.Next()
var res int
rows.Scan(&res)
return res
}
func setDBVersion(conn *sql.DB, ver int) {
_, err := conn.Exec(fmt.Sprintf("PRAGMA user_version=%d", ver))
if err != nil {
log.Panic(err)
}
}
func NewHistoryEntry(cmd string, retval int) 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,
timestamp: time.Now(),
retval: retval,
}
}
func importFromStdin(conn *sql.DB) {
scanner := bufio.NewScanner(os.Stdin)
_, err := conn.Exec("BEGIN;")
if err != nil {
log.Panic(err)
}
for scanner.Scan() {
entry := NewHistoryEntry(scanner.Text(), -9001)
entry.cwd = ""
entry.timestamp = time.Unix(0, 0)
add(conn, entry)
}
_, err = conn.Exec("END;")
if err != nil {
log.Panic(err)
}
}
type searchopts struct {
command *string
workdir *string
after *time.Time
before *time.Time
retval *int
order *string
limit *int
}
func search(conn *sql.DB, opts searchopts) list.List {
args := make([]interface{}, 0)
var sb strings.Builder
sb.WriteString("SELECT id, command, workdir, user, hostname, retval, timestamp ")
sb.WriteString("FROM history ")
sb.WriteString("WHERE 1=1 ") //1=1 so we can append as many AND foo as we want, or none
if opts.command != nil {
sb.WriteString("AND command LIKE ? ")
args = append(args, opts.command)
}
if opts.workdir != nil {
sb.WriteString("AND workdir LIKE ? ")
args = append(args, opts.workdir)
}
if opts.after != nil {
sb.WriteString("AND timestamp > ? ")
args = append(args, opts.after.Unix())
}
if opts.before != nil {
sb.WriteString("AND timestamp < ? ")
args = append(args, opts.before.Unix())
}
if opts.retval != nil {
sb.WriteString("AND retval = ? ")
args = append(args, opts.retval)
}
sb.WriteString("ORDER BY timestamp ")
if opts.order != nil {
sb.WriteString(*opts.order)
sb.WriteRune(' ')
} else {
sb.WriteString("ASC ")
}
if opts.limit != nil {
sb.WriteString("LIMIT ")
sb.WriteString(strconv.Itoa(*opts.limit))
sb.WriteRune(' ')
}
queryStmt := sb.String()
rows, err := conn.Query(queryStmt, args...)
if err != nil {
log.Panic(err)
}
var result list.List
defer rows.Close()
for rows.Next() {
var entry HistoryEntry
var timestamp int64
err = rows.Scan(&entry.id, &entry.cmd, &entry.cwd, &entry.user, &entry.hostname, &entry.retval, ×tamp)
if err != nil {
log.Panic(err)
}
entry.timestamp = time.Unix(timestamp, 0)
result.PushBack(&entry)
}
return result
}
func delete(conn *sql.DB, entryId uint32) {
queryStmt := "DELETE FROM history WHERE id = ?"
_, err := conn.Exec(queryStmt, entryId)
if err != nil {
log.Panic(err)
}
}
func add(conn *sql.DB, entry HistoryEntry) {
stmt, err := conn.Prepare("INSERT INTO history (user, command, hostname, workdir, timestamp, retval) VALUES (?, ?, ?, ?, ?,?)")
if err != nil {
log.Panic(err)
}
_, err = stmt.Exec(entry.user, entry.cmd, entry.hostname, entry.cwd, entry.timestamp.Unix(), entry.retval)
if err != nil {
log.Panic(err)
}
}
func xdgOrFallback(xdg string, fallback string) string {
dir := os.Getenv(xdg)
if dir != "" {
if ok, err := exists(dir); ok && err == nil {
return dir
}
}
return fallback
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func printUsage() {
fmt.Fprintf(os.Stderr, "Usage: ./hs9001 <add/search/import/nolog/bash-enable>\n")
}
func main() {
addCmd := flag.NewFlagSet("add", flag.ExitOnError)
searchCmd := flag.NewFlagSet("search", flag.ExitOnError)
if len(os.Args) < 2 {
printUsage()
return
}
cmd := os.Args[1]
globalargs := os.Args[2:]
var conn *sql.DB
ok, _ := exists(databaseLocation())
if !ok {
err := os.MkdirAll(filepath.Dir(databaseLocation()), 0755)
if err != nil {
log.Panic(err)
}
conn = createConnection()
initDatabase(conn)
} else {
conn = createConnection()
}
migrateDatabase(conn, fetchDBVersion(conn))
switch cmd {
case "bash-ctrlr":
line := liner.NewLiner()
defer line.Close()
line.SetCtrlCAborts(true)
line.SetHistoryProvider(&history{conn: conn})
line.SetMultiLineMode(true)
rdlineline := os.Getenv("READLINE_LINE")
rdlinepos := os.Getenv("READLINE_POS")
rdlineposint, _ := strconv.Atoi(rdlinepos)
if name, err := line.PromptWithSuggestionReverse("", rdlineline, rdlineposint); err == nil {
fmt.Fprintf(os.Stderr, "%s\n", name)
}
case "bash-enable":
fmt.Printf(`
if [ -n "$PS1" ] ; then
PROMPT_COMMAND='hs9001 add -ret $? "$(history 1)"'
bind -x '"\C-r": " READLINE_LINE=$(hs9001 bash-ctrlr 3>&1 1>&2 2>&3) READLINE_POINT=0"'
fi
alias hs='hs9001 search'
`)
case "bash-disable":
fmt.Printf("unset PROMPT_COMMAND\n")
case "add":
var ret int
addCmd.IntVar(&ret, "ret", 0, "Return value of the command to add")
addCmd.Parse(globalargs)
args := addCmd.Args()
if ret == 23 { // 23 is our secret do not log status code
return
}
if len(args) < 1 {
fmt.Fprint(os.Stderr, "Error: You need to provide the command to be added")
}
historycmd := args[0]
var rgx = regexp.MustCompile(`\s+\d+\s+(.*)`)
rs := rgx.FindStringSubmatch(historycmd)
if len(rs) == 2 {
add(conn, NewHistoryEntry(rs[1], ret))
}
case "search":
fallthrough
case "delete":
var workDir string
var afterTime string
var beforeTime string
var distinct bool = true
var today bool = false
var retVal int
searchCmd.StringVar(&workDir, "cwd", "", "Search only within this workdir")
searchCmd.StringVar(&afterTime, "after", "", "Start searching from this timeframe")
searchCmd.StringVar(&beforeTime, "before", "", "End searching from this timeframe")
searchCmd.BoolVar(&distinct, "distinct", true, "Remove consecutive duplicate commands from output")
searchCmd.BoolVar(&today, "today", false, "Search only today's entries. Overrides --after")
searchCmd.IntVar(&retVal, "ret", -9001, "Only query commands that returned with this exit code. -9001=all (default)")
searchCmd.Parse(globalargs)
args := searchCmd.Args()
q := strings.Join(args, " ")
opts := searchopts{}
o := "ASC"
opts.order = &o
if q != "" {
cmd := "%" + q + "%"
opts.command = &cmd
}
if workDir != "" {
wd, err := filepath.Abs(workDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed parse working directory path: %s\n", err.Error())
}
opts.workdir = &wd
}
if today {
afterTime = "today"
}
if afterTime != "" {
afterTimestamp, err := naturaldate.Parse(afterTime, time.Now())
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to convert time string: %s\n", err.Error())
}
opts.after = &afterTimestamp
}
if beforeTime != "" {
beforeTimestamp, err := naturaldate.Parse(beforeTime, time.Now())
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to convert time string: %s\n", err.Error())
}
opts.before = &beforeTimestamp
}
if retVal != -9001 {
opts.retval = &retVal
}
results := search(conn, opts)
previousCmd := ""
previousReturn := -1
fi, err := os.Stdout.Stat()
if err != nil {
panic(err)
}
//Don't print colors if output is piped
printColors := true
if (fi.Mode() & os.ModeCharDevice) == 0 {
printColors = false
}
for e := results.Front(); e != nil; e = e.Next() {
entry, ok := e.Value.(*HistoryEntry)
if !ok {
log.Panic("Failed to retrieve entries")
}
if !distinct || !(previousCmd == entry.cmd && previousReturn == entry.retval) {
prefix := ""
postfix := ""
if printColors && entry.retval != 0 {
prefix = "\033[38;5;88m"
postfix = "\033[0m"
}
fmt.Printf("%s%s%s\n", prefix, entry.cmd, postfix)
}
previousCmd = entry.cmd
previousReturn = entry.retval
}
if cmd == "delete" {
_, err := conn.Exec("BEGIN;")
if err != nil {
log.Panic(err)
}
for e := results.Front(); e != nil; e = e.Next() {
entry, ok := e.Value.(*HistoryEntry)
if !ok {
log.Panic("Failed to retrieve entries")
}
delete(conn, entry.id)
}
_, err = conn.Exec("END;")
if err != nil {
log.Panic(err)
}
_, err = conn.Exec("VACUUM")
if err != nil {
log.Panic(err)
}
}
os.Exit(23)
case "import":
importFromStdin(conn)
case "version":
fmt.Fprintf(os.Stdout, "Git Tag: %s\nGit Commit: %s\n", GitTag, GitCommit)
default:
fmt.Fprintf(os.Stderr, "Error: Unknown subcommand '%s' supplied\n\n", cmd)
printUsage()
return
}
}