Merge pull request #62 from tockins/dev

v1.4
This commit is contained in:
Alessio Pracchia 2017-06-19 13:14:46 +02:00 committed by GitHub
commit dea66a7725
8 changed files with 318 additions and 206 deletions

View File

@ -17,7 +17,6 @@ import (
const ( const (
appVersion = "1.3" appVersion = "1.3"
config = "realize.yaml" config = "realize.yaml"
outputs = "outputs.log" outputs = "outputs.log"
errs = "errors.log" errs = "errors.log"
@ -81,7 +80,6 @@ func main() {
if err := r.Read(&r); err != nil { if err := r.Read(&r); err != nil {
return err return err
} }
// increase the file limit // increase the file limit
if r.Config.Flimit != 0 { if r.Config.Flimit != 0 {
if err := r.Flimit(); err != nil { if err := r.Flimit(); err != nil {
@ -112,6 +110,7 @@ func main() {
Description: "Run a toolchain on a project or a list of projects. If not exist a config file it creates a new one", Description: "Run a toolchain on a project or a list of projects. If not exist a config file it creates a new one",
Flags: []cli.Flag{ Flags: []cli.Flag{
&cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: "", Usage: "Project base path."}, &cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: "", Usage: "Project base path."},
&cli.StringFlag{Name: "name", Aliases: []string{"n"}, Value: "", Usage: "Run a project by its name."},
&cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test."}, &cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test."},
&cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate."}, &cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate."},
&cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build."}, &cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build."},
@ -122,6 +121,14 @@ func main() {
&cli.BoolFlag{Name: "no-config", Aliases: []string{"nc"}, Value: false, Usage: "Ignore existing configurations."}, &cli.BoolFlag{Name: "no-config", Aliases: []string{"nc"}, Value: false, Usage: "Ignore existing configurations."},
}, },
Action: func(p *cli.Context) error { Action: func(p *cli.Context) error {
c := r
if p.String("name") != ""{
for index, project := range r.Blueprint.Projects{
if project.Name == p.String("name"){
c.Blueprint.Projects = []watcher.Project{r.Blueprint.Projects[index]}
}
}
}
if p.Bool("legacy") { if p.Bool("legacy") {
r.Config.Legacy = settings.Legacy{ r.Config.Legacy = settings.Legacy{
Status: p.Bool("legacy"), Status: p.Bool("legacy"),
@ -137,13 +144,13 @@ func main() {
return err return err
} }
} }
if err := r.Server.Start(p); err != nil { if err := c.Server.Start(p); err != nil {
return err return err
} }
if err := r.Blueprint.Run(); err != nil { if err := c.Blueprint.Run(p); err != nil {
return err return err
} }
if err := r.Record(r); err != nil { if err := r.Record(c); err != nil {
return err return err
} }
return nil return nil
@ -195,7 +202,7 @@ func main() {
Questions: []*interact.Question{ Questions: []*interact.Question{
{ {
Before: func(d interact.Context) error { Before: func(d interact.Context) error {
if _, err := os.Stat(".realize/" + config); err != nil { if _, err := os.Stat(settings.Dir + config); err != nil {
d.Skip() d.Skip()
} }
d.SetDef(false, style.Green.Regular("(n)")) d.SetDef(false, style.Green.Regular("(n)"))
@ -462,7 +469,25 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Fmt = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Fmt = val
return nil
},
},
{
Before: func(d interact.Context) error {
d.SetDef(true, style.Green.Regular("(y)"))
return nil
},
Quest: interact.Quest{
Options: style.Yellow.Regular("[y/n]"),
Msg: "Enable go vet",
},
Action: func(d interact.Context) interface{} {
val, err := d.Ans().Bool()
if err != nil {
return d.Err()
}
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Vet = val
return nil return nil
}, },
}, },
@ -480,7 +505,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Test = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Test = val
return nil return nil
}, },
}, },
@ -498,7 +523,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Generate = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Generate = val
return nil return nil
}, },
}, },
@ -516,7 +541,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Bin = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Bin.Status = val
return nil return nil
}, },
}, },
@ -534,7 +559,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Build = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Build.Status = val
return nil return nil
}, },
}, },
@ -552,7 +577,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Run = val r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Cmds.Run = val
return nil return nil
}, },
}, },
@ -674,7 +699,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Params = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Params, val) r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Args = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Args, val)
d.Reload() d.Reload()
return nil return nil
}, },
@ -716,7 +741,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts, watcher.Command{Type: "before", Command: val}) r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts, watcher.Command{Type: "before", Command: val, Changed: true, Startup: true})
d.Reload() d.Reload()
return nil return nil
}, },
@ -758,7 +783,7 @@ func main() {
if err != nil { if err != nil {
return d.Err() return d.Err()
} }
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts, watcher.Command{Type: "after", Command: val}) r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts = append(r.Blueprint.Projects[len(r.Blueprint.Projects)-1].Watcher.Scripts, watcher.Command{Type: "after", Command: val, Changed: true, Startup: true})
d.Reload() d.Reload()
return nil return nil
}, },
@ -844,6 +869,24 @@ func main() {
return nil return nil
}, },
}, },
{
Before: func(d interact.Context) error {
d.SetDef("", style.Green.Regular("(none)"))
return nil
},
Quest: interact.Quest{
Options: style.Yellow.Regular("[string]"),
Msg: "Set an error output pattern",
},
Action: func(d interact.Context) interface{} {
val, err := d.Ans().String()
if err != nil {
return d.Err()
}
r.Blueprint.Projects[len(r.Blueprint.Projects)-1].ErrorOutputPattern = val
return nil
},
},
}, },
Action: func(d interact.Context) interface{} { Action: func(d interact.Context) interface{} {
if val, err := d.Ans().Bool(); err != nil { if val, err := d.Ans().Bool(); err != nil {

View File

@ -26,8 +26,8 @@ func (s Settings) Write(name string, data []byte) error {
// Create a new file and return its pointer // Create a new file and return its pointer
func (s Settings) Create(path string, name string) *os.File { func (s Settings) Create(path string, name string) *os.File {
var file string var file string
if _, err := os.Stat(".realize/"); err == nil { if _, err := os.Stat(Dir); err == nil {
file = filepath.Join(path, ".realize/", name) file = filepath.Join(path, Dir, name)
} else { } else {
file = filepath.Join(path, name) file = filepath.Join(path, name)
} }

View File

@ -3,10 +3,11 @@ package settings
import ( import (
"os" "os"
"time" "time"
yaml "gopkg.in/yaml.v2" yaml "gopkg.in/yaml.v2"
) )
var Dir = ".realize/"
// Settings defines a group of general settings // Settings defines a group of general settings
type Settings struct { type Settings struct {
Config `yaml:",inline" json:"config"` Config `yaml:",inline" json:"config"`
@ -46,8 +47,8 @@ type Resources struct {
// Read from config file // Read from config file
func (s *Settings) Read(out interface{}) error { func (s *Settings) Read(out interface{}) error {
localConfigPath := s.Resources.Config localConfigPath := s.Resources.Config
if _, err := os.Stat(".realize/" + s.Resources.Config); err == nil { if _, err := os.Stat(Dir + s.Resources.Config); err == nil {
localConfigPath = ".realize/" + s.Resources.Config localConfigPath = Dir + s.Resources.Config
} }
content, err := s.Stream(localConfigPath) content, err := s.Stream(localConfigPath)
if err == nil { if err == nil {
@ -64,20 +65,20 @@ func (s *Settings) Record(out interface{}) error {
if err != nil { if err != nil {
return err return err
} }
if _, err := os.Stat(".realize/"); os.IsNotExist(err) { if _, err := os.Stat(Dir); os.IsNotExist(err) {
if err = os.Mkdir(".realize/", 0770); err != nil { if err = os.Mkdir(Dir, 0770); err != nil {
return s.Write(s.Resources.Config, y) return s.Write(s.Resources.Config, y)
} }
} }
return s.Write(".realize/"+s.Resources.Config, y) return s.Write(Dir+s.Resources.Config, y)
} }
return nil return nil
} }
// Remove realize folder // Remove realize folder
func (s *Settings) Remove() error { func (s *Settings) Remove() error {
if _, err := os.Stat(".realize/"); !os.IsNotExist(err) { if _, err := os.Stat(Dir); !os.IsNotExist(err) {
return os.RemoveAll(".realize/") return os.RemoveAll(Dir)
} }
return nil return nil
} }

View File

@ -3,19 +3,52 @@ package watcher
import ( import (
"errors" "errors"
"fmt" "fmt"
"strings"
"github.com/tockins/realize/style" "github.com/tockins/realize/style"
cli "gopkg.in/urfave/cli.v2" cli "gopkg.in/urfave/cli.v2"
"strings"
) )
// Run launches the toolchain for each project // Run launches the toolchain for each project
func (h *Blueprint) Run() error { func (h *Blueprint) Run(p *cli.Context) error {
err := h.check() err := h.check()
if err == nil { if err == nil {
// loop projects // loop projects
wg.Add(len(h.Projects)) wg.Add(len(h.Projects))
for k := range h.Projects { for k, element := range h.Projects {
tools := tools{}
if element.Cmds.Fmt{
tools.Fmt = tool{
status: &h.Projects[k].Cmds.Fmt,
cmd: "gofmt",
options: []string{"-s", "-w", "-e"},
name: "Go Fmt",
}
}
if element.Cmds.Generate{
tools.Generate = tool{
status: &h.Projects[k].Cmds.Generate,
cmd: "go",
options: []string{"generate"},
name: "Go Generate",
}
}
if element.Cmds.Test{
tools.Test = tool{
status: &h.Projects[k].Cmds.Test,
cmd: "go",
options: []string{"test"},
name: "Go Test",
}
}
if element.Cmds.Vet {
tools.Vet = tool{
status: &h.Projects[k].Cmds.Vet,
cmd: "go",
options: []string{"vet"},
name: "Go Vet",
}
}
h.Projects[k].tools = tools
h.Projects[k].parent = h h.Projects[k].parent = h
h.Projects[k].path = h.Projects[k].Path h.Projects[k].path = h.Projects[k].Path
if h.Legacy.Status { if h.Legacy.Status {
@ -35,25 +68,26 @@ func (h *Blueprint) Add(p *cli.Context) error {
project := Project{ project := Project{
Name: h.Name(p.String("name"), p.String("path")), Name: h.Name(p.String("name"), p.String("path")),
Path: h.Path(p.String("path")), Path: h.Path(p.String("path")),
Cmds: Cmds{
Vet: p.Bool("vet"),
Fmt: !p.Bool("no-fmt"), Fmt: !p.Bool("no-fmt"),
Generate: p.Bool("generate"),
Test: p.Bool("test"), Test: p.Bool("test"),
Build: p.Bool("build"), Generate: p.Bool("generate"),
Bin: !p.Bool("no-bin"), Build: Cmd{
Status: p.Bool("build"),
},
Bin: Cmd{
Status: !p.Bool("no-bin"),
},
Run: !p.Bool("no-run"), Run: !p.Bool("no-run"),
Params: argsParam(p), },
Args: argsParam(p),
Watcher: Watcher{ Watcher: Watcher{
Paths: []string{"/"}, Paths: []string{"/"},
Ignore: []string{"vendor"}, Ignore: []string{"vendor"},
Exts: []string{".go"}, Exts: []string{".go"},
Preview: p.Bool("preview"), Preview: p.Bool("preview"),
Scripts: []Command{},
},
Streams: Streams{
CliOut: true,
FileOut: false,
FileLog: false,
FileErr: false,
}, },
} }
if _, err := duplicates(project, h.Projects); err != nil { if _, err := duplicates(project, h.Projects); err != nil {
@ -94,14 +128,14 @@ func (h *Blueprint) List() error {
name := style.Magenta.Bold("[") + strings.ToUpper(val.Name) + style.Magenta.Bold("]") name := style.Magenta.Bold("[") + strings.ToUpper(val.Name) + style.Magenta.Bold("]")
fmt.Println(name, style.Yellow.Regular("Base Path"), ":", style.Magenta.Regular(val.Path)) fmt.Println(name, style.Yellow.Regular("Base Path"), ":", style.Magenta.Regular(val.Path))
fmt.Println(name, style.Yellow.Regular("Fmt"), ":", style.Magenta.Regular(val.Fmt)) fmt.Println(name, style.Yellow.Regular("Fmt"), ":", style.Magenta.Regular(val.Cmds.Fmt))
fmt.Println(name, style.Yellow.Regular("Generate"), ":", style.Magenta.Regular(val.Generate)) fmt.Println(name, style.Yellow.Regular("Generate"), ":", style.Magenta.Regular(val.Cmds.Generate))
fmt.Println(name, style.Yellow.Regular("Test"), ":", style.Magenta.Regular(val.Test)) fmt.Println(name, style.Yellow.Regular("Test"), ":", style.Magenta.Regular(val.Cmds.Test))
fmt.Println(name, style.Yellow.Regular("Install"), ":", style.Magenta.Regular(val.Bin)) fmt.Println(name, style.Yellow.Regular("Install"), ":", style.Magenta.Regular(val.Cmds.Bin))
fmt.Println(name, style.Yellow.Regular("Build"), ":", style.Magenta.Regular(val.Build)) fmt.Println(name, style.Yellow.Regular("Build"), ":", style.Magenta.Regular(val.Cmds.Build))
fmt.Println(name, style.Yellow.Regular("Run"), ":", style.Magenta.Regular(val.Run)) fmt.Println(name, style.Yellow.Regular("Run"), ":", style.Magenta.Regular(val.Cmds.Run))
if len(val.Params) > 0 { if len(val.Args) > 0 {
fmt.Println(name, style.Yellow.Regular("Params"), ":", style.Magenta.Regular(val.Params)) fmt.Println(name, style.Yellow.Regular("Params"), ":", style.Magenta.Regular(val.Args))
} }
fmt.Println(name, style.Yellow.Regular("Watcher"), ":") fmt.Println(name, style.Yellow.Regular("Watcher"), ":")
fmt.Println(name, "\t", style.Yellow.Regular("Preview"), ":", style.Magenta.Regular(val.Watcher.Preview)) fmt.Println(name, "\t", style.Yellow.Regular("Preview"), ":", style.Magenta.Regular(val.Watcher.Preview))
@ -129,7 +163,6 @@ func (h *Blueprint) List() error {
} }
} }
fmt.Println(name, style.Yellow.Regular("Streams"), ":") fmt.Println(name, style.Yellow.Regular("Streams"), ":")
fmt.Println(name, "\t", style.Yellow.Regular("Cli Out"), ":", style.Magenta.Regular(val.Streams.CliOut))
fmt.Println(name, "\t", style.Yellow.Regular("File Out"), ":", style.Magenta.Regular(val.Streams.FileOut)) fmt.Println(name, "\t", style.Yellow.Regular("File Out"), ":", style.Magenta.Regular(val.Streams.FileOut))
fmt.Println(name, "\t", style.Yellow.Regular("File Log"), ":", style.Magenta.Regular(val.Streams.FileLog)) fmt.Println(name, "\t", style.Yellow.Regular("File Log"), ":", style.Magenta.Regular(val.Streams.FileLog))
fmt.Println(name, "\t", style.Yellow.Regular("File Err"), ":", style.Magenta.Regular(val.Streams.FileErr)) fmt.Println(name, "\t", style.Yellow.Regular("File Err"), ":", style.Magenta.Regular(val.Streams.FileErr))

View File

@ -4,25 +4,38 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"github.com/tockins/realize/style"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/tockins/realize/style"
) )
// GoRun is an implementation of the bin execution // GoRun is an implementation of the bin execution
func (p *Project) goRun(channel chan bool, runner chan bool, wr *sync.WaitGroup) error { func (p *Project) goRun(channel chan bool, runner chan bool, wr *sync.WaitGroup) error {
var build *exec.Cmd var build *exec.Cmd
var params []string var args []string
var path = "" var path = ""
for _, param := range p.Params { isErrorText := func(string) bool {
arr := strings.Fields(param) return false
params = append(params, arr...) }
errRegexp, err := regexp.Compile(p.ErrorOutputPattern)
if err != nil {
msg := fmt.Sprintln(p.pname(p.Name, 3), ":", style.Blue.Regular(err.Error()))
out := BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Run"}
p.print("error", out, msg, "")
} else {
isErrorText = func(t string) bool {
return errRegexp.MatchString(t)
}
}
for _, arg := range p.Args {
arr := strings.Fields(arg)
args = append(args, arr...)
} }
if _, err := os.Stat(filepath.Join(p.base, p.path)); err == nil { if _, err := os.Stat(filepath.Join(p.base, p.path)); err == nil {
path = filepath.Join(p.base, p.path) path = filepath.Join(p.base, p.path)
@ -32,12 +45,12 @@ func (p *Project) goRun(channel chan bool, runner chan bool, wr *sync.WaitGroup)
} }
if path != "" { if path != "" {
build = exec.Command(path, params...) build = exec.Command(path, args...)
} else { } else {
if _, err := os.Stat(filepath.Join(os.Getenv("GOBIN"), filepath.Base(p.path))); err == nil { if _, err := os.Stat(filepath.Join(getEnvPath("GOBIN"), filepath.Base(p.path))); err == nil {
build = exec.Command(filepath.Join(os.Getenv("GOBIN"), filepath.Base(p.path)), params...) build = exec.Command(filepath.Join(getEnvPath("GOBIN"), filepath.Base(p.path)), args...)
} else if _, err := os.Stat(filepath.Join(os.Getenv("GOBIN"), filepath.Base(p.path)) + ".exe"); err == nil { } else if _, err := os.Stat(filepath.Join(getEnvPath("GOBIN"), filepath.Base(p.path)) + ".exe"); err == nil {
build = exec.Command(filepath.Join(os.Getenv("GOBIN"), filepath.Base(p.path))+".exe", params...) build = exec.Command(filepath.Join(getEnvPath("GOBIN"), filepath.Base(p.path))+".exe", args...)
} else { } else {
p.Buffer.StdLog = append(p.Buffer.StdLog, BufferOut{Time: time.Now(), Text: "Can't run a not compiled project"}) p.Buffer.StdLog = append(p.Buffer.StdLog, BufferOut{Time: time.Now(), Text: "Can't run a not compiled project"})
p.Fatal(err, "Can't run a not compiled project", ":") p.Fatal(err, "Can't run a not compiled project", ":")
@ -70,18 +83,16 @@ func (p *Project) goRun(channel chan bool, runner chan bool, wr *sync.WaitGroup)
stopOutput, stopError := make(chan bool, 1), make(chan bool, 1) stopOutput, stopError := make(chan bool, 1), make(chan bool, 1)
scanner := func(stop chan bool, output *bufio.Scanner, isError bool) { scanner := func(stop chan bool, output *bufio.Scanner, isError bool) {
for output.Scan() { for output.Scan() {
select { text := output.Text()
default: msg := fmt.Sprintln(p.pname(p.Name, 3), ":", style.Blue.Regular(text))
msg := fmt.Sprintln(p.pname(p.Name, 3), ":", style.Blue.Regular(output.Text())) if isError || isErrorText(text) {
if isError { out := BufferOut{Time: time.Now(), Text: text, Type: "Go Run"}
out := BufferOut{Time: time.Now(), Text: output.Text(), Type: "Go Run"}
p.print("error", out, msg, "") p.print("error", out, msg, "")
} else { } else {
out := BufferOut{Time: time.Now(), Text: output.Text()} out := BufferOut{Time: time.Now(), Text: text}
p.print("out", out, msg, "") p.print("out", out, msg, "")
} }
} }
}
close(stop) close(stop)
} }
go scanner(stopOutput, execOutput, false) go scanner(stopOutput, execOutput, false)
@ -102,7 +113,12 @@ func (p *Project) goRun(channel chan bool, runner chan bool, wr *sync.WaitGroup)
func (p *Project) goBuild() (string, error) { func (p *Project) goBuild() (string, error) {
var out bytes.Buffer var out bytes.Buffer
var stderr bytes.Buffer var stderr bytes.Buffer
build := exec.Command("go", "build") args := []string{"build"}
for _, arg := range p.Cmds.Build.Args {
arr := strings.Fields(arg)
args = append(args, arr...)
}
build := exec.Command("go", args...)
build.Dir = p.base build.Dir = p.base
build.Stdout = &out build.Stdout = &out
build.Stderr = &stderr build.Stderr = &stderr
@ -116,11 +132,16 @@ func (p *Project) goBuild() (string, error) {
func (p *Project) goInstall() (string, error) { func (p *Project) goInstall() (string, error) {
var out bytes.Buffer var out bytes.Buffer
var stderr bytes.Buffer var stderr bytes.Buffer
err := os.Setenv("GOBIN", filepath.Join(os.Getenv("GOPATH"), "bin")) err := os.Setenv("GOBIN", filepath.Join(getEnvPath("GOPATH"), "bin"))
if err != nil { if err != nil {
return "", err return "", err
} }
build := exec.Command("go", "install") args := []string{"install"}
for _, arg := range p.Cmds.Bin.Args {
arr := strings.Fields(arg)
args = append(args, arr...)
}
build := exec.Command("go", args...)
build.Dir = p.base build.Dir = p.base
build.Stdout = &out build.Stdout = &out
build.Stderr = &stderr build.Stderr = &stderr

View File

@ -1,11 +1,10 @@
package watcher package watcher
import ( import (
"github.com/tockins/realize/settings"
"log" "log"
"sync" "sync"
"time" "time"
"github.com/tockins/realize/settings"
) )
var wg sync.WaitGroup var wg sync.WaitGroup
@ -21,8 +20,7 @@ type pollWatcher struct {
} }
// Log struct // Log struct
type logWriter struct { type logWriter struct{}
}
// Blueprint struct contains a projects list // Blueprint struct contains a projects list
type Blueprint struct { type Blueprint struct {
@ -38,18 +36,42 @@ type Project struct {
base string base string
Name string `yaml:"name" json:"name"` Name string `yaml:"name" json:"name"`
Path string `yaml:"path" json:"path"` Path string `yaml:"path" json:"path"`
Fmt bool `yaml:"fmt" json:"fmt"` Cmds Cmds `yaml:"commands" json:"commands"`
Generate bool `yaml:"generate" json:"generate"` Args []string `yaml:"args,omitempty" json:"args,omitempty"`
Test bool `yaml:"test" json:"test"`
Bin bool `yaml:"bin" json:"bin"`
Build bool `yaml:"build" json:"build"`
Run bool `yaml:"run" json:"run"`
Params []string `yaml:"params,omitempty" json:"params,omitempty"`
Watcher Watcher `yaml:"watcher" json:"watcher"` Watcher Watcher `yaml:"watcher" json:"watcher"`
Streams Streams `yaml:"streams" json:"streams"` Streams Streams `yaml:"streams,omitempty" json:"streams,omitempty"`
Buffer Buffer `yaml:"-" json:"buffer"` Buffer Buffer `yaml:"-" json:"buffer"`
ErrorOutputPattern string `yaml:"errorOutputPattern,omitempty" json:"errorOutputPattern,omitempty"`
parent *Blueprint parent *Blueprint
path string path string
tools tools
}
type tools struct {
Fmt, Test, Generate, Vet tool
}
type tool struct {
status *bool
cmd string
options []string
name string
}
type Cmds struct {
Vet bool `yaml:"vet" json:"vet"`
Fmt bool `yaml:"fmt" json:"fmt"`
Test bool `yaml:"test" json:"test"`
Generate bool `yaml:"generate" json:"generate"`
Bin Cmd `yaml:"bin" json:"bin"`
Build Cmd `yaml:"build" json:"build"`
Run bool `yaml:"run" json:"run"`
}
// Buildmode options
type Cmd struct {
Status bool `yaml:"status" json:"status"`
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
} }
// Watcher struct defines the livereload's logic // Watcher struct defines the livereload's logic
@ -65,12 +87,13 @@ type Watcher struct {
type Command struct { type Command struct {
Type string `yaml:"type" json:"type"` Type string `yaml:"type" json:"type"`
Command string `yaml:"command" json:"command"` Command string `yaml:"command" json:"command"`
Path string `yaml:"path" json:"path"` Path string `yaml:"path,omitempty" json:"path,omitempty"`
Changed bool `yaml:"changed,omitempty" json:"changed,omitempty"`
Startup bool `yaml:"startup,omitempty" json:"startup,omitempty"`
} }
// Streams is a collection of names and values for the logs functionality // Streams is a collection of names and values for the logs functionality
type Streams struct { type Streams struct {
CliOut bool `yaml:"cli_out" json:"cli_out"`
FileOut bool `yaml:"file_out" json:"file_out"` FileOut bool `yaml:"file_out" json:"file_out"`
FileLog bool `yaml:"file_log" json:"file_log"` FileLog bool `yaml:"file_log" json:"file_log"`
FileErr bool `yaml:"file_err" json:"file_err"` FileErr bool `yaml:"file_err" json:"file_err"`

View File

@ -3,6 +3,8 @@ package watcher
import ( import (
"errors" "errors"
"fmt" "fmt"
"os"
"path/filepath"
"time" "time"
"github.com/tockins/realize/style" "github.com/tockins/realize/style"
@ -46,3 +48,13 @@ func inArray(str string, list []string) bool {
func (w logWriter) Write(bytes []byte) (int, error) { func (w logWriter) Write(bytes []byte) (int, error) {
return fmt.Print(style.Yellow.Regular("[") + time.Now().Format("15:04:05") + style.Yellow.Regular("]") + string(bytes)) return fmt.Print(style.Yellow.Regular("[") + time.Now().Format("15:04:05") + style.Yellow.Regular("]") + string(bytes))
} }
// getEnvPath returns the first path found in env or empty string
func getEnvPath(env string) string {
path := filepath.SplitList(os.Getenv(env))
if len(path) == 0 {
return ""
} else {
return path[0]
}
}

View File

@ -3,24 +3,25 @@ package watcher
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/fsnotify/fsnotify"
"github.com/tockins/realize/style"
"log" "log"
"math/big" "math/big"
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"reflect"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"syscall" "syscall"
"time" "time"
"github.com/fsnotify/fsnotify"
"github.com/tockins/realize/style"
) )
var msg string var msg string
var out BufferOut var out BufferOut
// Add a path to paths list
func (w *pollWatcher) Add(path string) error { func (w *pollWatcher) Add(path string) error {
if w.paths == nil { if w.paths == nil {
w.paths = map[string]bool{} w.paths = map[string]bool{}
@ -29,6 +30,7 @@ func (w *pollWatcher) Add(path string) error {
return nil return nil
} }
// Check if is watching
func (w *pollWatcher) isWatching(path string) bool { func (w *pollWatcher) isWatching(path string) bool {
a, b := w.paths[path] a, b := w.paths[path]
return a && b return a && b
@ -41,13 +43,9 @@ func (p *Project) watchByPolling() {
channel, exit := make(chan bool, 1), make(chan os.Signal, 2) channel, exit := make(chan bool, 1), make(chan os.Signal, 2)
signal.Notify(exit, os.Interrupt, syscall.SIGTERM) signal.Notify(exit, os.Interrupt, syscall.SIGTERM)
defer func() { defer func() {
p.cmd("after")
wg.Done() wg.Done()
}() }()
go p.routines(&wr, channel, watcher, "")
p.cmd("before")
p.Fatal(p.watch(watcher))
go p.routines(channel, &wr)
p.LastChangedOn = time.Now().Truncate(time.Second) p.LastChangedOn = time.Now().Truncate(time.Second)
walk := func(changed string, info os.FileInfo, err error) error { walk := func(changed string, info os.FileInfo, err error) error {
var ext string var ext string
@ -65,9 +63,8 @@ func (p *Project) watchByPolling() {
} }
i := strings.Index(changed, filepath.Ext(changed)) i := strings.Index(changed, filepath.Ext(changed))
file := changed[:i] + ext file := changed[:i] + ext
path := filepath.Dir(changed[:i])
if changed[:i] != "" && inArray(ext, p.Watcher.Exts) { if changed[:i] != "" && inArray(ext, p.Watcher.Exts) {
if p.Run { if p.Cmds.Run {
close(channel) close(channel)
channel = make(chan bool) channel = make(chan bool)
} }
@ -76,12 +73,7 @@ func (p *Project) watchByPolling() {
msg = fmt.Sprintln(p.pname(p.Name, 4), ":", style.Magenta.Bold(strings.ToUpper(ext[1:])+" changed"), style.Magenta.Bold(file)) 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} out = BufferOut{Time: time.Now(), Text: strings.ToUpper(ext[1:]) + " changed " + file}
p.print("log", out, msg, "") p.print("log", out, msg, "")
go p.routines(&wr, channel, watcher, file)
p.cmd("change")
p.fmt(file)
p.test(path)
p.generate(path)
go p.routines(channel, &wr)
} }
return nil return nil
} }
@ -101,6 +93,7 @@ func (p *Project) watchByPolling() {
} }
select { select {
case <-exit: case <-exit:
p.cmd("after", false)
return return
case <-time.After(p.parent.Legacy.Interval / time.Duration(len(p.Watcher.Paths))): case <-time.After(p.parent.Legacy.Interval / time.Duration(len(p.Watcher.Paths))):
} }
@ -117,13 +110,9 @@ func (p *Project) watchByNotify() {
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
p.Fatal(err) p.Fatal(err)
defer func() { defer func() {
p.cmd("after")
wg.Done() wg.Done()
}() }()
go p.routines(&wr, channel, watcher, "")
p.cmd("before")
p.Fatal(p.watch(watcher))
go p.routines(channel, &wr)
p.LastChangedOn = time.Now().Truncate(time.Second) p.LastChangedOn = time.Now().Truncate(time.Second)
for { for {
select { select {
@ -141,23 +130,17 @@ func (p *Project) watchByNotify() {
} }
i := strings.Index(event.Name, filepath.Ext(event.Name)) i := strings.Index(event.Name, filepath.Ext(event.Name))
file := event.Name[:i] + ext file := event.Name[:i] + ext
path := filepath.Dir(event.Name[:i])
if event.Name[:i] != "" && inArray(ext, p.Watcher.Exts) { if event.Name[:i] != "" && inArray(ext, p.Watcher.Exts) {
if p.Run { if p.Cmds.Run {
close(channel) close(channel)
channel = make(chan bool) channel = make(chan bool)
} }
p.LastChangedOn = time.Now().Truncate(time.Second)
// repeat the initial cycle // repeat the initial cycle
msg = fmt.Sprintln(p.pname(p.Name, 4), ":", style.Magenta.Bold(strings.ToUpper(ext[1:])+" changed"), style.Magenta.Bold(file)) 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} out = BufferOut{Time: time.Now(), Text: strings.ToUpper(ext[1:]) + " changed " + file}
p.print("log", out, msg, "") p.print("log", out, msg, "")
go p.routines(&wr, channel, watcher, file)
p.cmd("change") p.LastChangedOn = time.Now().Truncate(time.Second)
p.fmt(file)
p.test(path)
p.generate(path)
go p.routines(channel, &wr)
} }
} }
} }
@ -166,6 +149,7 @@ func (p *Project) watchByNotify() {
out = BufferOut{Time: time.Now(), Text: err.Error()} out = BufferOut{Time: time.Now(), Text: err.Error()}
p.print("error", out, msg, "") p.print("error", out, msg, "")
case <-exit: case <-exit:
p.cmd("after", false)
return return
} }
} }
@ -186,11 +170,12 @@ func (p *Project) watch(watcher watcher) error {
} }
if inArray(filepath.Ext(path), p.Watcher.Exts) { if inArray(filepath.Ext(path), p.Watcher.Exts) {
files++ files++
p.fmt(path) p.tool(path, p.tools.Fmt)
} else { } else {
folders++ folders++
p.generate(path) p.tool(path, p.tools.Vet)
p.test(path) p.tool(path, p.tools.Test)
p.tool(path, p.tools.Generate)
} }
} }
} }
@ -222,7 +207,7 @@ func (p *Project) watch(watcher watcher) error {
// Install calls an implementation of "go install" // Install calls an implementation of "go install"
func (p *Project) install() error { func (p *Project) install() error {
if p.Bin { if p.Cmds.Bin.Status {
start := time.Now() start := time.Now()
log.Println(p.pname(p.Name, 1), ":", "Installing..") log.Println(p.pname(p.Name, 1), ":", "Installing..")
stream, err := p.goInstall() stream, err := p.goInstall()
@ -242,7 +227,7 @@ func (p *Project) install() error {
// Install calls an implementation of "go run" // Install calls an implementation of "go run"
func (p *Project) run(channel chan bool, wr *sync.WaitGroup) { func (p *Project) run(channel chan bool, wr *sync.WaitGroup) {
if p.Run { if p.Cmds.Run {
start := time.Now() start := time.Now()
runner := make(chan bool, 1) runner := make(chan bool, 1)
log.Println(p.pname(p.Name, 1), ":", "Running..") log.Println(p.pname(p.Name, 1), ":", "Running..")
@ -250,8 +235,8 @@ func (p *Project) run(channel chan bool, wr *sync.WaitGroup) {
for { for {
select { select {
case <-runner: case <-runner:
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Regular("Has been run")+" after", style.Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s")) 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: "Has been run after " + 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"}
p.print("log", out, msg, "") p.print("log", out, msg, "")
return return
} }
@ -261,7 +246,7 @@ func (p *Project) run(channel chan bool, wr *sync.WaitGroup) {
// Build calls an implementation of the "go build" // Build calls an implementation of the "go build"
func (p *Project) build() error { func (p *Project) build() error {
if p.Build { if p.Cmds.Build.Status {
start := time.Now() start := time.Now()
log.Println(p.pname(p.Name, 1), ":", "Building..") log.Println(p.pname(p.Name, 1), ":", "Building..")
stream, err := p.goBuild() stream, err := p.goBuild()
@ -270,8 +255,8 @@ func (p *Project) build() error {
out = BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Build", Stream: stream} out = BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Build", Stream: stream}
p.print("error", out, msg, stream) p.print("error", out, msg, stream)
} else { } else {
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Regular("Builded")+" after", style.Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s")) 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: "Builded after " + 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"}
p.print("log", out, msg, stream) p.print("log", out, msg, stream)
} }
return err return err
@ -279,51 +264,32 @@ func (p *Project) build() error {
return nil return nil
} }
// Fmt calls an implementation of the "go fmt" func (p *Project) tool(path string, tool tool) error {
func (p *Project) fmt(path string) error { if tool.status != nil {
if p.Fmt && strings.HasSuffix(path, ".go") { v := reflect.ValueOf(tool.status).Elem()
if stream, err := p.goTools(p.base, "gofmt", "-s", "-w", "-e", path); err != nil { if v.Interface().(bool) && (strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "")) {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold("Go Fmt"), style.Red.Regular("there are some errors in"), ":", style.Magenta.Bold(path)) if strings.HasSuffix(path, ".go") {
out = BufferOut{Time: time.Now(), Text: "there are some errors in", Path: path, Type: "Go Fmt", Stream: stream} tool.options = append(tool.options, path)
path = p.base
}
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}
p.print("error", out, msg, stream) p.print("error", out, msg, stream)
return err return err
} }
} }
return nil
}
// Generate calls an implementation of the "go generate"
func (p *Project) generate(path string) error {
if p.Generate {
if stream, err := p.goTools(path, "go", "generate"); err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold("Go Generate"), 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: "Go Generate", Stream: stream}
p.print("error", out, msg, stream)
return err
}
}
return nil
}
// Test calls an implementation of the "go test"
func (p *Project) test(path string) error {
if p.Test {
if stream, err := p.goTools(path, "go", "test"); err != nil {
msg = fmt.Sprintln(p.pname(p.Name, 2), ":", style.Red.Bold("Go Test"), 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: "Go Test", Stream: stream}
p.print("error", out, msg, stream)
return err
}
} }
return nil return nil
} }
// Cmd calls an wrapper for execute the commands after/before // Cmd calls an wrapper for execute the commands after/before
func (p *Project) cmd(flag string) { func (p *Project) cmd(flag string, changed bool) {
for _, cmd := range p.Watcher.Scripts { for _, cmd := range p.Watcher.Scripts {
if strings.ToLower(cmd.Type) == flag { if strings.ToLower(cmd.Type) == flag{
if changed && cmd.Changed || !changed && cmd.Startup {
errors, logs := p.command(cmd) errors, logs := p.command(cmd)
msg = fmt.Sprintln(p.pname(p.Name, 5), ":", style.Green.Bold("Command"), style.Green.Bold("\"")+cmd.Command+style.Green.Bold("\"")) 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} out = BufferOut{Time: time.Now(), Text: cmd.Command, Type: flag}
if logs != "" { if logs != "" {
p.print("log", out, msg, "") p.print("log", out, msg, "")
@ -343,6 +309,7 @@ func (p *Project) cmd(flag string) {
} }
} }
} }
}
} }
// Ignore and validate a path // Ignore and validate a path
@ -356,7 +323,18 @@ func (p *Project) ignore(str string) bool {
} }
// Routines launches the toolchain run, build, install // Routines launches the toolchain run, build, install
func (p *Project) routines(channel chan bool, wr *sync.WaitGroup) { func (p *Project) routines(wr *sync.WaitGroup,channel chan bool, watcher watcher, file string) {
if len(file) > 0 {
p.cmd("before", true)
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)
} else {
p.cmd("before", false)
p.Fatal(p.watch(watcher))
}
install := p.install() install := p.install()
build := p.build() build := p.build()
wr.Add(1) wr.Add(1)
@ -364,6 +342,10 @@ func (p *Project) routines(channel chan bool, wr *sync.WaitGroup) {
go p.run(channel, wr) go p.run(channel, wr)
} }
wr.Wait() wr.Wait()
if len(file) > 0 {
p.cmd("after", true)
}
} }
// Defines the colors scheme for the project name // Defines the colors scheme for the project name
@ -401,9 +383,6 @@ func (p *Project) print(t string, o BufferOut, msg string, stream string) {
p.Fatal(err, "") p.Fatal(err, "")
} }
} }
if msg != "" && p.Streams.CliOut {
log.Print(msg)
}
case "log": case "log":
p.Buffer.StdLog = append(p.Buffer.StdLog, o) p.Buffer.StdLog = append(p.Buffer.StdLog, o)
if p.Streams.FileLog { if p.Streams.FileLog {