1
0
réplica de https://github.com/quitesimpleorg/hs9001.git sincronizado 2024-11-01 02:04:37 +01:00
hs9001/main.go

320 linhas
6.2 KiB
Go
Em bruto Vista normal Histórico

2021-03-20 19:39:18 +01:00
package main
import (
"bufio"
"container/list"
2021-03-20 19:39:18 +01:00
"database/sql"
"flag"
"fmt"
"log"
"os"
2021-03-20 20:18:27 +01:00
"path/filepath"
2021-03-20 19:39:18 +01:00
"regexp"
"strings"
2021-04-05 14:00:51 +02:00
"time"
2021-03-20 20:18:27 +01:00
2021-04-05 14:00:51 +02:00
"github.com/tj/go-naturaldate"
2021-03-20 20:18:27 +01:00
_ "modernc.org/sqlite"
2021-03-20 19:39:18 +01:00
)
type HistoryEntry struct {
2021-04-05 14:00:51 +02:00
id uint32
cmd string
cwd string
hostname string
user string
timestamp time.Time
}
2021-03-20 20:18:27 +01:00
func databaseLocation() string {
envOverride := os.Getenv("HS9001_DB_PATH")
if envOverride != "" {
return envOverride
}
2021-03-20 20:18:27 +01:00
return filepath.Join(xdgOrFallback("XDG_DATA_HOME", filepath.Join(os.Getenv("HOME"), ".local/share")), "hs9001/db.sqlite")
}
func createConnection() *sql.DB {
2021-03-20 19:39:18 +01:00
2021-03-20 20:18:27 +01:00
db, err := sql.Open("sqlite", databaseLocation())
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
2021-04-05 11:44:07 +02:00
2021-03-20 19:39:18 +01:00
return db
}
func initDatabase(conn *sql.DB) {
2021-03-20 20:18:27 +01:00
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)
}
}
2021-04-05 11:44:07 +02:00
func migrateDatabase(conn *sql.DB, currentVersion int) {
2021-04-05 11:54:09 +02:00
migrations := []string{
"ALTER TABLE history add column workdir varchar(4096)",
}
2021-04-05 11:44:07 +02:00
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)
}
}
2021-04-05 13:00:27 +02:00
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{
2021-04-05 14:00:51 +02:00
user: os.Getenv("USER"),
hostname: hostname,
cmd: cmd,
cwd: wd,
timestamp: time.Now(),
2021-04-05 13:00:27 +02:00
}
}
func importFromStdin(conn *sql.DB) {
scanner := bufio.NewScanner(os.Stdin)
_, err := conn.Exec("BEGIN;")
if err != nil {
log.Panic(err)
}
for scanner.Scan() {
2021-04-05 13:00:27 +02:00
entry := NewHistoryEntry(scanner.Text())
entry.cwd = ""
2021-04-05 14:00:51 +02:00
entry.timestamp = time.Unix(0, 0)
2021-04-05 13:00:27 +02:00
add(conn, entry)
}
2021-03-20 19:39:18 +01:00
_, err = conn.Exec("END;")
if err != nil {
log.Panic(err)
}
}
2021-04-05 13:15:20 +02:00
func search(conn *sql.DB, q string, workdir string) list.List {
queryStmt := "SELECT id, command, workdir, user, hostname FROM history WHERE command LIKE ? AND workdir LIKE ? ORDER BY timestamp ASC"
2021-03-20 19:39:18 +01:00
2021-04-05 13:15:20 +02:00
rows, err := conn.Query(queryStmt, q, workdir)
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
var result list.List
2021-04-05 11:44:07 +02:00
defer rows.Close()
2021-03-20 19:39:18 +01:00
for rows.Next() {
var entry HistoryEntry
err = rows.Scan(&entry.id, &entry.cmd, &entry.cwd, &entry.user, &entry.hostname)
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
result.PushBack(&entry)
2021-03-20 19:39:18 +01:00
}
return result
2021-03-20 19:39:18 +01:00
}
func delete(conn *sql.DB, entryId uint32) {
queryStmt := "DELETE FROM history WHERE id = ?"
_, err := conn.Exec(queryStmt, entryId)
if err != nil {
log.Panic(err)
}
}
2021-04-05 13:15:20 +02:00
func add(conn *sql.DB, entry HistoryEntry) {
2021-04-05 14:00:51 +02:00
stmt, err := conn.Prepare("INSERT INTO history (user, command, hostname, workdir, timestamp) VALUES (?, ?, ?, ?, datetime(?, 'unixepoch'))")
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
2021-04-05 14:00:51 +02:00
_, err = stmt.Exec(entry.user, entry.cmd, entry.hostname, entry.cwd, entry.timestamp.Unix())
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
}
2021-03-20 20:18:27 +01:00
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
}
2021-03-20 19:39:18 +01:00
func printUsage() {
2021-04-05 11:44:07 +02:00
fmt.Fprintf(os.Stderr, "Usage: ./hs9001 <add/search/import>\n")
}
2021-03-20 19:39:18 +01:00
func main() {
addCmd := flag.NewFlagSet("add", flag.ExitOnError)
searchCmd := flag.NewFlagSet("search", flag.ExitOnError)
2021-04-05 10:43:54 +02:00
if len(os.Args) < 2 {
printUsage()
return
}
cmd := os.Args[1]
globalargs := os.Args[2:]
2021-03-20 19:39:18 +01:00
2021-04-05 11:44:07 +02:00
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 "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 {
2021-03-20 19:39:18 +01:00
fmt.Fprint(os.Stderr, "Error: You need to provide the command to be added")
}
historycmd := args[0]
2021-03-20 19:39:18 +01:00
var rgx = regexp.MustCompile("\\s+\\d+\\s+(.*)")
rs := rgx.FindStringSubmatch(historycmd)
if len(rs) == 2 {
2021-04-05 13:00:27 +02:00
add(conn, NewHistoryEntry(rs[1]))
}
2021-04-05 13:15:20 +02:00
case "search":
fallthrough
case "delete":
2021-04-05 13:15:20 +02:00
var workDir string
searchCmd.StringVar(&workDir, "workdir", "%", "Search only within this workdir")
searchCmd.Parse(globalargs)
2021-04-05 13:15:20 +02:00
args := searchCmd.Args()
q := strings.Join(args, " ")
2021-04-05 13:15:20 +02:00
results := search(conn, "%"+q+"%", workDir)
for e := results.Front(); e != nil; e = e.Next() {
entry, ok := e.Value.(*HistoryEntry)
if !ok {
log.Panic("Failed to retrieve entries")
}
fmt.Printf("%s\n", entry.cmd)
}
if cmd == "delete" {
2021-04-05 11:44:07 +02:00
_, 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)
default:
fmt.Fprintf(os.Stderr, "Error: Unknown subcommand '%s' supplied\n\n", cmd)
printUsage()
return
2021-03-20 19:39:18 +01:00
}
2021-03-20 19:39:18 +01:00
}