add: --timeout option in watch command

This commit is contained in:
ShuheiKubota 2019-11-18 16:08:13 +09:00
parent abbe58ff5e
commit 01d16d4cfd

View file

@ -1,7 +1,10 @@
package main package main
import ( import (
"context"
"errors" "errors"
"fmt"
"os"
"strings" "strings"
"time" "time"
@ -13,6 +16,7 @@ type waitCmd struct {
Closed bool `help:"wait until the window is closed"` Closed bool `help:"wait until the window is closed"`
Intervals gli.Duration `cli:"intervals,i=DURATION" default:"1s"` Intervals gli.Duration `cli:"intervals,i=DURATION" default:"1s"`
Timeout gli.Duration `cli:"timeout=DURATION" default:"0s" help:"zelo value means ininite"`
} }
func (c waitCmd) Run(args []string) error { func (c waitCmd) Run(args []string) error {
@ -23,6 +27,14 @@ func (c waitCmd) Run(args []string) error {
an := ancestors() an := ancestors()
t := strings.ToLower(args[0]) t := strings.ToLower(args[0])
var ctx context.Context
if c.Timeout == 0 {
ctx = context.Background()
} else {
ctx, _ = context.WithTimeout(context.Background(), c.Timeout.Duration())
}
waitLoop:
for { for {
wins, err := listAllWindows() wins, err := listAllWindows()
if err != nil { if err != nil {
@ -40,6 +52,14 @@ func (c waitCmd) Run(args []string) error {
} }
} }
select {
case <-ctx.Done():
fmt.Fprintln(os.Stderr, "cancelled")
break waitLoop
default:
//nop
}
time.Sleep(c.Intervals.Duration()) time.Sleep(c.Intervals.Duration())
} }