-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathsearch.go
More file actions
447 lines (384 loc) · 13.6 KB
/
search.go
File metadata and controls
447 lines (384 loc) · 13.6 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package registry
import (
"context"
"fmt"
"os"
"strings"
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/cobra"
"github.com/spf13/viper"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/pkg/data"
"github.com/cloudposse/atmos/pkg/flags"
"github.com/cloudposse/atmos/pkg/flags/compat"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/ui"
"github.com/cloudposse/atmos/pkg/ui/theme"
"github.com/cloudposse/atmos/toolchain"
toolchainregistry "github.com/cloudposse/atmos/toolchain/registry"
)
const (
defaultSearchLimit = 20
columnWidthTool = 30
columnWidthToolType = 15
columnWidthToolRegistry = 20
)
var searchParser *flags.StandardParser
// searchCmd represents the 'toolchain registry search' command.
var searchCmd = &cobra.Command{
Use: "search <query>",
Short: "Search for tools across registries",
Long: `Search for tools matching the query string across all configured registries.
The query is matched against tool owner, repo name, and description.
Results are sorted by relevance score.`,
Args: cobra.ExactArgs(1),
RunE: executeSearchCommand,
SilenceUsage: true, // Don't show usage on error.
SilenceErrors: true, // Don't show errors twice.
}
func init() {
// Create parser with search-specific flags.
searchParser = flags.NewStandardParser(
flags.WithIntFlag("limit", "", defaultSearchLimit, "Maximum number of results to show"),
flags.WithStringFlag("registry", "", "", "Search only in specific registry"),
flags.WithStringFlag("format", "", "table", "Output format (table, json, yaml)"),
flags.WithBoolFlag("installed-only", "", false, "Show only installed tools"),
flags.WithBoolFlag("available-only", "", false, "Show only non-installed tools"),
flags.WithEnvVars("limit", "ATMOS_TOOLCHAIN_LIMIT"),
flags.WithEnvVars("registry", "ATMOS_TOOLCHAIN_REGISTRY"),
flags.WithEnvVars("format", "ATMOS_TOOLCHAIN_FORMAT"),
flags.WithEnvVars("installed-only", "ATMOS_TOOLCHAIN_INSTALLED_ONLY"),
flags.WithEnvVars("available-only", "ATMOS_TOOLCHAIN_AVAILABLE_ONLY"),
)
// Register flags.
searchParser.RegisterFlags(searchCmd)
// Bind flags to Viper.
if err := searchParser.BindToViper(viper.GetViper()); err != nil {
panic(err)
}
}
// validateSearchFormat validates the search format flag.
func validateSearchFormat(format string) error {
switch format {
case "table", "json", "yaml":
return nil
default:
return fmt.Errorf("%w: format must be one of: table, json, yaml (got: %s)",
errUtils.ErrInvalidFlag, format)
}
}
// createSearchRegistry creates a registry based on the name.
func createSearchRegistry(registryName string) (toolchainregistry.ToolRegistry, error) {
if registryName == "" {
// Use default aqua registry for MVP.
return toolchain.NewAquaRegistry(), nil
}
switch registryName {
case "aqua-public", "aqua":
return toolchain.NewAquaRegistry(), nil
default:
return nil, fmt.Errorf("%w: '%s' (supported registries: 'aqua-public', 'aqua')",
toolchainregistry.ErrUnknownRegistry, registryName)
}
}
// displaySearchTable displays search results in table format.
func displaySearchTable(results []*toolchainregistry.Tool, query string, searchLimit int) {
totalMatches := len(results)
displayResults := results
// Only apply limit when searchLimit > 0 (0 means no limit).
if searchLimit > 0 && totalMatches > searchLimit {
displayResults = results[:searchLimit]
}
// Display results with info toast showing range vs total.
if searchLimit <= 0 || totalMatches <= searchLimit {
// Showing all results (no limit or within limit).
ui.Infof("Found **%d tools** matching `%s`:", totalMatches, query)
} else {
// Showing subset of results.
ui.Infof("Showing **%d** of **%d tools** matching `%s`:", len(displayResults), totalMatches, query)
}
ui.Writeln("") // Blank line after toast.
displaySearchResults(displayResults)
// Show helpful hints after table.
ui.Writeln("")
ui.Hintf("Use `atmos toolchain info <tool>` for details")
ui.Hintf("Use `atmos toolchain install <tool>@<version>` to install")
}
// searchFlags holds parsed search command flags.
type searchFlags struct {
limit int
registry string
installedOnly bool
availableOnly bool
format string
}
func executeSearchCommand(cmd *cobra.Command, args []string) error {
defer perf.Track(nil, "registry.executeSearchCommand")()
// Bind flags to Viper for precedence handling.
v := viper.GetViper()
if err := searchParser.BindFlagsToViper(cmd, v); err != nil {
return err
}
flags := parseSearchFlags(v)
if err := validateSearchFlags(flags); err != nil {
return err
}
query := args[0]
ctx := context.Background()
// Create registry based on flag or use default.
reg, err := createSearchRegistry(flags.registry)
if err != nil {
return err
}
// Execute search.
results, err := performSearch(ctx, reg, query, flags)
if err != nil {
return err
}
return outputSearchResults(results, query, flags)
}
// parseSearchFlags extracts search flags from Viper.
func parseSearchFlags(v *viper.Viper) searchFlags {
return searchFlags{
limit: v.GetInt("limit"),
registry: v.GetString("registry"),
installedOnly: v.GetBool("installed-only"),
availableOnly: v.GetBool("available-only"),
format: strings.ToLower(v.GetString("format")),
}
}
// validateSearchFlags validates all search flags.
func validateSearchFlags(flags searchFlags) error {
if err := validateSearchFormat(flags.format); err != nil {
return err
}
if flags.limit < 0 {
return fmt.Errorf("%w: limit must be non-negative", errUtils.ErrInvalidFlag)
}
if flags.installedOnly && flags.availableOnly {
return fmt.Errorf("%w: cannot use both --installed-only and --available-only", errUtils.ErrInvalidFlag)
}
return nil
}
// performSearch executes the search and returns results.
func performSearch(ctx context.Context, reg toolchainregistry.ToolRegistry, query string, flags searchFlags) ([]*toolchainregistry.Tool, error) {
opts := []toolchainregistry.SearchOption{
toolchainregistry.WithLimit(0), // 0 = no limit, get all matches.
}
if flags.installedOnly {
opts = append(opts, toolchainregistry.WithInstalledOnly(true))
}
if flags.availableOnly {
opts = append(opts, toolchainregistry.WithAvailableOnly(true))
}
results, err := reg.Search(ctx, query, opts...)
if err != nil {
return nil, fmt.Errorf("search failed: %w", err)
}
return results, nil
}
// outputSearchResults outputs search results in the specified format.
func outputSearchResults(results []*toolchainregistry.Tool, query string, flags searchFlags) error {
if len(results) == 0 {
message := fmt.Sprintf(`No tools found matching '%s'
Try:
- Using a different search term
- Checking 'atmos toolchain registry list' for available tools
`, query)
ui.Info(message)
return nil
}
// Apply display limit for JSON/YAML (0 means no limit).
displayResults := results
if flags.limit > 0 && len(results) > flags.limit {
displayResults = results[:flags.limit]
}
switch flags.format {
case "json":
return data.WriteJSON(displayResults)
case "yaml":
return data.WriteYAML(displayResults)
case "table":
displaySearchTable(results, query, flags.limit)
return nil
default:
return fmt.Errorf("%w: unsupported format: %s", errUtils.ErrInvalidFlag, flags.format)
}
}
// searchRow represents a single row in the search results table.
type searchRow struct {
status string
toolName string
toolType string
registry string
isInstalled bool
isInConfig bool
}
func displaySearchResults(tools []*toolchainregistry.Tool) {
defer perf.Track(nil, "registry.displaySearchResults")()
toolVersions, installer := loadSearchToolVersions()
rows, widths := buildSearchRows(tools, toolVersions, installer)
styled := renderSearchTable(rows, widths)
ui.Writeln(styled)
}
// loadSearchToolVersions loads tool versions and creates an installer for search.
func loadSearchToolVersions() (*toolchain.ToolVersions, *toolchain.Installer) {
installer := toolchain.NewInstaller()
toolVersionsFile := toolchain.GetToolVersionsFilePath()
toolVersions, err := toolchain.LoadToolVersions(toolVersionsFile)
if err != nil && !os.IsNotExist(err) {
ui.Warningf("Could not load .tool-versions: %v", err)
}
return toolVersions, installer
}
// searchColumnWidths holds the calculated widths for search table columns.
type searchColumnWidths struct {
status int
toolName int
toolType int
registry int
}
// buildSearchRows processes tools and returns search rows with column widths.
func buildSearchRows(tools []*toolchainregistry.Tool, toolVersions *toolchain.ToolVersions, installer *toolchain.Installer) ([]searchRow, searchColumnWidths) {
widths := searchColumnWidths{
status: 1,
toolName: len("TOOL"),
toolType: len("TYPE"),
registry: len("REGISTRY"),
}
rows := make([]searchRow, 0, len(tools))
for _, tool := range tools {
row := buildSingleSearchRow(tool, toolVersions, installer)
widths = updateSearchColumnWidths(widths, tool, row.toolName)
rows = append(rows, row)
}
return rows, widths
}
// buildSingleSearchRow creates a searchRow for a single tool.
func buildSingleSearchRow(tool *toolchainregistry.Tool, toolVersions *toolchain.ToolVersions, installer *toolchain.Installer) searchRow {
toolName := fmt.Sprintf("%s/%s", tool.RepoOwner, tool.RepoName)
row := searchRow{
toolName: toolName,
toolType: tool.Type,
registry: tool.Registry,
}
if toolVersions != nil && toolVersions.Tools != nil {
row.isInConfig, row.isInstalled = checkSearchToolStatus(tool, toolVersions, installer)
}
row.status = getSearchStatusIndicator(row.isInstalled, row.isInConfig)
return row
}
// checkSearchToolStatus checks if a tool is in config and installed.
func checkSearchToolStatus(tool *toolchainregistry.Tool, toolVersions *toolchain.ToolVersions, installer *toolchain.Installer) (inConfig, installed bool) {
fullName := tool.RepoOwner + "/" + tool.RepoName
_, foundFull := toolVersions.Tools[fullName]
_, foundRepo := toolVersions.Tools[tool.RepoName]
inConfig = foundFull || foundRepo
if !inConfig {
return inConfig, false
}
version := getSearchToolVersion(fullName, tool.RepoName, toolVersions, foundFull, foundRepo)
if version == "" {
return inConfig, false
}
_, err := installer.FindBinaryPath(tool.RepoOwner, tool.RepoName, version, tool.BinaryName)
return inConfig, err == nil
}
// getSearchToolVersion gets the version string for a tool from tool-versions.
func getSearchToolVersion(fullName, repoName string, toolVersions *toolchain.ToolVersions, foundFull, foundRepo bool) string {
if foundFull {
if versions := toolVersions.Tools[fullName]; len(versions) > 0 {
return versions[0]
}
} else if foundRepo {
if versions := toolVersions.Tools[repoName]; len(versions) > 0 {
return versions[0]
}
}
return ""
}
// getSearchStatusIndicator returns the status indicator character based on tool state.
func getSearchStatusIndicator(isInstalled, isInConfig bool) string {
switch {
case isInstalled:
return statusIndicator
case isInConfig:
return statusIndicator
default:
return " "
}
}
// updateSearchColumnWidths updates widths based on a tool's field lengths.
func updateSearchColumnWidths(widths searchColumnWidths, tool *toolchainregistry.Tool, toolName string) searchColumnWidths {
if len(toolName) > widths.toolName {
widths.toolName = len(toolName)
}
if len(tool.Type) > widths.toolType {
widths.toolType = len(tool.Type)
}
if len(tool.Registry) > widths.registry {
widths.registry = len(tool.Registry)
}
return widths
}
// renderSearchTable creates and renders the search results table with styling.
func renderSearchTable(rows []searchRow, widths searchColumnWidths) string {
const columnPaddingPerSide = 2
const totalColumnPadding = columnPaddingPerSide * 2
const statusPadding = 2
widths.status += statusPadding
widths.toolName += totalColumnPadding
widths.toolType += totalColumnPadding
widths.registry += totalColumnPadding
columns := []table.Column{
{Title: " ", Width: widths.status},
{Title: "TOOL", Width: widths.toolName},
{Title: "TYPE", Width: widths.toolType},
{Title: "REGISTRY", Width: widths.registry},
}
tableRows := make([]table.Row, 0, len(rows))
for _, row := range rows {
tableRows = append(tableRows, table.Row{row.status, row.toolName, row.toolType, row.registry})
}
t := table.New(
table.WithColumns(columns),
table.WithRows(tableRows),
table.WithFocused(false),
table.WithHeight(len(tableRows)+1),
)
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color(theme.ColorBorder)).
BorderBottom(true).
Bold(true)
s.Cell = s.Cell.PaddingLeft(1).PaddingRight(1)
s.Selected = s.Cell
t.SetStyles(s)
return renderTableWithConditionalStyling(t.View(), rows)
}
// SearchCommandProvider implements the CommandProvider interface for the 'toolchain registry search' command, wiring the search subcommand into the CLI framework with its associated flags and behaviors.
type SearchCommandProvider struct{}
func (s *SearchCommandProvider) GetCommand() *cobra.Command {
return searchCmd
}
func (s *SearchCommandProvider) GetName() string {
return "search"
}
func (s *SearchCommandProvider) GetGroup() string {
return "Toolchain Commands"
}
func (s *SearchCommandProvider) GetFlagsBuilder() flags.Builder {
return searchParser
}
func (s *SearchCommandProvider) GetPositionalArgsBuilder() *flags.PositionalArgsBuilder {
return nil
}
func (s *SearchCommandProvider) GetCompatibilityFlags() map[string]compat.CompatibilityFlag {
return nil
}
// GetSearchParser returns the search command's parser for use by aliases and other commands that need access to search-specific flag definitions.
func GetSearchParser() *flags.StandardParser {
return searchParser
}