search.go 1.28 KB
Newer Older
ale's avatar
ale committed
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
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/google/subcommands"
)

type searchCommand struct{}

func (c *searchCommand) SetFlags(f *flag.FlagSet) {}
func (c *searchCommand) Name() string             { return "search" }
func (c *searchCommand) Synopsis() string         { return "Search the database" }
func (c *searchCommand) Usage() string {
	return `search <QUERY>
  Search the local database.

`
}

func (c *searchCommand) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	query := strings.Join(f.Args(), " ")
	if query == "" {
		log.Printf("Must specify a query")
		return subcommands.ExitUsageError
	}

	db := openDB()
	defer db.Close()

	results, err := db.Search(query, 0, 100)
	if err != nil {
		log.Printf("error: %v", err)
		return subcommands.ExitFailure
	}
	if results.NumResults == 0 {
		fmt.Printf("No results.\n")
	} else {
		fmt.Printf("%d results found:\n\n", results.NumResults)
		for i, book := range results.Results {
			fmt.Printf("%d) %s\n", i+1, book.Metadata.String())
			if files, err := db.GetBookFiles(book.Id); err == nil {
				for _, f := range files {
					fmt.Printf("      %s: %s\n", strings.TrimPrefix(f.FileType, "."), f.Path)
				}
			}
			fmt.Printf("\n")
		}
	}

	return subcommands.ExitSuccess
}