zk/cmd/list.go

84 lines
1.7 KiB
Go
Raw Normal View History

2021-01-03 20:19:21 +00:00
package cmd
import (
2021-01-09 16:14:54 +00:00
"fmt"
"io"
2021-01-23 12:29:14 +00:00
"os"
2021-01-09 16:14:54 +00:00
2021-01-03 20:19:21 +00:00
"github.com/mickael-menu/zk/adapter/sqlite"
"github.com/mickael-menu/zk/core/note"
"github.com/mickael-menu/zk/core/zk"
2021-01-12 19:54:08 +00:00
"github.com/mickael-menu/zk/util/errors"
2021-01-09 16:14:54 +00:00
"github.com/mickael-menu/zk/util/opt"
"github.com/mickael-menu/zk/util/strings"
2021-01-03 20:19:21 +00:00
)
// List displays notes matching a set of criteria.
type List struct {
2021-01-23 14:39:47 +00:00
Format string `help:"Pretty prints the list using the given format" short:"f" placeholder:"<template>"`
NoPager bool `help:"Do not pipe zk output into a pager" short:"P"`
Filtering `embed`
Sorting `embed`
2021-01-03 20:19:21 +00:00
}
func (cmd *List) Run(container *Container) error {
zk, err := zk.Open(".")
if err != nil {
return err
}
2021-01-23 14:39:47 +00:00
opts, err := NewFinderOpts(zk, cmd.Filtering, cmd.Sorting)
2021-01-12 19:54:08 +00:00
if err != nil {
2021-01-14 21:10:35 +00:00
return errors.Wrapf(err, "incorrect criteria")
2021-01-12 19:54:08 +00:00
}
2021-01-03 20:19:21 +00:00
db, err := container.Database(zk.DBPath())
if err != nil {
return err
}
2021-01-23 12:29:14 +00:00
wd, err := os.Getwd()
if err != nil {
return err
}
2021-01-23 12:29:14 +00:00
templates := container.TemplateLoader(zk.Config.Lang)
2021-01-23 20:15:17 +00:00
styler := container.TTY
2021-01-23 12:29:14 +00:00
format := opt.NewNotEmptyString(cmd.Format)
formatter, err := note.NewFormatter(zk.Path, wd, format, templates, styler)
if err != nil {
return err
}
2021-01-03 20:19:21 +00:00
2021-01-23 12:29:14 +00:00
var notes []note.Match
err = db.WithTransaction(func(tx sqlite.Transaction) error {
notes, err = container.NoteFinder(tx).Find(*opts)
return err
})
if err != nil {
return err
}
2021-01-23 12:29:14 +00:00
count := len(notes)
if count > 0 {
err = container.Paginate(cmd.NoPager, zk.Config, func(out io.Writer) error {
2021-01-23 12:29:14 +00:00
for _, note := range notes {
ft, err := formatter.Format(note)
if err != nil {
return err
}
2021-01-23 14:24:08 +00:00
fmt.Fprintf(out, "%v\n", ft)
2021-01-23 12:29:14 +00:00
}
return nil
})
2021-01-23 12:29:14 +00:00
}
2021-01-23 12:29:14 +00:00
if err == nil {
2021-01-23 14:24:08 +00:00
fmt.Printf("\nFound %d %s\n", count, strings.Pluralize("note", count))
2021-01-23 12:29:14 +00:00
}
2021-01-12 19:54:08 +00:00
2021-01-23 12:29:14 +00:00
return err
2021-01-12 19:54:08 +00:00
}