shiori/internal/cmd/delete.go

88 lines
2.1 KiB
Go
Raw Normal View History

2019-05-21 11:31:40 +08:00
package cmd
import (
2019-05-22 09:13:52 +08:00
"fmt"
"os"
fp "path/filepath"
2019-06-09 15:54:07 +08:00
"strconv"
2019-05-22 09:13:52 +08:00
"strings"
2019-05-21 11:31:40 +08:00
"github.com/spf13/cobra"
)
func deleteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "delete [indices]",
Short: "Delete the saved bookmarks",
Long: "Delete bookmarks. " +
"When a record is deleted, the last record is moved to the removed index. " +
2019-05-22 09:13:52 +08:00
"Accepts space-separated list of indices (e.g. 5 6 23 4 110 45), " +
"hyphenated range (e.g. 100-200) or both (e.g. 1-3 7 9). " +
2019-05-21 11:31:40 +08:00
"If no arguments, ALL records will be deleted.",
Aliases: []string{"rm"},
2019-05-22 09:13:52 +08:00
Run: deleteHandler,
2019-05-21 11:31:40 +08:00
}
cmd.Flags().BoolP("yes", "y", false, "Skip confirmation prompt and delete ALL bookmarks")
return cmd
}
2019-05-22 09:13:52 +08:00
func deleteHandler(cmd *cobra.Command, args []string) {
// Parse flags
skipConfirm, _ := cmd.Flags().GetBool("yes")
// If no arguments (i.e all bookmarks going to be deleted), confirm to user
if len(args) == 0 && !skipConfirm {
confirmDelete := ""
fmt.Print("Remove ALL bookmarks? (y/N): ")
fmt.Scanln(&confirmDelete)
if confirmDelete != "y" {
fmt.Println("No bookmarks deleted")
return
}
}
// Convert args to ids
ids, err := parseStrIndices(args)
if err != nil {
cError.Printf("Failed to parse args: %v\n", err)
os.Exit(1)
2019-05-22 09:13:52 +08:00
}
// Delete bookmarks from database
2019-08-09 11:19:43 +08:00
err = db.DeleteBookmarks(ids...)
2019-05-22 09:13:52 +08:00
if err != nil {
cError.Printf("Failed to delete bookmarks: %v\n", err)
os.Exit(1)
2019-05-22 09:13:52 +08:00
}
2019-06-09 15:54:07 +08:00
// Delete thumbnail image and archives from local disk
2019-05-22 09:13:52 +08:00
if len(ids) == 0 {
2019-08-09 11:19:43 +08:00
thumbDir := fp.Join(dataDir, "thumb")
archiveDir := fp.Join(dataDir, "archive")
2019-05-22 09:13:52 +08:00
os.RemoveAll(thumbDir)
2019-06-09 15:54:07 +08:00
os.RemoveAll(archiveDir)
2019-05-22 09:13:52 +08:00
} else {
for _, id := range ids {
2019-06-09 15:54:07 +08:00
strID := strconv.Itoa(id)
2019-08-09 11:19:43 +08:00
imgPath := fp.Join(dataDir, "thumb", strID)
archivePath := fp.Join(dataDir, "archive", strID)
2019-05-22 09:13:52 +08:00
2019-06-09 15:54:07 +08:00
os.Remove(imgPath)
os.Remove(archivePath)
2019-05-22 09:13:52 +08:00
}
}
// Show finish message
switch len(args) {
case 0:
fmt.Println("All bookmarks have been deleted")
case 1, 2, 3, 4, 5:
fmt.Printf("Bookmark(s) %s have been deleted\n", strings.Join(args, ", "))
default:
fmt.Println("Bookmark(s) have been deleted")
}
}