vvin/cmd_wait.go

68 lines
1.1 KiB
Go
Raw Normal View History

2019-11-18 00:48:49 -05:00
package main
import (
2019-11-18 02:08:13 -05:00
"context"
2019-11-18 00:48:49 -05:00
"errors"
2019-11-18 02:08:13 -05:00
"fmt"
"os"
2019-11-18 00:48:49 -05:00
"strings"
"time"
"github.com/shu-go/gli"
)
type waitCmd struct {
2019-11-18 00:55:17 -05:00
_ struct{} `help:"[--close] {Title}"`
2019-11-18 00:48:49 -05:00
2019-11-18 00:55:17 -05:00
Closed bool `help:"wait until the window is closed"`
2019-11-18 00:48:49 -05:00
Intervals gli.Duration `cli:"intervals,i=DURATION" default:"1s"`
2019-11-18 02:08:13 -05:00
Timeout gli.Duration `cli:"timeout=DURATION" default:"0s" help:"zelo value means ininite"`
2019-11-18 00:48:49 -05:00
}
func (c waitCmd) Run(args []string) error {
if len(args) != 1 {
return errors.New("not one target")
}
an := ancestors()
t := strings.ToLower(args[0])
2019-11-18 02:08:13 -05:00
var ctx context.Context
if c.Timeout == 0 {
ctx = context.Background()
} else {
ctx, _ = context.WithTimeout(context.Background(), c.Timeout.Duration())
}
waitLoop:
2019-11-18 00:48:49 -05:00
for {
wins, err := listAllWindows()
if err != nil {
return err
}
win := findFirstTarget(t, wins, an)
if c.Closed {
if win == nil {
break
}
} else {
if win != nil {
break
}
}
2019-11-18 02:08:13 -05:00
select {
case <-ctx.Done():
fmt.Fprintln(os.Stderr, "cancelled")
break waitLoop
default:
//nop
}
2019-11-18 00:48:49 -05:00
time.Sleep(c.Intervals.Duration())
}
return nil
}