-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlivegrep.go
122 lines (103 loc) · 2.49 KB
/
livegrep.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const livegrepPath = "/api/v1/search"
// Livegrep is a client object for connecting to a Livegrep instance
type Livegrep struct {
Host string
UseHTTPS bool
Client *http.Client
}
// Query represents a single query against a Livegrep instance
type Query struct {
Term string
FoldCase bool
Regex bool
Repositories []string
}
// QueryResult is a single match in a result from Livegrep
type QueryResult struct {
Tree string `json:"tree"`
Version string `json:"version"`
Path string `json:"path"`
Lno int `json:"lno"`
ContextBefore []string `json:"context_before"`
Line string `json:"line"`
ContextAfter []string `json:"context_after"`
Bounds []int `json:"bounds"`
}
// QueryResponse is the overall result from a query against a Livegrep instance
type QueryResponse struct {
Re2Tme int `json:"re2_time"`
GitTme int `json:"git_time"`
SortTime int `json:"sort_time"`
IndexTime int `json:"index_time"`
AnalyzeTime int `json:"analyze_time"`
Why string `json:"why"`
Results []QueryResult `json:"results"`
FileResults []QueryResult `json:"file_results"`
SearchType string `json:"search_type"`
}
// NewLivegrep returns a new Livegrep client
func NewLivegrep(host string) Livegrep {
return Livegrep{
Host: host,
UseHTTPS: true,
Client: &http.Client{},
}
}
// NewQuery returns a new query for Livegrep
func (lg *Livegrep) NewQuery(q string) Query {
return Query{
Term: q,
FoldCase: false,
Regex: true,
}
}
// Query runs the specified Query against the given Livegrep instance
func (lg *Livegrep) Query(q Query) (QueryResponse, error) {
var protocol string
if lg.UseHTTPS {
protocol = "https"
} else {
protocol = "http"
}
query := fmt.Sprintf(
"q=%s&fold_case=%t®ex=%t",
q.Term,
q.FoldCase,
q.Regex,
)
for _, repo := range q.Repositories {
query += fmt.Sprintf(
"&repo[]=%s",
repo,
)
}
uri := &url.URL{
Scheme: protocol,
Host: lg.Host,
Path: livegrepPath,
RawQuery: query,
}
resp, err := lg.Client.Get(uri.String())
if err != nil {
return QueryResponse{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return QueryResponse{}, err
}
var results QueryResponse
err = json.Unmarshal(body, &results)
if err != nil {
return QueryResponse{}, err
}
return results, nil
}