Skip to content

Commit b81882c

Browse files
authored
fix: show filters in query list command (#63)
Also adds a json output for scripting fixes #60
1 parent d65f103 commit b81882c

File tree

2 files changed

+276
-78
lines changed

2 files changed

+276
-78
lines changed

cmd/queryList.go

Lines changed: 131 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,88 @@
1616
package cmd
1717

1818
import (
19+
"encoding/json"
1920
"fmt"
21+
"io"
22+
"net/http"
2023
"os"
24+
"pb/pkg/config"
2125
"pb/pkg/model"
2226
"strings"
2327
"time"
2428

2529
"github.com/spf13/cobra"
2630
)
2731

32+
var outputFlag string
33+
2834
var SavedQueryList = &cobra.Command{
2935
Use: "list",
30-
Example: "pb query list ",
36+
Example: "pb query list [-o | --output]",
3137
Short: "List of saved queries",
32-
Long: "\nShow the list of saved quries for active user",
38+
Long: "\nShow the list of saved queries for active user",
3339
PreRunE: PreRunDefaultProfile,
3440
Run: func(_ *cobra.Command, _ []string) {
3541
client := DefaultClient()
3642

43+
// Check if the output flag is set
44+
if outputFlag != "" {
45+
// Display all filters if output flag is set
46+
userConfig, err := config.ReadConfigFromFile()
47+
if err != nil {
48+
fmt.Println("Error reading Default Profile")
49+
}
50+
var userProfile config.Profile
51+
if profile, ok := userConfig.Profiles[userConfig.DefaultProfile]; ok {
52+
userProfile = profile
53+
}
54+
55+
client := &http.Client{
56+
Timeout: time.Second * 60,
57+
}
58+
userSavedQueries := fetchFilters(client, &userProfile)
59+
// Collect all filter titles in a slice and join with commas
60+
var filterDetails []string
61+
62+
if outputFlag == "json" {
63+
// If JSON output is requested, marshal the saved queries to JSON
64+
jsonOutput, err := json.MarshalIndent(userSavedQueries, "", " ")
65+
if err != nil {
66+
fmt.Println("Error converting saved queries to JSON:", err)
67+
return
68+
}
69+
fmt.Println(string(jsonOutput))
70+
} else {
71+
for _, query := range userSavedQueries {
72+
// Build the line conditionally
73+
var parts []string
74+
if query.Title != "" {
75+
parts = append(parts, query.Title)
76+
}
77+
if query.Stream != "" {
78+
parts = append(parts, query.Stream)
79+
}
80+
if query.Desc != "" {
81+
parts = append(parts, query.Desc)
82+
}
83+
if query.From != "" {
84+
parts = append(parts, query.From)
85+
}
86+
if query.To != "" {
87+
parts = append(parts, query.To)
88+
}
89+
90+
// Join parts with commas and print each query on a new line
91+
fmt.Println(strings.Join(parts, ", "))
92+
}
93+
}
94+
// Print all titles as a single line, comma-separated
95+
fmt.Println(strings.Join(filterDetails, " "))
96+
return
97+
98+
}
99+
100+
// Normal Saved Queries Menu if output flag not set
37101
p := model.SavedQueriesMenu()
38102
if _, err := p.Run(); err != nil {
39103
os.Exit(1)
@@ -80,9 +144,7 @@ func savedQueryToPbQuery(query string, start string, end string) {
80144
endFormatted := formatToRFC3339(end)
81145
timeStamps = ` --from=` + startFormatted + ` --to=` + endFormatted
82146
}
83-
queryTemplate := `pb query run ` + query + timeStamps
84-
fmt.Printf("\nCopy and paste the command")
85-
fmt.Printf("\n\n%s\n\n", queryTemplate)
147+
_ = `pb query run ` + query + timeStamps
86148
}
87149

88150
// Parses all UTC time format from string to time interface
@@ -140,3 +202,67 @@ func formatToRFC3339(time string) string {
140202
}
141203
return formattedTime
142204
}
205+
206+
func init() {
207+
// Add the output flag to the SavedQueryList command
208+
SavedQueryList.Flags().StringVarP(&outputFlag, "output", "o", "", "Output format (text or json)")
209+
}
210+
211+
type Item struct {
212+
ID string `json:"id"`
213+
Title string `json:"title"`
214+
Stream string `json:"stream"`
215+
Desc string `json:"desc"`
216+
From string `json:"from,omitempty"`
217+
To string `json:"to,omitempty"`
218+
}
219+
220+
func fetchFilters(client *http.Client, profile *config.Profile) []Item {
221+
endpoint := fmt.Sprintf("%s/%s", profile.URL, "api/v1/filters")
222+
req, err := http.NewRequest("GET", endpoint, nil)
223+
if err != nil {
224+
fmt.Println("Error creating request:", err)
225+
return nil
226+
}
227+
228+
req.SetBasicAuth(profile.Username, profile.Password)
229+
req.Header.Add("Content-Type", "application/json")
230+
resp, err := client.Do(req)
231+
if err != nil {
232+
fmt.Println("Error making request:", err)
233+
return nil
234+
}
235+
defer resp.Body.Close()
236+
237+
body, err := io.ReadAll(resp.Body)
238+
if err != nil {
239+
fmt.Println("Error reading response body:", err)
240+
return nil
241+
}
242+
243+
var filters []model.Filter
244+
err = json.Unmarshal(body, &filters)
245+
if err != nil {
246+
fmt.Println("Error unmarshalling response:", err)
247+
return nil
248+
}
249+
250+
// This returns only the SQL type filters
251+
var userSavedQueries []Item
252+
for _, filter := range filters {
253+
254+
queryBytes, _ := json.Marshal(filter.Query.FilterQuery)
255+
256+
userSavedQuery := Item{
257+
ID: filter.FilterID,
258+
Title: filter.FilterName,
259+
Stream: filter.StreamName,
260+
Desc: string(queryBytes),
261+
From: filter.TimeFilter.From,
262+
To: filter.TimeFilter.To,
263+
}
264+
userSavedQueries = append(userSavedQueries, userSavedQuery)
265+
266+
}
267+
return userSavedQueries
268+
}

0 commit comments

Comments
 (0)