Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
397 lines (342 loc) · 10.3 KB
/
Copy pathmain.go
File metadata and controls
397 lines (342 loc) · 10.3 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
type Step struct {
Title string `json:"title"`
Command string `json:"command"`
Done bool `json:"-"`
}
// Config structure for config.json (including git_username, editor and tasks)
type Config struct {
VoidPackagesPath string `json:"void_packages_path"`
GitUsername string `json:"git_username"`
Editor string `json:"editor"`
Tasks []Step `json:"tasks"`
}
type model struct {
pkgName string
config Config
currentVersion string
updateStatus string
steps []Step
cursor int
outputLog string
running bool
message string
activeChan chan tea.Msg
width int
height int
}
var (
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("205")).Bold(true)
versionStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("246")).Italic(true)
cursorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("99")).Bold(true)
doneStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Strikethrough(true)
normalStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("252"))
helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Italic(true)
boxStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 2).BorderForeground(lipgloss.Color("63"))
outputBoxStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 2).BorderForeground(lipgloss.Color("39"))
statusBoxStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 2).BorderForeground(lipgloss.Color("214"))
)
type outputLineMsg string
type updateCheckFinishedMsg struct {
output string
err error
}
type execFinishedMsg struct {
err error
}
// Load config file and parse tasks with variable substitution
func loadConfig(pkgName string) Config {
defaultPath := "./void-packages"
file, err := os.Open("config.json")
if err != nil {
return Config{
VoidPackagesPath: defaultPath,
GitUsername: "your-username",
Editor: "nano",
Tasks: []Step{
{Title: "Binary Bootstrap", Command: fmt.Sprintf("cd %s && ./xbps-src binary-bootstrap", defaultPath)},
},
}
}
defer file.Close()
var cfg Config
decoder := json.NewDecoder(file)
if err := decoder.Decode(&cfg); err != nil || cfg.VoidPackagesPath == "" {
cfg.VoidPackagesPath = defaultPath
}
if cfg.GitUsername == "" {
cfg.GitUsername = "your-username"
}
// Determine editor: config.json -> $EDITOR -> fallback (nano)
editor := cfg.Editor
if editor == "" {
editor = os.Getenv("EDITOR")
if editor == "" {
editor = "nano"
}
}
// Fallback if no tasks defined in json
if len(cfg.Tasks) == 0 {
cfg.Tasks = []Step{
{Title: "Binary Bootstrap", Command: fmt.Sprintf("cd %s && ./xbps-src binary-bootstrap", cfg.VoidPackagesPath)},
}
}
// Replace placeholders ({{repo}}, {{pkg}}, {{git_username}}, and {{editor}}) in all tasks
for i := range cfg.Tasks {
cmd := cfg.Tasks[i].Command
cmd = strings.ReplaceAll(cmd, "{{repo}}", cfg.VoidPackagesPath)
cmd = strings.ReplaceAll(cmd, "{{pkg}}", pkgName)
cmd = strings.ReplaceAll(cmd, "{{git_username}}", cfg.GitUsername)
cmd = strings.ReplaceAll(cmd, "{{editor}}", editor)
cfg.Tasks[i].Command = cmd
}
return cfg
}
// Reads the current version from the void-packages template if available
func parseTemplateVersion(cfg Config, pkgName string) string {
templatePath := filepath.Join(cfg.VoidPackagesPath, "srcpkgs", pkgName, "template")
file, err := os.Open(templatePath)
if err != nil {
return "unknown"
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "version=") {
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
return strings.Trim(parts[1], `"'`)
}
}
}
if scanErr := scanner.Err(); scanErr != nil {
return "unknown"
}
return "unknown"
}
func initialModel(pkgName string) model {
p := pkgName
if p == "" {
p = "<pkgname>"
}
cfg := loadConfig(p)
detectedVersion := parseTemplateVersion(cfg, p)
return model{
pkgName: p,
config: cfg,
currentVersion: detectedVersion,
updateStatus: "Checking...",
steps: cfg.Tasks,
width: 80,
}
}
// Automatically check for updates on startup in the background
func checkUpdatesCmd(cfg Config, pkgName string) tea.Cmd {
return func() tea.Msg {
repoDir := cfg.VoidPackagesPath
if _, err := os.Stat(repoDir); os.IsNotExist(err) {
return updateCheckFinishedMsg{output: "", err: fmt.Errorf("repo not cloned")}
}
cmdStr := fmt.Sprintf("cd %s && ./xbps-src update-check %s", repoDir, pkgName)
cmd := exec.Command("bash", "-c", cmdStr)
cmd.Env = append(os.Environ(), "PYTHONUNBUFFERED=1")
outBytes, err := cmd.CombinedOutput()
return updateCheckFinishedMsg{output: string(outBytes), err: err}
}
}
func (m model) Init() tea.Cmd {
return checkUpdatesCmd(m.config, m.pkgName)
}
// Background worker that executes command and pushes lines into buffered channel
func runCommandAndStream(command string, ch chan tea.Msg) {
cmd := exec.Command("bash", "-c", command)
cmd.Env = append(os.Environ(), "PYTHONUNBUFFERED=1")
r, w := io.Pipe()
cmd.Stdout = w
cmd.Stderr = w
if err := cmd.Start(); err != nil {
w.Close()
ch <- execFinishedMsg{err: err}
close(ch)
return
}
go func() {
err := cmd.Wait()
w.Close()
ch <- execFinishedMsg{err: err}
}()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
ch <- outputLineMsg(scanner.Text() + "\n")
}
if scanErr := scanner.Err(); scanErr != nil {
ch <- outputLineMsg(fmt.Sprintf("[Scanner Error: %v]\n", scanErr))
}
close(ch)
}
// Continuously polls the channel for new lines without blocking the TUI event loop
func waitForData(ch chan tea.Msg) tea.Cmd {
return func() tea.Msg {
msg, ok := <-ch
if !ok {
return nil
}
return msg
}
}
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 updateCheckFinishedMsg:
out := strings.TrimSpace(msg.output)
if msg.err != nil || out == "" {
m.updateStatus = "Up to date"
} else {
lines := strings.Split(out, "\n")
m.updateStatus = strings.TrimSpace(lines[len(lines)-1])
}
return m, nil
case tea.KeyMsg:
if m.running {
return m, nil
}
m.message = ""
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(m.steps)-1 {
m.cursor++
}
case " ", "enter":
m.steps[m.cursor].Done = !m.steps[m.cursor].Done
case "r":
cmdStr := m.steps[m.cursor].Command
// Prüfen, ob der Befehl interaktiv sein muss (Editor, xi-Installationen oder sudo)
isInteractive := strings.Contains(cmdStr, "nano") || strings.Contains(cmdStr, "hx") ||
strings.Contains(cmdStr, "vim") || strings.Contains(cmdStr, "vi") ||
strings.Contains(cmdStr, "micro") || strings.Contains(cmdStr, "emacs") ||
strings.Contains(cmdStr, "xi ") || strings.Contains(cmdStr, "sudo") ||
strings.Contains(cmdStr, "xbps-install ") || strings.Contains(cmdStr, "sudo")
if isInteractive {
// Terminal-Kontrolle kurz abgeben, damit sudo/xi Passwörter sauber abfragen kann
c := exec.Command("bash", "-c", cmdStr)
return m, tea.ExecProcess(c, func(err error) tea.Msg {
return execFinishedMsg{err: err}
})
} else {
// Nicht-interaktive Befehle im Hintergrund mit Live-Log-Stream ausführen
m.running = true
m.outputLog = ""
m.message = "Running..."
m.activeChan = make(chan tea.Msg, 256)
go runCommandAndStream(cmdStr, m.activeChan)
return m, waitForData(m.activeChan)
}
}
case outputLineMsg:
m.outputLog += string(msg)
lines := strings.Split(m.outputLog, "\n")
if len(lines) > 12 {
m.outputLog = strings.Join(lines[len(lines)-12:], "\n")
}
return m, waitForData(m.activeChan)
case execFinishedMsg:
m.running = false
if msg.err != nil {
m.message = fmt.Sprintf("Execution Error: %v", msg.err)
} else {
m.message = "Command executed successfully!"
m.steps[m.cursor].Done = true
// Template-Version nach Änderungen automatisch aktualisieren
m.currentVersion = parseTemplateVersion(m.config, m.pkgName)
}
return m, nil
}
return m, nil
}
func (m model) View() string {
var sb strings.Builder
boxWidth := m.width - 4
if boxWidth < 40 {
boxWidth = 40
}
titleLine := fmt.Sprintf(" Void Linux Package Update Wizard: [%s]", m.pkgName)
sb.WriteString(titleStyle.Render(titleLine))
sb.WriteString("\n")
versionDisplay := m.currentVersion
if m.updateStatus != "" && m.updateStatus != "Checking..." {
versionDisplay = fmt.Sprintf("%s (%s)", m.currentVersion, m.updateStatus)
}
versionLine := fmt.Sprintf(" Version: %s\n", versionDisplay)
sb.WriteString(versionStyle.Render(versionLine))
sb.WriteString("\n")
for i, step := range m.steps {
cursor := " "
if m.cursor == i {
cursor = cursorStyle.Render("> ")
}
box := "[ ]"
if step.Done {
box = "[x]"
}
titleStr := step.Title
if step.Done {
titleStr = doneStyle.Render(titleStr)
} else {
titleStr = normalStyle.Render(titleStr)
}
sb.WriteString(fmt.Sprintf("%s%s %s\n", cursor, box, titleStr))
}
sb.WriteString("\n")
styledCmdBox := boxStyle.Width(boxWidth).Render(fmt.Sprintf("Command: %s", m.steps[m.cursor].Command))
sb.WriteString(styledCmdBox)
sb.WriteString("\n\n")
logDisplay := m.outputLog
if logDisplay == "" {
logDisplay = "(No output yet / ready)"
}
styledOutputBox := outputBoxStyle.Width(boxWidth).Render(fmt.Sprintf("Live Output:\n%s", logDisplay))
sb.WriteString(styledOutputBox)
sb.WriteString("\n\n")
statusText := m.message
if statusText == "" {
statusText = "Status: Ready"
}
styledStatusBox := statusBoxStyle.Width(boxWidth).Render(statusText)
sb.WriteString(styledStatusBox)
sb.WriteString("\n\n")
sb.WriteString(helpStyle.Render("[↑/↓] Navigate [Space/Enter] Toggle [r] Run [q] Quit"))
return sb.String()
}
func main() {
pkg := ""
if len(os.Args) > 1 {
pkg = os.Args[1]
}
p := tea.NewProgram(initialModel(pkg), tea.WithAltScreen())
if _, err := p.Run(); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
}