File: comments.go

package info (click to toggle)
tea-cli 0.9.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,364 kB
  • sloc: makefile: 120; sh: 17
file content (76 lines) | stat: -rw-r--r-- 2,353 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package interact

import (
	"fmt"
	"os"

	"code.gitea.io/sdk/gitea"
	"code.gitea.io/tea/modules/context"
	"code.gitea.io/tea/modules/print"

	"github.com/AlecAivazis/survey/v2"
	"golang.org/x/crypto/ssh/terminal"
)

// ShowCommentsMaybeInteractive fetches & prints comments, depending on the --comments flag.
// If that flag is unset, and output is not piped, prompts the user first.
func ShowCommentsMaybeInteractive(ctx *context.TeaContext, idx int64, totalComments int) error {
	if ctx.Bool("comments") {
		opts := gitea.ListIssueCommentOptions{ListOptions: ctx.GetListOptions()}
		c := ctx.Login.Client()
		comments, _, err := c.ListIssueComments(ctx.Owner, ctx.Repo, idx, opts)
		if err != nil {
			return err
		}
		print.Comments(comments)
	} else if print.IsInteractive() && !ctx.IsSet("comments") {
		// if we're interactive, but --comments hasn't been explicitly set to false
		if err := ShowCommentsPaginated(ctx, idx, totalComments); err != nil {
			fmt.Printf("error while loading comments: %v\n", err)
		}
	}
	return nil
}

// ShowCommentsPaginated prompts if issue/pr comments should be shown and continues to do so.
func ShowCommentsPaginated(ctx *context.TeaContext, idx int64, totalComments int) error {
	c := ctx.Login.Client()
	opts := gitea.ListIssueCommentOptions{ListOptions: ctx.GetListOptions()}
	prompt := "show comments?"
	commentsLoaded := 0

	// paginated fetch
	// NOTE: as of gitea 1.13, pagination is not provided by this endpoint, but handles
	// this function gracefully anyways.
	for {
		loadComments := false
		confirm := survey.Confirm{Message: prompt, Default: true}
		if err := survey.AskOne(&confirm, &loadComments); err != nil {
			return err
		} else if !loadComments {
			break
		} else {
			if comments, _, err := c.ListIssueComments(ctx.Owner, ctx.Repo, idx, opts); err != nil {
				return err
			} else if len(comments) != 0 {
				print.Comments(comments)
				commentsLoaded += len(comments)
			}
			if commentsLoaded >= totalComments {
				break
			}
			opts.ListOptions.Page++
			prompt = "load more?"
		}
	}
	return nil
}

// IsStdinPiped checks if stdin is piped
func IsStdinPiped() bool {
	return !terminal.IsTerminal(int(os.Stdin.Fd()))
}