DEVELOPMENT ENVIRONMENT

~liljamo/tamma

ref: e760917e8531f5438ae184ec0c1599f5a3785d1b tamma/main.go -rw-r--r-- 6.6 KiB
e760917eJonni Liljamo feat: enable help, add bindings there 2 months ago
                                                                                
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-only, see NOTICE and LICENSE for
 * more information.
 */

// nolint
package main

import (
	"fmt"
	"os"
	"os/exec"

	"git.src.quest/~skye/tamma/styles"
	"git.src.quest/~skye/tamma/types"
	"github.com/charmbracelet/bubbles/key"
	"github.com/charmbracelet/bubbles/list"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"gopkg.in/yaml.v3"
)

type state int

const (
	hostSelect state = iota
	actionSelect
)

type model struct {
	width          int
	height         int
	err            string
	state          state
	hostList       list.Model
	selectedHost   types.HostItem
	actionList     list.Model
	selectedAction types.ActionItem
	actionListKeys *types.ActionListKeyMap
}

type execFinishedMsg struct{ err error }

func (m model) Init() tea.Cmd {
	return nil
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height
		return m, nil
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c":
			return m, tea.Quit
		case "enter":
			switch m.state {
			case hostSelect:
				i, ok := m.hostList.SelectedItem().(types.HostItem)
				if ok {
					m.selectedHost = i
					m.state = actionSelect
				}
			case actionSelect:
				a, ok := m.actionList.SelectedItem().(types.ActionItem)
				if ok {
					execString, err := a.ExecString(m.selectedHost)
					if err != nil {
						m.err = err.Error()
					} else {
						c := exec.Command("sh", "-c", execString)
						return m, tea.ExecProcess(c, func(err error) tea.Msg {
							return execFinishedMsg{err}
						})
					}
				}
			}
		case "q":
			switch m.state {
			case hostSelect:
				return m, tea.Quit
			case actionSelect:
				if m.actionList.FilterState() != list.Filtering {
					m.actionList.ResetSelected()
					m.state = hostSelect
				}
			}
		case "c":
			switch m.state {
			case actionSelect:
				if m.actionList.FilterState() != list.Filtering {
					if os.Getenv("WAYLAND_DISPLAY") != "" {
						a, ok := m.actionList.SelectedItem().(types.ActionItem)
						if ok {
							execString, err := a.ExecString(m.selectedHost)
							if err != nil {
								m.err = err.Error()
							} else {
								err := exec.Command("wl-copy", execString).Run()
								if err != nil {
									m.err = err.Error()
								}
							}
						}
					}
				}
			}
		}
	case execFinishedMsg:
		if msg.err != nil {
			m.err = msg.err.Error()
		}
	}

	switch m.state {
	case hostSelect:
		var cmd tea.Cmd
		m.hostList, cmd = m.hostList.Update(msg)
		return m, cmd
	case actionSelect:
		var cmd tea.Cmd
		m.actionList, cmd = m.actionList.Update(msg)
		return m, cmd
	}

	return m, nil
}

func (m model) View() string {
	tlw := lipgloss.Width(styles.TopLevel.Render("")) - 2

	msg := "\n"
	switch m.state {
	case hostSelect:
		msg += m.hostList.View()
		msg += "\n"
	case actionSelect:
		alb := m.actionList.View()
		//alw := lipgloss.Width(alb)
		msg += alb
		msg += "\n"
		// NOTE: type asserting here will return nil if we've filtered the list to
		// have no results, thus this check is needed.
		selectedAction, ok := m.actionList.SelectedItem().(types.ActionItem)
		if ok {
			execString, err := selectedAction.ExecString(m.selectedHost)
			if err != nil {
				msg += fmt.Sprintf("error in ExecString(): %s\n", err.Error())
			}
			msg += styles.ActionExecString.Width(tlw).SetString(execString).String()
		}
	}

	if m.err != "" {
		msg += m.err
	}

	msg = styles.TopLevel.Render(msg)
	return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, msg)
}

