Compare commits

...

8 Commits

Author SHA1 Message Date
edaa60c13a Fix CPU use bug
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
When I publish program level commands, they also come back around to my app causing it to
eat tons of CPU. Now I'm only publishing this when the state changes.
2024-10-24 15:54:30 -07:00
631dc539f2 Move some of the test functions around for readability
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-24 12:24:37 -07:00
5dc0d173f4 Refactor tests to handle batch message returns
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/tag Build is passing
2024-10-24 12:17:35 -07:00
c0f979a48a Add title setting
Some checks reported errors
continuous-integration/drone/push Build is failing
continuous-integration/drone/tag Build was killed
2024-10-24 10:08:15 -07:00
6d5cd3bad5 Update tortoise to include better error handling
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-23 14:01:32 -07:00
c86f080bc7 Refactor and improve test coverage 2024-10-23 14:00:45 -07:00
7729646093 Rename go-shell-runner to tortoise
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-21 17:17:51 -07:00
195004a4f4 Add example usage to Readme
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-21 16:24:09 -07:00
5 changed files with 399 additions and 145 deletions

View File

@ -87,6 +87,30 @@ Set custom colors for the progress bar:
./gomodoro --color-left="#ff0000" --color-right="#00ff00" ./gomodoro --color-left="#ff0000" --color-right="#00ff00"
``` ```
## Some Pro Tips!
- Use the `--on-focus-start` and `--on-focus-end` options to run commands that help you get into the zone and wind down after a focus period or to control your environment (e.g., turning off notifications).
### My example usage
I used Shortcuts on my mac to control macOS Focus mode. I named them "Turn On Focus" and "Turn Off Focus". This allows my focus start and end commands to control my notifications for my computer and phone (since I have them synced).
I also use [Slack Status CLI](https://git.iamthefij.com/iamthefij/slack-status-cli) to set my Slack status to a snooze mode with a tomato emoji when I'm in focus mode and turn it off after.
```sh
gomodoro \
--fullscreen \
--color-left '#ecdfb1' \
--color-right '#c6e889 ' \
--on-focus-start "shortcuts run 'Turn On Focus'" \
--on-focus-start "say 'Time to focus'" \
--on-focus-start "slack-status -snooze -duration 1h -emoji :tomato: Focus" \
--on-focus-end "shortcuts run 'Turn Off Focus'" \
--on-focus-end "say 'Break time you slacker'" \
--on-focus-end "slack-status" \
--on-interval-end "say 'Interval done! Phew!'"
```
## License ## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

4
go.mod
View File

@ -3,10 +3,11 @@ module git.iamthefij.com/iamthefij/gomodoro
go 1.21.4 go 1.21.4
require ( require (
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0
git.iamthefij.com/iamthefij/slog v1.3.0 git.iamthefij.com/iamthefij/slog v1.3.0
git.iamthefij.com/iamthefij/tortoise v1.0.1
github.com/charmbracelet/bubbles v0.20.0 github.com/charmbracelet/bubbles v0.20.0
github.com/charmbracelet/bubbletea v1.1.1 github.com/charmbracelet/bubbletea v1.1.1
github.com/charmbracelet/huh v0.6.0
github.com/charmbracelet/lipgloss v0.13.0 github.com/charmbracelet/lipgloss v0.13.0
github.com/urfave/cli/v2 v2.27.5 github.com/urfave/cli/v2 v2.27.5
) )
@ -16,7 +17,6 @@ require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/catppuccin/go v0.2.0 // indirect github.com/catppuccin/go v0.2.0 // indirect
github.com/charmbracelet/harmonica v0.2.0 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect
github.com/charmbracelet/huh v0.6.0 // indirect
github.com/charmbracelet/x/ansi v0.2.3 // indirect github.com/charmbracelet/x/ansi v0.2.3 // indirect
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.0 // indirect github.com/charmbracelet/x/term v0.2.0 // indirect

12
go.sum
View File

@ -1,7 +1,9 @@
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0 h1:dqiBCMwyD+sTYqDXu5OshDy4NrO3WfVa2jKSQZKFqO4=
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0/go.mod h1:Wcke8kBfFj9QDlnRwY/aGSvTRirBc3hC7fKhCsDPbQg=
git.iamthefij.com/iamthefij/slog v1.3.0 h1:4Hu5PQvDrW5e3FrTS3q2iIXW0iPvhNY/9qJsqDR3K3I= git.iamthefij.com/iamthefij/slog v1.3.0 h1:4Hu5PQvDrW5e3FrTS3q2iIXW0iPvhNY/9qJsqDR3K3I=
git.iamthefij.com/iamthefij/slog v1.3.0/go.mod h1:1RUj4hcCompZkAxXCRfUX786tb3cM/Zpkn97dGfUfbg= git.iamthefij.com/iamthefij/slog v1.3.0/go.mod h1:1RUj4hcCompZkAxXCRfUX786tb3cM/Zpkn97dGfUfbg=
git.iamthefij.com/iamthefij/tortoise v1.0.1 h1:dtUJuBhMZb9PlBR7bdcxLHLZDxhP2IPtT+YCR7tXdDk=
git.iamthefij.com/iamthefij/tortoise v1.0.1/go.mod h1:Y8Sn7jZaMbJw1AWoklp784o3pscfNiy1DkRy60Ne1KQ=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
@ -44,8 +46,6 @@ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg= github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg=
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ= github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@ -61,11 +61,7 @@ golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=

238
main.go
View File

@ -9,15 +9,14 @@ import (
"strings" "strings"
"time" "time"
shellrunner "git.iamthefij.com/iamthefij/go-shell-runner"
"git.iamthefij.com/iamthefij/slog" "git.iamthefij.com/iamthefij/slog"
"git.iamthefij.com/iamthefij/tortoise"
"github.com/charmbracelet/bubbles/progress" "github.com/charmbracelet/bubbles/progress"
"github.com/charmbracelet/bubbles/textinput" "github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss" "github.com/charmbracelet/lipgloss"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/charmbracelet/huh"
) )
type screen int type screen int
@ -34,12 +33,19 @@ const (
) )
type model struct { type model struct {
// View state
form *huh.Form form *huh.Form
progressBar progress.Model progressBar progress.Model
state string state string
intervalNum int intervalNum int
remaining time.Duration
currentScreen screen currentScreen screen
isFocus bool
fullscreen bool
width int
height int
// Timer state
remaining time.Duration
intervals int intervals int
breakTime time.Duration breakTime time.Duration
focusTime time.Duration focusTime time.Duration
@ -47,15 +53,28 @@ type model struct {
onFocusStart []string onFocusStart []string
onFocusEnd []string onFocusEnd []string
onIntervalEnd []string onIntervalEnd []string
isFocus bool
fullscreen bool
width int
height int
err error err error
shellrunner *shellrunner.ShellRunner shellrunner *tortoise.ShellRunner
} }
func initialModel(fullscreen bool, colorLeft string, colorRight string, defaultFocusTime, defaultBreakTime, defaultIntervals *string) model { // Message that signals to start the timer
type startTimerMsg struct{}
// Command that triggers start message
func startTimer() tea.Msg {
return startTimerMsg{}
}
// Message that signals to get values from the form
type formSubmitMsg struct{}
// Command that triggers form submit message
func formSubmit() tea.Msg {
return formSubmitMsg{}
}
// Create input form with default values if provided
func createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals *string) *huh.Form {
// Ceate validation functions for input // Ceate validation functions for input
validateDuration := func(text string) error { validateDuration := func(text string) error {
_, err := parseDuration(text) _, err := parseDuration(text)
@ -70,10 +89,6 @@ func initialModel(fullscreen bool, colorLeft string, colorRight string, defaultF
return nil return nil
} }
if colorLeft == "" || colorRight == "" {
slog.Panicf("Color flags can't be empty")
}
// Create form fields // Create form fields
focusTime := huh.NewInput(). focusTime := huh.NewInput().
Key(FORM_FOCUS). Key(FORM_FOCUS).
@ -108,8 +123,19 @@ func initialModel(fullscreen bool, colorLeft string, colorRight string, defaultF
intervals = intervals.Value(defaultIntervals) intervals = intervals.Value(defaultIntervals)
} }
f := huh.NewForm(huh.NewGroup(focusTime, breakTime, intervals)).WithShowErrors(true)
f.SubmitCmd = formSubmit
return f
}
func newModelBasic(fullscreen bool, colorLeft, colorRight string) model {
if colorLeft == "" || colorRight == "" {
slog.Panicf("Color flags can't be empty")
}
return model{ return model{
form: huh.NewForm(huh.NewGroup(focusTime, breakTime, intervals)).WithShowErrors(true), form: nil,
progressBar: progress.New(progress.WithScaledGradient(colorLeft, colorRight)), progressBar: progress.New(progress.WithScaledGradient(colorLeft, colorRight)),
state: "stopped", state: "stopped",
intervalNum: 1, intervalNum: 1,
@ -117,15 +143,55 @@ func initialModel(fullscreen bool, colorLeft string, colorRight string, defaultF
currentScreen: INPUT_SCREEN, // Start on input screen currentScreen: INPUT_SCREEN, // Start on input screen
isFocus: true, isFocus: true,
fullscreen: fullscreen, fullscreen: fullscreen,
shellrunner: shellrunner.NewShellRunner(), shellrunner: tortoise.NewShellRunner(),
} }
} }
func newModel(fullscreen bool, colorLeft, colorRight string, focusTime, breakTime time.Duration, intervals int, onFocusStart, onFocusEnd, onIntervalEnd []string) model {
m := newModelBasic(fullscreen, colorLeft, colorRight)
if focusTime != 0 && breakTime != 0 && intervals != 0 {
// All values provided, initialize timer
m.focusTime = focusTime
m.breakTime = breakTime
m.intervals = intervals
m.currentScreen = TIMER_SCREEN
} else {
// Prompt for input
var defaultFocusTime, defaultBreakTime, defaultIntervals *string
if value := focusTime.String(); value != "0s" {
defaultFocusTime = &value
}
if value := breakTime.String(); value != "0s" {
defaultBreakTime = &value
}
if intervals != 0 {
intervalsString := strconv.Itoa(intervals)
defaultIntervals = &intervalsString
}
m.form = createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals)
m.currentScreen = INPUT_SCREEN
}
// Collect command flags
m.onFocusStart = onFocusStart
m.onFocusEnd = onFocusEnd
m.onIntervalEnd = onIntervalEnd
return m
}
func (m model) Init() tea.Cmd { func (m model) Init() tea.Cmd {
// Handle Ctrl+C for graceful exit // Handle Ctrl+C for graceful exit
c := make(chan os.Signal, 1) c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt) signal.Notify(c, os.Interrupt)
cmds := []tea.Cmd{tea.WindowSize(), textinput.Blink}
go func() { go func() {
<-c <-c
@ -135,10 +201,20 @@ func (m model) Init() tea.Cmd {
os.Exit(0) os.Exit(0)
}() }()
m.form.Init() if m.form != nil {
m.shellrunner.Start() // Start input form if it exists
cmds = append(cmds, m.form.Init())
} else {
// Start timer if no form
cmds = append(cmds, startTimer)
}
return tea.Batch(tea.WindowSize(), textinput.Blink) // Start shell runner if there are any commands to run
if len(m.onFocusStart) > 0 || len(m.onFocusEnd) > 0 || len(m.onIntervalEnd) > 0 {
m.shellrunner.Start()
}
return tea.Batch(cmds...)
} }
// totalTime returns the total time for the current period (focus or break) // totalTime returns the total time for the current period (focus or break)
@ -154,52 +230,13 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds := []tea.Cmd{} cmds := []tea.Cmd{}
// Handle input screen // Handle input screen
if m.currentScreen == INPUT_SCREEN { if m.currentScreen == INPUT_SCREEN && m.form != nil {
form, cmd := m.form.Update(msg) form, cmd := m.form.Update(msg)
if f, ok := form.(*huh.Form); ok { if f, ok := form.(*huh.Form); ok {
m.form = f m.form = f
} }
cmds = append(cmds, cmd) cmds = append(cmds, cmd)
if m.form.State == huh.StateCompleted {
// Kick off the timer
focusTime, err := parseDuration(m.form.GetString(FORM_FOCUS))
if err != nil {
m.err = fmt.Errorf("error parsing focus time duration: %w", err)
slog.Fatalf("Error parsing focus time: %v", err)
return m, tea.Quit
}
breakTime, err := parseDuration(m.form.GetString(FORM_BREAK))
if err != nil {
m.err = fmt.Errorf("error parsing break time duration: %w", err)
slog.Fatalf("Error parsing break time: %v", err)
return m, tea.Quit
}
m.intervals, err = strconv.Atoi(m.form.GetString(FORM_INTERVALS))
if err != nil {
m.err = fmt.Errorf("error parsing interval: %w", err)
slog.Fatalf("Error parsing interval: %v", err)
return m, tea.Quit
}
m.focusTime = focusTime
m.breakTime = breakTime
m.remaining = focusTime
m.state = "Focus"
m.currentScreen = TIMER_SCREEN
m.startTime = time.Now()
// Run onFocusStart commands
m.startCommands(m.onFocusStart)
return m, tick()
}
} }
// Handle any uncaptured input screen updates // Handle any uncaptured input screen updates
@ -217,9 +254,52 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
} }
} }
case formSubmitMsg:
// Get values from the form and send start timer command
var err error
m.focusTime, err = parseDuration(m.form.GetString(FORM_FOCUS))
if err != nil {
m.err = fmt.Errorf("error parsing focus time duration: %w", err)
slog.Fatalf("Error parsing focus time: %v", err)
return m, tea.Quit
}
m.breakTime, err = parseDuration(m.form.GetString(FORM_BREAK))
if err != nil {
m.err = fmt.Errorf("error parsing break time duration: %w", err)
slog.Fatalf("Error parsing break time: %v", err)
return m, tea.Quit
}
m.intervals, err = strconv.Atoi(m.form.GetString(FORM_INTERVALS))
if err != nil {
m.err = fmt.Errorf("error parsing interval: %w", err)
slog.Fatalf("Error parsing interval: %v", err)
return m, tea.Quit
}
return m, startTimer
case startTimerMsg:
// Start the timer
m.currentScreen = TIMER_SCREEN
// TODO: Could maybe set startTime to 0 and then send a tick command to start the timer
// since much of this is duplicate of below
m.startTime = time.Now()
m.remaining = m.focusTime
m.state = "Focus"
m.startCommands(m.onFocusStart)
cmds = append(cmds, tea.SetWindowTitle(fmt.Sprintf("Gomodoro - %s", m.state)), tick())
case timeMsg: case timeMsg:
// Handle timer update for each second // Handle timer update for each second
m.remaining = m.totalTime() - time.Since(m.startTime) m.remaining = m.totalTime() - time.Since(m.startTime)
// Check if we've reached a new period
if m.remaining < 0 { if m.remaining < 0 {
if m.isFocus { if m.isFocus {
// Focus period ends, switch to break // Focus period ends, switch to break
@ -247,16 +327,17 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.startCommands(m.onFocusStart) m.startCommands(m.onFocusStart)
} }
return m, tick() cmds = append(cmds, tea.SetWindowTitle(fmt.Sprintf("Gomodoro - %s", m.state)))
} }
return m, tick() cmds = append(cmds, tick())
case tea.WindowSizeMsg: case tea.WindowSizeMsg:
m.width = msg.Width m.width = msg.Width
m.height = msg.Height m.height = msg.Height
} }
// Get errors from shellrunner
for { for {
result := m.shellrunner.GetResults() result := m.shellrunner.GetResults()
if result == nil { if result == nil {
@ -304,6 +385,10 @@ func (m model) View() string {
// View for input screen // View for input screen
func (m model) inputScreenView() string { func (m model) inputScreenView() string {
if m.form == nil {
return "Loading..."
}
var builder strings.Builder var builder strings.Builder
builder.WriteString("Enter your Pomodoro settings:\n\n") builder.WriteString("Enter your Pomodoro settings:\n\n")
@ -415,34 +500,17 @@ func main() {
return nil return nil
} }
// Set focus, break, and interval values if provided m := newModel(
var defaultFocusTime, defaultBreakTime, defaultIntervals *string
if focusTime := c.Duration("focus").String(); focusTime != "0s" {
defaultFocusTime = &focusTime
}
if breakTime := c.Duration("break").String(); breakTime != "0s" {
defaultBreakTime = &breakTime
}
if intervals := c.Int("intervals"); intervals != 0 {
intervalsString := strconv.Itoa(intervals)
defaultIntervals = &intervalsString
}
m := initialModel(
c.Bool("fullscreen"), c.Bool("fullscreen"),
c.String("color-left"), c.String("color-left"),
c.String("color-right"), c.String("color-right"),
defaultFocusTime, c.Duration("focus"),
defaultBreakTime, c.Duration("break"),
defaultIntervals, c.Int("intervals"),
c.StringSlice("on-focus-start"),
c.StringSlice("on-focus-end"),
c.StringSlice("on-interval-end"),
) )
// Collect command flags
m.onFocusStart = c.StringSlice("on-focus-start")
m.onFocusEnd = c.StringSlice("on-focus-end")
m.onIntervalEnd = c.StringSlice("on-interval-end")
// Start tea program // Start tea program
options := []tea.ProgramOption{} options := []tea.ProgramOption{}

View File

@ -1,12 +1,20 @@
package main package main
import ( import (
"fmt"
"strings"
"testing" "testing"
"time" "time"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
) )
func notThis[T comparable](f compareFunc[T]) compareFunc[T] {
return func(a, b T) bool {
return !f(a, b)
}
}
type compareFunc[T comparable] func(T, T) bool type compareFunc[T comparable] func(T, T) bool
func assertFunc[T comparable](t *testing.T, compare compareFunc[T], actual, expected T, msg string) { func assertFunc[T comparable](t *testing.T, compare compareFunc[T], actual, expected T, msg string) {
@ -35,6 +43,171 @@ func assertNotEqual(t *testing.T, actual, expected interface{}, msg string) {
} }
} }
// keyMsgs converts a series of strings or KeyTypes into a slice of KeyMsgs
func keyMsgs(keys ...interface{}) []tea.KeyMsg {
keyMessages := []tea.KeyMsg{}
for _, key := range keys {
switch keyType := key.(type) {
case tea.KeyType:
keyMessages = append(keyMessages, tea.KeyMsg{Type: keyType})
case string:
for _, r := range key.(string) {
keyMessages = append(keyMessages, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
}
default:
panic(fmt.Sprintf("Unknown key type: %v", key))
}
}
return keyMessages
}
func sendKeys[T tea.Model](m T, keys ...interface{}) (T, []tea.Cmd) {
var updatedModel tea.Model
var cmd tea.Cmd
var cmds []tea.Cmd
for _, key := range keyMsgs(keys...) {
updatedModel, cmd = m.Update(key)
m = updatedModel.(T)
if cmd != nil {
m, cmds, _ = batchCmdUpdate(m, cmd)
}
}
return m, cmds
}
func batchCmdUpdate[T tea.Model](m T, cmd tea.Cmd) (T, []tea.Cmd, error) {
var updatedModel tea.Model
var resultCmd tea.Cmd
var cmds []tea.Cmd
resultMsg := cmd()
batchMsg, ok := resultMsg.(tea.BatchMsg)
if !ok {
updatedModel, resultCmd = m.Update(resultMsg)
m = updatedModel.(T)
cmds = append(cmds, resultCmd)
return m, cmds, fmt.Errorf("Expected a batch message, got %v", resultMsg)
}
// Apply batch messages
for _, cmd := range batchMsg {
updatedModel, resultCmd = m.Update(cmd())
m = updatedModel.(T)
cmds = append(cmds, resultCmd)
}
return m, cmds, nil
}
type mockModel struct {
messages []tea.Msg
}
func (m mockModel) Init() tea.Cmd {
return nil
}
func (m mockModel) View() string {
s := ""
for _, msg := range m.messages {
if keyMsg, ok := msg.(tea.KeyMsg); ok {
if keyMsg.Type == tea.KeyRunes {
s += string(keyMsg.Runes)
}
}
}
return s
}
func (m mockModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
m.messages = append(m.messages, msg)
if msg, ok := msg.(tea.KeyMsg); ok {
if msg.Type == tea.KeyEnter {
cmds = append(cmds, func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'\n'}} })
}
}
return m, tea.Batch(cmds...)
}
func TestBatchCmdUpdate(t *testing.T) {
m := mockModel{}
cmds := []tea.Cmd{
func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'a'}} },
func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'b'}} },
}
m, _, err := batchCmdUpdate(m, tea.Batch(cmds...))
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if len(m.messages) != 2 {
t.Fatalf("Expected 2 messages, got %v", len(m.messages))
}
if m.View() != "ab" {
t.Fatalf("Expected 'ab', got %s, %+v", m.View(), m)
}
m, _, err = batchCmdUpdate(m, func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'c'}} })
if err == nil {
t.Fatalf("Expected error, got nil")
}
if len(m.messages) != 3 {
t.Fatalf("Expected 3 messages, got %v", len(m.messages))
}
if m.View() != "abc" {
t.Fatalf("Expected 'abc', got %v", m.View())
}
}
func TestSendKeys(t *testing.T) {
m := mockModel{}
m, _ = sendKeys(m, "ab")
if len(m.messages) != 2 {
t.Fatalf("Expected 2 messages, got %v", len(m.messages))
}
if m.View() != "ab" {
t.Fatalf("Expected 'ab', got %s", m.View())
}
m, _ = sendKeys(m, "c", tea.KeyEnter)
// We expect 5 because enter key should create a new message for the newline
if len(m.messages) != 5 {
t.Fatalf("Expected 5 messages, got %v", len(m.messages))
}
if m.View() != "abc\n" {
t.Fatalf("Expected 'abc\n', got %s", m.View())
}
}
// TestParseDuration tests the parseDuration function // TestParseDuration tests the parseDuration function
func TestParseDuration(t *testing.T) { func TestParseDuration(t *testing.T) {
tests := []struct { tests := []struct {
@ -60,83 +233,76 @@ func TestParseDuration(t *testing.T) {
// TestRunCommands tests the runCommands function // TestRunCommands tests the runCommands function
func TestRunCommands(t *testing.T) { func TestRunCommands(t *testing.T) {
m := initialModel(false, "#ffdd57", "#57ddff", nil, nil, nil) m := newModelBasic(false, "#ffdd57", "#57ddff")
m.onFocusStart = []string{"echo Focus Start"}
m.Init() m.Init()
m.startCommands(m.onFocusStart)
m.startCommands([]string{"echo Hello, World!"})
m.shellrunner.Stop()
}
func sendKeys(m model, keys ...tea.KeyType) (model, tea.Cmd) {
var updatedModel tea.Model
var cmd tea.Cmd
for _, key := range keys {
updatedModel, cmd = m.Update(tea.KeyMsg{Type: key})
m = updatedModel.(model)
m.form.UpdateFieldPositions()
}
return m, cmd
} }
// TestInputView tests the Update method of the model for the input view // TestInputView tests the Update method of the model for the input view
func TestInputView(t *testing.T) { func TestInputView(t *testing.T) {
focusInput := "10m" m := newModel(false, "#ffdd57", "#57ddff", 0, 0, 0, []string{}, []string{}, []string{})
breakInput := "5m"
intervalInput := "1"
m := initialModel(false, "#ffdd57", "#57ddff", &focusInput, &breakInput, &intervalInput) var err error
m.View()
assertEqual(t, m.currentScreen, INPUT_SCREEN, "Expected currentScreen to be inputScreen") m, _, err = batchCmdUpdate(m, m.Init())
if err != nil {
t.Fatalf("Expected batch command after init: %v", err)
}
var resultCmd tea.Cmd // Verify we're on the input screen
m, resultCmd = sendKeys(m, tea.KeyTab, tea.KeyTab, tea.KeyTab, tea.KeyEnter) assertEqual(t, m.currentScreen, INPUT_SCREEN, "Expected currentScreen to be INPUT_SCREEN")
assertNotEqual(t, resultCmd, nil, "Expected resultCmd to be not nil") assertFunc(t, strings.Contains, m.View(), "Break time", "Expected view to contain 'Break time'")
/* // Fill the form
* assertEqual(t, m.form.State, huh.StateCompleted, fmt.Sprintf("Expected form state to be completed: %s", m.form.View())) m, _ = sendKeys(m, "10m", tea.KeyEnter, "10m", tea.KeyEnter, "2", tea.KeyEnter)
* assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be timerScreen")
* assertEqual(t, m.remaining.Round(time.Second), 10*time.Minute, "Expected remaining to be 10 minutes")
*/
assertEqual(t, m.err, nil, "Expected no error") // Pass on submit command, doesn't happen because we have multiple layers of batching at the end
m, _, _ = batchCmdUpdate(m, formSubmit)
assertEqual(t, m.focusTime, 10*time.Minute, "Expected focus time to be 10 minutes")
assertEqual(t, m.breakTime, 10*time.Minute, "Expected break time to be 10 minutes")
assertEqual(t, m.intervals, 2, "Expected rounds to be 2")
// Pass on start command, doesn't happen because we have multiple layers of batching at the end
m, _, _ = batchCmdUpdate(m, startTimer)
assertFunc(t, notThis(strings.Contains), m.View(), "Break time", "Expected view to NOT contain 'Break time'")
assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be TIMER_SCREEN")
} }
func TestTimerView(t *testing.T) { func TestTimerView(t *testing.T) {
m := initialModel(false, "#ffdd57", "#57ddff", nil, nil, nil) m := newModel(false, "#ffdd57", "#57ddff", 10*time.Minute, 10*time.Minute, 2, []string{}, []string{}, []string{})
m.View()
m.focusTime = 10 * time.Minute // Init model with timer values
m.breakTime = 10 * time.Minute m, _, err := batchCmdUpdate(m, m.Init())
m.intervals = 2 if err != nil {
m.state = "Focus" t.Fatalf("Expected batch command after init: %v", err)
m.currentScreen = TIMER_SCREEN }
m.startTime = time.Now()
// Start timer (batch result from above doesn't apply here)
m, _, _ = batchCmdUpdate(m, startTimer)
// Test timer view // Test timer view
m.View() assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be timerScreen")
assertFunc(t, strings.Contains, m.View(), "Focus", "Expected view to contain 'Focus'")
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
oneSec := timeMsg(time.Now().Add(1 * time.Second)) oneSecCmd := func() tea.Msg { return timeMsg(time.Now().Add(1 * time.Second)) }
updatedModel, _ := m.Update(oneSec) m, _, _ = batchCmdUpdate(m, oneSecCmd)
m = updatedModel.(model)
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'") assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
// Test switch to break time // Test switch to break time
m.startTime = m.startTime.Add(-10 * time.Minute) m.startTime = m.startTime.Add(-10 * time.Minute)
updatedModel, _ = m.Update(oneSec) m, _, _ = batchCmdUpdate(m, oneSecCmd)
m = updatedModel.(model)
assertEqual(t, m.state, "Break", "Expected state to be 'Break'") assertEqual(t, m.state, "Break", "Expected state to be 'Break'")
// Switch back to focus time // Switch back to focus time
m.startTime = m.startTime.Add(-10 * time.Minute) m.startTime = m.startTime.Add(-10 * time.Minute)
updatedModel, _ = m.Update(oneSec) m, _, _ = batchCmdUpdate(m, oneSecCmd)
m = updatedModel.(model)
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'") assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
t.Logf("Incorrect state %+v", m) t.Logf("Incorrect state %+v", m)