-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.go
More file actions
305 lines (265 loc) · 6.64 KB
/
render.go
File metadata and controls
305 lines (265 loc) · 6.64 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"fmt"
"os"
"regexp"
"strings"
"time"
"golang.org/x/term"
)
// ANSI escape codes
const (
bold = "\033[1m"
dim = "\033[2m"
ul = "\033[4m"
noul = "\033[24m"
reset = "\033[0m"
cyan = "\033[36m"
green = "\033[32m"
yellow = "\033[33m"
magenta = "\033[35m"
)
type RenderOpts struct {
Query string
Channel string
Total int
Elapsed time.Duration
}
var hasColor bool
func init() {
hasColor = term.IsTerminal(int(os.Stdout.Fd()))
}
func c(code, s string) string {
if !hasColor {
return s
}
return code + s + reset
}
// queryRegexCache caches compiled regexes by query string.
var queryRegexCache = struct {
query string
re *regexp.Regexp
}{}
// queryRegex returns a cached compiled regex for the given query terms.
func queryRegex(query string) *regexp.Regexp {
if query == "" {
return nil
}
if queryRegexCache.query == query {
return queryRegexCache.re
}
terms := strings.Fields(query)
var escaped []string
for _, t := range terms {
escaped = append(escaped, regexp.QuoteMeta(t))
}
re, err := regexp.Compile("(?i)" + strings.Join(escaped, "|"))
if err != nil {
return nil
}
queryRegexCache.query = query
queryRegexCache.re = re
return re
}
func highlight(s string, query string) string {
if !hasColor || query == "" {
return s
}
re := queryRegex(query)
if re == nil {
return s
}
return re.ReplaceAllStringFunc(s, func(match string) string {
return bold + ul + match + reset
})
}
// highlightInline underlines matching terms without resetting surrounding styles.
func highlightInline(s string, query string) string {
if !hasColor || query == "" {
return s
}
re := queryRegex(query)
if re == nil {
return s
}
return re.ReplaceAllStringFunc(s, func(match string) string {
return ul + match + noul
})
}
func renderResults(hits []ESHit, opts RenderOpts) {
count := len(hits)
// Reverse: best match last (bottom of terminal), numbered [1] = best
for i := count - 1; i >= 0; i-- {
p := hits[i].Source
num := i + 1
fmt.Println(c(dim, "───"))
matchTag := ""
if hasExactMatch(p, opts.Query) {
matchTag = " " + c(bold+green, "*")
}
fmt.Printf("%s %s %s%s\n",
c(cyan, fmt.Sprintf("[%d]", num)),
c(bold+green, highlightInline(p.PackageAttrName, opts.Query)),
c(dim, nvl(p.PackageVersion, "?")),
matchTag,
)
fmt.Printf(" %s\n", highlight(nvl(p.PackageDescription, "-"), opts.Query))
if len(p.PackagePrograms) > 0 {
fmt.Printf(" %s %s\n",
c(magenta, "programs"),
peekPrograms(p.PackagePrograms, 5, opts.Query),
)
}
if num == 1 {
if hp := homepage(p); hp != "" {
fmt.Printf(" %s %s\n", c(yellow, "home"), hp)
}
fmt.Printf(" %s\n", c(dim, "nix profile install nixpkgs#"+p.PackageAttrName))
fmt.Printf(" %s\n", c(dim, "nix-env -iA nixpkgs."+p.PackageAttrName))
}
}
printSummary(count, opts)
}
func renderResultsVerbose(hits []ESHit, opts RenderOpts) {
count := len(hits)
// Reverse: best match last (bottom of terminal), numbered [1] = best
for i := count - 1; i >= 0; i-- {
p := hits[i].Source
num := i + 1
fmt.Println(c(dim, "───"))
matchTag := ""
if hasExactMatch(p, opts.Query) {
matchTag = " " + c(bold+green, "*")
}
fmt.Printf("%s %s %s%s\n",
c(cyan, fmt.Sprintf("[%d]", num)),
c(bold+green, highlightInline(p.PackageAttrName, opts.Query)),
c(dim, nvl(p.PackageVersion, "?")),
matchTag,
)
fmt.Printf(" %s\n", highlight(nvl(p.PackageDescription, "-"), opts.Query))
if ld := longDesc(p); ld != "" {
fmt.Printf(" %s\n", c(dim, ld))
}
if len(p.PackagePrograms) > 0 {
fmt.Printf(" %s %s\n",
c(magenta, "programs"),
peekPrograms(p.PackagePrograms, 10, opts.Query),
)
}
if hp := homepage(p); hp != "" {
fmt.Printf(" %s %s\n", c(yellow, "home"), hp)
}
if lic := licenses(p); lic != "" {
fmt.Printf(" %s %s\n", c(yellow, "license"), lic)
}
if num == 1 {
fmt.Printf(" %s\n", c(dim, "nix profile install nixpkgs#"+p.PackageAttrName))
fmt.Printf(" %s\n", c(dim, "nix-env -iA nixpkgs."+p.PackageAttrName))
}
}
printSummary(count, opts)
}
func printSummary(count int, opts RenderOpts) {
fmt.Println()
fmt.Println(c(dim, fmt.Sprintf("channel: %s | query: '%s' | showing %d of %d | %dms",
opts.Channel, opts.Query, count, opts.Total, opts.Elapsed.Milliseconds())))
}
func nvl(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
func homepage(p SearchResult) string {
switch v := p.PackageHomepage.(type) {
case []interface{}:
if len(v) > 0 {
if s, ok := v[0].(string); ok {
return s
}
}
case string:
return v
}
return ""
}
func licenses(p SearchResult) string {
if len(p.PackageLicenseSet) == 0 {
return ""
}
var parts []string
for _, l := range p.PackageLicenseSet {
switch {
case l.Raw != "":
parts = append(parts, l.Raw)
case l.SpdxID != "":
parts = append(parts, l.SpdxID)
case l.FullName != "":
parts = append(parts, l.FullName)
}
}
return strings.Join(parts, ", ")
}
var htmlTagRe = regexp.MustCompile("<[^>]*>")
// stripHTML removes HTML tags and cleans up a long description for terminal display.
func stripHTML(s string) string {
s = strings.TrimPrefix(s, "<rendered-html>")
s = strings.TrimSuffix(s, "</rendered-html>")
s = htmlTagRe.ReplaceAllString(s, "")
s = strings.Join(strings.Fields(s), " ")
return strings.TrimSpace(s)
}
func longDesc(p SearchResult) string {
if p.PackageLongDescription == "" {
return ""
}
s := stripHTML(p.PackageLongDescription)
if s == p.PackageDescription {
return ""
}
return s
}
func peekPrograms(progs []string, max int, query string) string {
// Partition: matching programs first, then the rest
var matched, rest []string
terms := strings.Fields(strings.ToLower(query))
for _, p := range progs {
if matchesAnyTerm(p, terms) {
matched = append(matched, highlight(p, query))
} else {
rest = append(rest, p)
}
}
ordered := append(matched, rest...)
if len(ordered) <= max {
return strings.Join(ordered, " ")
}
return strings.Join(ordered[:max], " ") + fmt.Sprintf(" (+%d more)", len(ordered)-max)
}
func hasExactMatch(p SearchResult, query string) bool {
if query == "" {
return false
}
q := strings.ToLower(query)
// Check package name and attr name
if strings.ToLower(p.PackagePname) == q || strings.ToLower(p.PackageAttrName) == q {
return true
}
// Check programs
for _, prog := range p.PackagePrograms {
if strings.ToLower(prog) == q {
return true
}
}
return false
}
func matchesAnyTerm(prog string, terms []string) bool {
lower := strings.ToLower(prog)
for _, t := range terms {
if strings.Contains(lower, t) {
return true
}
}
return false
}