internal/terminal_screen.go

33 lines · 596 bytes

4 symbols in this file
 1package internal
 2
 3import (
 4	"os"
 5	"os/signal"
 6	"sync"
 7	"syscall"
 8)
 9
10var (
11	interruptHandlerOnce sync.Once
12	interruptExitOnce    sync.Once
13)
14
15// InstallTerminalInterruptHandler restores the terminal before exiting on Ctrl+C or SIGTERM.
16func InstallTerminalInterruptHandler() {
17	interruptHandlerOnce.Do(func() {
18		interrupts := make(chan os.Signal, 1)
19		signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
20		go func() {
21			for range interrupts {
22				exitWithRestore(130)
23			}
24		}()
25	})
26}
27
28func exitWithRestore(code int) {
29	interruptExitOnce.Do(func() {
30		RestoreScreen()
31		os.Exit(code)
32	})
33}