git-bug/util/interrupt/cleaner.go

49 lines
1.1 KiB
Go
Raw Normal View History

package interrupt
2018-10-24 00:00:55 +03:00
import (
"fmt"
"os"
"os/signal"
"syscall"
)
2018-10-27 12:51:50 +03:00
// Cleaner type refers to a function with no inputs that returns an error
type Cleaner func() error
2018-10-24 00:00:55 +03:00
2018-10-25 00:27:43 +03:00
var cleaners []Cleaner
2018-10-25 00:55:02 +03:00
var active = false
2018-10-24 00:00:55 +03:00
2018-10-27 12:51:50 +03:00
// RegisterCleaner is responsible for registering a cleaner function. When a function is registered, the Signal watcher is started in a goroutine.
func RegisterCleaner(f ...Cleaner) {
for _, fn := range f {
cleaners = append([]Cleaner{fn}, cleaners...)
if !active {
active = true
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-ch
// Prevent un-terminated ^C character in terminal
fmt.Println()
2018-10-27 12:51:50 +03:00
errl := clean()
for _, err := range errl {
fmt.Println(err)
}
os.Exit(1)
}()
}
2018-10-24 00:00:55 +03:00
}
}
2018-10-27 12:51:50 +03:00
// clean invokes all registered cleanup functions, and returns a list of errors, if they exist.
func clean() (errorlist []error) {
2018-10-24 00:00:55 +03:00
for _, f := range cleaners {
err := f()
if err != nil {
errorlist = append(errorlist, err)
}
2018-10-24 00:00:55 +03:00
}
2018-10-25 00:27:43 +03:00
cleaners = []Cleaner{}
return
2018-10-24 00:00:55 +03:00
}