aboutsummaryrefslogtreecommitdiffstats
path: root/commands/patch/list.go
blob: 73461f2e3ce68bd3590a27483a654fbae5029b23 (plain) (blame)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package patch

import (
	"bufio"
	"fmt"
	"io"
	"os/exec"
	"time"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/config"
	"git.sr.ht/~rjarry/aerc/lib/pama"
	"git.sr.ht/~rjarry/aerc/lib/pama/models"
	"git.sr.ht/~rjarry/aerc/lib/ui"
	"git.sr.ht/~rjarry/go-opt"
	"github.com/gdamore/tcell/v2"
)

type List struct {
	All bool `opt:"-a"`
}

func init() {
	register(List{})
}

func (List) Context() commands.CommandContext {
	return commands.GLOBAL
}

func (List) Aliases() []string {
	return []string{"list", "ls"}
}

func (l List) Execute(args []string) error {
	m := pama.New()
	current, err := m.CurrentProject()
	if err != nil {
		return err
	}

	projects := []models.Project{current}
	if l.All {
		projects, err = m.Projects("")
		if err != nil {
			return err
		}
	}

	app.PushStatus(fmt.Sprintf("Current project: %s", current.Name), 30*time.Second)

	createWidget := func(r io.Reader) (ui.DrawableInteractive, error) {
		pagerCmd, err := app.CmdFallbackSearch(config.PagerCmds(), true)
		if err != nil {
			return nil, err
		}

		cmd := opt.SplitArgs(pagerCmd)
		pager := exec.Command(cmd[0], cmd[1:]...)
		pager.Stdin = r

		term, err := app.NewTerminal(pager)
		if err != nil {
			return nil, err
		}
		start := time.Now()
		term.OnClose = func(err error) {
			if time.Since(start) > 250*time.Millisecond {
				app.CloseDialog()
				return
			}
			term.OnEvent = func(_ tcell.Event) bool {
				app.CloseDialog()
				return true
			}
		}
		return term, nil
	}

	viewer, err := createWidget(m.NewReader(projects))
	if err != nil {
		viewer = app.NewListBox(
			"Press <Esc> or <Enter> to close. "+
				"Start typing to filter.",
			numerify(m.NewReader(projects)), app.SelectedAccountUiConfig(),
			func(_ string) { app.CloseDialog() },
		)
	}

	app.AddDialog(app.NewDialog(
		ui.NewBox(viewer, "Patch Management", "",
			app.SelectedAccountUiConfig(),
		),
		// start pos on screen
		func(h int) int {
			return h / 8
		},
		// dialog height
		func(h int) int {
			return h - 2*h/8
		},
	))

	return nil
}

func numerify(r io.Reader) []string {
	var lines []string
	nr := 1
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		s := scanner.Text()
		lines = append(lines, fmt.Sprintf("%3d %s", nr, s))
		nr++
	}
	return lines
}