github.com/soulteary/pocket-bookcase@v0.0.0-20240428065142-0b5a9a0fc98a/internal/cmd/delete.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 fp "path/filepath" 7 "strconv" 8 "strings" 9 10 "github.com/spf13/cobra" 11 ) 12 13 func deleteCmd() *cobra.Command { 14 cmd := &cobra.Command{ 15 Use: "delete [indices]", 16 Short: "Delete the saved bookmarks", 17 Long: "Delete bookmarks. " + 18 "When a record is deleted, the last record is moved to the removed index. " + 19 "Accepts space-separated list of indices (e.g. 5 6 23 4 110 45), " + 20 "hyphenated range (e.g. 100-200) or both (e.g. 1-3 7 9). " + 21 "If no arguments, ALL records will be deleted.", 22 Aliases: []string{"rm"}, 23 Run: deleteHandler, 24 } 25 26 cmd.Flags().BoolP("yes", "y", false, "Skip confirmation prompt and delete ALL bookmarks") 27 28 return cmd 29 } 30 31 func deleteHandler(cmd *cobra.Command, args []string) { 32 cfg, deps := initShiori(cmd.Context(), cmd) 33 34 // Parse flags 35 skipConfirm, _ := cmd.Flags().GetBool("yes") 36 37 // If no arguments (i.e all bookmarks going to be deleted), confirm to user 38 if len(args) == 0 && !skipConfirm { 39 confirmDelete := "" 40 fmt.Print("Remove ALL bookmarks? (y/N): ") 41 fmt.Scanln(&confirmDelete) 42 43 if confirmDelete != "y" { 44 fmt.Println("No bookmarks deleted") 45 return 46 } 47 } 48 49 // Convert args to ids 50 ids, err := parseStrIndices(args) 51 if err != nil { 52 cError.Printf("Failed to parse args: %v\n", err) 53 os.Exit(1) 54 } 55 56 // Delete bookmarks from database 57 err = deps.Database.DeleteBookmarks(cmd.Context(), ids...) 58 if err != nil { 59 cError.Printf("Failed to delete bookmarks: %v\n", err) 60 os.Exit(1) 61 } 62 63 // Delete thumbnail image and archives from local disk 64 if len(ids) == 0 { 65 thumbDir := fp.Join(cfg.Storage.DataDir, "thumb") 66 archiveDir := fp.Join(cfg.Storage.DataDir, "archive") 67 os.RemoveAll(thumbDir) 68 os.RemoveAll(archiveDir) 69 } else { 70 for _, id := range ids { 71 strID := strconv.Itoa(id) 72 imgPath := fp.Join(cfg.Storage.DataDir, "thumb", strID) 73 archivePath := fp.Join(cfg.Storage.DataDir, "archive", strID) 74 75 os.Remove(imgPath) 76 os.Remove(archivePath) 77 } 78 } 79 80 // Show finish message 81 switch len(args) { 82 case 0: 83 fmt.Println("All bookmarks have been deleted") 84 case 1, 2, 3, 4, 5: 85 fmt.Printf("Bookmark(s) %s have been deleted\n", strings.Join(args, ", ")) 86 default: 87 fmt.Println("Bookmark(s) have been deleted") 88 } 89 }