github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/cmd/camtool/search.go (about) 1 /* 2 Copyright 2014 The Camlistore Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "encoding/json" 21 "flag" 22 "fmt" 23 "io/ioutil" 24 "os" 25 "strings" 26 27 "camlistore.org/pkg/cmdmain" 28 "camlistore.org/pkg/search" 29 ) 30 31 type searchCmd struct { 32 server string 33 limit int 34 describe bool 35 } 36 37 func init() { 38 cmdmain.RegisterCommand("search", func(flags *flag.FlagSet) cmdmain.CommandRunner { 39 cmd := new(searchCmd) 40 flags.StringVar(&cmd.server, "server", "", "Server to search. "+serverFlagHelp) 41 flags.IntVar(&cmd.limit, "limit", 0, "Limit number of results. 0 is default. Negative means no limit.") 42 flags.BoolVar(&cmd.describe, "describe", false, "Describe results as well.") 43 return cmd 44 }) 45 } 46 47 func (c *searchCmd) Describe() string { 48 return "Execute a search query" 49 } 50 51 func (c *searchCmd) Usage() { 52 fmt.Fprintf(os.Stderr, "Usage: camtool [globalopts] search <expr or Constraint JSON>\n") 53 } 54 55 func (c *searchCmd) Examples() []string { 56 return []string{ 57 `"loc:paris is:portrait" # expression`, 58 `'{"blobrefPrefix":"sha1-f00d"}' # SearchConstraint JSON`, 59 `- # piped from stdin`, 60 } 61 } 62 63 func (c *searchCmd) RunCommand(args []string) error { 64 if len(args) != 1 { 65 return cmdmain.UsageError("requires search expression or Constraint JSON") 66 } 67 q := args[0] 68 if q == "-" { 69 slurp, err := ioutil.ReadAll(cmdmain.Stdin) 70 if err != nil { 71 return err 72 } 73 q = string(slurp) 74 } 75 q = strings.TrimSpace(q) 76 77 req := &search.SearchQuery{ 78 Limit: c.limit, 79 } 80 if plausibleJSON(q) { 81 cs := new(search.Constraint) 82 if err := json.NewDecoder(strings.NewReader(q)).Decode(&cs); err != nil { 83 return err 84 } 85 req.Constraint = cs 86 } else { 87 req.Expression = q 88 } 89 if c.describe { 90 req.Describe = &search.DescribeRequest{} 91 } 92 93 cl := newClient(c.server) 94 res, err := cl.Search(req) 95 if err != nil { 96 return err 97 } 98 resj, err := json.MarshalIndent(res, "", " ") 99 if err != nil { 100 return err 101 } 102 resj = append(resj, '\n') 103 _, err = os.Stdout.Write(resj) 104 return err 105 } 106 107 func plausibleJSON(s string) bool { 108 return strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}") 109 }