Skip to content

Commit

Permalink
feat: tea.WithContext ProgramOption to supply a context
Browse files Browse the repository at this point in the history
WithContext lets you specify a context in which to run the Program.
This is useful if you want to cancel the execution from outside.
When a Program gets cancelled it will exit with an error
ErrProgramKilled.
  • Loading branch information
muesli committed Oct 23, 2022
1 parent 0f1ce7f commit e15bcb7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
10 changes: 10 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tea

import (
"context"
"io"

"github.com/muesli/termenv"
Expand All @@ -14,6 +15,15 @@ import (
// p := NewProgram(model, WithInput(someInput), WithOutput(someOutput))
type ProgramOption func(*Program)

// WithContext lets you specify a context in which to run the Program. This is
// useful if you want to cancel the execution from outside. When a Program gets
// cancelled it will exit with an error ErrProgramKilled.
func WithContext(ctx context.Context) ProgramOption {
return func(p *Program) {
p.ctx = ctx
}
}

// WithOutput sets the output which, by default, is stdout. In most cases you
// won't need to use this.
func WithOutput(output io.Writer) ProgramOption {
Expand Down
8 changes: 7 additions & 1 deletion tea.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,14 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
msgs: make(chan Msg),
}

// A context can be provided with a ProgramOption, but if none was provided
// we'll use the default background context.
if p.ctx == nil {
p.ctx = context.Background()
}

// Initialize context and teardown channel.
p.ctx, p.cancel = context.WithCancel(context.Background())
p.ctx, p.cancel = context.WithCancel(p.ctx)

// Apply all options to the program.
for _, opt := range opts {
Expand Down
23 changes: 23 additions & 0 deletions tea_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tea

import (
"bytes"
"context"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -97,6 +98,28 @@ func TestTeaKill(t *testing.T) {
}
}

func TestTeaContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var buf bytes.Buffer
var in bytes.Buffer

m := &testModel{}
p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))
go func() {
for {
time.Sleep(time.Millisecond)
if m.executed.Load() != nil {
cancel()
return
}
}
}()

if _, err := p.Run(); err != ErrProgramKilled {
t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)
}
}

func TestTeaBatchMsg(t *testing.T) {
var buf bytes.Buffer
var in bytes.Buffer
Expand Down

0 comments on commit e15bcb7

Please sign in to comment.