probo/cmd/filter.go
2024-05-13 12:00:47 +02:00

114 lines
2.6 KiB
Go

/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"log"
"os"
"git.andreafazzi.eu/andrea/probo/cmd/filter"
"git.andreafazzi.eu/andrea/probo/cmd/util"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/glamour"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
)
var longDescription string = `
# Filters
**Filters can made selection over stores.**
Filters allow you to narrow down selections across various stores. By
using filters, you can select participants, quizzes, and
responses. The command triggers a Text User Interface (TUI) that runs
a jq filter, displaying the outcome in real-time. After you're content
with the filtered JSON, pressing ⏎ will present the result on
stdout, enabling you to further process it by piping it forward.
## Examples
Filter over participants store.
**probo filter participants**
Filter over quizzes store using the jq filter in tags.jq file
**probo filter quizzes -i data/filters/tags.jq**
Filter over participants and pipe the result on the next filter. The result is then stored in a JSON file.
**probo filter participants | probo filter quizzes > data/json/selection.json**
`
func init() {
desc, err := glamour.Render(fmt.Sprintf("```\n%s```\n%s", logo, longDescription), "dark")
if err != nil {
panic(err)
}
filterCmd := &cobra.Command{
Use: "filter {participants,quizzes,responses}",
Short: "Filter the given store",
Long: desc,
Run: runFilter,
}
rootCmd.AddCommand(filterCmd)
filterCmd.PersistentFlags().StringP("input", "i", "", "Specify an input file")
}
func runFilter(cmd *cobra.Command, args []string) {
var storeType string
path, err := cmd.Flags().GetString("input")
if err != nil {
panic(err)
}
if len(args) < 1 {
f := util.LogToFile()
if f != nil {
defer f.Close()
}
lipgloss.SetColorProfile(termenv.TrueColor)
form := huh.NewForm(huh.NewGroup(
huh.NewSelect[string]().
Title("Choose the store you want to filter").
Options(
huh.NewOption("Participants", "participants"),
huh.NewOption("Quizzes", "quizzes"),
huh.NewOption("Responses", "responses"),
).Value(&storeType),
))
err = form.Run()
if err != nil {
log.Fatal(err)
}
} else {
storeType = args[0]
}
model, err := tea.NewProgram(
filter.New(path, storeType, util.ReadStdin()),
tea.WithOutput(os.Stderr),
).Run()
if err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
result := model.(*filter.FilterModel)
if result.Result != "" {
fmt.Fprintf(os.Stdout, result.Result)
}
}