-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_search.go
More file actions
202 lines (190 loc) · 6.63 KB
/
Copy pathcommand_search.go
File metadata and controls
202 lines (190 loc) · 6.63 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
package contexting
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/spf13/cobra"
)
func newSearchCommand() *cobra.Command {
var rootPath string
var indexPath string
var runtimeFile string
var opts SearchOptions
var dirSummary bool
var dirLimit int
var drillLimit int
var jsonOut bool
var showTokens bool
var useMemory bool
var memoryOnly bool
var summary bool
cmd := &cobra.Command{
Use: "search-hints [query]",
Short: "Find top matching paths from context JSON",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var absConfigPath string
if configPath != "" {
var cfgErr error
absConfigPath, cfgErr = filepath.Abs(configPath)
if cfgErr != nil {
return fmt.Errorf("resolve config path: %w", cfgErr)
}
}
cfg, err := LoadContextingConfig(absConfigPath)
if err != nil {
return err
}
if rootPath == "" {
rootPath, err = os.Getwd()
if err != nil {
return fmt.Errorf("get working directory: %w", err)
}
}
absRoot, err := filepath.Abs(rootPath)
if err != nil {
return fmt.Errorf("resolve root path: %w", err)
}
applyStringFlag(cmd, "index", &indexPath, cfg.Search.IndexPath)
applyIntFlag(cmd, "limit", &opts.Limit, cfg.Search.Limit)
applyIntFlag(cmd, "min-score", &opts.MinScore, cfg.Search.MinScore)
applyStringFlag(cmd, "type", &opts.TypeFilter, cfg.Search.TypeFilter)
if cfg.Search.DirSummary != nil {
applyBoolFlag(cmd, "dir-summary", &dirSummary, *cfg.Search.DirSummary)
}
applyIntFlag(cmd, "dir-limit", &dirLimit, cfg.Search.DirLimit)
applyIntFlag(cmd, "drill-limit", &drillLimit, cfg.Search.DrillLimit)
if cfg.Search.Explain != nil {
applyBoolFlag(cmd, "explain", &opts.IncludeDebug, *cfg.Search.Explain)
}
if cfg.Search.JSON != nil {
applyBoolFlag(cmd, "json", &jsonOut, *cfg.Search.JSON)
}
if cfg.Search.ShowTokens != nil {
applyBoolFlag(cmd, "show-tokens", &showTokens, *cfg.Search.ShowTokens)
}
if cfg.Search.UseMemory != nil {
applyBoolFlag(cmd, "memory", &useMemory, *cfg.Search.UseMemory)
}
applyStringFlag(cmd, "runtime-file", &runtimeFile, cfg.Search.RuntimeFile)
if !cmd.Flags().Changed("index") {
indexPath = resolveConfigPath(absConfigPath, indexPath)
}
if runtimeFile == "" {
runtimeFile = resolveProjectPath(filepath.Dir(indexPath), "ctx_runtime.json")
} else if !cmd.Flags().Changed("runtime-file") {
runtimeFile = resolveConfigPath(absConfigPath, runtimeFile)
}
query := args[0]
results := make([]SearchResult, 0)
var source string
var indexGeneratedAt *time.Time
var fallback *bool
usedMemory := false
if useMemory {
memResp, memErr := QueryMemorySearch(runtimeFile, query, opts, absRoot)
if memErr == nil {
results = memResp.Results
usedMemory = true
source = "memory"
if !memResp.GeneratedAt.IsZero() {
indexGeneratedAt = &memResp.GeneratedAt
}
f := false
fallback = &f
} else if memoryOnly {
return memErr
}
}
if !usedMemory {
index, err := LoadContextIndex(indexPath)
if err != nil {
if useMemory {
source = "none"
f := true
fallback = &f
}
results = []SearchResult{}
} else {
if index.RootPath == "" {
return fmt.Errorf("index missing root_path: regenerate index by running 'ctxt watch' or 'ctxt init' in the project directory")
}
if index.RootPath != absRoot {
return fmt.Errorf("index root path mismatch: expected %s, got %s. Use --root to specify the project directory or run from the project root", absRoot, index.RootPath)
}
results = SearchHintsWithOptions(index, query, opts)
source = "snapshot"
if !index.GeneratedAt.IsZero() {
indexGeneratedAt = &index.GeneratedAt
}
if useMemory {
f := true
fallback = &f
}
}
}
if showTokens {
fmt.Printf("Tokens: %v\n", tokenize(query))
}
if summary {
for i := range results {
results[i].Matches = nil
results[i].Breakdown = nil
}
}
if dirSummary {
summaries := SummarizeDirectories(results, dirLimit, drillLimit)
if jsonOut {
jsonStr, err := directorySummariesToJSON(summaries)
if err != nil {
return err
}
fmt.Println(jsonStr)
return nil
}
printDirectorySummaries(summaries)
return nil
}
if jsonOut {
resp := SearchResponse{
Source: source,
IndexGeneratedAt: indexGeneratedAt,
Fallback: fallback,
Results: results,
}
jsonStr, err := searchResponseToJSON(resp)
if err != nil {
return err
}
fmt.Println(jsonStr)
return nil
}
if summary {
printSummaryResults(results)
return nil
}
printSearchResults(results)
return nil
},
}
cmd.Flags().StringVar(&rootPath, "root", "", "Project root path (defaults to current working directory)")
cmd.Flags().StringVarP(&indexPath, "index", "i", ".ctxt/ctx_index.json", "Path to context JSON")
cmd.Flags().IntVarP(&opts.Limit, "limit", "n", 10, "Maximum number of matches")
cmd.Flags().IntVar(&opts.MinScore, "min-score", 1, "Minimum score required to return a match")
cmd.Flags().StringVar(&opts.TypeFilter, "type", "all", "Filter result type: all|files|dirs")
cmd.Flags().BoolVar(&dirSummary, "dir-summary", false, "Summarize top matching directories with rationale and drill-down hits")
cmd.Flags().IntVar(&dirLimit, "dir-limit", 5, "Maximum number of directories returned in --dir-summary mode")
cmd.Flags().IntVar(&drillLimit, "drill-limit", 3, "Maximum top hits shown per directory in --dir-summary mode")
cmd.Flags().BoolVar(&opts.IncludeDebug, "explain", false, "Include score breakdown in output")
cmd.Flags().BoolVar(&opts.ContentFallback, "hybrid", false, "Augment index results with content matching via ripgrep")
cmd.Flags().IntVar(&opts.ContentMatchScore, "hybrid-score", 1, "Score for content-matched results (default 1)")
cmd.Flags().StringVar(&opts.ContentRoot, "hybrid-root", "", "Project root for content matching (defaults to index root)")
cmd.Flags().BoolVar(&useMemory, "memory", true, "Query live in-memory watch index when available")
cmd.Flags().BoolVar(&memoryOnly, "memory-only", false, "Require live memory search and fail instead of falling back to snapshot")
cmd.Flags().StringVar(&runtimeFile, "runtime-file", "", "Path to runtime memory-search state file (defaults near index path)")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Print search results as JSON")
cmd.Flags().BoolVar(&showTokens, "show-tokens", false, "Print normalized query tokens before results")
cmd.Flags().BoolVar(&summary, "summary", false, "Minimal output: path, type, score only")
return cmd
}