1
0
дзеркало https://github.com/quitesimpleorg/hs9001.git synced 2024-10-31 23:44:38 +01:00
hs9001/main.go

215 рядки
4.2 KiB
Go

2021-03-20 19:39:18 +01:00
package main
import (
"bufio"
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-03-20 20:18:27 +01:00
_ "modernc.org/sqlite"
2021-03-20 19:39:18 +01:00
)
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)
}
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)
}
}
func importFromStdin(conn *sql.DB) {
scanner := bufio.NewScanner(os.Stdin)
_, err := conn.Exec("BEGIN;")
if err != nil {
log.Panic(err)
}
for scanner.Scan() {
add(conn, scanner.Text())
}
2021-03-20 19:39:18 +01:00
_, err = conn.Exec("END;")
if err != nil {
log.Panic(err)
}
}
func search(conn *sql.DB, q string) {
2021-03-20 19:39:18 +01:00
queryStmt := "SELECT command FROM history WHERE command LIKE ? ORDER BY timestamp ASC"
2021-03-20 20:18:27 +01:00
rows, err := conn.Query(queryStmt, "%"+q+"%")
2021-03-20 19:39:18 +01:00
if err != nil {
log.Panic(err)
}
for rows.Next() {
var command string
err = rows.Scan(&command)
if err != nil {
log.Panic(err)
}
2021-03-20 20:18:27 +01:00
fmt.Printf("%s\n", command)
2021-03-20 19:39:18 +01:00
}
}
func delete(conn *sql.DB, q string) {
queryStmt := "DELETE FROM history WHERE command LIKE ?"
_, err := conn.Exec(queryStmt, "%"+q+"%")
if err != nil {
log.Panic(err)
}
_, err = conn.Exec("VACUUM")
if err != nil {
log.Panic(err)
}
}
func add(conn *sql.DB, cmd string) {
2021-03-20 19:39:18 +01:00
user := os.Getenv("USER")
hostname, err := os.Hostname()
if err != nil {
log.Panic(err)
}
stmt, err := conn.Prepare("INSERT INTO history (user, command, hostname) VALUES (?, ?, ?)")
if err != nil {
log.Panic(err)
}
_, err = stmt.Exec(user, cmd, hostname)
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() {
fmt.Fprintf(os.Stderr, "Usage: ./hs9001 <add/search/init/import>\n")
}
2021-03-20 19:39:18 +01:00
func main() {
addCmd := flag.NewFlagSet("add", flag.ExitOnError)
searchCmd := flag.NewFlagSet("search", flag.ExitOnError)
deleteCmd := flag.NewFlagSet("delete", 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
conn := createConnection()
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 {
add(conn, rs[1])
}
case "search":
searchCmd.Parse(globalargs)
args := searchCmd.Args()
if len(args) < 1 {
2021-03-20 19:39:18 +01:00
fmt.Fprint(os.Stderr, "Please provide the search query\n")
2021-04-05 09:53:25 +02:00
os.Exit(1)
2021-03-20 19:39:18 +01:00
}
q := strings.Join(args, " ")
search(conn, q)
os.Exit(23)
case "delete":
deleteCmd.Parse(globalargs)
args := deleteCmd.Args()
if len(args) < 1 {
fmt.Fprint(os.Stderr, "Error: You need to provide a search query for records to delete")
}
q := strings.Join(args, " ")
delete(conn, q)
//we do not want to leak what we just deleted :^)
os.Exit(23)
case "init":
2021-03-20 20:18:27 +01:00
err := os.MkdirAll(filepath.Dir(databaseLocation()), 0755)
if err != nil {
log.Panic(err)
}
initDatabase(conn)
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
}