github.com/kcmerrill/alfred@v0.0.0-20180727171036-06445dcb5e3d/pkg/alfred/watch.go (about)

     1  package alfred
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"regexp"
     8  	"time"
     9  )
    10  
    11  func watch(task Task, context *Context, tasks map[string]Task) {
    12  	if task.Watch == "" {
    13  		return
    14  	}
    15  	dir, _ := task.dir(context)
    16  	outOK("watching", dir, context)
    17  	for {
    18  		matched := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
    19  			if f.ModTime().After(time.Now().Add(-2 * time.Second)) {
    20  				m, _ := regexp.Match(translate(task.Watch, context), []byte(path))
    21  				if m {
    22  					// If not a match ...
    23  					return fmt.Errorf(path)
    24  				}
    25  			}
    26  			// continue on
    27  			return nil
    28  		})
    29  
    30  		if matched != nil {
    31  			// seems weird, but we are passing back an error
    32  			outOK("modified", matched.Error(), context)
    33  			break
    34  		} else {
    35  			<-time.After(time.Second)
    36  		}
    37  	}
    38  }