type config struct {
	Hosts   []types.HostItem   `yaml:"hosts"`
	Actions []types.ActionItem `yaml:"actions"`
	// Wheter default actions should be enabled, defaults to true.
	DefaultActions bool `yaml:"default_actions"`
}

func main() {
	config := config{}

	configContent, err := os.ReadFile("./tamma.yaml")
	if err != nil {
		fmt.Printf("failed to read config file: %s\n", err.Error())
		os.Exit(1)
	}

	err = yaml.Unmarshal(configContent, &config)
	if err != nil {
		fmt.Printf("failed to unmarshal config file: %s\n", err.Error())
		os.Exit(1)
	}

	hostListItems := []list.Item{}
	for _, i := range config.Hosts {
		hostListItems = append(hostListItems, i)
	}

	hostListH := len(hostListItems)
	if hostListH > 10 {
		hostListH = 10
	}
	hostListKeys := types.NewHostListKeyMap()
	hostList := list.New(hostListItems, types.HostItemDelegate{}, 48, hostListH+4)
	hostList.Title = "Select host:"
	hostList.SetShowHelp(true)
	hostList.SetFilteringEnabled(true)
	hostList.SetShowStatusBar(false)
	hostList.DisableQuitKeybindings()
	hostList.AdditionalShortHelpKeys = func() []key.Binding {
		return []key.Binding{
			hostListKeys.Quit,
		}
	}
	hostList.AdditionalFullHelpKeys = func() []key.Binding {
		return []key.Binding{
			hostListKeys.Quit,
		}
	}
	hostList.Styles.Title = styles.ListTitle
	hostList.Styles.PaginationStyle = styles.ListPaginaton

	actionListItems := []list.Item{}
	if !config.DefaultActions {
		actionListItems = []list.Item{
			types.ActionItem{
				Name:         "ssh",
				ExecTemplate: "ssh {{ .A.host.Data.user }}@{{ .A.host.IP }}",
				A:            map[string]interface{}{},
			},
			types.ActionItem{
				Name:         "remote switch",
				ExecTemplate: "nixos-rebuild switch --flake \".?submodules=1#{{ .A.host.Name }}\" --target-host {{ .A.host.Data.user }}@{{ .A.host.IP }}",
				A:            map[string]interface{}{},
			},
		}
	}
	for _, i := range config.Actions {
		if i.A == nil {
			i.A = map[string]interface{}{}
		}
		actionListItems = append(actionListItems, i)
	}

	actionListH := len(actionListItems)
	if actionListH > 10 {
		actionListH = 10
	}
	actionListKeys := types.NewActionListKeyMap()
	actionList := list.New(actionListItems, types.ActionItemDelegate{}, 48, actionListH+4)
	actionList.Title = "What shall we do today?"
	actionList.SetShowHelp(true)
	actionList.SetFilteringEnabled(true)
	actionList.SetShowStatusBar(false)
	actionList.DisableQuitKeybindings()
	actionList.AdditionalShortHelpKeys = func() []key.Binding {
		return []key.Binding{
			actionListKeys.Back,
			actionListKeys.CopyCommand,
		}
	}
	actionList.AdditionalFullHelpKeys = func() []key.Binding {
		return []key.Binding{
			actionListKeys.Back,
			actionListKeys.CopyCommand,
		}
	}
	actionList.Styles.Title = styles.ListTitle
	actionList.Styles.PaginationStyle = styles.ListPaginaton

	p := tea.NewProgram(model{
		state:          hostSelect,
		hostList:       hostList,
		actionList:     actionList,
		actionListKeys: actionListKeys,
	}, tea.WithAltScreen())
	if _, err := p.Run(); err != nil {
		fmt.Printf("An error occured while running: %v\n", err)
		os.Exit(1)
	}

	os.Exit(0)
}