Skip to content
Myr

chore: merge pull request #1376 from desertwitch/stacked-patches

Before adoption: this commit came in with the history the project adopted, so no landing records it.

(v1-0/3) tea.go: all fixes combined (for convenience/CI)

authored by Ayman Bagabas · committed by GitHub · parents 5a360c9, e24d6b2 · Browse files · 4 files+346 added−28 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+346 added−28 removed

  • other:+346 added−28 removed

4 files+346 added−28 removed

modified:options_test.go+11 added
1package tea23import (4 "bytes"5 "context"6 "os"7 "sync/atomic"8 "testing"9)
41 unmodified lines
51 t.Errorf("expected filter to be set")52 }53 })5455 t.Run("external context", func(t *testing.T) {56 extCtx, extCancel := context.WithCancel(context.Background())57 defer extCancel()5859 p := NewProgram(nil, WithContext(extCtx))60 if p.externalCtx != extCtx || p.externalCtx == context.Background() {61 t.Errorf("expected passed in external context, got default (nil)")62 }63 })6465 t.Run("input options", func(t *testing.T) {66 exercise := func(t *testing.T, opt ProgramOption, expect inputType) {67 p := NewProgram(nil, opt)68 if p.inputType != expect {
75 unmodified lines
modified:options.go+1 added-1 removed
17 unmodified lines
18// useful if you want to cancel the execution from outside. When a Program gets19// cancelled it will exit with an error ErrProgramKilled.20func WithContext(ctx context.Context) ProgramOption {21 return func(p *Program) {22 p.ctx = ctx22 p.externalCtx = ctx23 }24}2526// WithOutput sets the output which, by default, is stdout. In most cases you
226 unmodified lines
modified:tea_test.go+246 added-2 removed
2 unmodified lines
3import (4 "bytes"5 "context"6 "errors"7 "sync"8 "sync/atomic"9 "testing"10 "time"11)1213type ctxImplodeMsg struct {14 cancel context.CancelFunc15}1617type incrementMsg struct{}1819type panicMsg struct{}2021type testModel struct {22 executed atomic.Value23 counter atomic.Value24}
2 unmodified lines
27 return nil28}2930func (m *testModel) Update(msg Msg) (Model, Cmd) {24 switch msg.(type) {31 switch msg := msg.(type) {32 case ctxImplodeMsg:33 msg.cancel()34 time.Sleep(100 * time.Millisecond)3536 case incrementMsg:37 i := m.counter.Load()38 if i == nil {39 m.counter.Store(1)
2 unmodified lines
42 }4344 case KeyMsg:45 return m, Quit4647 case panicMsg:48 panic("testing panic behavior")49 }5051 return m, nil52}
41 unmodified lines
94 t.Fatal(err)95 }96}9798func TestTeaWaitQuit(t *testing.T) {99 var buf bytes.Buffer100 var in bytes.Buffer101102 progStarted := make(chan struct{})103 waitStarted := make(chan struct{})104 errChan := make(chan error, 1)105106 m := &testModel{}107 p := NewProgram(m, WithInput(&in), WithOutput(&buf))108109 go func() {110 _, err := p.Run()111 errChan <- err112 }()113114 go func() {115 for {116 time.Sleep(time.Millisecond)117 if m.executed.Load() != nil {118 close(progStarted)119120 <-waitStarted121 time.Sleep(50 * time.Millisecond)122 p.Quit()123124 return125 }126 }127 }()128129 <-progStarted130131 var wg sync.WaitGroup132 for i := 0; i < 5; i++ {133 wg.Add(1)134 go func() {135 p.Wait()136 wg.Done()137 }()138 }139 close(waitStarted)140 wg.Wait()141142 err := <-errChan143 if err != nil {144 t.Fatalf("Expected nil, got %v", err)145 }146}147148func TestTeaWaitKill(t *testing.T) {149 var buf bytes.Buffer150 var in bytes.Buffer151152 progStarted := make(chan struct{})153 waitStarted := make(chan struct{})154 errChan := make(chan error, 1)155156 m := &testModel{}157 p := NewProgram(m, WithInput(&in), WithOutput(&buf))158159 go func() {160 _, err := p.Run()161 errChan <- err162 }()163164 go func() {165 for {166 time.Sleep(time.Millisecond)167 if m.executed.Load() != nil {168 close(progStarted)169170 <-waitStarted171 time.Sleep(50 * time.Millisecond)172 p.Kill()173174 return175 }176 }177 }()178179 <-progStarted180181 var wg sync.WaitGroup182 for i := 0; i < 5; i++ {183 wg.Add(1)184 go func() {185 p.Wait()186 wg.Done()187 }()188 }189 close(waitStarted)190 wg.Wait()191192 err := <-errChan193 if !errors.Is(err, ErrProgramKilled) {194 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)195 }196}197198func TestTeaWithFilter(t *testing.T) {199 testTeaWithFilter(t, 0)200 testTeaWithFilter(t, 1)201 testTeaWithFilter(t, 2)
49 unmodified lines
251 }252 }253 }()254255 _, err := p.Run()256141 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {257 if !errors.Is(err, ErrProgramKilled) {258 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)259 }260261 if errors.Is(err, context.Canceled) {262 // The end user should not know about the program's internal context state.263 // The program should only report external context cancellation as a context error.264 t.Fatalf("Internal context cancellation was reported as context error!")265 }266}267268func TestTeaContext(t *testing.T) {269 ctx, cancel := context.WithCancel(context.Background())
11 unmodified lines
281 }282 }283 }()284285 _, err := p.Run()286287 if !errors.Is(err, ErrProgramKilled) {288 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)289 }290291 if !errors.Is(err, context.Canceled) {292 // The end user should know that their passed in context caused the kill.293 t.Fatalf("Expected %v, got %v", context.Canceled, err)294 }295}296297func TestTeaContextImplodeDeadlock(t *testing.T) {298 ctx, cancel := context.WithCancel(context.Background())299 var buf bytes.Buffer300 var in bytes.Buffer301302 m := &testModel{}303 p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))304 go func() {305 for {306 time.Sleep(time.Millisecond)307 if m.executed.Load() != nil {308 p.Send(ctxImplodeMsg{cancel: cancel})309 return310 }311 }312 }()313314 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {315 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)316 }317}318319func TestTeaContextBatchDeadlock(t *testing.T) {320 ctx, cancel := context.WithCancel(context.Background())321 var buf bytes.Buffer322 var in bytes.Buffer323324 inc := func() Msg {325 cancel()326 return incrementMsg{}327 }328329 m := &testModel{}330 p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))331 go func() {332 for {333 time.Sleep(time.Millisecond)334 if m.executed.Load() != nil {335 batch := make(BatchMsg, 100)336 for i := range batch {337 batch[i] = inc338 }339 p.Send(batch)340 return341 }342 }343 }()344345 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {346 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)347 }348}349350func TestTeaBatchMsg(t *testing.T) {351 var buf bytes.Buffer352 var in bytes.Buffer353
94 unmodified lines
448449 m := &testModel{}450 NewProgram(m, WithInput(&in), WithOutput(&buf))451}452453func TestTeaPanic(t *testing.T) {454 var buf bytes.Buffer455 var in bytes.Buffer456457 m := &testModel{}458 p := NewProgram(m, WithInput(&in), WithOutput(&buf))459 go func() {460 for {461 time.Sleep(time.Millisecond)462 if m.executed.Load() != nil {463 p.Send(panicMsg{})464 return465 }466 }467 }()468469 _, err := p.Run()470471 if !errors.Is(err, ErrProgramPanic) {472 t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)473 }474475 if !errors.Is(err, ErrProgramKilled) {476 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)477 }478}479480func TestTeaGoroutinePanic(t *testing.T) {481 var buf bytes.Buffer482 var in bytes.Buffer483484 panicCmd := func() Msg {485 panic("testing goroutine panic behavior")486 }487488 m := &testModel{}489 p := NewProgram(m, WithInput(&in), WithOutput(&buf))490 go func() {491 for {492 time.Sleep(time.Millisecond)493 if m.executed.Load() != nil {494 batch := make(BatchMsg, 10)495 for i := range batch {496 batch[i] = panicCmd497 }498 p.Send(batch)499 return500 }501 }502 }()503504 _, err := p.Run()505506 if !errors.Is(err, ErrProgramPanic) {507 t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)508 }509510 if !errors.Is(err, ErrProgramKilled) {511 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)512 }513}
modified:tea.go+88 added-25 removed
25 unmodified lines
26 "github.com/muesli/cancelreader"27 "golang.org/x/sync/errgroup"28)2930// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.31var ErrProgramPanic = errors.New("program experienced a panic")3233// ErrProgramKilled is returned by [Program.Run] when the program gets killed.34var ErrProgramKilled = errors.New("program was killed")3536// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT
112 unmodified lines
149 startupTitle string150151 inputType inputType152153 // externalCtx is a context that was passed in via WithContext, otherwise defaulting154 // to ctx.Background() (in case it was not), the internal context is derived from it.155 externalCtx context.Context156157 // ctx is the programs's internal context for signalling internal teardown.158 // It is built and derived from the externalCtx in NewProgram().159 ctx context.Context160 cancel context.CancelFunc161162 msgs chan Msg
88 unmodified lines
251 }252253 // A context can be provided with a ProgramOption, but if none was provided254 // we'll use the default background context.246 if p.ctx == nil {247 p.ctx = context.Background()255 if p.externalCtx == nil {256 p.externalCtx = context.Background()257 }258 // Initialize context and teardown channel.250 p.ctx, p.cancel = context.WithCancel(p.ctx)259 p.ctx, p.cancel = context.WithCancel(p.externalCtx)260261 // if no output was set, set it to stdout262 if p.output == nil {263 p.output = os.Stdout
90 unmodified lines
354 // until Cmd returns.355 go func() {356 // Recover from panics.357 if !p.startupOptions.has(withoutCatchPanics) {349 defer p.recoverFromPanic()358 defer func() {359 if r := recover(); r != nil {360 p.recoverFromGoPanic(r)361 }362 }()363 }364365 msg := cmd() // this can be long.366 p.Send(msg)
105 unmodified lines
472 p.exec(msg.cmd, msg.fn)473474 case BatchMsg:475 for _, cmd := range msg {463 cmds <- cmd476 select {477 case <-p.ctx.Done():478 return model, nil479 case cmds <- cmd:480 }481 }482 continue483484 case sequenceMsg:
37 unmodified lines
522 }523524 var cmd Cmd525 model, cmd = model.Update(msg) // run update526527 select {528 case <-p.ctx.Done():529 return model, nil509 cmds <- cmd // process command (if any)530 case cmds <- cmd: // process command (if any)531 }532533 p.renderer.write(model.View()) // send view to renderer534 }535 }536}537538// Run initializes the program and runs its event loops, blocking until it gets539// terminated by either [Program.Quit], [Program.Kill], or its signal handler.540// Returns the final model.518func (p *Program) Run() (Model, error) {541func (p *Program) Run() (returnModel Model, returnErr error) {542 p.handlers = channelHandlers{}543 cmds := make(chan Cmd)521 p.errs = make(chan error)522 p.finished = make(chan struct{}, 1)544 p.errs = make(chan error, 1)545546 p.finished = make(chan struct{})547 defer func() {548 close(p.finished)549 }()550551 defer p.cancel()552553 switch p.inputType {554 case defaultInput:
39 unmodified lines
594 }595596 // Recover from panics.597 if !p.startupOptions.has(withoutCatchPanics) {571 defer p.recoverFromPanic()598 defer func() {599 if r := recover(); r != nil {600 returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)601 p.recoverFromPanic(r)602 }603 }()604 }605606 // If no renderer is set use the standard one.607 if p.renderer == nil {
68 unmodified lines
676 p.handlers.add(p.handleCommands(cmds))677678 // Run event loop, handle updates and draw.679 model, err := p.eventLoop(model, cmds)648 killed := p.ctx.Err() != nil || err != nil649 if killed && err == nil {650 err = fmt.Errorf("%w: %s", ErrProgramKilled, p.ctx.Err())680681 if err == nil && len(p.errs) > 0 {682 err = <-p.errs // Drain a leftover error in case eventLoop crashed683 }652 if err == nil {684685 killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil686 if killed {687 if err == nil && p.externalCtx.Err() != nil {688 // Return also as context error the cancellation of an external context.689 // This is the context the user knows about and should be able to act on.690 err = fmt.Errorf("%w: %w", ErrProgramKilled, p.externalCtx.Err())691 } else if err == nil && p.ctx.Err() != nil {692 // Return only that the program was killed (not the internal mechanism).693 // The user does not know or need to care about the internal program context.694 err = ErrProgramKilled695 } else {696 // Return that the program was killed and also the error that caused it.697 err = fmt.Errorf("%w: %w", ErrProgramKilled, err)698 }699 } else {700 // Graceful shutdown of the program (not killed):701 // Ensure we rendered the final state of the model.702 p.renderer.write(model.View())703 }704
46 unmodified lines
751func (p *Program) Quit() {752 p.Send(Quit())753}754707// Kill stops the program immediately and restores the former terminal state.755// Kill signals the program to stop immediately and restore the former terminal state.756// The final render that you would normally see when quitting will be skipped.757// [program.Run] returns a [ErrProgramKilled] error.758func (p *Program) Kill() {711 p.shutdown(true)759 p.cancel()760}761762// Wait waits/blocks until the underlying Program finished shutting down.763func (p *Program) Wait() {764 <-p.finished765}766767// shutdown performs operations to free up resources and restore the terminal720// to its original state.768// to its original state. It is called once at the end of the program's lifetime.769//770// This method should not be called to signal the program to be killed/shutdown.771// Doing so can lead to race conditions with the eventual call at the program's end.772// As alternatives, the [Quit] or [Kill] convenience methods should be used instead.773func (p *Program) shutdown(kill bool) {774 p.cancel()775776 // Wait for all handlers to finish.
18 unmodified lines
795 }796 }797798 _ = p.restoreTerminalState()747 if !kill {748 p.finished <- struct{}{}749 }799}800801// recoverFromPanic recovers from a panic, prints the stack trace, and restores802// the terminal to a usable state.754func (p *Program) recoverFromPanic() {755 if r := recover(); r != nil {756 p.shutdown(true)757 fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)758 debug.PrintStack()803func (p *Program) recoverFromPanic(r interface{}) {804 select {805 case p.errs <- ErrProgramPanic:806 default:807 }808 p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore.809 fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)810 debug.PrintStack()811}812813// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and814// signals for the program to be killed and terminal restored to a usable state.815func (p *Program) recoverFromGoPanic(r interface{}) {816 select {817 case p.errs <- ErrProgramPanic:818 default:819 }820 p.cancel()821 fmt.Printf("Caught goroutine panic:\n\n%s\n\nRestoring terminal...\n\n", r)822 debug.PrintStack()823}824825// ReleaseTerminal restores the original terminal state and cancels the input826// reader. You can return control to the Program with RestoreTerminal.827func (p *Program) ReleaseTerminal() error {828 atomic.StoreUint32(&p.ignoreSignals, 1)
76 unmodified lines