package commands import ( "context" "fmt" "git.loyso.art/frx/eway/cmd/cli/components" "github.com/rodaine/table" "github.com/rs/zerolog" "github.com/urfave/cli/v3" ) func CategoriesCommandTree() *cli.Command { var h categoriesHandlers return &cli.Command{ Name: "categories", Usage: "Interact with stored categories", Commands: []*cli.Command{ newCategoriesListCommand(h), }, } } func newCategoriesListCommand(h categoriesHandlers) *cli.Command { cmd := cli.Command{ Name: "list", Usage: "List categories, stories in db", Flags: []cli.Flag{ &cli.IntFlag{ Name: "limit", Usage: "limits output to selected items", Value: 20, }, &cli.IntFlag{ Name: "page", Usage: "in case of limit, selects page", Value: 0, }, &cli.BoolFlag{ Name: "with-total", Usage: "prints total count of categories", }, }, } return cmdWithAction(cmd, h.List) } type categoriesHandlers struct{} func (categoriesHandlers) List(ctx context.Context, c *cli.Command) error { r, err := components.GetRepository() if err != nil { return fmt.Errorf("getting repository: %w", err) } categories, err := r.Category().List(ctx) if err != nil { return fmt.Errorf("listing categories: %w", err) } limit := int(c.Int("limit")) page := int(c.Int("page")) total := len(categories) if page == 0 { page = 1 } if limit > 0 { offset := (page - 1) * limit if offset > len(categories) { offset = len(categories) - 1 } limit = offset + limit if limit > len(categories) { limit = len(categories) } categories = categories[offset:limit] } tbl := table.New("ID", "Name") for _, category := range categories { if category.ID == 0 && category.Name == "" { continue } tbl.AddRow(category.ID, category.Name) } tbl.Print() if c.Bool("with-total") { zerolog.Ctx(ctx).Info().Int("count", total).Msg("total categories stats") } return nil }