Skip to content

Commit

Permalink
better handle force ctrlc
Browse files Browse the repository at this point in the history
  • Loading branch information
raphaelvigee committed Apr 20, 2024
1 parent 4c57149 commit e238179
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
10 changes: 7 additions & 3 deletions utils/xcontext/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/hephbuild/heph/log/log"
"github.com/hephbuild/heph/utils/ads"
"github.com/hephbuild/heph/utils/xsync"
"github.com/hephbuild/heph/utils/xtea"
"os"
"os/signal"
"sync"
Expand Down Expand Up @@ -138,6 +139,8 @@ func Cancel(ctx context.Context) {
cancel()
}

const stuckTimeout = 5 * time.Second

func BootstrapSoftCancel() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())

Expand Down Expand Up @@ -168,12 +171,12 @@ func BootstrapSoftCancel() (context.Context, context.CancelFunc) {
// Wait for soft cancel to all be unregistered, should be fast, unless something is stuck
case <-sc.wait():
// Wait for graceful exit
<-time.After(2 * time.Second)
case <-time.After(2 * time.Second):
<-time.After(stuckTimeout)
case <-time.After(stuckTimeout):
// All soft cancel did not unregister, something is stuck...
}
} else {
<-time.After(2 * time.Second)
<-time.After(stuckTimeout)
}

log.Error("Something seems to be stuck, ctrl+c one more time to forcefully exit")
Expand All @@ -182,6 +185,7 @@ func BootstrapSoftCancel() (context.Context, context.CancelFunc) {
if sig, ok := sig.(syscall.Signal); ok {
sigN = int(sig)
}
xtea.ResetTerminal()
os.Exit(128 + sigN)
}()

Expand Down
2 changes: 2 additions & 0 deletions utils/xtea/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ func RunModel(model tea.Model, opts ...tea.ProgramOption) error {

func Run(p *tea.Program) error {
defer func() {
SetResetTerminal(nil)
log.SetDiversion(nil)
}()

SetResetTerminal(p)
_, err := p.Run()
return err
}
Expand Down
20 changes: 20 additions & 0 deletions utils/xtea/singletui.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package xtea

import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"runtime/debug"
"sync"
)
Expand Down Expand Up @@ -33,3 +34,22 @@ func SingleflightDone() {
}
tuim.Unlock()
}

var resetTermFunc func()

func SetResetTerminal(p *tea.Program) {
if p == nil {
return
}

resetTermFunc = func() {
_ = p.ReleaseTerminal()
_ = p.RestoreTerminal()
}
}

func ResetTerminal() {
if f := resetTermFunc; f != nil {
f()
}
}

0 comments on commit e238179

Please sign in to comment.