Skip to content

Commit b73beba

Browse files
committed
add a basic spinner to the project
1 parent 8ef5050 commit b73beba

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

internal/cmd/root.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ package cmd
22

33
import (
44
"fmt"
5+
"os"
6+
"os/signal"
7+
"time"
58

69
"github.com/github/gh-combine/internal/version"
710
)
@@ -13,5 +16,29 @@ func Run() error {
1316
return fmt.Errorf("oh no")
1417
}
1518

19+
spinner := NewSpinner("")
20+
// Ensure the spinner is stopped before exiting the function.
21+
// If reference to `spinner` is changed, the reference to the new
22+
// spinner will be used to stop the spinner, so this works as
23+
// expected even in that case.
24+
defer func() { spinner.Stop() }()
25+
26+
// Set up a channel to catch `Ctrl+C` (SIGINT) signals
27+
signalChan := make(chan os.Signal, 1)
28+
signal.Notify(signalChan, os.Interrupt)
29+
defer signal.Stop(signalChan)
30+
31+
// Start a goroutine to handle the signal
32+
go func() {
33+
<-signalChan
34+
Logger.Debug("Received SIGINT (Ctrl+C), stopping spinner and exiting...")
35+
spinner.Stop()
36+
os.Exit(1) // Exit with a non-zero code to indicate interruption
37+
}()
38+
39+
// for initial testing, just sleep for 1 second and stop the spinner
40+
time.Sleep(1 * time.Second)
41+
spinner.Stop()
42+
1643
return nil
1744
}

internal/cmd/spinner.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package cmd
2+
3+
import (
4+
"time"
5+
6+
"github.com/briandowns/spinner"
7+
)
8+
9+
type Spinner struct {
10+
spinner *spinner.Spinner
11+
}
12+
13+
func NewSpinner(message string) *Spinner {
14+
dotStyle := spinner.CharSets[11]
15+
color := spinner.WithColor("fgCyan")
16+
duration := 60 * time.Millisecond
17+
spinner := spinner.New(dotStyle, duration, color)
18+
if message != "" {
19+
spinner.Suffix = " " + message
20+
}
21+
spinner.Start()
22+
23+
return &Spinner{
24+
spinner: spinner,
25+
}
26+
}
27+
28+
func (s *Spinner) Stop() {
29+
defer func() {
30+
if r := recover(); r != nil {
31+
s.spinner.Stop()
32+
panic(r) // Re-raise the panic after stopping the spinner
33+
}
34+
}()
35+
s.spinner.Stop()
36+
}
37+
38+
func (s *Spinner) Suffix(message string) {
39+
s.spinner.Suffix = " " + message
40+
}

0 commit comments

Comments
 (0)