Skip to content

Commit

Permalink
feat: add delete-stdin command
Browse files Browse the repository at this point in the history
closes #18
  • Loading branch information
sentriz committed Oct 24, 2021
1 parent e1781cb commit db1ebf1
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion cliphist.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const bucketKey = "b"

func main() {
if len(os.Args) < 2 {
log.Fatalf("please provide a command <store|list|decode|delete>")
log.Fatalf("please provide a command <store|list|decode|delete|delete-stdin>")
}
switch command := os.Args[1]; command {
case "store":
Expand All @@ -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)
}
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit db1ebf1

Please sign in to comment.