1package commands
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"regexp"
  7	"strings"
  8	"time"
  9
 10	text "github.com/MichaelMure/go-term-text"
 11	"github.com/spf13/cobra"
 12
 13	"github.com/MichaelMure/git-bug/bug"
 14	"github.com/MichaelMure/git-bug/cache"
 15	"github.com/MichaelMure/git-bug/query"
 16	"github.com/MichaelMure/git-bug/util/colors"
 17)
 18
 19type lsOptions struct {
 20	statusQuery      []string
 21	authorQuery      []string
 22	metadataQuery    []string
 23	participantQuery []string
 24	actorQuery       []string
 25	labelQuery       []string
 26	titleQuery       []string
 27	noQuery          []string
 28	sortBy           string
 29	sortDirection    string
 30	outputFormat     string
 31}
 32
 33func newLsCommand() *cobra.Command {
 34	env := newEnv()
 35	options := lsOptions{}
 36
 37	cmd := &cobra.Command{
 38		Use:   "ls [QUERY]",
 39		Short: "List bugs.",
 40		Long: `Display a summary of each bugs.
 41
 42You can pass an additional query to filter and order the list. This query can be expressed either with a simple query language, flags, a natural language full text search, or a combination of the aforementioned.`,
 43		Example: `List open bugs sorted by last edition with a query:
 44git bug ls status:open sort:edit-desc
 45
 46List closed bugs sorted by creation with flags:
 47git bug ls --status closed --by creation
 48
 49Do a full text search of all bugs:
 50git bug ls "foo bar" baz
 51
 52Use queries, flags, and full text search:
 53git bug ls status:open --by creation "foo bar" baz
 54`,
 55		PreRunE: loadBackend(env),
 56		RunE: closeBackend(env, func(cmd *cobra.Command, args []string) error {
 57			return runLs(env, options, args)
 58		}),
 59	}
 60
 61	flags := cmd.Flags()
 62	flags.SortFlags = false
 63
 64	flags.StringSliceVarP(&options.statusQuery, "status", "s", nil,
 65		"Filter by status. Valid values are [open,closed]")
 66	flags.StringSliceVarP(&options.authorQuery, "author", "a", nil,
 67		"Filter by author")
 68	flags.StringSliceVarP(&options.metadataQuery, "metadata", "m", nil,
 69		"Filter by metadata. Example: github-url=URL")
 70	flags.StringSliceVarP(&options.participantQuery, "participant", "p", nil,
 71		"Filter by participant")
 72	flags.StringSliceVarP(&options.actorQuery, "actor", "A", nil,
 73		"Filter by actor")
 74	flags.StringSliceVarP(&options.labelQuery, "label", "l", nil,
 75		"Filter by label")
 76	flags.StringSliceVarP(&options.titleQuery, "title", "t", nil,
 77		"Filter by title")
 78	flags.StringSliceVarP(&options.noQuery, "no", "n", nil,
 79		"Filter by absence of something. Valid values are [label]")
 80	flags.StringVarP(&options.sortBy, "by", "b", "creation",
 81		"Sort the results by a characteristic. Valid values are [id,creation,edit]")
 82	flags.StringVarP(&options.sortDirection, "direction", "d", "asc",
 83		"Select the sorting direction. Valid values are [asc,desc]")
 84	flags.StringVarP(&options.outputFormat, "format", "f", "default",
 85		"Select the output formatting style. Valid values are [default,plain,json,org-mode]")
 86
 87	return cmd
 88}
 89
 90func runLs(env *Env, opts lsOptions, args []string) error {
 91	var q *query.Query
 92	var err error
 93
 94	if len(args) >= 1 {
 95		// either the shell or cobra remove the quotes, we need them back for the parsing
 96		for i, arg := range args {
 97			if strings.Contains(arg, " ") {
 98				args[i] = fmt.Sprintf("\"%s\"", arg)
 99			}
100		}
101		assembled := strings.Join(args, " ")
102		q, err = query.Parse(assembled)
103		if err != nil {
104			return err
105		}
106	} else {
107		q = query.NewQuery()
108	}
109
110	err = completeQuery(q, opts)
111	if err != nil {
112		return err
113	}
114
115	allIds, err := env.backend.QueryBugs(q)
116	if err != nil {
117		return err
118	}
119
120	bugExcerpt := make([]*cache.BugExcerpt, len(allIds))
121	for i, id := range allIds {
122		b, err := env.backend.ResolveBugExcerpt(id)
123		if err != nil {
124			return err
125		}
126		bugExcerpt[i] = b
127	}
128
129	switch opts.outputFormat {
130	case "org-mode":
131		return lsOrgmodeFormatter(env, bugExcerpt)
132	case "plain":
133		return lsPlainFormatter(env, bugExcerpt)
134	case "json":
135		return lsJsonFormatter(env, bugExcerpt)
136	case "compact":
137		return lsCompactFormatter(env, bugExcerpt)
138	case "default":
139		return lsDefaultFormatter(env, bugExcerpt)
140	default:
141		return fmt.Errorf("unknown format %s", opts.outputFormat)
142	}
143}
144
145type JSONBugExcerpt struct {
146	Id         string   `json:"id"`
147	HumanId    string   `json:"human_id"`
148	CreateTime JSONTime `json:"create_time"`
149	EditTime   JSONTime `json:"edit_time"`
150
151	Status       string         `json:"status"`
152	Labels       []bug.Label    `json:"labels"`
153	Title        string         `json:"title"`
154	Actors       []JSONIdentity `json:"actors"`
155	Participants []JSONIdentity `json:"participants"`
156	Author       JSONIdentity   `json:"author"`
157
158	Comments int               `json:"comments"`
159	Metadata map[string]string `json:"metadata"`
160}
161
162func lsJsonFormatter(env *Env, bugExcerpts []*cache.BugExcerpt) error {
163	jsonBugs := make([]JSONBugExcerpt, len(bugExcerpts))
164	for i, b := range bugExcerpts {
165		jsonBug := JSONBugExcerpt{
166			Id:         b.Id.String(),
167			HumanId:    b.Id.Human(),
168			CreateTime: NewJSONTime(b.CreateTime(), b.CreateLamportTime),
169			EditTime:   NewJSONTime(b.EditTime(), b.EditLamportTime),
170			Status:     b.Status.String(),
171			Labels:     b.Labels,
172			Title:      b.Title,
173			Comments:   b.LenComments,
174			Metadata:   b.CreateMetadata,
175		}
176
177		author, err := env.backend.ResolveIdentityExcerpt(b.AuthorId)
178		if err != nil {
179			return err
180		}
181		jsonBug.Author = NewJSONIdentityFromExcerpt(author)
182
183		jsonBug.Actors = make([]JSONIdentity, len(b.Actors))
184		for i, element := range b.Actors {
185			actor, err := env.backend.ResolveIdentityExcerpt(element)
186			if err != nil {
187				return err
188			}
189			jsonBug.Actors[i] = NewJSONIdentityFromExcerpt(actor)
190		}
191
192		jsonBug.Participants = make([]JSONIdentity, len(b.Participants))
193		for i, element := range b.Participants {
194			participant, err := env.backend.ResolveIdentityExcerpt(element)
195			if err != nil {
196				return err
197			}
198			jsonBug.Participants[i] = NewJSONIdentityFromExcerpt(participant)
199		}
200
201		jsonBugs[i] = jsonBug
202	}
203	jsonObject, _ := json.MarshalIndent(jsonBugs, "", "    ")
204	env.out.Printf("%s\n", jsonObject)
205	return nil
206}
207
208func lsCompactFormatter(env *Env, bugExcerpts []*cache.BugExcerpt) error {
209	for _, b := range bugExcerpts {
210		author, err := env.backend.ResolveIdentityExcerpt(b.AuthorId)
211		if err != nil {
212			return err
213		}
214
215		var labelsTxt strings.Builder
216		for _, l := range b.Labels {
217			lc256 := l.Color().Term256()
218			labelsTxt.WriteString(lc256.Escape())
219			labelsTxt.WriteString("◼")
220			labelsTxt.WriteString(lc256.Unescape())
221		}
222
223		env.out.Printf("%s %s %s %s %s\n",
224			colors.Cyan(b.Id.Human()),
225			colors.Yellow(b.Status),
226			text.LeftPadMaxLine(strings.TrimSpace(b.Title), 40, 0),
227			text.LeftPadMaxLine(labelsTxt.String(), 5, 0),
228			colors.Magenta(text.TruncateMax(author.DisplayName(), 15)),
229		)
230	}
231	return nil
232}
233
234func lsDefaultFormatter(env *Env, bugExcerpts []*cache.BugExcerpt) error {
235	for _, b := range bugExcerpts {
236		author, err := env.backend.ResolveIdentityExcerpt(b.AuthorId)
237		if err != nil {
238			return err
239		}
240
241		var labelsTxt strings.Builder
242		for _, l := range b.Labels {
243			lc256 := l.Color().Term256()
244			labelsTxt.WriteString(lc256.Escape())
245			labelsTxt.WriteString(" ◼")
246			labelsTxt.WriteString(lc256.Unescape())
247		}
248
249		// truncate + pad if needed
250		labelsFmt := text.TruncateMax(labelsTxt.String(), 10)
251		titleFmt := text.LeftPadMaxLine(strings.TrimSpace(b.Title), 50-text.Len(labelsFmt), 0)
252		authorFmt := text.LeftPadMaxLine(author.DisplayName(), 15, 0)
253
254		comments := fmt.Sprintf("%3d 💬", b.LenComments-1)
255		if b.LenComments-1 <= 0 {
256			comments = ""
257		}
258		if b.LenComments-1 > 999 {
259			comments = "  ∞ 💬"
260		}
261
262		env.out.Printf("%s %s\t%s\t%s\t%s\n",
263			colors.Cyan(b.Id.Human()),
264			colors.Yellow(b.Status),
265			titleFmt+labelsFmt,
266			colors.Magenta(authorFmt),
267			comments,
268		)
269	}
270	return nil
271}
272
273func lsPlainFormatter(env *Env, bugExcerpts []*cache.BugExcerpt) error {
274	for _, b := range bugExcerpts {
275		env.out.Printf("%s [%s] %s\n", b.Id.Human(), b.Status, strings.TrimSpace(b.Title))
276	}
277	return nil
278}
279
280func lsOrgmodeFormatter(env *Env, bugExcerpts []*cache.BugExcerpt) error {
281	// see https://orgmode.org/manual/Tags.html
282	orgTagRe := regexp.MustCompile("[^[:alpha:]_@]")
283	formatTag := func(l bug.Label) string {
284		return orgTagRe.ReplaceAllString(l.String(), "_")
285	}
286
287	formatTime := func(time time.Time) string {
288		return time.Format("[2006-01-02 Mon 15:05]")
289	}
290
291	env.out.Println("#+TODO: OPEN | CLOSED")
292
293	for _, b := range bugExcerpts {
294		status := strings.ToUpper(b.Status.String())
295
296		var title string
297		if link, ok := b.CreateMetadata["github-url"]; ok {
298			title = fmt.Sprintf("[[%s][%s]]", link, b.Title)
299		} else {
300			title = b.Title
301		}
302
303		author, err := env.backend.ResolveIdentityExcerpt(b.AuthorId)
304		if err != nil {
305			return err
306		}
307
308		var labels strings.Builder
309		labels.WriteString(":")
310		for i, l := range b.Labels {
311			if i > 0 {
312				labels.WriteString(":")
313			}
314			labels.WriteString(formatTag(l))
315		}
316		labels.WriteString(":")
317
318		env.out.Printf("* %-6s %s %s %s: %s %s\n",
319			status,
320			b.Id.Human(),
321			formatTime(b.CreateTime()),
322			author.DisplayName(),
323			title,
324			labels.String(),
325		)
326
327		env.out.Printf("** Last Edited: %s\n", formatTime(b.EditTime()))
328
329		env.out.Printf("** Actors:\n")
330		for _, element := range b.Actors {
331			actor, err := env.backend.ResolveIdentityExcerpt(element)
332			if err != nil {
333				return err
334			}
335
336			env.out.Printf(": %s %s\n",
337				actor.Id.Human(),
338				actor.DisplayName(),
339			)
340		}
341
342		env.out.Printf("** Participants:\n")
343		for _, element := range b.Participants {
344			participant, err := env.backend.ResolveIdentityExcerpt(element)
345			if err != nil {
346				return err
347			}
348
349			env.out.Printf(": %s %s\n",
350				participant.Id.Human(),
351				participant.DisplayName(),
352			)
353		}
354	}
355
356	return nil
357}
358
359// Finish the command flags transformation into the query.Query
360func completeQuery(q *query.Query, opts lsOptions) error {
361	for _, str := range opts.statusQuery {
362		status, err := bug.StatusFromString(str)
363		if err != nil {
364			return err
365		}
366		q.Status = append(q.Status, status)
367	}
368
369	q.Author = append(q.Author, opts.authorQuery...)
370	for _, str := range opts.metadataQuery {
371		tokens := strings.Split(str, "=")
372		if len(tokens) < 2 {
373			return fmt.Errorf("no \"=\" in key=value metadata markup")
374		}
375		var pair query.StringPair
376		pair.Key = tokens[0]
377		pair.Value = tokens[1]
378		q.Metadata = append(q.Metadata, pair)
379	}
380	q.Participant = append(q.Participant, opts.participantQuery...)
381	q.Actor = append(q.Actor, opts.actorQuery...)
382	q.Label = append(q.Label, opts.labelQuery...)
383	q.Title = append(q.Title, opts.titleQuery...)
384
385	for _, no := range opts.noQuery {
386		switch no {
387		case "label":
388			q.NoLabel = true
389		default:
390			return fmt.Errorf("unknown \"no\" filter %s", no)
391		}
392	}
393
394	switch opts.sortBy {
395	case "id":
396		q.OrderBy = query.OrderById
397	case "creation":
398		q.OrderBy = query.OrderByCreation
399	case "edit":
400		q.OrderBy = query.OrderByEdit
401	default:
402		return fmt.Errorf("unknown sort flag %s", opts.sortBy)
403	}
404
405	switch opts.sortDirection {
406	case "asc":
407		q.OrderDirection = query.OrderAscending
408	case "desc":
409		q.OrderDirection = query.OrderDescending
410	default:
411		return fmt.Errorf("unknown sort direction %s", opts.sortDirection)
412	}
413
414	return nil
415}