probo/cmd/filter.go

101 lines
2.1 KiB
Go
Raw Normal View History

2024-03-25 15:53:20 +01:00
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"os"
"git.andreafazzi.eu/andrea/probo/cmd/filter"
2024-04-10 08:44:49 +02:00
"bufio"
"io"
"strings"
2024-03-25 15:53:20 +01:00
tea "github.com/charmbracelet/bubbletea"
2024-04-10 08:44:49 +02:00
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
2024-03-25 15:53:20 +01:00
"github.com/spf13/cobra"
)
// filterCmd represents the filter command
var filterCmd = &cobra.Command{
Use: "filter",
Short: "Create a new filter",
Long: "Create a new filter to select quizzes and participants",
Run: createFilter,
}
func init() {
createCmd.AddCommand(filterCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// filterCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
2024-04-10 08:44:49 +02:00
filterCmd.Flags().StringP("type", "t", "participants", "Select the type of filter (participants or quizzes)")
2024-03-25 15:53:20 +01:00
}
func createFilter(cmd *cobra.Command, args []string) {
2024-03-27 11:45:33 +01:00
if len(os.Getenv("DEBUG")) > 0 {
f, err := tea.LogToFile("debug.log", "debug")
if err != nil {
fmt.Println("fatal:", err)
os.Exit(1)
}
defer f.Close()
}
2024-04-10 08:44:49 +02:00
var b strings.Builder
stat, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
if stat.Mode()&os.ModeNamedPipe != 0 || stat.Size() != 0 {
reader := bufio.NewReader(os.Stdin)
for {
r, _, err := reader.ReadRune()
if err != nil && err == io.EOF {
break
}
_, err = b.WriteRune(r)
if err != nil {
fmt.Println("Error getting input:", err)
os.Exit(1)
}
}
}
path, err := cmd.Flags().GetString("input")
if err != nil {
panic(err)
}
filterType, err := cmd.Flags().GetString("type")
if err != nil {
panic(err)
}
lipgloss.SetColorProfile(termenv.TrueColor)
model, err := tea.NewProgram(
filter.New(path, filterType, strings.TrimSpace(b.String())),
tea.WithOutput(os.Stderr),
).Run()
if err != nil {
2024-03-25 15:53:20 +01:00
fmt.Println("Error running program:", err)
os.Exit(1)
}
2024-04-10 08:44:49 +02:00
result := model.(*filter.FilterModel)
2024-04-12 09:52:11 +02:00
if result.Result != "" {
fmt.Fprintf(os.Stdout, result.Result)
2024-04-10 08:44:49 +02:00
}
2024-03-25 15:53:20 +01:00
}