Skip to content

Instantly share code, notes, and snippets.

@ironmike-au
Created June 7, 2023 01:01
Show Gist options
  • Save ironmike-au/621a89603f64590ac2ef748c1dd1b20e to your computer and use it in GitHub Desktop.
Save ironmike-au/621a89603f64590ac2ef748c1dd1b20e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"os"
"time"
tea "github.com/charmbracelet/bubbletea"
)
type command struct {
ID string
Message string
Result string
}
type model struct {
Commands map[string]command
status string
err error
}
type TickMsg time.Time
func doTick() tea.Cmd {
return tea.Tick(time.Second, func(t time.Time) tea.Msg {
return TickMsg(t)
})
}
func (m model) Init() tea.Cmd {
return tea.Batch(
task0(m.Commands["task0"]),
task1(m.Commands["task1"]),
doTick(),
)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case command:
m.Commands[msg.ID] = msg
return m, nil
case tea.KeyMsg:
if msg.Type == tea.KeyCtrlC {
return m, tea.Quit
}
case TickMsg:
m.status = fmt.Sprint(rand.Intn(100))
}
quit := false
for _, v := range m.Commands {
if v.Result == "Finished" {
quit = true
} else {
quit = false
}
}
if quit {
return m, tea.Quit
}
return m, nil
}
func (m model) View() string {
if m.err != nil {
return fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err)
}
s := fmt.Sprintf("%s - %s \n", m.Commands["task0"].Message, m.Commands["task0"].Result)
s += fmt.Sprintf("%s - %s \n", m.Commands["task1"].Message, m.Commands["task1"].Result)
return "\n" + s + "\n\n"
}
func main() {
m := model{
Commands: map[string]command{
"task0": {
ID: "task0",
Message: "task0",
Result: "Running",
},
"task1": {
ID: "task1",
Message: "task1",
Result: "Running",
},
},
}
if _, err := tea.NewProgram(m).Run(); err != nil {
fmt.Printf("Uh oh, there was an error: %v\n", err)
os.Exit(1)
}
}
func task0(cmd command) tea.Cmd {
rand.Seed(time.Now().UnixNano())
minDuration := 2
maxDuration := 5
duration := rand.Intn(maxDuration-minDuration+1) + minDuration
time.Sleep(time.Duration(duration) * time.Second)
cmd.Result = "Finished"
return func() tea.Msg {
return cmd
}
}
func task1(cmd command) tea.Cmd {
rand.Seed(time.Now().UnixNano())
minDuration := 2
maxDuration := 5
duration := rand.Intn(maxDuration-minDuration+1) + minDuration
time.Sleep(time.Duration(duration) * time.Second)
cmd.Result = "Finished"
return func() tea.Msg {
return cmd
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment