realize/watcher/watcher.go

414 lines
13 KiB
Go
Raw Normal View History

package watcher
2016-07-29 23:02:11 +00:00
import (
2016-08-30 17:27:47 +00:00
"errors"
2016-07-31 21:39:56 +00:00
"fmt"
2017-06-16 09:15:56 +00:00
"github.com/fsnotify/fsnotify"
"github.com/tockins/realize/style"
2016-08-21 13:38:00 +00:00
"log"
"math/big"
2016-07-29 23:02:11 +00:00
"os"
2016-09-05 15:53:37 +00:00
"os/signal"
2016-08-17 23:35:37 +00:00
"path/filepath"
2017-06-16 09:15:56 +00:00
"reflect"
2016-12-18 23:30:58 +00:00
"strconv"
2016-07-31 21:39:56 +00:00
"strings"
2016-08-16 10:20:55 +00:00
"sync"
2016-09-05 15:53:37 +00:00
"syscall"
2016-08-17 23:35:37 +00:00
"time"
2016-07-29 23:02:11 +00:00
)
2016-12-25 17:08:22 +00:00
var msg string
var out BufferOut
2016-12-21 23:28:08 +00:00
2017-06-16 14:35:00 +00:00
// Add a path to paths list
2016-12-21 23:28:08 +00:00
func (w *pollWatcher) Add(path string) error {
if w.paths == nil {
w.paths = map[string]bool{}
}
w.paths[path] = true
return nil
}
2017-06-16 14:35:00 +00:00
// Check if is watching
2016-12-25 17:08:22 +00:00
func (w *pollWatcher) isWatching(path string) bool {
a, b := w.paths[path]
return a && b
}
// Watch the project by polling
2016-12-21 23:28:08 +00:00
func (p *Project) watchByPolling() {
var wr sync.WaitGroup
var watcher = new(pollWatcher)
channel, exit := make(chan bool, 1), make(chan os.Signal, 2)
signal.Notify(exit, os.Interrupt, syscall.SIGTERM)
2016-12-21 23:28:08 +00:00
defer func() {
2017-08-29 23:54:52 +00:00
p.cmd("after", true)
2016-12-21 23:28:08 +00:00
wg.Done()
}()
2017-08-29 23:54:52 +00:00
p.cmd("before", true)
2017-06-16 14:35:00 +00:00
go p.routines(&wr, channel, watcher, "")
2016-12-21 23:28:08 +00:00
p.LastChangedOn = time.Now().Truncate(time.Second)
2016-12-25 17:08:22 +00:00
walk := func(changed string, info os.FileInfo, err error) error {
var ext string
2016-12-21 23:28:08 +00:00
if err != nil {
return err
} else if !watcher.isWatching(changed) {
return nil
} else if !info.ModTime().Truncate(time.Second).After(p.LastChangedOn) {
return nil
}
if index := strings.Index(filepath.Ext(changed), "_"); index == -1 {
ext = filepath.Ext(changed)
} else {
ext = filepath.Ext(changed)[0:index]
}
i := strings.Index(changed, filepath.Ext(changed))
file := changed[:i] + ext
if changed[:i] != "" && inArray(ext, p.Watcher.Exts) {
if p.Cmds.Run {
2016-12-21 23:28:08 +00:00
close(channel)
channel = make(chan bool)
}
p.LastChangedOn = time.Now().Truncate(time.Second)
// repeat the initial cycle
msg = fmt.Sprintln(p.pname(p.Name, 4), ":", style.Magenta.Bold(strings.ToUpper(ext[1:])+" changed"), style.Magenta.Bold(file))
out = BufferOut{Time: time.Now(), Text: strings.ToUpper(ext[1:]) + " changed " + file}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, "")
2017-06-16 14:35:00 +00:00
go p.routines(&wr, channel, watcher, file)
2016-12-21 23:28:08 +00:00
}
return nil
}
for {
for _, dir := range p.Watcher.Paths {
base := filepath.Join(p.base, dir)
if _, err := os.Stat(base); err == nil {
if err := filepath.Walk(base, walk); err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Regular(err.Error()))
2016-12-25 17:08:22 +00:00
out = BufferOut{Time: time.Now(), Text: err.Error()}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, "")
2016-12-21 23:28:08 +00:00
}
} else {
2016-12-25 17:08:22 +00:00
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", base, "path doesn't exist")
out = BufferOut{Time: time.Now(), Text: base + " path doesn't exist"}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, "")
2016-12-21 23:28:08 +00:00
}
select {
case <-exit:
return
case <-time.After(p.parent.Legacy.Interval / time.Duration(len(p.Watcher.Paths))):
2016-12-21 23:28:08 +00:00
}
}
}
}
2016-12-25 17:08:22 +00:00
// Watch the project by fsnotify
func (p *Project) watchByNotify() {
2016-08-16 10:20:55 +00:00
var wr sync.WaitGroup
2016-07-31 23:52:11 +00:00
var watcher *fsnotify.Watcher
2016-12-25 17:08:22 +00:00
channel, exit := make(chan bool, 1), make(chan os.Signal, 2)
signal.Notify(exit, os.Interrupt, syscall.SIGTERM)
2016-08-17 14:56:06 +00:00
watcher, err := fsnotify.NewWatcher()
2016-12-25 17:08:22 +00:00
p.Fatal(err)
2016-11-11 16:24:01 +00:00
defer func() {
2017-08-29 23:54:52 +00:00
p.cmd("after", true)
2016-08-17 14:56:06 +00:00
wg.Done()
2016-11-11 16:24:01 +00:00
}()
2017-08-29 23:54:52 +00:00
p.cmd("before", true)
2017-06-16 14:35:00 +00:00
go p.routines(&wr, channel, watcher, "")
2016-09-22 22:41:42 +00:00
p.LastChangedOn = time.Now().Truncate(time.Second)
2016-08-01 17:08:37 +00:00
for {
select {
2016-08-04 22:59:41 +00:00
case event := <-watcher.Events:
2016-09-22 22:41:42 +00:00
if time.Now().Truncate(time.Second).After(p.LastChangedOn) {
2016-12-25 17:08:22 +00:00
if event.Op&fsnotify.Chmod == fsnotify.Chmod {
2016-08-04 22:59:41 +00:00
continue
2016-08-01 17:08:37 +00:00
}
2016-08-04 22:59:41 +00:00
if _, err := os.Stat(event.Name); err == nil {
2016-08-23 12:07:01 +00:00
var ext string
if index := strings.Index(filepath.Ext(event.Name), "_"); index == -1 {
ext = filepath.Ext(event.Name)
} else {
2016-11-11 16:24:01 +00:00
ext = filepath.Ext(event.Name)[0:index]
2016-08-23 12:07:01 +00:00
}
2016-08-04 22:59:41 +00:00
i := strings.Index(event.Name, filepath.Ext(event.Name))
2016-11-11 16:24:01 +00:00
file := event.Name[:i] + ext
2016-08-24 13:06:23 +00:00
if event.Name[:i] != "" && inArray(ext, p.Watcher.Exts) {
if p.Cmds.Run {
2016-08-23 08:52:00 +00:00
close(channel)
2016-08-23 14:32:25 +00:00
channel = make(chan bool)
2016-08-23 08:52:00 +00:00
}
// repeat the initial cycle
msg = fmt.Sprintln(p.pname(p.Name, 4), ":", style.Magenta.Bold(strings.ToUpper(ext[1:])+" changed"), style.Magenta.Bold(file))
out = BufferOut{Time: time.Now(), Text: strings.ToUpper(ext[1:]) + " changed " + file}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, "")
2017-06-16 14:35:00 +00:00
go p.routines(&wr, channel, watcher, file)
2017-04-24 09:52:22 +00:00
p.LastChangedOn = time.Now().Truncate(time.Second)
2016-08-20 10:47:32 +00:00
}
2016-08-04 22:59:41 +00:00
}
}
case err := <-watcher.Errors:
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Regular(err.Error()))
2016-12-25 17:08:22 +00:00
out = BufferOut{Time: time.Now(), Text: err.Error()}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, "")
2016-09-17 19:07:22 +00:00
case <-exit:
return
}
}
}
2016-08-03 16:49:37 +00:00
// Watch the files tree of a project
func (p *Project) watch(watcher watcher) error {
var files, folders int64
walk := func(path string, info os.FileInfo, err error) error {
if !p.ignore(path) {
2017-08-25 10:51:41 +00:00
if ((info.IsDir() && len(filepath.Ext(path)) == 0 && !strings.HasPrefix(path, ".")) && !strings.Contains(path, "/.")) || (inArray(filepath.Ext(path), p.Watcher.Exts)) {
if p.Watcher.Preview {
log.Println(p.pname(p.Name, 1), ":", path)
}
if err = watcher.Add(path); err != nil {
return filepath.SkipDir
}
if inArray(filepath.Ext(path), p.Watcher.Exts) {
files++
} else {
folders++
}
}
}
return nil
}
2017-08-29 23:54:52 +00:00
for _, dir := range p.Watcher.Paths {
base := filepath.Join(p.base, dir)
if _, err := os.Stat(base); err == nil {
if err := filepath.Walk(base, walk); err != nil {
log.Println(style.Red.Bold(err.Error()))
2017-08-29 23:54:52 +00:00
p.tool(base, p.tools.Fmt)
p.tool(base, p.tools.Vet)
p.tool(base, p.tools.Test)
p.tool(base, p.tools.Generate)
}
} else {
return errors.New(base + " path doesn't exist")
}
}
msg = fmt.Sprintln(p.pname(p.Name, 1), ":", style.Blue.Bold("Watching"), style.Magenta.Bold(files), "file/s", style.Magenta.Bold(folders), "folder/s")
out = BufferOut{Time: time.Now(), Text: "Watching " + strconv.FormatInt(files, 10) + " files/s " + strconv.FormatInt(folders, 10) + " folder/s"}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, "")
return nil
}
2016-12-17 10:43:27 +00:00
// Install calls an implementation of "go install"
2016-12-18 17:26:10 +00:00
func (p *Project) install() error {
if p.Cmds.Bin.Status {
2016-08-20 14:14:11 +00:00
start := time.Now()
2016-12-16 22:54:07 +00:00
log.Println(p.pname(p.Name, 1), ":", "Installing..")
2016-12-18 17:26:10 +00:00
stream, err := p.goInstall()
if err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold("Go Install"), style.Red.Regular(err.Error()))
2016-12-25 17:08:22 +00:00
out = BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Install", Stream: stream}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, stream)
2016-08-04 22:59:41 +00:00
} else {
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Regular("Installed")+" after", style.Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s"))
2016-12-25 17:08:22 +00:00
out = BufferOut{Time: time.Now(), Text: "Installed after " + big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3) + " s"}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, stream)
2016-12-16 22:54:07 +00:00
}
2016-12-18 17:26:10 +00:00
return err
2016-12-16 22:54:07 +00:00
}
2016-12-18 17:26:10 +00:00
return nil
2016-12-16 22:54:07 +00:00
}
2016-11-17 00:02:25 +00:00
2016-12-17 10:43:27 +00:00
// Install calls an implementation of "go run"
2016-12-16 22:54:07 +00:00
func (p *Project) run(channel chan bool, wr *sync.WaitGroup) {
if p.Cmds.Run {
2016-12-16 22:54:07 +00:00
start := time.Now()
runner := make(chan bool, 1)
log.Println(p.pname(p.Name, 1), ":", "Running..")
go p.goRun(channel, runner, wr)
for {
select {
case <-runner:
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Regular("Started")+" after", style.Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s"))
out = BufferOut{Time: time.Now(), Text: "Started after " + big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3) + " s"}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, "")
2016-12-16 22:54:07 +00:00
return
2016-08-19 20:52:53 +00:00
}
2016-07-31 21:39:56 +00:00
}
2016-07-31 23:52:11 +00:00
}
2016-08-01 17:08:37 +00:00
}
2016-07-31 21:39:56 +00:00
2016-08-24 13:32:57 +00:00
// Build calls an implementation of the "go build"
2016-12-18 17:26:10 +00:00
func (p *Project) build() error {
if p.Cmds.Build.Status {
2016-08-20 14:14:11 +00:00
start := time.Now()
2016-12-16 22:54:07 +00:00
log.Println(p.pname(p.Name, 1), ":", "Building..")
2016-12-18 17:26:10 +00:00
stream, err := p.goBuild()
if err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold("Go Build"), style.Red.Regular(err.Error()))
2016-12-25 17:08:22 +00:00
out = BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Build", Stream: stream}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, stream)
2016-08-04 22:59:41 +00:00
} else {
2017-06-13 13:57:26 +00:00
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Regular("Built")+" after", style.Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s"))
out = BufferOut{Time: time.Now(), Text: "Built after " + big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3) + " s"}
2017-08-28 08:49:38 +00:00
p.stamp("log", out, msg, stream)
2016-07-29 23:02:11 +00:00
}
2016-12-18 17:26:10 +00:00
return err
2016-07-29 23:02:11 +00:00
}
2016-12-18 17:26:10 +00:00
return nil
}
2017-08-29 23:54:52 +00:00
// Tool logs the result of a go command
func (p *Project) tool(path string, tool tool) error {
if tool.status != nil {
v := reflect.ValueOf(tool.status).Elem()
2017-06-16 09:15:56 +00:00
if v.Interface().(bool) && (strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "")) {
if strings.HasSuffix(path, ".go") {
2017-04-24 00:14:17 +00:00
tool.options = append(tool.options, path)
path = p.base
}
2017-04-24 00:07:37 +00:00
if stream, err := p.goTools(path, tool.cmd, tool.options...); err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold(tool.name), style.Red.Regular("there are some errors in"), ":", style.Magenta.Bold(path))
out = BufferOut{Time: time.Now(), Text: "there are some errors in", Path: path, Type: tool.name, Stream: stream}
2017-08-28 08:49:38 +00:00
p.stamp("error", out, msg, stream)
return err
}
2016-12-17 16:15:56 +00:00
}
}
return nil
}
2016-09-05 15:53:37 +00:00
// Cmd calls an wrapper for execute the commands after/before
2017-08-28 08:49:38 +00:00
func (p *Project) cmd(flag string, global bool) {
for _, cmd := range p.Watcher.Scripts {
2017-08-29 23:54:52 +00:00
if strings.ToLower(cmd.Type) == flag && cmd.Global == global {
2017-08-28 08:49:38 +00:00
err, logs := p.command(cmd)
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Bold("Command"), style.Green.Bold("\"")+cmd.Command+style.Green.Bold("\""))
out = BufferOut{Time: time.Now(), Text: cmd.Command, Type: flag}
if err != "" {
p.stamp("error", out, msg, "")
2017-08-29 23:54:52 +00:00
} else {
p.stamp("log", out, msg, "")
2017-08-28 08:49:38 +00:00
}
if logs != "" {
msg = fmt.Sprintln(logs)
out = BufferOut{Time: time.Now(), Text: logs, Type: flag}
p.stamp("log", out, "", msg)
}
if err != "" {
msg = fmt.Sprintln(style.Red.Regular(err))
out = BufferOut{Time: time.Now(), Text: err, Type: flag}
p.stamp("error", out, "", msg)
2016-12-18 17:26:10 +00:00
}
2016-09-05 15:53:37 +00:00
}
}
2016-12-21 23:28:08 +00:00
}
2016-12-17 10:43:27 +00:00
// Ignore and validate a path
2016-08-17 14:56:06 +00:00
func (p *Project) ignore(str string) bool {
for _, v := range p.Watcher.Ignore {
2016-08-23 00:07:07 +00:00
if strings.Contains(str, filepath.Join(p.base, v)) {
2016-08-03 08:30:45 +00:00
return true
}
}
return false
}
2016-12-17 10:43:27 +00:00
// Routines launches the toolchain run, build, install
2017-07-27 18:48:16 +00:00
func (p *Project) routines(wr *sync.WaitGroup, channel chan bool, watcher watcher, file string) {
2017-06-19 10:08:51 +00:00
if len(file) > 0 {
2017-08-28 08:49:38 +00:00
p.cmd("before", false)
2017-06-16 14:35:00 +00:00
path := filepath.Dir(file)
p.tool(file, p.tools.Fmt)
p.tool(path, p.tools.Vet)
p.tool(path, p.tools.Test)
p.tool(path, p.tools.Generate)
2017-06-19 10:08:51 +00:00
} else {
2017-06-16 14:35:00 +00:00
p.Fatal(p.watch(watcher))
}
2016-12-18 17:26:10 +00:00
install := p.install()
build := p.build()
2016-08-23 20:21:15 +00:00
wr.Add(1)
2016-12-18 17:26:10 +00:00
if install == nil && build == nil {
go p.run(channel, wr)
}
2016-08-23 20:21:15 +00:00
wr.Wait()
2017-06-16 14:35:00 +00:00
if len(file) > 0 {
2017-08-28 08:49:38 +00:00
p.cmd("after", false)
2017-06-16 14:35:00 +00:00
}
2017-06-19 10:08:51 +00:00
2016-08-23 00:23:17 +00:00
}
2016-11-01 09:56:12 +00:00
// Defines the colors scheme for the project name
func (p *Project) pname(name string, color int) string {
switch color {
case 1:
name = style.Yellow.Regular("[") + strings.ToUpper(name) + style.Yellow.Regular("]")
2016-11-01 09:56:12 +00:00
break
case 2:
name = style.Yellow.Regular("[") + style.Red.Bold(strings.ToUpper(name)) + style.Yellow.Regular("]")
2016-11-01 09:56:12 +00:00
break
case 3:
name = style.Yellow.Regular("[") + style.Blue.Bold(strings.ToUpper(name)) + style.Yellow.Regular("]")
2016-11-01 09:56:12 +00:00
break
case 4:
name = style.Yellow.Regular("[") + style.Magenta.Bold(strings.ToUpper(name)) + style.Yellow.Regular("]")
2016-11-01 09:56:12 +00:00
break
case 5:
name = style.Yellow.Regular("[") + style.Green.Bold(strings.ToUpper(name)) + style.Yellow.Regular("]")
2016-11-01 09:56:12 +00:00
break
}
return name
}
2016-11-17 00:02:25 +00:00
2016-12-18 23:30:58 +00:00
// Print on files, cli, ws
2017-08-28 08:49:38 +00:00
func (p *Project) stamp(t string, o BufferOut, msg string, stream string) {
2016-11-17 00:02:25 +00:00
switch t {
case "out":
p.Buffer.StdOut = append(p.Buffer.StdOut, o)
2017-08-29 23:54:52 +00:00
if p.Resources.Outputs.Status {
f := p.Create(p.base, p.Resources.Outputs.Name)
2016-11-17 00:02:25 +00:00
t := time.Now()
2016-12-18 23:30:58 +00:00
s := []string{t.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Text, "\r\n"}
if _, err := f.WriteString(strings.Join(s, " ")); err != nil {
2016-12-16 22:54:07 +00:00
p.Fatal(err, "")
2016-11-17 00:02:25 +00:00
}
}
case "log":
p.Buffer.StdLog = append(p.Buffer.StdLog, o)
2017-08-29 23:54:52 +00:00
if p.Resources.Logs.Status {
f := p.Create(p.base, p.Resources.Logs.Name)
2016-11-17 00:02:25 +00:00
t := time.Now()
2016-12-18 23:30:58 +00:00
s := []string{t.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Text, "\r\n"}
if stream != "" {
s = []string{t.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Text, "\r\n", stream}
}
if _, err := f.WriteString(strings.Join(s, " ")); err != nil {
2016-12-16 22:54:07 +00:00
p.Fatal(err, "")
2016-11-17 00:02:25 +00:00
}
}
case "error":
p.Buffer.StdErr = append(p.Buffer.StdErr, o)
2017-08-29 23:54:52 +00:00
if p.Resources.Errors.Status {
f := p.Create(p.base, p.Resources.Errors.Name)
2016-11-17 00:02:25 +00:00
t := time.Now()
2016-12-18 23:30:58 +00:00
s := []string{t.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Type, o.Text, o.Path, "\r\n"}
if stream != "" {
s = []string{t.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Type, o.Text, o.Path, "\r\n", stream}
}
if _, err := f.WriteString(strings.Join(s, " ")); err != nil {
2016-12-16 22:54:07 +00:00
p.Fatal(err, "")
2016-11-17 00:02:25 +00:00
}
}
2017-08-08 21:56:19 +00:00
}
if msg != "" {
log.Print(msg)
2016-12-18 17:26:10 +00:00
}
2016-11-17 00:02:25 +00:00
if stream != "" {
fmt.Fprint(style.Output, stream)
2016-11-17 00:02:25 +00:00
}
2016-12-18 23:30:58 +00:00
go func() {
p.parent.Sync <- "sync"
}()
2016-11-17 00:02:25 +00:00
}