/
show.go
86 lines (71 loc) · 2 KB
/
show.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright © 2018 Tyler Spivey <tspivey@pcdesk.net> and Niko Carpenter <nikoacarpenter@gmail.com>
//
// This source code is governed by the MIT license, which can be found in the LICENSE file.
package commands
import (
"fmt"
"os"
"strconv"
"text/template"
"github.com/tspivey/books"
"github.com/spf13/cobra"
)
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show BOOK_ID",
Short: "Show details for a book",
Long: `Show details and files for a book by its ID.
Use search to find the ID of the book you want to show.`,
Run: CPUProfile(showRun),
}
func showRun(cmd *cobra.Command, args []string) {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "No book ID specified.")
os.Exit(1)
}
bookID, err := strconv.Atoi(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, "Book ID must be a number.")
os.Exit(1)
}
lib, err := books.OpenLibrary(libraryFile, booksRoot)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot open library: %s\n", err)
os.Exit(1)
}
books, err := lib.GetBooksByID([]int64{int64(bookID)})
if err != nil {
fmt.Fprintf(os.Stderr, "Error while getting book by id: %s\n", err)
os.Exit(1)
}
if len(books) == 0 {
fmt.Fprintln(os.Stderr, "No book found")
os.Exit(1)
} else if len(books) > 1 {
fmt.Fprintln(os.Stderr, "More than one book found; exiting")
os.Exit(1)
}
bookDetailsTmplSrc := `{{joinNaturally "and" .Authors}} - {{.Title }}
{{if .Series}}Series: {{.Series}}
{{end }}
{{ if .Files}}{{range .Files -}}
{{ .Extension -}}
: {{if .Tags}}({{range $i, $v := .Tags -}}
{{if $i}}, {{end -}}
{{ $v }}{{end}}){{end }} ({{ .ID }})
{{ end -}}
{{ else }}No files available for this book{{ end }}`
tmpl, err := template.New("book_details").Funcs(funcMap).Parse(bookDetailsTmplSrc)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing template: %s\n", err)
os.Exit(1)
}
err = tmpl.Execute(os.Stdout, books[0])
if err != nil {
fmt.Fprintf(os.Stderr, "Error executing template: %s\n", err)
os.Exit(1)
}
}
func init() {
rootCmd.AddCommand(showCmd)
}