-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetCommand.go
More file actions
492 lines (410 loc) · 13.4 KB
/
getCommand.go
File metadata and controls
492 lines (410 loc) · 13.4 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
"sort"
"strings"
)
// Configuration represents the entire configuration file
type Configuration struct {
Version string `json:"version"`
LastUpdated string `json:"lastUpdated"`
Schema Schema `json:"schema"`
Encodings map[string]Encoding `json:"encodings"`
Patterns []Pattern `json:"patterns"`
// Dynamic entity collections stored as maps of map[string]interface{}
EntityCollections map[string]map[string]map[string]interface{} `json:"-"`
}
// Schema defines the structure of entities and how they relate
type Schema struct {
Entities map[string]EntitySchema `json:"entities"`
Variables map[string]VariableSchema `json:"variables"`
Paths map[string]PathSchema `json:"paths"`
Generators map[string]GeneratorSchema `json:"generators"`
}
// EntitySchema defines an entity type like browsers or websites
type EntitySchema struct {
IdentifierField string `json:"identifierField"`
Properties map[string]PropertySchema `json:"properties"`
}
// PropertySchema defines a property within an entity
type PropertySchema struct {
Type string `json:"type"`
Description string `json:"description"`
RefersTo string `json:"refersTo,omitempty"`
}
// VariableSchema defines a variable used in patterns
type VariableSchema struct {
Type string `json:"type"`
EntityType string `json:"entityType,omitempty"`
Greedy bool `json:"greedy,omitempty"`
Description string `json:"description"`
}
// PathSchema defines a path reference like browser.command
type PathSchema struct {
Description string `json:"description"`
Path []string `json:"path,omitempty"`
Generator string `json:"generator,omitempty"`
Requires []string `json:"requires,omitempty"`
}
// GeneratorSchema defines a generator function
type GeneratorSchema struct {
Description string `json:"description"`
Code string `json:"code"` // In a real implementation, this would be executed
}
// Encoding represents a text encoding method
type Encoding struct {
Description string `json:"description"`
SpaceReplacement string `json:"spaceReplacement"`
}
// Pattern represents a command pattern
type Pattern struct {
Pattern string `json:"pattern"`
Action string `json:"action"`
Description string `json:"description"`
Priority int `json:"priority"`
}
// func main() {
// // Load configuration
// config := loadConfiguration("config.json")
// // Get user command from arguments
// if len(os.Args) < 2 {
// fmt.Println("Please provide a command")
// os.Exit(1)
// }
// userCommand := strings.Join(os.Args[1:], " ")
// fmt.Printf("Processing command: %s\n", userCommand)
// // Process the command
// output := processCommand(userCommand, config)
// if output != "" {
// fmt.Println(output)
// } else {
// fmt.Println("No matching pattern found for the command")
// }
// }
func loadConfiguration(filename string) Configuration {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf("Error reading configuration file: %v\n", err)
os.Exit(1)
}
// First parse the JSON into a temporary map
var rawConfig map[string]interface{}
if err := json.Unmarshal(data, &rawConfig); err != nil {
fmt.Printf("Error parsing configuration JSON: %v\n", err)
os.Exit(1)
}
// Then parse into our structured config
var config Configuration
if err := json.Unmarshal(data, &config); err != nil {
fmt.Printf("Error parsing configuration structure: %v\n", err)
os.Exit(1)
}
// Initialize the entity collections map
config.EntityCollections = make(map[string]map[string]map[string]interface{})
// Extract dynamic entity collections
for entityType := range config.Schema.Entities {
if entityData, exists := rawConfig[entityType]; exists {
// Convert to the right format
if entitiesMap, ok := entityData.(map[string]interface{}); ok {
// Create the entity collection
config.EntityCollections[entityType] = make(map[string]map[string]interface{})
// Fill it with the data from raw config
for entityID, entityObj := range entitiesMap {
if entityMap, ok := entityObj.(map[string]interface{}); ok {
config.EntityCollections[entityType][entityID] = entityMap
}
}
}
}
}
return config
}
func processCommand(command string, config Configuration) string {
// Apply shortcuts
mappedCommand := applyShortcuts(command, config)
fmt.Printf("Command after applying shortcuts: %s\n", mappedCommand)
// Sort patterns by priority (lower number = higher priority)
sort.Slice(config.Patterns, func(i, j int) bool {
return config.Patterns[i].Priority < config.Patterns[j].Priority
})
// Try to match patterns
for _, pattern := range config.Patterns {
fmt.Printf("Trying pattern: %s\n", pattern.Pattern)
if captures, matched := matchPattern(pattern.Pattern, mappedCommand, config); matched {
fmt.Printf("Pattern matched! Captures: %v\n", captures)
return expandAction(pattern.Action, captures, config)
}
}
return ""
}
func applyShortcuts(command string, config Configuration) string {
words := strings.Fields(command)
// Iterate through all entity collections
for entityType, entityCollection := range config.EntityCollections {
// Get the entity schema
entitySchema, exists := config.Schema.Entities[entityType]
if !exists {
continue
}
// Check if this entity type has a shortcut property
if _, hasShortcut := entitySchema.Properties["shortcut"]; !hasShortcut {
continue
}
// Check shortcuts for all entities of this type
for entityID, entityData := range entityCollection {
shortcut, ok := entityData["shortcut"].(string)
if !ok {
continue
}
// Replace shortcuts with entity IDs
for i, word := range words {
if word == shortcut {
words[i] = entityID
break
}
}
}
}
return strings.Join(words, " ")
}
func matchPattern(pattern, command string, config Configuration) (map[string]string, bool) {
// Build regex from pattern using the variables defined in the config
regexPattern := pattern
varPositions := make(map[string]int)
// Find all variable placeholders in the pattern
varRegex := regexp.MustCompile(`\{\{([a-zA-Z0-9_]+)\}\}`)
matches := varRegex.FindAllStringSubmatchIndex(pattern, -1)
// We need to process them in reverse order to avoid messing up the indexes
// when we replace the placeholders with regex patterns
reverseMatches := make([][]int, len(matches))
for i, j := 0, len(matches)-1; i <= j; i, j = i+1, j-1 {
reverseMatches[i], reverseMatches[j] = matches[j], matches[i]
}
// Store variable names in order of appearance
varNames := make([]string, len(matches))
for i, match := range matches {
varNames[i] = pattern[match[2]:match[3]]
}
// Create capture groups for each variable
modifiedPattern := pattern
captureIndex := 1
for _, varName := range varNames {
if strings.Contains(varName, ".") {
continue // Skip references
}
varSchema, exists := config.Schema.Variables[varName]
if !exists {
continue
}
var replacement string
switch varSchema.Type {
case "entity":
// Build a regex that matches all entities of the specified type
options := []string{}
// Get all entity IDs of this type
if entityMap, exists := config.EntityCollections[varSchema.EntityType]; exists {
for entityID := range entityMap {
options = append(options, regexp.QuoteMeta(entityID))
}
}
replacement = fmt.Sprintf("(%s)", strings.Join(options, "|"))
case "text":
// Text variables capture text
if varSchema.Greedy {
replacement = "(.*)"
} else {
replacement = "([^\\s]+)"
}
}
placeholder := fmt.Sprintf("{{%s}}", varName)
modifiedPattern = strings.Replace(modifiedPattern, placeholder, replacement, 1)
varPositions[varName] = captureIndex
captureIndex++
}
// Convert to full regex pattern
regexPattern = "^" + modifiedPattern + "$"
// Compile and match
re, err := regexp.Compile(regexPattern)
if err != nil {
fmt.Printf("Error compiling regex: %v\n", err)
return nil, false
}
matchStrings := re.FindStringSubmatch(command)
if matchStrings == nil {
return nil, false
}
// Extract captures based on the variable positions
captures := make(map[string]string)
for varName, position := range varPositions {
if position < len(matchStrings) {
captures[varName] = matchStrings[position]
}
}
return captures, true
}
func expandAction(action string, captures map[string]string, config Configuration) string {
result := action
// First, replace any simple variables with their captured values
// This handles cases like $url and similar direct variable references
for varName, value := range captures {
varPlaceholder := "$" + varName
result = strings.Replace(result, varPlaceholder, value, -1)
}
// Then handle complex path references with dots (e.g., browser.command)
refRegex := regexp.MustCompile(`\{\{([a-zA-Z0-9_.]+)\}\}`)
refMatches := refRegex.FindAllStringSubmatch(result, -1)
for _, match := range refMatches {
placeholder := match[0] // Full placeholder like {{browser.command}}
refPath := match[1] // Just the path like browser.command
// Skip if it doesn't contain a dot (it's a variable, not a reference)
if !strings.Contains(refPath, ".") {
continue
}
// Get the path schema for this reference
pathSchema, exists := config.Schema.Paths[refPath]
if !exists {
continue
}
// Split the reference to get the base variable
parts := strings.Split(refPath, ".")
varName := parts[0] // Base variable name (e.g., "browser" from "browser.command")
// Check if we have a value for this variable
_, exists = captures[varName]
if !exists {
continue
}
// Handle different types of path resolutions
var replacement string
// If the path has a generator, use that
if pathSchema.Generator != "" {
// Check if all required variables are present
allPresent := true
for _, reqVar := range pathSchema.Requires {
if _, exists := captures[reqVar]; !exists {
allPresent = false
break
}
}
if !allPresent {
continue
}
// Handle specific generators
if pathSchema.Generator == "searchUrl" {
siteName := captures["site"]
searchTerm := captures["search"]
// Get the website data
websiteData, exists := config.EntityCollections["websites"][siteName]
if !exists {
continue
}
// Get the search config - be careful with type assertions
searchConfigRaw, exists := websiteData["search"]
if !exists {
continue
}
searchConfig, ok := searchConfigRaw.(map[string]interface{})
if !ok {
// Try to convert from json.RawMessage if needed
var parsedConfig map[string]interface{}
jsonData, ok := searchConfigRaw.(json.RawMessage)
if !ok {
continue
}
if err := json.Unmarshal(jsonData, &parsedConfig); err != nil {
continue
}
searchConfig = parsedConfig
}
// Get search URL and param
searchURL, ok := searchConfig["url"].(string)
if !ok {
continue
}
searchParam, ok := searchConfig["param"].(string)
if !ok {
continue
}
// Get encoding
encodingName, ok := searchConfig["encoding"].(string)
if !ok {
encodingName = "none"
}
encoding, exists := config.Encodings[encodingName]
if !exists {
encoding = Encoding{SpaceReplacement: " "}
}
// Encode search term
encodedSearch := strings.ReplaceAll(searchTerm, " ", encoding.SpaceReplacement)
// Build search URL
replacement = fmt.Sprintf("%s?%s=%s", searchURL, searchParam, encodedSearch)
}
} else if len(pathSchema.Path) > 0 {
// Use the path to navigate the configuration
entityType := pathSchema.Path[0]
// Check if the second element is a variable reference like ${browser}
entityIDVar := pathSchema.Path[1]
var entityID string
// Check if it's a variable reference
if strings.HasPrefix(entityIDVar, "${") && strings.HasSuffix(entityIDVar, "}") {
varName := entityIDVar[2 : len(entityIDVar)-1]
if id, exists := captures[varName]; exists {
entityID = id
} else {
continue
}
} else {
entityID = entityIDVar
}
// Get the property name
if len(pathSchema.Path) < 3 {
continue
}
propertyName := pathSchema.Path[2]
// Navigate to the entity
entityCollection, exists := config.EntityCollections[entityType]
if !exists {
continue
}
entity, exists := entityCollection[entityID]
if !exists {
continue
}
// Get the property value
propValue, exists := entity[propertyName]
if !exists {
continue
}
// Convert to string
switch v := propValue.(type) {
case string:
replacement = v
case float64:
replacement = fmt.Sprintf("%g", v)
case int:
replacement = fmt.Sprintf("%d", v)
case bool:
replacement = fmt.Sprintf("%t", v)
default:
continue
}
}
if replacement != "" {
result = strings.Replace(result, placeholder, replacement, 1)
}
}
// Finally, replace any remaining simple variable references that use the {{varName}} syntax
simpleVarRegex := regexp.MustCompile(`\{\{([a-zA-Z0-9_]+)\}\}`)
simpleVarMatches := simpleVarRegex.FindAllStringSubmatch(result, -1)
for _, match := range simpleVarMatches {
placeholder := match[0] // Full placeholder like {{url}}
varName := match[1] // Just the variable name like url
if value, exists := captures[varName]; exists {
result = strings.Replace(result, placeholder, value, 1)
}
}
return result
}