ui/progress: extract signal handling into own package

This commit is contained in:
Michael Eischer 2020-12-29 15:20:30 +01:00
parent 023eea6463
commit 34afc93ddc
5 changed files with 30 additions and 17 deletions

View file

@ -1,11 +1,11 @@
package progress
import (
"os"
"sync"
"time"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/ui/signals"
)
// A Func is a callback for a Counter.
@ -31,11 +31,6 @@ type Counter struct {
// New starts a new Counter.
func New(interval time.Duration, report Func) *Counter {
signals.Once.Do(func() {
signals.ch = make(chan os.Signal, 1)
setupSignals()
})
c := &Counter{
report: report,
start: time.Now(),
@ -93,12 +88,13 @@ func (c *Counter) run() {
if c.tick != nil {
tick = c.tick.C
}
signalsCh := signals.GetProgressChannel()
for {
var now time.Time
select {
case now = <-tick:
case sig := <-signals.ch:
case sig := <-signalsCh:
debug.Log("Signal received: %v\n", sig)
now = time.Now()
case <-c.stop:
@ -108,10 +104,3 @@ func (c *Counter) run() {
c.report(c.get(), now.Sub(c.start), false)
}
}
// XXX The fact that signals is a single global variable means that only one
// Counter receives each incoming signal.
var signals struct {
ch chan os.Signal
sync.Once
}

View file

@ -0,0 +1,24 @@
package signals
import (
"os"
"sync"
)
// GetProgressChannel returns a channel with which a single listener
// receives each incoming signal.
func GetProgressChannel() <-chan os.Signal {
signals.Once.Do(func() {
signals.ch = make(chan os.Signal, 1)
setupSignals()
})
return signals.ch
}
// XXX The fact that signals is a single global variable means that only one
// listener receives each incoming signal.
var signals struct {
ch chan os.Signal
sync.Once
}

View file

@ -1,6 +1,6 @@
// +build darwin dragonfly freebsd netbsd openbsd
package progress
package signals
import (
"os/signal"

View file

@ -1,6 +1,6 @@
// +build aix linux solaris
package progress
package signals
import (
"os/signal"

View file

@ -1,3 +1,3 @@
package progress
package signals
func setupSignals() {}