From db1ebf1e937c22d7dfbd51dd17854f9f282840e3 Mon Sep 17 00:00:00 2001 From: sentriz Date: Sat, 23 Oct 2021 15:41:15 +0100 Subject: [PATCH] feat: add delete-stdin command closes #18 --- cliphist.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/cliphist.go b/cliphist.go index 34aacee..3d473cb 100644 --- a/cliphist.go +++ b/cliphist.go @@ -21,7 +21,7 @@ const bucketKey = "b" func main() { if len(os.Args) < 2 { - log.Fatalf("please provide a command ") + log.Fatalf("please provide a command ") } switch command := os.Args[1]; command { case "store": @@ -43,6 +43,10 @@ func main() { if err := delete([]byte(os.Args[2])); err != nil { log.Fatalf("error deleting: %v", err) } + case "delete-stdin": + if err := deleteStdin(); err != nil { + log.Fatalf("error deleting: %v", err) + } default: log.Fatalf("unknown command %q", command) } @@ -218,6 +222,47 @@ func delete(query []byte) error { return nil } +func deleteStdin() error { + db, err := initDB(nil) + if err != nil { + return fmt.Errorf("creating db: %w", err) + } + defer db.Close() + + input, err := io.ReadAll(os.Stdin) + if err != nil { + return fmt.Errorf("read stdin: %w", err) + } + if len(input) <= 2 { + return fmt.Errorf("input too short to decode") + } + matches := decodeID.FindSubmatch(input) + if len(matches) != 2 { + return fmt.Errorf("input not prefixed with id") + } + idStr := string(matches[1]) + id, err := strconv.Atoi(idStr) + if err != nil { + return fmt.Errorf("converting id: %w", err) + } + + tx, err := db.Begin(true) + if err != nil { + return fmt.Errorf("begin tx: %w", err) + } + defer tx.Rollback() + + b := tx.Bucket([]byte(bucketKey)) + if err := b.Delete(itob(uint64(id))); err != nil { + return fmt.Errorf("delete key: %w", err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit tx: %w", err) + } + return nil +} + func initDB(opts *bolt.Options) (*bolt.DB, error) { userCacheDir, err := os.UserCacheDir() if err != nil {