DEVELOPMENT ENVIRONMENT

~liljamo/tamma

ref: 169aac93158f0d11a23f70fe687891766b483758 tamma/main.go -rw-r--r-- 5.8 KiB
169aac93Jonni Liljamo chore: bump version to 0.1.1 4 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
/*
 * 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/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
}

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 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
	}
	hostList := list.New(hostListItems, types.HostItemDelegate{}, 48, hostListH+4)
	hostList.Title = "Select host:"
	hostList.SetShowHelp(false)
	hostList.SetFilteringEnabled(true)
	hostList.SetShowStatusBar(false)
	hostList.DisableQuitKeybindings()
	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
	}
	actionList := list.New(actionListItems, types.ActionItemDelegate{}, 48, actionListH+4)
	actionList.Title = "What shall we do today?"
	actionList.SetShowHelp(false)
	actionList.SetFilteringEnabled(true)
	actionList.SetShowStatusBar(false)
	actionList.DisableQuitKeybindings()
	actionList.Styles.Title = styles.ListTitle
	actionList.Styles.PaginationStyle = styles.ListPaginaton

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

	os.Exit(0)
}