-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #16 from uselagoon/spinner
feat: show a spinner during ssh connection
- Loading branch information
Showing
3 changed files
with
88 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package k8s | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"sync" | ||
"time" | ||
) | ||
|
||
const ( | ||
framerate = 50 * time.Millisecond | ||
) | ||
|
||
var ( | ||
charset = []string{`|`, `/`, `-`, `\`} | ||
) | ||
|
||
// spinAfter will wait for the given time period and if the given context is | ||
// not cancelled will start animating a spinner on w until the given context | ||
// is cancelled. | ||
// | ||
// If the given context is cancelled before the wait duration, nothing is | ||
// written to w. | ||
// | ||
// The returned *sync.WaitGroup should be waited on to ensure the spinner | ||
// finishes cleaning up the animation. | ||
func spinAfter(ctx context.Context, w io.Writer, wait time.Duration) *sync.WaitGroup { | ||
var wg sync.WaitGroup | ||
wt := time.NewTimer(wait) | ||
wg.Add(1) | ||
go func() { | ||
defer wg.Done() | ||
select { | ||
case <-ctx.Done(): | ||
case <-wt.C: | ||
spin(ctx, w) | ||
} | ||
}() | ||
return &wg | ||
} | ||
|
||
// spin animates a spinner on w until ctx is cancelled. | ||
func spin(ctx context.Context, w io.Writer) { | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences | ||
fmt.Fprint(w, "\033[2K") | ||
return | ||
default: | ||
for _, char := range charset { | ||
fmt.Fprintf(w, "%s getting you a shell\r", char) | ||
time.Sleep(framerate) | ||
} | ||
} | ||
} | ||
} |