├── Dockerfile ├── docker-compose.yml ├── realize ├── settings_windows.go ├── settings_unix_test.go ├── server_test.go ├── utils_unix.go ├── settings_unix.go ├── utils_windows.go ├── tools_test.go ├── style.go ├── style_test.go ├── cli_test.go ├── utils_test.go ├── utils.go ├── schema.go ├── settings_test.go ├── schema_test.go ├── notify_test.go ├── cli.go ├── projects_test.go ├── settings.go ├── server.go ├── tools.go ├── notify.go └── projects.go ├── .travis.yml ├── .gitignore ├── go.mod ├── .realize.yaml ├── CONTRIBUTING.md ├── realize_test.go ├── go.sum ├── README.md ├── LICENSE └── realize.go /Dockerfile: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /realize/settings_windows.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package realize 4 | 5 | // Flimit defines the max number of watched files 6 | func (s *Settings) Flimit() error { 7 | return nil 8 | } 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.8.x 5 | - 1.9.x 6 | - tip 7 | matrix: 8 | allow_failures: 9 | - go: tip 10 | 11 | install: 12 | - go get ./... 13 | 14 | script: 15 | - go install . 16 | - go test -v ./... -------------------------------------------------------------------------------- /realize/settings_unix_test.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | package realize 4 | 5 | import ( 6 | "testing" 7 | ) 8 | 9 | func TestSettings_Flimit(t *testing.T) { 10 | s := Settings{} 11 | s.FileLimit = 100 12 | if err := s.Flimit(); err != nil { 13 | t.Error("Unable to increase limit", err) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /realize/server_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "runtime" 5 | "testing" 6 | ) 7 | 8 | func TestServer_Open(t *testing.T) { 9 | cmd := map[string]string{ 10 | "windows": "start", 11 | "darwin": "open", 12 | "linux": "xdg-open", 13 | } 14 | key := runtime.GOOS 15 | if _, ok := cmd[key]; !ok { 16 | t.Error("System not supported") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /realize/utils_unix.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | package realize 4 | 5 | import "strings" 6 | 7 | // isHidden check if a file or a path is hidden 8 | func isHidden(path string) bool { 9 | arr := strings.Split(path[len(Wdir()):], "/") 10 | for _, elm := range arr { 11 | if strings.HasPrefix(elm, ".") { 12 | return true 13 | } 14 | } 15 | return false 16 | } 17 | -------------------------------------------------------------------------------- /realize/settings_unix.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | package realize 4 | 5 | import "syscall" 6 | 7 | // Flimit defines the max number of watched files 8 | func (s *Settings) Flimit() error { 9 | var rLimit syscall.Rlimit 10 | rLimit.Max = uint64(s.FileLimit) 11 | rLimit.Cur = uint64(s.FileLimit) 12 | 13 | return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 14 | } 15 | -------------------------------------------------------------------------------- /realize/utils_windows.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package realize 4 | 5 | import "syscall" 6 | 7 | // isHidden check if a file or a path is hidden 8 | func isHidden(path string) bool { 9 | p, e := syscall.UTF16PtrFromString(path) 10 | if e != nil { 11 | return false 12 | } 13 | attrs, e := syscall.GetFileAttributes(p) 14 | if e != nil { 15 | return false 16 | } 17 | return attrs&syscall.FILE_ATTRIBUTE_HIDDEN != 0 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | .glide 27 | .idea 28 | .DS_Store 29 | .realize 30 | 31 | realize/assets/* 32 | docker 33 | vendor 34 | bin 35 | glide.* 36 | Dockerfile 37 | docker-compose.yml 38 | -------------------------------------------------------------------------------- /realize/tools_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import "testing" 4 | 5 | func TestTools_Setup(t *testing.T) { 6 | tools := Tools{ 7 | Clean: Tool{ 8 | Status: true, 9 | name: "test", 10 | isTool: false, 11 | Method: "test", 12 | Args: []string{"arg"}, 13 | }, 14 | } 15 | tools.Setup() 16 | if tools.Clean.name == "test" { 17 | t.Error("Unexpected value") 18 | } 19 | if tools.Clean.Method != "test" { 20 | t.Error("Unexpected value") 21 | } 22 | if !tools.Clean.isTool { 23 | t.Error("Unexpected value") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/oxequa/realize 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect 7 | github.com/fatih/color v1.9.0 8 | github.com/fsnotify/fsnotify v1.4.9 9 | github.com/labstack/echo v3.3.10+incompatible 10 | github.com/labstack/gommon v0.3.0 // indirect 11 | github.com/oxequa/interact v0.0.0-20171114182912-f8fb5795b5d7 12 | github.com/sirupsen/logrus v1.5.0 13 | github.com/urfave/cli/v2 v2.2.0 14 | github.com/valyala/fasttemplate v1.1.0 // indirect 15 | golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 16 | gopkg.in/yaml.v2 v2.2.8 17 | ) 18 | -------------------------------------------------------------------------------- /realize/style.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "github.com/fatih/color" 5 | ) 6 | 7 | var ( 8 | //Output writer 9 | Output = color.Output 10 | // Red color 11 | Red = colorBase(color.FgHiRed) 12 | // Blue color 13 | Blue = colorBase(color.FgHiBlue) 14 | // Green color 15 | Green = colorBase(color.FgHiGreen) 16 | // Yellow color 17 | Yellow = colorBase(color.FgHiYellow) 18 | // Magenta color 19 | Magenta = colorBase(color.FgHiMagenta) 20 | ) 21 | 22 | // ColorBase type 23 | type colorBase color.Attribute 24 | 25 | // Regular font with a color 26 | func (c colorBase) Regular(a ...interface{}) string { 27 | return color.New(color.Attribute(c)).Sprint(a...) 28 | } 29 | 30 | // Bold font with a color 31 | func (c colorBase) Bold(a ...interface{}) string { 32 | return color.New(color.Attribute(c), color.Bold).Sprint(a...) 33 | } 34 | -------------------------------------------------------------------------------- /realize/style_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/fatih/color" 7 | "testing" 8 | ) 9 | 10 | func TestStyle_Regular(t *testing.T) { 11 | strs := []string{"a", "b", "c"} 12 | input := make([]interface{}, len(strs)) 13 | for i, s := range strs { 14 | input[i] = s 15 | } 16 | result := Red.Regular(input) 17 | c := color.New(color.FgHiRed).SprintFunc() 18 | expected := fmt.Sprint(c(input)) 19 | if !bytes.Equal([]byte(result), []byte(expected)) { 20 | t.Error("Expected:", expected, "instead", result) 21 | } 22 | } 23 | 24 | func TestStyle_Bold(t *testing.T) { 25 | strs := []string{"a", "b", "c"} 26 | input := make([]interface{}, len(strs)) 27 | for i, s := range strs { 28 | input[i] = s 29 | } 30 | result := Red.Bold(input) 31 | c := color.New(color.FgHiRed, color.Bold).SprintFunc() 32 | expected := fmt.Sprint(c(input)) 33 | if !bytes.Equal([]byte(result), []byte(expected)) { 34 | t.Error("Expected:", expected, "instead", result) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /.realize.yaml: -------------------------------------------------------------------------------- 1 | settings: 2 | recovery: 3 | index: true # print files indexing 4 | events: false # print each event 5 | tools: false # print each tool 6 | legacy: 7 | force: false # enable polling watcher 8 | interval: 0s # polling interval 9 | server: 10 | status: false # web panel 11 | open: true # open in default browser 12 | port: 3000 # server port 13 | host: localhost # server host 14 | schema: 15 | - name: realize # project name 16 | path: . # project path, '.' is for wdir path 17 | commands: # all go commands supported 18 | generate: # go generate 19 | status: true 20 | install: # go install 21 | status: true 22 | vet: # go vet 23 | status: true 24 | test: # go test 25 | status: true 26 | fmt: # go fmt 27 | status: true 28 | watcher: 29 | paths: # paths watched 30 | - / 31 | extensions: # extensions watched 32 | - go 33 | - html 34 | - css 35 | - js 36 | ignored_paths: # paths ignored 37 | - .git 38 | - .realize 39 | - .idea 40 | - vendor 41 | - realize/assets 42 | - realize/bindata.go 43 | -------------------------------------------------------------------------------- /realize/cli_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "os" 7 | "strings" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | func TestRealize_Stop(t *testing.T) { 13 | r := Realize{} 14 | r.Projects = append(r.Schema.Projects, Project{exit: make(chan os.Signal, 1)}) 15 | r.Stop() 16 | _, ok := <-r.Projects[0].exit 17 | if ok != false { 18 | t.Error("Unexpected error", "channel should be closed") 19 | } 20 | } 21 | 22 | func TestRealize_Start(t *testing.T) { 23 | r := Realize{} 24 | err := r.Start() 25 | if err == nil { 26 | t.Error("Error expected") 27 | } 28 | r.Projects = append(r.Projects, Project{Name: "test", exit: make(chan os.Signal, 1)}) 29 | go func() { 30 | time.Sleep(100) 31 | close(r.Projects[0].exit) 32 | _, ok := <-r.Projects[0].exit 33 | if ok != false { 34 | t.Error("Unexpected error", "channel should be closed") 35 | } 36 | }() 37 | err = r.Start() 38 | if err != nil { 39 | t.Error("Unexpected error", err) 40 | } 41 | } 42 | 43 | func TestRealize_Prefix(t *testing.T) { 44 | r := Realize{} 45 | input := "test" 46 | result := r.Prefix(input) 47 | if len(result) == 0 && !strings.Contains(result, input) { 48 | t.Error("Unexpected error") 49 | } 50 | } 51 | 52 | func TestLogWriter_Write(t *testing.T) { 53 | var buf bytes.Buffer 54 | log.SetOutput(&buf) 55 | w := LogWriter{} 56 | input := "" 57 | val, err := w.Write([]byte(input)) 58 | if err != nil || val > 0 { 59 | t.Error("Unexpected error", err, "string length should be 0 instead", val) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Realize 2 | 3 | :+1: First off, thanks for taking the time to contribute! :+1: 4 | 5 | The following is a set of guidelines for contributing to this node package. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | #### Table Of Contents 8 | 9 | [Code of Conduct](#code-of-conduct) 10 | 11 | [How Can I Contribute?](#how-can-i-contribute) 12 | 13 | ## Code of Conduct 14 | This project and everyone participating in it is governed by following best pratices: 15 | 16 | * Using welcoming and inclusive language 17 | * Being respectful of differing viewpoints and experiences 18 | * Gracefully accepting constructive criticism 19 | * Focusing on what is best for the community 20 | * Showing empathy towards other community members 21 | 22 | Examples of unacceptable behavior by participants include: 23 | 24 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 25 | * Trolling, insulting/derogatory comments, and personal or political attacks 26 | * Public or private harassment 27 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 28 | * Other conduct which could reasonably be considered inappropriate in a professional setting 29 | 30 | By participating, you are expected to uphold this code. Please report unacceptable behavior. 31 | 32 | ## How Can I Contribute? 33 | * Report Bugs 34 | * Suggest Features 35 | * Make Pull Requests 36 | * Give a star :star: to the project 37 | -------------------------------------------------------------------------------- /realize/utils_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "flag" 5 | "github.com/urfave/cli/v2" 6 | "os" 7 | "path/filepath" 8 | "testing" 9 | ) 10 | 11 | func TestParams(t *testing.T) { 12 | set := flag.NewFlagSet("test", 0) 13 | set.Bool("myflag", false, "doc") 14 | p := cli.NewContext(nil, set, nil) 15 | set.Parse([]string{"--myflag", "bat", "baz"}) 16 | result := params(p) 17 | if len(result) != 2 { 18 | t.Fatal("Expected 2 instead", len(result)) 19 | } 20 | } 21 | 22 | func TestDuplicates(t *testing.T) { 23 | projects := []Project{ 24 | { 25 | Name: "a", 26 | Path: "a", 27 | }, { 28 | Name: "a", 29 | Path: "a", 30 | }, { 31 | Name: "c", 32 | Path: "c", 33 | }, 34 | } 35 | _, err := duplicates(projects[0], projects) 36 | if err == nil { 37 | t.Fatal("Error unexpected", err) 38 | } 39 | _, err = duplicates(Project{}, projects) 40 | if err != nil { 41 | t.Fatal("Error unexpected", err) 42 | } 43 | 44 | } 45 | 46 | func TestWdir(t *testing.T) { 47 | expected, err := os.Getwd() 48 | if err != nil { 49 | t.Error(err) 50 | } 51 | result := Wdir() 52 | if result != expected { 53 | t.Error("Expected", filepath.Base(expected), "instead", result) 54 | } 55 | } 56 | 57 | func TestExt(t *testing.T) { 58 | paths := map[string]string{ 59 | "/test/a/b/c": "", 60 | "/test/a/ac.go": "go", 61 | "/test/a/ac.test.go": "go", 62 | "/test/a/ac_test.go": "go", 63 | "/test/./ac_test.go": "go", 64 | "/test/a/.test": "test", 65 | "/test/a/.": "", 66 | } 67 | for i, v := range paths { 68 | if ext(i) != v { 69 | t.Error("Wrong extension", ext(i), v) 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /realize/utils.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "os" 7 | "path" 8 | "strings" 9 | 10 | "github.com/urfave/cli/v2" 11 | ) 12 | 13 | // Params parse one by one the given argumentes 14 | func params(params *cli.Context) []string { 15 | argsN := params.NArg() 16 | if argsN > 0 { 17 | var args []string 18 | for i := 0; i <= argsN-1; i++ { 19 | args = append(args, params.Args().Get(i)) 20 | } 21 | return args 22 | } 23 | return nil 24 | } 25 | 26 | // Split each arguments in multiple fields 27 | func split(args, fields []string) []string { 28 | for _, arg := range fields { 29 | arr := strings.Fields(arg) 30 | args = append(args, arr...) 31 | } 32 | return args 33 | } 34 | 35 | // Duplicates check projects with same name or same combinations of main/path 36 | func duplicates(value Project, arr []Project) (Project, error) { 37 | for _, val := range arr { 38 | if value.Name == val.Name { 39 | return val, errors.New("There is already a project with name '" + val.Name + "'. Check your config file!") 40 | } 41 | } 42 | return Project{}, nil 43 | } 44 | 45 | // Get file extensions 46 | func ext(path string) string { 47 | var ext string 48 | for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- { 49 | if path[i] == '.' { 50 | ext = path[i:] 51 | if index := strings.LastIndex(ext, "."); index > 0 { 52 | ext = ext[index:] 53 | } 54 | } 55 | } 56 | if ext != "" { 57 | return ext[1:] 58 | } 59 | return "" 60 | } 61 | 62 | // Replace if isn't empty and create a new array 63 | func replace(a []string, b string) []string { 64 | if len(b) > 0 { 65 | return strings.Fields(b) 66 | } 67 | return a 68 | } 69 | 70 | // Wdir return current working directory 71 | func Wdir() string { 72 | dir, err := os.Getwd() 73 | if err != nil { 74 | log.Fatal(err.Error()) 75 | } 76 | return dir 77 | } 78 | 79 | func hasGoMod(dir string) bool { 80 | filename := path.Join(dir, "go.mod") 81 | if _, err := os.Stat(filename); os.IsNotExist(err) { 82 | return false 83 | } 84 | 85 | return true 86 | } 87 | -------------------------------------------------------------------------------- /realize/schema.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "errors" 5 | "path/filepath" 6 | "reflect" 7 | 8 | "github.com/urfave/cli/v2" 9 | ) 10 | 11 | // Schema projects list 12 | type Schema struct { 13 | Projects []Project `yaml:"schema" json:"schema"` 14 | } 15 | 16 | // Add a project if unique 17 | func (s *Schema) Add(p Project) { 18 | for _, val := range s.Projects { 19 | if reflect.DeepEqual(val, p) { 20 | return 21 | } 22 | } 23 | s.Projects = append(s.Projects, p) 24 | } 25 | 26 | // Remove a project 27 | func (s *Schema) Remove(name string) error { 28 | for key, val := range s.Projects { 29 | if name == val.Name { 30 | s.Projects = append(s.Projects[:key], s.Projects[key+1:]...) 31 | return nil 32 | } 33 | } 34 | return errors.New("project not found") 35 | } 36 | 37 | // New create a project using cli fields 38 | func (s *Schema) New(c *cli.Context) Project { 39 | var vgo bool 40 | name := filepath.Base(c.String("path")) 41 | if len(name) == 0 || name == "." { 42 | name = filepath.Base(Wdir()) 43 | } 44 | 45 | if hasGoMod(Wdir()) { 46 | vgo = true 47 | } 48 | 49 | project := Project{ 50 | Name: name, 51 | Path: c.String("path"), 52 | Tools: Tools{ 53 | Vet: Tool{ 54 | Status: c.Bool("vet"), 55 | }, 56 | Fmt: Tool{ 57 | Status: c.Bool("fmt"), 58 | }, 59 | Test: Tool{ 60 | Status: c.Bool("test"), 61 | }, 62 | Generate: Tool{ 63 | Status: c.Bool("generate"), 64 | }, 65 | Build: Tool{ 66 | Status: c.Bool("build"), 67 | }, 68 | Install: Tool{ 69 | Status: c.Bool("install"), 70 | }, 71 | Run: Tool{ 72 | Status: c.Bool("run"), 73 | }, 74 | vgo: vgo, 75 | }, 76 | Args: params(c), 77 | Watcher: Watch{ 78 | Paths: []string{"/"}, 79 | Ignore: []string{".git", ".realize", "vendor"}, 80 | Exts: []string{"go"}, 81 | }, 82 | } 83 | return project 84 | } 85 | 86 | // Filter project list by field 87 | func (s *Schema) Filter(field string, value interface{}) []Project { 88 | result := []Project{} 89 | for _, item := range s.Projects { 90 | v := reflect.ValueOf(item) 91 | for i := 0; i < v.NumField(); i++ { 92 | if v.Type().Field(i).Name == field { 93 | if reflect.DeepEqual(v.Field(i).Interface(), value) { 94 | result = append(result, item) 95 | } 96 | } 97 | } 98 | } 99 | return result 100 | } 101 | -------------------------------------------------------------------------------- /realize/settings_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "io/ioutil" 5 | "math/rand" 6 | "os" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | // Rand is used for generate a random string 12 | func random(n int) string { 13 | src := rand.NewSource(time.Now().UnixNano()) 14 | b := make([]byte, n) 15 | for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { 16 | if remain == 0 { 17 | cache, remain = src.Int63(), letterIdxMax 18 | } 19 | if idx := int(cache & letterIdxMask); idx < len(letterBytes) { 20 | b[i] = letterBytes[idx] 21 | i-- 22 | } 23 | cache >>= letterIdxBits 24 | remain-- 25 | } 26 | return string(b) 27 | } 28 | 29 | func TestSettings_Stream(t *testing.T) { 30 | s := Settings{} 31 | filename := random(4) 32 | if _, err := s.Stream(filename); err == nil { 33 | t.Fatal("Error expected, none found", filename, err) 34 | } 35 | 36 | filename = "settings.go" 37 | if _, err := s.Stream(filename); err != nil { 38 | t.Fatal("Error unexpected", filename, err) 39 | } 40 | } 41 | 42 | func TestSettings_Remove(t *testing.T) { 43 | s := Settings{} 44 | if err := s.Remove("abcd"); err == nil { 45 | t.Fatal("Error unexpected, dir dosn't exist", err) 46 | } 47 | 48 | d, err := ioutil.TempDir("", "settings_test") 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | if err := s.Remove(d); err != nil { 53 | t.Fatal("Error unexpected, dir exist", err) 54 | } 55 | } 56 | 57 | func TestSettings_Write(t *testing.T) { 58 | s := Settings{} 59 | data := "abcdefgh" 60 | d, err := ioutil.TempFile("", "io_test") 61 | if err != nil { 62 | t.Fatal(err) 63 | } 64 | RFile = d.Name() 65 | if err := s.Write([]byte(data)); err != nil { 66 | t.Fatal(err) 67 | } 68 | } 69 | 70 | func TestSettings_Read(t *testing.T) { 71 | s := Settings{} 72 | var a interface{} 73 | RFile = "settings_b" 74 | if err := s.Read(a); err == nil { 75 | t.Fatal("Error unexpected", err) 76 | } 77 | RFile = "settings_test.yaml" 78 | d, err := ioutil.TempFile("", "settings_test.yaml") 79 | if err != nil { 80 | t.Fatal(err) 81 | } 82 | RFile = d.Name() 83 | if err := s.Read(a); err != nil { 84 | t.Fatal("Error unexpected", err) 85 | } 86 | } 87 | 88 | func TestSettings_Fatal(t *testing.T) { 89 | s := Settings{} 90 | s.Fatal(nil, "test") 91 | } 92 | 93 | func TestSettings_Create(t *testing.T) { 94 | s := Settings{} 95 | p, err := os.Getwd() 96 | if err != nil { 97 | t.Fatal(err) 98 | } 99 | f := s.Create(p, "io_test") 100 | os.Remove(f.Name()) 101 | } 102 | -------------------------------------------------------------------------------- /realize/schema_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "flag" 5 | "github.com/urfave/cli/v2" 6 | "path/filepath" 7 | "testing" 8 | ) 9 | 10 | func TestSchema_Add(t *testing.T) { 11 | r := Realize{} 12 | p := Project{Name: "test"} 13 | r.Add(p) 14 | if len(r.Schema.Projects) != 1 { 15 | t.Error("Unexpected error there are", len(r.Schema.Projects), "instead one") 16 | } 17 | r.Add(p) 18 | if len(r.Schema.Projects) != 1 { 19 | t.Error("Unexpected error there are", len(r.Schema.Projects), "instead one") 20 | } 21 | r.Add(Project{Name: "testing"}) 22 | if len(r.Schema.Projects) != 2 { 23 | t.Error("Unexpected error there are", len(r.Schema.Projects), "instead two") 24 | } 25 | } 26 | 27 | func TestSchema_Remove(t *testing.T) { 28 | r := Realize{} 29 | r.Schema.Projects = []Project{ 30 | { 31 | Name: "test", 32 | }, { 33 | Name: "testing", 34 | }, { 35 | Name: "testing", 36 | }, 37 | } 38 | r.Remove("testing") 39 | if len(r.Schema.Projects) != 2 { 40 | t.Error("Unexpected errore there are", len(r.Schema.Projects), "instead one") 41 | } 42 | } 43 | 44 | func TestSchema_New(t *testing.T) { 45 | r := Realize{} 46 | set := flag.NewFlagSet("test", 0) 47 | set.Bool("fmt", false, "") 48 | set.Bool("vet", false, "") 49 | set.Bool("test", false, "") 50 | set.Bool("install", false, "") 51 | set.Bool("run", false, "") 52 | set.Bool("build", false, "") 53 | set.Bool("generate", false, "") 54 | set.String("path", "", "") 55 | c := cli.NewContext(nil, set, nil) 56 | set.Parse([]string{"--fmt", "--install", "--run", "--build", "--generate", "--test", "--vet"}) 57 | p := r.New(c) 58 | if p.Name != filepath.Base(Wdir()) { 59 | t.Error("Unexpected error", p.Name, "instead", filepath.Base(Wdir())) 60 | } 61 | if !p.Tools.Install.Status { 62 | t.Error("Install should be enabled") 63 | } 64 | if !p.Tools.Fmt.Status { 65 | t.Error("Fmt should be enabled") 66 | } 67 | if !p.Tools.Run.Status { 68 | t.Error("Run should be enabled") 69 | } 70 | if !p.Tools.Build.Status { 71 | t.Error("Build should be enabled") 72 | } 73 | if !p.Tools.Generate.Status { 74 | t.Error("Generate should be enabled") 75 | } 76 | if !p.Tools.Test.Status { 77 | t.Error("Test should be enabled") 78 | } 79 | if !p.Tools.Vet.Status { 80 | t.Error("Vet should be enabled") 81 | } 82 | } 83 | 84 | func TestSchema_Filter(t *testing.T) { 85 | r := Realize{} 86 | r.Schema.Projects = []Project{ 87 | { 88 | Name: "test", 89 | }, { 90 | Name: "test", 91 | }, 92 | { 93 | Name: "example", 94 | }, 95 | } 96 | result := r.Filter("Name", "test") 97 | if len(result) != 2 { 98 | t.Error("Expected two project") 99 | } 100 | result = r.Filter("Name", "example") 101 | if len(result) != 1 { 102 | t.Error("Expected one project") 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /realize/notify_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "fmt" 5 | "github.com/fsnotify/fsnotify" 6 | "io/ioutil" 7 | "os" 8 | "runtime" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | const ( 14 | interval = 100 * time.Millisecond 15 | ) 16 | 17 | func TestPoller_AddRemove(t *testing.T) { 18 | w := PollingWatcher(interval) 19 | 20 | if err := w.Add("no-such-file"); err == nil { 21 | t.Fatal("should have gotten error when adding a non-existent file") 22 | } 23 | if err := w.Remove("no-such-file"); err == nil { 24 | t.Fatal("should have gotten error when removing non-existent watch") 25 | } 26 | 27 | f, err := ioutil.TempFile("", "asdf") 28 | if err != nil { 29 | t.Fatal(err) 30 | } 31 | defer os.RemoveAll(f.Name()) 32 | 33 | if err := w.Add(f.Name()); err != nil { 34 | t.Fatal(err) 35 | } 36 | 37 | if err := w.Remove(f.Name()); err != nil { 38 | t.Fatal(err) 39 | } 40 | } 41 | 42 | func TestPoller_Event(t *testing.T) { 43 | if runtime.GOOS == "windows" { 44 | t.Skip("No chmod on Windows") 45 | } 46 | w := PollingWatcher(interval) 47 | 48 | f, err := ioutil.TempFile("", "test-poller") 49 | if err != nil { 50 | t.Fatal("error creating temp file") 51 | } 52 | defer os.RemoveAll(f.Name()) 53 | f.Close() 54 | 55 | if err := w.Add(f.Name()); err != nil { 56 | t.Fatal(err) 57 | } 58 | 59 | select { 60 | case <-w.Events(): 61 | t.Fatal("got event before anything happened") 62 | case <-w.Errors(): 63 | t.Fatal("got error before anything happened") 64 | default: 65 | } 66 | 67 | if err := ioutil.WriteFile(f.Name(), []byte("hello"), 0644); err != nil { 68 | t.Fatal(err) 69 | } 70 | if err := assertEvent(w, fsnotify.Write); err != nil { 71 | t.Fatal(err) 72 | } 73 | 74 | if err := os.Chmod(f.Name(), 600); err != nil { 75 | t.Fatal(err) 76 | } 77 | if err := assertEvent(w, fsnotify.Chmod); err != nil { 78 | t.Fatal(err) 79 | } 80 | 81 | if err := os.Remove(f.Name()); err != nil { 82 | t.Fatal(err) 83 | } 84 | if err := assertEvent(w, fsnotify.Remove); err != nil { 85 | t.Fatal(err) 86 | } 87 | } 88 | 89 | func TestPoller_Close(t *testing.T) { 90 | w := PollingWatcher(interval) 91 | if err := w.Close(); err != nil { 92 | t.Fatal(err) 93 | } 94 | // test double-close 95 | if err := w.Close(); err != nil { 96 | t.Fatal(err) 97 | } 98 | 99 | f, err := ioutil.TempFile("", "asdf") 100 | if err != nil { 101 | t.Fatal(err) 102 | } 103 | defer os.RemoveAll(f.Name()) 104 | if err := w.Add(f.Name()); err == nil { 105 | t.Fatal("should have gotten error adding watch for closed watcher") 106 | } 107 | } 108 | 109 | func assertEvent(w FileWatcher, eType fsnotify.Op) error { 110 | var err error 111 | select { 112 | case e := <-w.Events(): 113 | if e.Op != eType { 114 | err = fmt.Errorf("got wrong event type, expected %q: %v", eType, e.Op) 115 | } 116 | case e := <-w.Errors(): 117 | err = fmt.Errorf("got unexpected error waiting for events %v: %v", eType, e) 118 | case <-time.After(time.Duration(1) * time.Second): 119 | err = fmt.Errorf("timeout waiting for event %v", eType) 120 | } 121 | return err 122 | } 123 | -------------------------------------------------------------------------------- /realize/cli.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "go/build" 7 | "log" 8 | "os" 9 | "os/signal" 10 | "path/filepath" 11 | "strings" 12 | "sync" 13 | "time" 14 | 15 | "github.com/fsnotify/fsnotify" 16 | ) 17 | 18 | var ( 19 | // RPrefix tool name 20 | RPrefix = "realize" 21 | // RVersion current version 22 | RVersion = "2.0.3" 23 | // RExt file extension 24 | RExt = ".yaml" 25 | // RFile config file name 26 | RFile = "." + RPrefix + RExt 27 | //RExtWin windows extension 28 | RExtWin = ".exe" 29 | ) 30 | 31 | type ( 32 | // LogWriter used for all log 33 | LogWriter struct{} 34 | 35 | // Realize main struct 36 | Realize struct { 37 | Settings Settings `yaml:"settings" json:"settings"` 38 | Server Server `yaml:"server,omitempty" json:"server,omitempty"` 39 | Schema `yaml:",inline" json:",inline"` 40 | Sync chan string `yaml:"-" json:"-"` 41 | Err Func `yaml:"-" json:"-"` 42 | After Func `yaml:"-" json:"-"` 43 | Before Func `yaml:"-" json:"-"` 44 | Change Func `yaml:"-" json:"-"` 45 | Reload Func `yaml:"-" json:"-"` 46 | } 47 | 48 | // Context is used as argument for func 49 | Context struct { 50 | Path string 51 | Project *Project 52 | Stop <-chan bool 53 | Watcher FileWatcher 54 | Event fsnotify.Event 55 | } 56 | 57 | // Func is used instead realize func 58 | Func func(Context) 59 | ) 60 | 61 | // init check 62 | func init() { 63 | // custom log 64 | log.SetFlags(0) 65 | log.SetOutput(LogWriter{}) 66 | if build.Default.GOPATH == "" { 67 | log.Fatal("$GOPATH isn't set properly") 68 | } 69 | path := filepath.SplitList(build.Default.GOPATH) 70 | if err := os.Setenv("GOBIN", filepath.Join(path[len(path)-1], "bin")); err != nil { 71 | log.Fatal(err) 72 | } 73 | } 74 | 75 | // Stop realize workflow 76 | func (r *Realize) Stop() error { 77 | for k := range r.Schema.Projects { 78 | if r.Schema.Projects[k].exit != nil { 79 | close(r.Schema.Projects[k].exit) 80 | } 81 | } 82 | return nil 83 | } 84 | 85 | // Start realize workflow 86 | func (r *Realize) Start() error { 87 | if len(r.Schema.Projects) > 0 { 88 | var wg sync.WaitGroup 89 | wg.Add(len(r.Schema.Projects)) 90 | for k := range r.Schema.Projects { 91 | r.Schema.Projects[k].exit = make(chan os.Signal, 1) 92 | signal.Notify(r.Schema.Projects[k].exit, os.Interrupt) 93 | r.Schema.Projects[k].parent = r 94 | go r.Schema.Projects[k].Watch(&wg) 95 | } 96 | wg.Wait() 97 | } else { 98 | return errors.New("there are no projects") 99 | } 100 | return nil 101 | } 102 | 103 | // Prefix a given string with tool name 104 | func (r *Realize) Prefix(input string) string { 105 | if len(input) > 0 { 106 | return fmt.Sprint(Yellow.Bold("["), strings.ToUpper(RPrefix), Yellow.Bold("]"), " : ", input) 107 | } 108 | return input 109 | } 110 | 111 | // Rewrite the layout of the log timestamp 112 | func (w LogWriter) Write(bytes []byte) (int, error) { 113 | if len(bytes) > 0 { 114 | return fmt.Fprint(Output, Yellow.Regular("["), time.Now().Format("15:04:05"), Yellow.Regular("]"), string(bytes)) 115 | } 116 | return 0, nil 117 | } 118 | -------------------------------------------------------------------------------- /realize_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "github.com/oxequa/realize/realize" 7 | "log" 8 | "strings" 9 | "testing" 10 | ) 11 | 12 | var mockResponse interface{} 13 | 14 | type mockRealize realize.Realize 15 | 16 | func (m *mockRealize) add() error { 17 | if mockResponse != nil { 18 | return mockResponse.(error) 19 | } 20 | m.Projects = append(m.Projects, realize.Project{Name: "One"}) 21 | return nil 22 | } 23 | 24 | func (m *mockRealize) setup() error { 25 | if mockResponse != nil { 26 | return mockResponse.(error) 27 | } 28 | return nil 29 | } 30 | 31 | func (m *mockRealize) start() error { 32 | if mockResponse != nil { 33 | return mockResponse.(error) 34 | } 35 | return nil 36 | } 37 | 38 | func (m *mockRealize) clean() error { 39 | if mockResponse != nil { 40 | return mockResponse.(error) 41 | } 42 | return nil 43 | } 44 | 45 | func (m *mockRealize) remove() error { 46 | if mockResponse != nil { 47 | return mockResponse.(error) 48 | } 49 | m.Projects = []realize.Project{} 50 | return nil 51 | } 52 | 53 | func TestRealize_add(t *testing.T) { 54 | m := mockRealize{} 55 | mockResponse = nil 56 | if err := m.add(); err != nil { 57 | t.Error("Unexpected error") 58 | } 59 | if len(m.Projects) == 0 { 60 | t.Error("Unexpected error") 61 | } 62 | 63 | m = mockRealize{} 64 | m.Projects = []realize.Project{{Name: "Default"}} 65 | mockResponse = nil 66 | if err := m.add(); err != nil { 67 | t.Error("Unexpected error") 68 | } 69 | if len(m.Projects) != 2 { 70 | t.Error("Unexpected error") 71 | } 72 | 73 | m = mockRealize{} 74 | mockResponse = errors.New("error") 75 | if err := m.clean(); err == nil { 76 | t.Error("Expected error") 77 | } 78 | if len(m.Projects) != 0 { 79 | t.Error("Unexpected error") 80 | } 81 | } 82 | 83 | func TestRealize_start(t *testing.T) { 84 | m := mockRealize{} 85 | mockResponse = nil 86 | if err := m.add(); err != nil { 87 | t.Error("Unexpected error") 88 | } 89 | } 90 | 91 | func TestRealize_setup(t *testing.T) { 92 | m := mockRealize{} 93 | mockResponse = nil 94 | if err := m.setup(); err != nil { 95 | t.Error("Unexpected error") 96 | } 97 | } 98 | 99 | func TestRealize_clean(t *testing.T) { 100 | m := mockRealize{} 101 | mockResponse = nil 102 | if err := m.clean(); err != nil { 103 | t.Error("Unexpected error") 104 | } 105 | mockResponse = errors.New("error") 106 | if err := m.clean(); err == nil { 107 | t.Error("Expected error") 108 | } 109 | } 110 | 111 | func TestRealize_remove(t *testing.T) { 112 | m := mockRealize{} 113 | mockResponse = nil 114 | if err := m.remove(); err != nil { 115 | t.Error("Unexpected error") 116 | } 117 | 118 | m = mockRealize{} 119 | mockResponse = nil 120 | m.Projects = []realize.Project{{Name: "Default"}, {Name: "Default"}} 121 | if err := m.remove(); err != nil { 122 | t.Error("Unexpected error") 123 | } 124 | if len(m.Projects) != 0 { 125 | t.Error("Unexpected error") 126 | } 127 | 128 | mockResponse = errors.New("error") 129 | if err := m.clean(); err == nil { 130 | t.Error("Expected error") 131 | } 132 | } 133 | 134 | func TestRealize_version(t *testing.T) { 135 | var buf bytes.Buffer 136 | log.SetOutput(&buf) 137 | version() 138 | if !strings.Contains(buf.String(), realize.RVersion) { 139 | t.Error("Version expted", realize.RVersion) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /realize/projects_test.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "github.com/fsnotify/fsnotify" 7 | "log" 8 | "os" 9 | "strings" 10 | "sync" 11 | "testing" 12 | "time" 13 | ) 14 | 15 | func TestProject_After(t *testing.T) /**/ { 16 | var buf bytes.Buffer 17 | log.SetOutput(&buf) 18 | r := Realize{} 19 | input := "text" 20 | r.After = func(context Context) { 21 | log.Println(input) 22 | } 23 | r.Projects = append(r.Projects, Project{ 24 | parent: &r, 25 | }) 26 | r.Projects[0].After() 27 | if !strings.Contains(buf.String(), input) { 28 | t.Error("Unexpected error") 29 | } 30 | } 31 | 32 | func TestProject_Before(t *testing.T) { 33 | var buf bytes.Buffer 34 | log.SetOutput(&buf) 35 | r := Realize{} 36 | r.Projects = append(r.Projects, Project{ 37 | parent: &r, 38 | }) 39 | input := "text" 40 | r.Before = func(context Context) { 41 | log.Println(input) 42 | } 43 | r.Projects[0].Before() 44 | if !strings.Contains(buf.String(), input) { 45 | t.Error("Unexpected error") 46 | } 47 | } 48 | 49 | func TestProject_Err(t *testing.T) { 50 | var buf bytes.Buffer 51 | log.SetOutput(&buf) 52 | r := Realize{} 53 | r.Projects = append(r.Projects, Project{ 54 | parent: &r, 55 | }) 56 | input := "text" 57 | r.Err = func(context Context) { 58 | log.Println(input) 59 | } 60 | r.Projects[0].Err(errors.New(input)) 61 | if !strings.Contains(buf.String(), input) { 62 | t.Error("Unexpected error") 63 | } 64 | } 65 | 66 | func TestProject_Change(t *testing.T) { 67 | var buf bytes.Buffer 68 | log.SetOutput(&buf) 69 | r := Realize{} 70 | r.Projects = append(r.Projects, Project{ 71 | parent: &r, 72 | }) 73 | r.Change = func(context Context) { 74 | log.Println(context.Event.Name) 75 | } 76 | event := fsnotify.Event{Name: "test", Op: fsnotify.Write} 77 | r.Projects[0].Change(event) 78 | if !strings.Contains(buf.String(), event.Name) { 79 | t.Error("Unexpected error") 80 | } 81 | } 82 | 83 | func TestProject_Reload(t *testing.T) { 84 | var buf bytes.Buffer 85 | log.SetOutput(&buf) 86 | r := Realize{} 87 | r.Projects = append(r.Projects, Project{ 88 | parent: &r, 89 | }) 90 | input := "test/path" 91 | r.Settings.Legacy.Force = false 92 | r.Settings.Legacy.Interval = 0 93 | r.Projects[0].watcher, _ = NewFileWatcher(r.Settings.Legacy) 94 | r.Reload = func(context Context) { 95 | log.Println(context.Path) 96 | } 97 | stop := make(chan bool) 98 | r.Projects[0].Reload(input, stop) 99 | if !strings.Contains(buf.String(), input) { 100 | t.Error("Unexpected error") 101 | } 102 | } 103 | 104 | func TestProject_Validate(t *testing.T) { 105 | data := map[string]bool{ 106 | "": false, 107 | "/test/.path/": true, 108 | "./test/path/": true, 109 | "/test/path/test.html": false, 110 | "/test/path/test.go": false, 111 | "/test/ignore/test.go": false, 112 | "/test/check/notexist.go": false, 113 | "/test/check/exist.go": false, 114 | } 115 | r := Realize{} 116 | r.Projects = append(r.Projects, Project{ 117 | parent: &r, 118 | Watcher: Watch{ 119 | Exts: []string{}, 120 | Ignore: []string{"/test/ignore"}, 121 | }, 122 | }) 123 | for i, v := range data { 124 | result := r.Projects[0].Validate(i, false) 125 | if result != v { 126 | t.Error("Unexpected error", i, "expected", v, result) 127 | } 128 | } 129 | } 130 | 131 | func TestProject_Watch(t *testing.T) { 132 | var wg sync.WaitGroup 133 | r := Realize{} 134 | r.Projects = append(r.Projects, Project{ 135 | parent: &r, 136 | exit: make(chan os.Signal, 1), 137 | }) 138 | go func() { 139 | time.Sleep(100) 140 | close(r.Projects[0].exit) 141 | }() 142 | wg.Add(1) 143 | // test before after and file change 144 | r.Projects[0].Watch(&wg) 145 | wg.Wait() 146 | } 147 | -------------------------------------------------------------------------------- /realize/settings.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "gopkg.in/yaml.v2" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | "path/filepath" 9 | "time" 10 | ) 11 | 12 | // settings const 13 | const ( 14 | Permission = 0775 15 | File = ".realize.yaml" 16 | FileOut = ".r.outputs.log" 17 | FileErr = ".r.errors.log" 18 | FileLog = ".r.logs.log" 19 | ) 20 | 21 | // random string preference 22 | const ( 23 | letterIdxBits = 6 // 6 bits to represent a letter index 24 | letterIdxMask = 1< 0 { 118 | log.Fatalln(Red.Regular(msg...), err.Error()) 119 | } else { 120 | log.Fatalln(err.Error()) 121 | } 122 | } 123 | } 124 | 125 | // Create a new file and return its pointer 126 | func (s Settings) Create(path string, name string) *os.File { 127 | file := filepath.Join(path, name) 128 | out, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY|os.O_CREATE|os.O_SYNC, Permission) 129 | s.Fatal(err) 130 | return out 131 | } 132 | -------------------------------------------------------------------------------- /realize/server.go: -------------------------------------------------------------------------------- 1 | //go:generate go-bindata -pkg=realize -o=bindata.go assets/... 2 | 3 | package realize 4 | 5 | import ( 6 | "bytes" 7 | "encoding/json" 8 | "errors" 9 | "fmt" 10 | "github.com/labstack/echo" 11 | "github.com/labstack/echo/middleware" 12 | "golang.org/x/net/websocket" 13 | "log" 14 | "net/http" 15 | "os/exec" 16 | "runtime" 17 | "strconv" 18 | ) 19 | 20 | // Dafault host and port 21 | const ( 22 | Host = "localhost" 23 | Port = 5002 24 | ) 25 | 26 | // Server settings 27 | type Server struct { 28 | Parent *Realize `yaml:"-" json:"-"` 29 | Status bool `yaml:"status" json:"status"` 30 | Open bool `yaml:"open" json:"open"` 31 | Port int `yaml:"port" json:"port"` 32 | Host string `yaml:"host" json:"host"` 33 | } 34 | 35 | // Websocket projects 36 | func (s *Server) projects(c echo.Context) (err error) { 37 | websocket.Handler(func(ws *websocket.Conn) { 38 | msg, _ := json.Marshal(s.Parent) 39 | err = websocket.Message.Send(ws, string(msg)) 40 | go func() { 41 | for { 42 | select { 43 | case <-s.Parent.Sync: 44 | msg, _ := json.Marshal(s.Parent) 45 | err = websocket.Message.Send(ws, string(msg)) 46 | if err != nil { 47 | break 48 | } 49 | } 50 | } 51 | }() 52 | for { 53 | // Read 54 | text := "" 55 | err = websocket.Message.Receive(ws, &text) 56 | if err != nil { 57 | break 58 | } else { 59 | err := json.Unmarshal([]byte(text), &s.Parent) 60 | if err == nil { 61 | s.Parent.Settings.Write(s.Parent) 62 | break 63 | } 64 | } 65 | } 66 | ws.Close() 67 | }).ServeHTTP(c.Response(), c.Request()) 68 | return nil 69 | } 70 | 71 | // Render return a web pages defined in bindata 72 | func (s *Server) render(c echo.Context, path string, mime int) error { 73 | data, err := Asset(path) 74 | if err != nil { 75 | return echo.NewHTTPError(http.StatusNotFound) 76 | } 77 | rs := c.Response() 78 | // check content type by extensions 79 | switch mime { 80 | case 1: 81 | rs.Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8) 82 | break 83 | case 2: 84 | rs.Header().Set(echo.HeaderContentType, echo.MIMEApplicationJavaScriptCharsetUTF8) 85 | break 86 | case 3: 87 | rs.Header().Set(echo.HeaderContentType, "text/css") 88 | break 89 | case 4: 90 | rs.Header().Set(echo.HeaderContentType, "image/svg+xml") 91 | break 92 | case 5: 93 | rs.Header().Set(echo.HeaderContentType, "image/png") 94 | break 95 | } 96 | rs.WriteHeader(http.StatusOK) 97 | rs.Write(data) 98 | return nil 99 | } 100 | 101 | func (s *Server) Set(status bool, open bool, port int, host string) { 102 | s.Open = open 103 | s.Port = port 104 | s.Host = host 105 | s.Status = status 106 | } 107 | 108 | // Start the web server 109 | func (s *Server) Start() (err error) { 110 | if s.Status { 111 | e := echo.New() 112 | e.Use(middleware.GzipWithConfig(middleware.GzipConfig{ 113 | Level: 2, 114 | })) 115 | e.Use(middleware.Recover()) 116 | 117 | // web panel 118 | e.GET("/", func(c echo.Context) error { 119 | return s.render(c, "assets/index.html", 1) 120 | }) 121 | e.GET("/assets/js/all.min.js", func(c echo.Context) error { 122 | return s.render(c, "assets/assets/js/all.min.js", 2) 123 | }) 124 | e.GET("/assets/css/app.css", func(c echo.Context) error { 125 | return s.render(c, "assets/assets/css/app.css", 3) 126 | }) 127 | e.GET("/app/components/settings/index.html", func(c echo.Context) error { 128 | return s.render(c, "assets/app/components/settings/index.html", 1) 129 | }) 130 | e.GET("/app/components/project/index.html", func(c echo.Context) error { 131 | return s.render(c, "assets/app/components/project/index.html", 1) 132 | }) 133 | e.GET("/app/components/index.html", func(c echo.Context) error { 134 | return s.render(c, "assets/app/components/index.html", 1) 135 | }) 136 | e.GET("/assets/img/logo.png", func(c echo.Context) error { 137 | return s.render(c, "assets/assets/img/logo.png", 5) 138 | }) 139 | e.GET("/assets/img/svg/github-logo.svg", func(c echo.Context) error { 140 | return s.render(c, "assets/assets/img/svg/github-logo.svg", 4) 141 | }) 142 | e.GET("/assets/img/svg/ic_arrow_back_black_48px.svg", func(c echo.Context) error { 143 | return s.render(c, "assets/assets/img/svg/ic_arrow_back_black_48px.svg", 4) 144 | }) 145 | e.GET("/assets/img/svg/ic_clear_white_48px.svg", func(c echo.Context) error { 146 | return s.render(c, "assets/assets/img/svg/ic_clear_white_48px.svg", 4) 147 | }) 148 | e.GET("/assets/img/svg/ic_menu_white_48px.svg", func(c echo.Context) error { 149 | return s.render(c, "assets/assets/img/svg/ic_menu_white_48px.svg", 4) 150 | }) 151 | e.GET("/assets/img/svg/ic_settings_black_48px.svg", func(c echo.Context) error { 152 | return s.render(c, "assets/assets/img/svg/ic_settings_black_48px.svg", 4) 153 | }) 154 | 155 | //websocket 156 | e.GET("/ws", s.projects) 157 | e.HideBanner = true 158 | e.Debug = false 159 | go func() { 160 | log.Println(s.Parent.Prefix("Started on " + string(s.Host) + ":" + strconv.Itoa(s.Port))) 161 | e.Start(string(s.Host) + ":" + strconv.Itoa(s.Port)) 162 | }() 163 | } 164 | return nil 165 | } 166 | 167 | // OpenURL in a new tab of default browser 168 | func (s *Server) OpenURL() error { 169 | url := "http://" + string(s.Parent.Server.Host) + ":" + strconv.Itoa(s.Parent.Server.Port) 170 | stderr := bytes.Buffer{} 171 | cmd := map[string]string{ 172 | "windows": "start", 173 | "darwin": "open", 174 | "linux": "xdg-open", 175 | } 176 | if s.Open { 177 | open, err := cmd[runtime.GOOS] 178 | if !err { 179 | return fmt.Errorf("operating system %q is not supported", runtime.GOOS) 180 | } 181 | cmd := exec.Command(open, url) 182 | cmd.Stderr = &stderr 183 | if err := cmd.Run(); err != nil { 184 | return errors.New(stderr.String()) 185 | } 186 | } 187 | return nil 188 | } 189 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 2 | github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= 4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/dgrijalva/jwt-go v1.0.2 h1:KPldsxuKGsS2FPWsNeg9ZO18aCrGKujPoWXn2yo+KQM= 7 | github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= 8 | github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= 9 | github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= 10 | github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= 11 | github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= 12 | github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= 13 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 14 | github.com/labstack/echo v1.4.4 h1:1bEiBNeGSUKxcPDGfZ/7IgdhJJZx8wV/pICJh4W2NJI= 15 | github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= 16 | github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= 17 | github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= 18 | github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= 19 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 20 | github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= 21 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 22 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 23 | github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= 24 | github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= 25 | github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= 26 | github.com/oxequa/interact v0.0.0-20171114182912-f8fb5795b5d7 h1:VhMyYEArWL80OqmBloufn/ABe355btZ3Md+EFFrv+zE= 27 | github.com/oxequa/interact v0.0.0-20171114182912-f8fb5795b5d7/go.mod h1:lYzYp3DJ1SPLrp8ZX8ODprgEoxmNelVN+TKaWvum0cg= 28 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 29 | github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= 30 | github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 31 | github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= 32 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= 33 | github.com/sirupsen/logrus v1.5.0 h1:1N5EYkVAPEywqZRJd7cwnRtCb6xJx7NH3T3WUTF980Q= 34 | github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo= 35 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 36 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 37 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 38 | github.com/urfave/cli v1.22.4 h1:u7tSpNPPswAFymm8IehJhy4uJMlUuU/GmqSkvJ1InXA= 39 | github.com/urfave/cli/v2 v2.2.0 h1:JTTnM6wKzdA0Jqodd966MVj4vWbbquZykeX1sKbe2C4= 40 | github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= 41 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 42 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 43 | github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= 44 | github.com/valyala/fasttemplate v1.1.0 h1:RZqt0yGBsps8NGvLSGW804QQqCUYYLsaOjTVHy1Ocw4= 45 | github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= 46 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= 47 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 48 | golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0 h1:Jcxah/M+oLZ/R4/z5RzfPzGbPXnVDPkEDtf2JnuxN+U= 49 | golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 50 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 51 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 52 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 53 | golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 54 | golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 55 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 56 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= 57 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 58 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 59 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 60 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 61 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 62 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 63 | -------------------------------------------------------------------------------- /realize/tools.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "io/ioutil" 7 | "log" 8 | "os/exec" 9 | "path/filepath" 10 | "strings" 11 | ) 12 | 13 | // Tool info 14 | type Tool struct { 15 | Args []string `yaml:"args,omitempty" json:"args,omitempty"` 16 | Method string `yaml:"method,omitempty" json:"method,omitempty"` 17 | Path string `yaml:"path,omitempty" json:"path,omitempty"` 18 | Dir string `yaml:"dir,omitempty" json:"dir,omitempty"` //wdir of the command 19 | Status bool `yaml:"status,omitempty" json:"status,omitempty"` 20 | Output bool `yaml:"output,omitempty" json:"output,omitempty"` 21 | dir bool 22 | isTool bool 23 | method []string 24 | cmd []string 25 | name string 26 | parent *Project 27 | } 28 | 29 | // Tools go 30 | type Tools struct { 31 | Clean Tool `yaml:"clean,omitempty" json:"clean,omitempty"` 32 | Vet Tool `yaml:"vet,omitempty" json:"vet,omitempty"` 33 | Fmt Tool `yaml:"fmt,omitempty" json:"fmt,omitempty"` 34 | Test Tool `yaml:"test,omitempty" json:"test,omitempty"` 35 | Generate Tool `yaml:"generate,omitempty" json:"generate,omitempty"` 36 | Install Tool `yaml:"install,omitempty" json:"install,omitempty"` 37 | Build Tool `yaml:"build,omitempty" json:"build,omitempty"` 38 | Run Tool `yaml:"run,omitempty" json:"run,omitempty"` 39 | vgo bool 40 | } 41 | 42 | // Setup go tools 43 | func (t *Tools) Setup() { 44 | var gocmd string 45 | if t.vgo { 46 | gocmd = "vgo" 47 | } else { 48 | gocmd = "go" 49 | } 50 | 51 | // go clean 52 | if t.Clean.Status { 53 | t.Clean.name = "Clean" 54 | t.Clean.isTool = true 55 | t.Clean.cmd = replace([]string{gocmd, "clean"}, t.Clean.Method) 56 | t.Clean.Args = split([]string{}, t.Clean.Args) 57 | } 58 | // go generate 59 | if t.Generate.Status { 60 | t.Generate.dir = true 61 | t.Generate.isTool = true 62 | t.Generate.name = "Generate" 63 | t.Generate.cmd = replace([]string{gocmd, "generate"}, t.Generate.Method) 64 | t.Generate.Args = split([]string{}, t.Generate.Args) 65 | } 66 | // go fmt 67 | if t.Fmt.Status { 68 | if len(t.Fmt.Args) == 0 { 69 | t.Fmt.Args = []string{"-s", "-w", "-e"} 70 | } 71 | t.Fmt.name = "Fmt" 72 | t.Fmt.isTool = true 73 | t.Fmt.cmd = replace([]string{"gofmt"}, t.Fmt.Method) 74 | t.Fmt.Args = split([]string{}, t.Fmt.Args) 75 | } 76 | // go vet 77 | if t.Vet.Status { 78 | t.Vet.dir = true 79 | t.Vet.name = "Vet" 80 | t.Vet.isTool = true 81 | t.Vet.cmd = replace([]string{gocmd, "vet"}, t.Vet.Method) 82 | t.Vet.Args = split([]string{}, t.Vet.Args) 83 | } 84 | // go test 85 | if t.Test.Status { 86 | t.Test.dir = true 87 | t.Test.isTool = true 88 | t.Test.name = "Test" 89 | t.Test.cmd = replace([]string{gocmd, "test"}, t.Test.Method) 90 | t.Test.Args = split([]string{}, t.Test.Args) 91 | } 92 | // go install 93 | t.Install.name = "Install" 94 | t.Install.cmd = replace([]string{gocmd, "install"}, t.Install.Method) 95 | t.Install.Args = split([]string{}, t.Install.Args) 96 | // go build 97 | if t.Build.Status { 98 | t.Build.name = "Build" 99 | t.Build.cmd = replace([]string{gocmd, "build"}, t.Build.Method) 100 | t.Build.Args = split([]string{}, t.Build.Args) 101 | } 102 | } 103 | 104 | // Exec a go tool 105 | func (t *Tool) Exec(path string, stop <-chan bool) (response Response) { 106 | if t.dir { 107 | if filepath.Ext(path) != "" { 108 | path = filepath.Dir(path) 109 | } 110 | // check if there is at least one go file 111 | matched := false 112 | files, _ := ioutil.ReadDir(path) 113 | for _, f := range files { 114 | matched, _ = filepath.Match("*.go", f.Name()) 115 | if matched { 116 | break 117 | } 118 | } 119 | if !matched { 120 | return 121 | } 122 | } else if !strings.HasSuffix(path, ".go") { 123 | return 124 | } 125 | args := t.Args 126 | if strings.HasSuffix(path, ".go") { 127 | args = append(args, path) 128 | path = filepath.Dir(path) 129 | } 130 | if s := ext(path); s == "" || s == "go" { 131 | if t.parent.parent.Settings.Recovery.Tools { 132 | log.Println("Tool:", t.name, path, args) 133 | } 134 | var out, stderr bytes.Buffer 135 | done := make(chan error) 136 | args = append(t.cmd, args...) 137 | cmd := exec.Command(args[0], args[1:]...) 138 | if t.Dir != "" { 139 | cmd.Dir, _ = filepath.Abs(t.Dir) 140 | } else { 141 | cmd.Dir = path 142 | } 143 | cmd.Stdout = &out 144 | cmd.Stderr = &stderr 145 | // Start command 146 | err := cmd.Start() 147 | if err != nil { 148 | response.Name = t.name 149 | response.Err = err 150 | return 151 | } 152 | go func() { done <- cmd.Wait() }() 153 | // Wait a result 154 | select { 155 | case <-stop: 156 | // Stop running command 157 | cmd.Process.Kill() 158 | case err := <-done: 159 | // Command completed 160 | response.Name = t.name 161 | if err != nil { 162 | response.Err = errors.New(stderr.String() + out.String() + err.Error()) 163 | } else { 164 | if t.Output { 165 | response.Out = out.String() 166 | } 167 | } 168 | } 169 | } 170 | return 171 | } 172 | 173 | // Compile is used for build and install 174 | func (t *Tool) Compile(path string, stop <-chan bool) (response Response) { 175 | var out bytes.Buffer 176 | var stderr bytes.Buffer 177 | done := make(chan error) 178 | args := append(t.cmd, t.Args...) 179 | cmd := exec.Command(args[0], args[1:]...) 180 | if t.Dir != "" { 181 | cmd.Dir, _ = filepath.Abs(t.Dir) 182 | } else { 183 | cmd.Dir = path 184 | } 185 | cmd.Stdout = &out 186 | cmd.Stderr = &stderr 187 | // Start command 188 | cmd.Start() 189 | go func() { done <- cmd.Wait() }() 190 | // Wait a result 191 | response.Name = t.name 192 | select { 193 | case <-stop: 194 | // Stop running command 195 | cmd.Process.Kill() 196 | case err := <-done: 197 | // Command completed 198 | if err != nil { 199 | response.Err = errors.New(stderr.String() + err.Error()) 200 | } 201 | } 202 | return 203 | } 204 | -------------------------------------------------------------------------------- /realize/notify.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | // this code is imported from moby, unfortunately i can't import it directly as dependencies from its repo, 4 | // cause there was a problem between moby vendor and fsnotify 5 | // i have just added only the walk methods and some little changes to polling interval, originally set as static. 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "github.com/fsnotify/fsnotify" 11 | "github.com/sirupsen/logrus" 12 | "os" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | var ( 18 | // errPollerClosed is returned when the poller is closed 19 | errPollerClosed = errors.New("poller is closed") 20 | // errNoSuchWatch is returned when trying to remove a watch that doesn't exist 21 | errNoSuchWatch = errors.New("watch does not exist") 22 | ) 23 | 24 | type ( 25 | // FileWatcher is an interface for implementing file notification watchers 26 | FileWatcher interface { 27 | Close() error 28 | Add(string) error 29 | Walk(string, bool) string 30 | Remove(string) error 31 | Errors() <-chan error 32 | Events() <-chan fsnotify.Event 33 | } 34 | // fsNotifyWatcher wraps the fsnotify package to satisfy the FileNotifier interface 35 | fsNotifyWatcher struct { 36 | *fsnotify.Watcher 37 | } 38 | // filePoller is used to poll files for changes, especially in cases where fsnotify 39 | // can't be run (e.g. when inotify handles are exhausted) 40 | // filePoller satisfies the FileWatcher interface 41 | filePoller struct { 42 | // watches is the list of files currently being polled, close the associated channel to stop the watch 43 | watches map[string]chan struct{} 44 | // events is the channel to listen to for watch events 45 | events chan fsnotify.Event 46 | // errors is the channel to listen to for watch errors 47 | errors chan error 48 | // mu locks the poller for modification 49 | mu sync.Mutex 50 | // closed is used to specify when the poller has already closed 51 | closed bool 52 | // polling interval 53 | interval time.Duration 54 | } 55 | ) 56 | 57 | // PollingWatcher returns a poll-based file watcher 58 | func PollingWatcher(interval time.Duration) FileWatcher { 59 | if interval == 0 { 60 | interval = time.Duration(1) * time.Second 61 | } 62 | return &filePoller{ 63 | interval: interval, 64 | events: make(chan fsnotify.Event), 65 | errors: make(chan error), 66 | } 67 | } 68 | 69 | // NewFileWatcher tries to use an fs-event watcher, and falls back to the poller if there is an error 70 | func NewFileWatcher(l Legacy) (FileWatcher, error) { 71 | if !l.Force { 72 | if w, err := EventWatcher(); err == nil { 73 | return w, nil 74 | } 75 | } 76 | return PollingWatcher(l.Interval), nil 77 | } 78 | 79 | // EventWatcher returns an fs-event based file watcher 80 | func EventWatcher() (FileWatcher, error) { 81 | w, err := fsnotify.NewWatcher() 82 | if err != nil { 83 | return nil, err 84 | } 85 | return &fsNotifyWatcher{Watcher: w}, nil 86 | } 87 | 88 | // Errors returns the fsnotify error channel receiver 89 | func (w *fsNotifyWatcher) Errors() <-chan error { 90 | return w.Watcher.Errors 91 | } 92 | 93 | // Events returns the fsnotify event channel receiver 94 | func (w *fsNotifyWatcher) Events() <-chan fsnotify.Event { 95 | return w.Watcher.Events 96 | } 97 | 98 | // Walk fsnotify 99 | func (w *fsNotifyWatcher) Walk(path string, init bool) string { 100 | if err := w.Add(path); err != nil { 101 | return "" 102 | } 103 | return path 104 | } 105 | 106 | // Close closes the poller 107 | // All watches are stopped, removed, and the poller cannot be added to 108 | func (w *filePoller) Close() error { 109 | w.mu.Lock() 110 | if w.closed { 111 | w.mu.Unlock() 112 | return nil 113 | } 114 | 115 | w.closed = true 116 | for name := range w.watches { 117 | w.remove(name) 118 | delete(w.watches, name) 119 | } 120 | w.mu.Unlock() 121 | return nil 122 | } 123 | 124 | // Errors returns the errors channel 125 | // This is used for notifications about errors on watched files 126 | func (w *filePoller) Errors() <-chan error { 127 | return w.errors 128 | } 129 | 130 | // Add adds a filename to the list of watches 131 | // once added the file is polled for changes in a separate goroutine 132 | func (w *filePoller) Add(name string) error { 133 | w.mu.Lock() 134 | defer w.mu.Unlock() 135 | 136 | if w.closed { 137 | return errPollerClosed 138 | } 139 | 140 | f, err := os.Open(name) 141 | if err != nil { 142 | return err 143 | } 144 | fi, err := os.Stat(name) 145 | if err != nil { 146 | return err 147 | } 148 | 149 | if w.watches == nil { 150 | w.watches = make(map[string]chan struct{}) 151 | } 152 | if _, exists := w.watches[name]; exists { 153 | return fmt.Errorf("watch exists") 154 | } 155 | chClose := make(chan struct{}) 156 | w.watches[name] = chClose 157 | go w.watch(f, fi, chClose) 158 | return nil 159 | } 160 | 161 | // Remove poller 162 | func (w *filePoller) remove(name string) error { 163 | if w.closed { 164 | return errPollerClosed 165 | } 166 | 167 | chClose, exists := w.watches[name] 168 | if !exists { 169 | return errNoSuchWatch 170 | } 171 | close(chClose) 172 | delete(w.watches, name) 173 | return nil 174 | } 175 | 176 | // Remove stops and removes watch with the specified name 177 | func (w *filePoller) Remove(name string) error { 178 | w.mu.Lock() 179 | defer w.mu.Unlock() 180 | return w.remove(name) 181 | } 182 | 183 | // Events returns the event channel 184 | // This is used for notifications on events about watched files 185 | func (w *filePoller) Events() <-chan fsnotify.Event { 186 | return w.events 187 | } 188 | 189 | // Walk poller 190 | func (w *filePoller) Walk(path string, init bool) string { 191 | check := w.watches[path] 192 | if err := w.Add(path); err != nil { 193 | return "" 194 | } 195 | if check == nil && init { 196 | _, err := os.Stat(path) 197 | if err == nil { 198 | go w.sendEvent(fsnotify.Event{Op: fsnotify.Create, Name: path}, w.watches[path]) 199 | } 200 | } 201 | return path 202 | } 203 | 204 | // sendErr publishes the specified error to the errors channel 205 | func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error { 206 | select { 207 | case w.errors <- e: 208 | case <-chClose: 209 | return fmt.Errorf("closed") 210 | } 211 | return nil 212 | } 213 | 214 | // sendEvent publishes the specified event to the events channel 215 | func (w *filePoller) sendEvent(e fsnotify.Event, chClose <-chan struct{}) error { 216 | select { 217 | case w.events <- e: 218 | case <-chClose: 219 | return fmt.Errorf("closed") 220 | } 221 | return nil 222 | } 223 | 224 | // watch is responsible for polling the specified file for changes 225 | // upon finding changes to a file or errors, sendEvent/sendErr is called 226 | func (w *filePoller) watch(f *os.File, lastFi os.FileInfo, chClose chan struct{}) { 227 | defer f.Close() 228 | for { 229 | time.Sleep(w.interval) 230 | select { 231 | case <-chClose: 232 | logrus.Debugf("watch for %s closed", f.Name()) 233 | return 234 | default: 235 | } 236 | 237 | fi, err := os.Stat(f.Name()) 238 | switch { 239 | case err != nil && lastFi != nil: 240 | // If it doesn't exist at this point, it must have been removed 241 | // no need to send the error here since this is a valid operation 242 | if os.IsNotExist(err) { 243 | if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Remove, Name: f.Name()}, chClose); err != nil { 244 | return 245 | } 246 | lastFi = nil 247 | } 248 | // at this point, send the error 249 | w.sendErr(err, chClose) 250 | return 251 | case lastFi == nil: 252 | if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Create, Name: f.Name()}, chClose); err != nil { 253 | return 254 | } 255 | lastFi = fi 256 | case fi.Mode() != lastFi.Mode(): 257 | if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Chmod, Name: f.Name()}, chClose); err != nil { 258 | return 259 | } 260 | lastFi = fi 261 | case fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size(): 262 | if err := w.sendEvent(fsnotify.Event{Op: fsnotify.Write, Name: f.Name()}, chClose); err != nil { 263 | return 264 | } 265 | lastFi = fi 266 | } 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |

5 | Build status 6 | GoReport 7 | GoDoc 8 | License 9 | Gitter 10 |

11 |
12 |

#1 Golang live reload and task runner

13 |
14 | 15 |

16 | 17 |

18 | 19 | 20 | ## Content 21 | 22 | ### - ⭐️ [Top Features](#top-features) 23 | ### - 💃🏻 [Get started](#get-started) 24 | ### - 📄 [Config sample](#config-sample) 25 | ### - 📚 [Commands List](#commands-list) 26 | ### - 🛠 [Support and Suggestions](#support-and-suggestions) 27 | ### - 😎 [Backers and Sponsors](#backers) 28 | 29 | ## Top Features 30 | 31 | - High performance Live Reload. 32 | - Manage multiple projects at the same time. 33 | - Watch by custom extensions and paths. 34 | - All Go commands supported. 35 | - Switch between different Go builds. 36 | - Custom env variables for project. 37 | - Execute custom commands before and after a file changes or globally. 38 | - Export logs and errors to an external file. 39 | - Step-by-step project initialization. 40 | - Redesigned panel that displays build errors, console outputs and warnings. 41 | - Any suggestion? [Suggest an amazing feature! 🕺🏻](https://github.com/oxequa/realize/issues/new) 42 | 43 | ## Supporters 44 |


45 | 46 |

47 | 48 | ## Quickstart 49 | ``` 50 | go get github.com/oxequa/realize 51 | ``` 52 | 53 | ## Commands List 54 | 55 | ### Run Command 56 | From **project/projects** root execute: 57 | 58 | $ realize start 59 | 60 | 61 | It will create a **.realize.yaml** file if doesn't already exist, add the working directory as project and run your workflow. 62 | 63 | ***start*** command supports the following custom parameters: 64 | 65 | --name="name" -> Run by name on existing configuration 66 | --path="realize/server" -> Custom Path (if not specified takes the working directory name) 67 | --generate -> Enable go generate 68 | --fmt -> Enable go fmt 69 | --test -> Enable go test 70 | --vet -> Enable go vet 71 | --install -> Enable go install 72 | --build -> Enable go build 73 | --run -> Enable go run 74 | --server -> Enable the web server 75 | --open -> Open web ui in default browser 76 | --no-config -> Ignore an existing config / skip the creation of a new one 77 | 78 | Some examples: 79 | 80 | $ realize start 81 | $ realize start --path="mypath" 82 | $ realize start --name="realize" --build 83 | $ realize start --path="realize" --run --no-config 84 | $ realize start --install --test --fmt --no-config 85 | $ realize start --path="/Users/username/go/src/github.com/oxequa/realize-examples/coin/" 86 | 87 | If you want, you can specify additional arguments for your project: 88 | 89 | ✅ $ realize start --path="/print/printer" --run yourParams --yourFlags // right 90 | ❌ $ realize start yourParams --yourFlags --path="/print/printer" --run // wrong 91 | 92 | ⚠️ The additional arguments **must go after** the params: 93 |
94 | 💡 The ***start*** command can be used with a project from its working directory without make a config file (*--no-config*). 95 | 96 | ### Add Command 97 | Add a project to an existing config file or create a new one. 98 | 99 | $ realize add 100 | 💡 ***add*** supports the same parameters as ***start*** command. 101 | ### Init Command 102 | This command allows you to create a custom configuration step-by-step. 103 | 104 | $ realize init 105 | 106 | 💡 ***init*** is the only command that supports a complete customization of all supported options. 107 | ### Remove Command 108 | Remove a project by its name 109 | 110 | $ realize remove --name="myname" 111 | 112 | 113 | ## Color reference 114 | 💙 BLUE: Outputs of the project.
115 | 💔 RED: Errors.
116 | 💜 PURPLE: Times or changed files.
117 | 💚 GREEN: Successfully completed action.
118 | 119 | 120 | ## Config sample 121 | 122 | *** there is no more a .realize dir, but only a .realize.yaml file *** 123 | 124 | For more examples check: [Realize Examples](https://github.com/oxequa/realize-examples) 125 | 126 | settings: 127 | legacy: 128 | force: true // force polling watcher instead fsnotifiy 129 | interval: 100ms // polling interval 130 | resources: // files names 131 | outputs: outputs.log 132 | logs: logs.log 133 | errors: errors.log 134 | server: 135 | status: false // server status 136 | open: false // open browser at start 137 | host: localhost // server host 138 | port: 5001 // server port 139 | schema: 140 | - name: coin 141 | path: coin // project path 142 | env: // env variables available at startup 143 | test: test 144 | myvar: value 145 | commands: // go commands supported 146 | vet: 147 | status: true 148 | fmt: 149 | status: true 150 | args: 151 | - -s 152 | - -w 153 | test: 154 | status: true 155 | method: gb test // support different build tools 156 | generate: 157 | status: true 158 | install: 159 | status: true 160 | build: 161 | status: false 162 | method: gb build // support differents build tool 163 | args: // additional params for the command 164 | - -race 165 | run: 166 | status: true 167 | args: // arguments to pass at the project 168 | - --myarg 169 | watcher: 170 | paths: // watched paths 171 | - / 172 | ignore_paths: // ignored paths 173 | - vendor 174 | extensions: // watched extensions 175 | - go 176 | - html 177 | scripts: 178 | - type: before 179 | command: echo before global 180 | global: true 181 | output: true 182 | - type: before 183 | command: echo before change 184 | output: true 185 | - type: after 186 | command: echo after change 187 | output: true 188 | - type: after 189 | command: echo after global 190 | global: true 191 | output: true 192 | errorOutputPattern: mypattern //custom error pattern 193 | 194 | ## Support and Suggestions 195 | 💬 Chat with us [Gitter](https://gitter.im/oxequa/realize)
196 | ⭐️ Suggest a new [Feature](https://github.com/oxequa/realize/issues/new) 197 | 198 | ## Backers 199 | 200 | Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/realize#backer)] 201 | 202 | 203 | 204 | 205 | 206 | 207 | ## Sponsors 208 | 209 | Become a sponsor and get your logo here! [[Become a sponsor](https://opencollective.com/realize#sponsor)] 210 | -------------------------------------------------------------------------------- /realize/projects.go: -------------------------------------------------------------------------------- 1 | package realize 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "errors" 7 | "fmt" 8 | "log" 9 | "math/big" 10 | "os" 11 | "os/exec" 12 | "path/filepath" 13 | "reflect" 14 | "regexp" 15 | "strconv" 16 | "strings" 17 | "sync" 18 | "time" 19 | 20 | "github.com/fsnotify/fsnotify" 21 | ) 22 | 23 | var ( 24 | msg string 25 | out BufferOut 26 | ) 27 | 28 | // Watch info 29 | type Watch struct { 30 | Exts []string `yaml:"extensions" json:"extensions"` 31 | Paths []string `yaml:"paths" json:"paths"` 32 | Scripts []Command `yaml:"scripts,omitempty" json:"scripts,omitempty"` 33 | Hidden bool `yaml:"hidden,omitempty" json:"hidden,omitempty"` 34 | Ignore []string `yaml:"ignored_paths,omitempty" json:"ignored_paths,omitempty"` 35 | } 36 | 37 | type Ignore struct { 38 | Exts []string `yaml:"exts,omitempty" json:"exts,omitempty"` 39 | Paths []string `yaml:"paths,omitempty" json:"paths,omitempty"` 40 | } 41 | 42 | // Command fields 43 | type Command struct { 44 | Cmd string `yaml:"command" json:"command"` 45 | Type string `yaml:"type" json:"type"` 46 | Path string `yaml:"path,omitempty" json:"path,omitempty"` 47 | Global bool `yaml:"global,omitempty" json:"global,omitempty"` 48 | Output bool `yaml:"output,omitempty" json:"output,omitempty"` 49 | } 50 | 51 | // Project info 52 | type Project struct { 53 | parent *Realize 54 | watcher FileWatcher 55 | stop chan bool 56 | exit chan os.Signal 57 | paths []string 58 | last last 59 | files int64 60 | folders int64 61 | init bool 62 | Name string `yaml:"name" json:"name"` 63 | Path string `yaml:"path" json:"path"` 64 | Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"` 65 | Args []string `yaml:"args,omitempty" json:"args,omitempty"` 66 | Tools Tools `yaml:"commands" json:"commands"` 67 | Watcher Watch `yaml:"watcher" json:"watcher"` 68 | Buffer Buffer `yaml:"-" json:"buffer"` 69 | ErrPattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"` 70 | } 71 | 72 | // Last is used to save info about last file changed 73 | type last struct { 74 | file string 75 | time time.Time 76 | } 77 | 78 | // Response exec 79 | type Response struct { 80 | Name string 81 | Out string 82 | Err error 83 | } 84 | 85 | // Buffer define an array buffer for each log files 86 | type Buffer struct { 87 | StdOut []BufferOut `json:"stdOut"` 88 | StdLog []BufferOut `json:"stdLog"` 89 | StdErr []BufferOut `json:"stdErr"` 90 | } 91 | 92 | // BufferOut is used for exchange information between "realize cli" and "web realize" 93 | type BufferOut struct { 94 | Time time.Time `json:"time"` 95 | Text string `json:"text"` 96 | Path string `json:"path"` 97 | Type string `json:"type"` 98 | Stream string `json:"stream"` 99 | Errors []string `json:"errors"` 100 | } 101 | 102 | // After stop watcher 103 | func (p *Project) After() { 104 | if p.parent.After != nil { 105 | p.parent.After(Context{Project: p}) 106 | return 107 | } 108 | p.cmd(nil, "after", true) 109 | } 110 | 111 | // Before start watcher 112 | func (p *Project) Before() { 113 | if p.parent.Before != nil { 114 | p.parent.Before(Context{Project: p}) 115 | return 116 | } 117 | 118 | if hasGoMod(Wdir()) { 119 | p.Tools.vgo = true 120 | } 121 | 122 | // setup go tools 123 | p.Tools.Setup() 124 | // global commands before 125 | p.cmd(p.stop, "before", true) 126 | // indexing files and dirs 127 | for _, dir := range p.Watcher.Paths { 128 | base, _ := filepath.Abs(p.Path) 129 | base = filepath.Join(base, dir) 130 | if _, err := os.Stat(base); err == nil { 131 | if err := filepath.Walk(base, p.walk); err != nil { 132 | p.Err(err) 133 | } 134 | } 135 | } 136 | // start message 137 | msg = fmt.Sprintln(p.pname(p.Name, 1), ":", Blue.Bold("Watching"), Magenta.Bold(p.files), "file/s", Magenta.Bold(p.folders), "folder/s") 138 | out = BufferOut{Time: time.Now(), Text: "Watching " + strconv.FormatInt(p.files, 10) + " files/s " + strconv.FormatInt(p.folders, 10) + " folder/s"} 139 | p.stamp("log", out, msg, "") 140 | } 141 | 142 | // Err occurred 143 | func (p *Project) Err(err error) { 144 | if p.parent.Err != nil { 145 | p.parent.Err(Context{Project: p}) 146 | return 147 | } 148 | if err != nil { 149 | msg = fmt.Sprintln(p.pname(p.Name, 2), ":", Red.Regular(err.Error())) 150 | out = BufferOut{Time: time.Now(), Text: err.Error()} 151 | p.stamp("error", out, msg, "") 152 | } 153 | } 154 | 155 | // Change event message 156 | func (p *Project) Change(event fsnotify.Event) { 157 | if p.parent.Change != nil { 158 | p.parent.Change(Context{Project: p, Event: event}) 159 | return 160 | } 161 | // file extension 162 | ext := ext(event.Name) 163 | if ext == "" { 164 | ext = "DIR" 165 | } 166 | // change message 167 | msg = fmt.Sprintln(p.pname(p.Name, 4), ":", Magenta.Bold(strings.ToUpper(ext)), "changed", Magenta.Bold(event.Name)) 168 | out = BufferOut{Time: time.Now(), Text: ext + " changed " + event.Name} 169 | p.stamp("log", out, msg, "") 170 | } 171 | 172 | // Reload launches the toolchain run, build, install 173 | func (p *Project) Reload(path string, stop <-chan bool) { 174 | if p.parent.Reload != nil { 175 | p.parent.Reload(Context{Project: p, Watcher: p.watcher, Path: path, Stop: stop}) 176 | return 177 | } 178 | var done bool 179 | var install, build Response 180 | go func() { 181 | for { 182 | select { 183 | case <-stop: 184 | done = true 185 | return 186 | } 187 | } 188 | }() 189 | if done { 190 | return 191 | } 192 | // before command 193 | p.cmd(stop, "before", false) 194 | if done { 195 | return 196 | } 197 | // Go supported tools 198 | if len(path) > 0 { 199 | fi, err := os.Stat(path) 200 | if filepath.Ext(path) == "" { 201 | fi, err = os.Stat(path) 202 | } 203 | if err != nil { 204 | p.Err(err) 205 | } 206 | p.tools(stop, path, fi) 207 | } 208 | // Prevent fake events on polling startup 209 | p.init = true 210 | // prevent errors using realize without config with only run flag 211 | if p.Tools.Run.Status && !p.Tools.Install.Status && !p.Tools.Build.Status { 212 | p.Tools.Install.Status = true 213 | } 214 | if done { 215 | return 216 | } 217 | if p.Tools.Install.Status { 218 | msg = fmt.Sprintln(p.pname(p.Name, 1), ":", Green.Regular(p.Tools.Install.name), "started") 219 | out = BufferOut{Time: time.Now(), Text: p.Tools.Install.name + " started"} 220 | p.stamp("log", out, msg, "") 221 | start := time.Now() 222 | install = p.Tools.Install.Compile(p.Path, stop) 223 | install.print(start, p) 224 | } 225 | if done { 226 | return 227 | } 228 | if p.Tools.Build.Status { 229 | msg = fmt.Sprintln(p.pname(p.Name, 1), ":", Green.Regular(p.Tools.Build.name), "started") 230 | out = BufferOut{Time: time.Now(), Text: p.Tools.Build.name + " started"} 231 | p.stamp("log", out, msg, "") 232 | start := time.Now() 233 | build = p.Tools.Build.Compile(p.Path, stop) 234 | build.print(start, p) 235 | } 236 | if done { 237 | return 238 | } 239 | if install.Err == nil && build.Err == nil && p.Tools.Run.Status { 240 | result := make(chan Response) 241 | go func() { 242 | for { 243 | select { 244 | case <-stop: 245 | return 246 | case r := <-result: 247 | if r.Err != nil { 248 | msg := fmt.Sprintln(p.pname(p.Name, 2), ":", Red.Regular(r.Err)) 249 | out := BufferOut{Time: time.Now(), Text: r.Err.Error(), Type: "Go Run"} 250 | p.stamp("error", out, msg, "") 251 | } 252 | if r.Out != "" { 253 | msg := fmt.Sprintln(p.pname(p.Name, 3), ":", Blue.Regular(r.Out)) 254 | out := BufferOut{Time: time.Now(), Text: r.Out, Type: "Go Run"} 255 | p.stamp("out", out, msg, "") 256 | } 257 | } 258 | } 259 | }() 260 | go func() { 261 | log.Println(p.pname(p.Name, 1), ":", "Running..") 262 | err := p.run(p.Path, result, stop) 263 | if err != nil { 264 | msg := fmt.Sprintln(p.pname(p.Name, 2), ":", Red.Regular(err)) 265 | out := BufferOut{Time: time.Now(), Text: err.Error(), Type: "Go Run"} 266 | p.stamp("error", out, msg, "") 267 | } 268 | }() 269 | } 270 | if done { 271 | return 272 | } 273 | p.cmd(stop, "after", false) 274 | } 275 | 276 | // Watch a project 277 | func (p *Project) Watch(wg *sync.WaitGroup) { 278 | var err error 279 | // change channel 280 | p.stop = make(chan bool) 281 | // init a new watcher 282 | p.watcher, err = NewFileWatcher(p.parent.Settings.Legacy) 283 | if err != nil { 284 | log.Fatal(err) 285 | } 286 | defer func() { 287 | close(p.stop) 288 | p.watcher.Close() 289 | }() 290 | // before start checks 291 | p.Before() 292 | // start watcher 293 | go p.Reload("", p.stop) 294 | L: 295 | for { 296 | select { 297 | case event := <-p.watcher.Events(): 298 | if p.parent.Settings.Recovery.Events { 299 | log.Println("File:", event.Name, "LastFile:", p.last.file, "Time:", time.Now(), "LastTime:", p.last.time) 300 | } 301 | if time.Now().Truncate(time.Second).After(p.last.time) { 302 | // switch event type 303 | switch event.Op { 304 | case fsnotify.Chmod: 305 | case fsnotify.Remove: 306 | p.watcher.Remove(event.Name) 307 | if p.Validate(event.Name, false) && ext(event.Name) != "" { 308 | // stop and restart 309 | close(p.stop) 310 | p.stop = make(chan bool) 311 | p.Change(event) 312 | go p.Reload("", p.stop) 313 | } 314 | default: 315 | if p.Validate(event.Name, true) { 316 | fi, err := os.Stat(event.Name) 317 | if err != nil { 318 | continue 319 | } 320 | if fi.IsDir() { 321 | filepath.Walk(event.Name, p.walk) 322 | } else { 323 | // stop and restart 324 | close(p.stop) 325 | p.stop = make(chan bool) 326 | p.Change(event) 327 | go p.Reload(event.Name, p.stop) 328 | p.last.time = time.Now().Truncate(time.Second) 329 | p.last.file = event.Name 330 | } 331 | } 332 | } 333 | } 334 | case err := <-p.watcher.Errors(): 335 | p.Err(err) 336 | case <-p.exit: 337 | p.After() 338 | break L 339 | } 340 | } 341 | wg.Done() 342 | } 343 | 344 | // Validate a file path 345 | func (p *Project) Validate(path string, fcheck bool) bool { 346 | if len(path) == 0 { 347 | return false 348 | } 349 | // check if skip hidden 350 | if p.Watcher.Hidden && isHidden(path) { 351 | return false 352 | } 353 | // check for a valid ext or path 354 | if e := ext(path); e != "" { 355 | if len(p.Watcher.Exts) == 0 { 356 | return false 357 | } 358 | // check ignored 359 | for _, v := range p.Watcher.Ignore { 360 | if v == e { 361 | return false 362 | } 363 | } 364 | // supported extensions 365 | for index, v := range p.Watcher.Exts { 366 | if e == v { 367 | break 368 | } 369 | if index == len(p.Watcher.Exts)-1 { 370 | return false 371 | } 372 | } 373 | } 374 | if p.shouldIgnore(path) { 375 | return false 376 | } 377 | // file check 378 | if fcheck { 379 | fi, err := os.Stat(path) 380 | if err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() && ext(path) == "" || fi.Size() <= 0 { 381 | return false 382 | } 383 | } 384 | return true 385 | 386 | } 387 | 388 | // Defines the colors scheme for the project name 389 | func (p *Project) pname(name string, color int) string { 390 | switch color { 391 | case 1: 392 | name = Yellow.Regular("[") + strings.ToUpper(name) + Yellow.Regular("]") 393 | break 394 | case 2: 395 | name = Yellow.Regular("[") + Red.Bold(strings.ToUpper(name)) + Yellow.Regular("]") 396 | break 397 | case 3: 398 | name = Yellow.Regular("[") + Blue.Bold(strings.ToUpper(name)) + Yellow.Regular("]") 399 | break 400 | case 4: 401 | name = Yellow.Regular("[") + Magenta.Bold(strings.ToUpper(name)) + Yellow.Regular("]") 402 | break 403 | case 5: 404 | name = Yellow.Regular("[") + Green.Bold(strings.ToUpper(name)) + Yellow.Regular("]") 405 | break 406 | } 407 | return name 408 | } 409 | 410 | // Tool logs the result of a go command 411 | func (p *Project) tools(stop <-chan bool, path string, fi os.FileInfo) { 412 | done := make(chan bool) 413 | result := make(chan Response) 414 | v := reflect.ValueOf(p.Tools) 415 | go func() { 416 | for i := 0; i < v.NumField()-1; i++ { 417 | tool := v.Field(i).Interface().(Tool) 418 | tool.parent = p 419 | if tool.Status && tool.isTool { 420 | if fi.IsDir() { 421 | if tool.dir { 422 | result <- tool.Exec(path, stop) 423 | } 424 | } else if !tool.dir { 425 | result <- tool.Exec(path, stop) 426 | } 427 | } 428 | } 429 | close(done) 430 | }() 431 | for { 432 | select { 433 | case <-done: 434 | return 435 | case <-stop: 436 | return 437 | case r := <-result: 438 | if r.Err != nil { 439 | if fi.IsDir() { 440 | path, _ = filepath.Abs(fi.Name()) 441 | } 442 | msg = fmt.Sprintln(p.pname(p.Name, 2), ":", Red.Bold(r.Name), Red.Regular("there are some errors in"), ":", Magenta.Bold(path)) 443 | buff := BufferOut{Time: time.Now(), Text: "there are some errors in", Path: path, Type: r.Name, Stream: r.Err.Error()} 444 | p.stamp("error", buff, msg, r.Err.Error()) 445 | } else if r.Out != "" { 446 | msg = fmt.Sprintln(p.pname(p.Name, 3), ":", Red.Bold(r.Name), Red.Regular("outputs"), ":", Blue.Bold(path)) 447 | buff := BufferOut{Time: time.Now(), Text: "outputs", Path: path, Type: r.Name, Stream: r.Out} 448 | p.stamp("out", buff, msg, r.Out) 449 | } 450 | } 451 | } 452 | } 453 | 454 | // Cmd after/before 455 | func (p *Project) cmd(stop <-chan bool, flag string, global bool) { 456 | done := make(chan bool) 457 | result := make(chan Response) 458 | // commands sequence 459 | go func() { 460 | for _, cmd := range p.Watcher.Scripts { 461 | if strings.ToLower(cmd.Type) == flag && cmd.Global == global { 462 | result <- cmd.exec(p.Path, stop) 463 | } 464 | } 465 | close(done) 466 | }() 467 | for { 468 | select { 469 | case <-stop: 470 | return 471 | case <-done: 472 | return 473 | case r := <-result: 474 | msg = fmt.Sprintln(p.pname(p.Name, 5), ":", Green.Bold("Command"), Green.Bold("\"")+r.Name+Green.Bold("\"")) 475 | if r.Err != nil { 476 | out = BufferOut{Time: time.Now(), Text: r.Err.Error(), Type: flag} 477 | p.stamp("error", out, msg, fmt.Sprint(Red.Regular(r.Err.Error()))) 478 | } else { 479 | out = BufferOut{Time: time.Now(), Text: r.Out, Type: flag} 480 | p.stamp("log", out, msg, fmt.Sprint(r.Out)) 481 | } 482 | } 483 | } 484 | } 485 | 486 | // Watch the files tree of a project 487 | func (p *Project) walk(path string, info os.FileInfo, err error) error { 488 | if p.shouldIgnore(path) { 489 | return filepath.SkipDir 490 | } 491 | 492 | if p.Validate(path, true) { 493 | result := p.watcher.Walk(path, p.init) 494 | if result != "" { 495 | if p.parent.Settings.Recovery.Index { 496 | log.Println("Indexing", path) 497 | } 498 | p.tools(p.stop, path, info) 499 | if info.IsDir() { 500 | // tools dir 501 | p.folders++ 502 | } else { 503 | // tools files 504 | p.files++ 505 | } 506 | } 507 | } 508 | return nil 509 | } 510 | 511 | func (p *Project) shouldIgnore(path string) bool { 512 | separator := string(os.PathSeparator) 513 | // supported paths 514 | for _, v := range p.Watcher.Ignore { 515 | s := append([]string{p.Path}, strings.Split(v, separator)...) 516 | abs, _ := filepath.Abs(filepath.Join(s...)) 517 | if path == abs || strings.HasPrefix(path, abs+separator) { 518 | return true 519 | } 520 | } 521 | return false 522 | } 523 | 524 | // Print on files, cli, ws 525 | func (p *Project) stamp(t string, o BufferOut, msg string, stream string) { 526 | ctime := time.Now() 527 | content := []string{ctime.Format("2006-01-02 15:04:05"), strings.ToUpper(p.Name), ":", o.Text, "\r\n", stream} 528 | switch t { 529 | case "out": 530 | p.Buffer.StdOut = append(p.Buffer.StdOut, o) 531 | if p.parent.Settings.Files.Outputs.Status { 532 | f := p.parent.Settings.Create(p.Path, p.parent.Settings.Files.Outputs.Name) 533 | if _, err := f.WriteString(strings.Join(content, " ")); err != nil { 534 | p.parent.Settings.Fatal(err, "") 535 | } 536 | } 537 | case "log": 538 | p.Buffer.StdLog = append(p.Buffer.StdLog, o) 539 | if p.parent.Settings.Files.Logs.Status { 540 | f := p.parent.Settings.Create(p.Path, p.parent.Settings.Files.Logs.Name) 541 | if _, err := f.WriteString(strings.Join(content, " ")); err != nil { 542 | p.parent.Settings.Fatal(err, "") 543 | } 544 | } 545 | case "error": 546 | p.Buffer.StdErr = append(p.Buffer.StdErr, o) 547 | if p.parent.Settings.Files.Errors.Status { 548 | f := p.parent.Settings.Create(p.Path, p.parent.Settings.Files.Errors.Name) 549 | if _, err := f.WriteString(strings.Join(content, " ")); err != nil { 550 | p.parent.Settings.Fatal(err, "") 551 | } 552 | } 553 | } 554 | if msg != "" { 555 | log.Print(msg) 556 | } 557 | if stream != "" { 558 | fmt.Fprintln(Output, stream) 559 | } 560 | go func() { 561 | p.parent.Sync <- "sync" 562 | }() 563 | } 564 | 565 | func (p Project) buildEnvs() (envs []string) { 566 | for k, v := range p.Env { 567 | envs = append(envs, fmt.Sprintf("%s=%s", strings.Replace(k, "=", "", -1), v)) 568 | } 569 | return 570 | } 571 | 572 | // Run a project 573 | func (p *Project) run(path string, stream chan Response, stop <-chan bool) (err error) { 574 | var args []string 575 | var build *exec.Cmd 576 | var r Response 577 | defer func() { 578 | // https://github.com/golang/go/issues/5615 579 | // https://github.com/golang/go/issues/6720 580 | if build != nil { 581 | build.Process.Signal(os.Interrupt) 582 | build.Process.Wait() 583 | } 584 | }() 585 | 586 | // custom error pattern 587 | isErrorText := func(string) bool { 588 | return false 589 | } 590 | errRegexp, err := regexp.Compile(p.ErrPattern) 591 | if err != nil { 592 | r.Err = err 593 | stream <- r 594 | } else { 595 | isErrorText = errRegexp.MatchString 596 | } 597 | 598 | // add additional arguments 599 | for _, arg := range p.Args { 600 | a := strings.FieldsFunc(arg, func(i rune) bool { 601 | return i == '"' || i == '=' || i == '\'' 602 | }) 603 | args = append(args, a...) 604 | } 605 | dirPath := os.Getenv("GOBIN") 606 | if p.Tools.Run.Path != "" { 607 | dirPath, _ = filepath.Abs(p.Tools.Run.Path) 608 | } 609 | name := filepath.Base(path) 610 | if path == "." && p.Tools.Run.Path == "" { 611 | name = filepath.Base(Wdir()) 612 | } else if p.Tools.Run.Path != "" { 613 | name = filepath.Base(dirPath) 614 | } 615 | path = filepath.Join(dirPath, name) 616 | if p.Tools.Run.Method != "" { 617 | path = p.Tools.Run.Method 618 | } 619 | if _, err := os.Stat(path); err == nil { 620 | build = exec.Command(path, args...) 621 | } else if _, err := os.Stat(path + RExtWin); err == nil { 622 | build = exec.Command(path+RExtWin, args...) 623 | } else { 624 | if _, err = os.Stat(path); err == nil { 625 | build = exec.Command(path, args...) 626 | } else if _, err = os.Stat(path + RExtWin); err == nil { 627 | build = exec.Command(path+RExtWin, args...) 628 | } else { 629 | return errors.New("project not found") 630 | } 631 | } 632 | appendEnvs := p.buildEnvs() 633 | if len(appendEnvs) > 0 { 634 | build.Env = append(build.Env, appendEnvs...) 635 | } 636 | // scan project stream 637 | stdout, err := build.StdoutPipe() 638 | stderr, err := build.StderrPipe() 639 | if err != nil { 640 | return err 641 | } 642 | if p.Tools.Run.Dir != "" { 643 | build.Dir = p.Tools.Run.Dir 644 | } 645 | if err := build.Start(); err != nil { 646 | return err 647 | } 648 | execOutput, execError := bufio.NewScanner(stdout), bufio.NewScanner(stderr) 649 | stopOutput, stopError := make(chan bool, 1), make(chan bool, 1) 650 | scanner := func(stop chan bool, output *bufio.Scanner, isError bool) { 651 | for output.Scan() { 652 | text := output.Text() 653 | if isError && !isErrorText(text) { 654 | r.Err = errors.New(text) 655 | stream <- r 656 | r.Err = nil 657 | } else { 658 | r.Out = text 659 | stream <- r 660 | r.Out = "" 661 | } 662 | } 663 | close(stop) 664 | } 665 | go scanner(stopOutput, execOutput, false) 666 | go scanner(stopError, execError, true) 667 | for { 668 | select { 669 | case <-stop: 670 | return 671 | case <-stopOutput: 672 | return 673 | case <-stopError: 674 | return 675 | } 676 | } 677 | } 678 | 679 | // Print with time after 680 | func (r *Response) print(start time.Time, p *Project) { 681 | if r.Err != nil { 682 | msg = fmt.Sprintln(p.pname(p.Name, 2), ":", Red.Bold(r.Name), "\n", r.Err.Error()) 683 | out = BufferOut{Time: time.Now(), Text: r.Err.Error(), Type: r.Name, Stream: r.Out} 684 | p.stamp("error", out, msg, r.Out) 685 | } else { 686 | msg = fmt.Sprintln(p.pname(p.Name, 5), ":", Green.Bold(r.Name), "completed in", Magenta.Regular(big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3), " s")) 687 | out = BufferOut{Time: time.Now(), Text: r.Name + " in " + big.NewFloat(float64(time.Since(start).Seconds())).Text('f', 3) + " s"} 688 | p.stamp("log", out, msg, r.Out) 689 | } 690 | } 691 | 692 | // Exec an additional command from a defined path if specified 693 | func (c *Command) exec(base string, stop <-chan bool) (response Response) { 694 | var stdout bytes.Buffer 695 | var stderr bytes.Buffer 696 | done := make(chan error) 697 | args := strings.Split(strings.Replace(strings.Replace(c.Cmd, "'", "", -1), "\"", "", -1), " ") 698 | ex := exec.Command(args[0], args[1:]...) 699 | ex.Dir = base 700 | // make cmd path 701 | if c.Path != "" { 702 | if strings.Contains(c.Path, base) { 703 | ex.Dir = c.Path 704 | } else { 705 | ex.Dir = filepath.Join(base, c.Path) 706 | } 707 | } 708 | ex.Stdout = &stdout 709 | ex.Stderr = &stderr 710 | // Start command 711 | ex.Start() 712 | go func() { done <- ex.Wait() }() 713 | // Wait a result 714 | select { 715 | case <-stop: 716 | // Stop running command 717 | ex.Process.Kill() 718 | case err := <-done: 719 | // Command completed 720 | response.Name = c.Cmd 721 | response.Out = stdout.String() 722 | if err != nil { 723 | response.Err = errors.New(stderr.String() + stdout.String()) 724 | } 725 | } 726 | return 727 | } 728 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /realize.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "path/filepath" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "github.com/oxequa/interact" 12 | "github.com/oxequa/realize/realize" 13 | "github.com/urfave/cli/v2" 14 | ) 15 | 16 | var r realize.Realize 17 | 18 | // Realize cli commands 19 | func main() { 20 | r.Sync = make(chan string) 21 | app := &cli.App{ 22 | Name: strings.Title(realize.RPrefix), 23 | Version: realize.RVersion, 24 | Description: "Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading.", 25 | Commands: []*cli.Command{ 26 | { 27 | Name: "start", 28 | Aliases: []string{"s"}, 29 | Description: "Start " + strings.Title(realize.RPrefix) + " on a given path. If not exist a config file it creates a new one.", 30 | Flags: []cli.Flag{ 31 | &cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: ".", Usage: "Project base path"}, 32 | &cli.StringFlag{Name: "name", Aliases: []string{"n"}, Value: "", Usage: "Run a project by its name"}, 33 | &cli.BoolFlag{Name: "fmt", Aliases: []string{"f"}, Value: false, Usage: "Enable go fmt"}, 34 | &cli.BoolFlag{Name: "vet", Aliases: []string{"v"}, Value: false, Usage: "Enable go vet"}, 35 | &cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test"}, 36 | &cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate"}, 37 | &cli.BoolFlag{Name: "server", Aliases: []string{"srv"}, Value: false, Usage: "Start server"}, 38 | &cli.BoolFlag{Name: "open", Aliases: []string{"op"}, Value: false, Usage: "Open into the default browser"}, 39 | &cli.BoolFlag{Name: "install", Aliases: []string{"i"}, Value: false, Usage: "Enable go install"}, 40 | &cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build"}, 41 | &cli.BoolFlag{Name: "run", Aliases: []string{"nr"}, Value: false, Usage: "Enable go run"}, 42 | &cli.BoolFlag{Name: "legacy", Aliases: []string{"l"}, Value: false, Usage: "Legacy watch by polling instead fsnotify"}, 43 | &cli.BoolFlag{Name: "no-config", Aliases: []string{"nc"}, Value: false, Usage: "Ignore existing config and doesn't create a new one"}, 44 | }, 45 | Action: start, 46 | }, 47 | { 48 | Name: "add", 49 | Category: "Configuration", 50 | Aliases: []string{"a"}, 51 | Description: "Add a project to an existing config or to a new one.", 52 | Flags: []cli.Flag{ 53 | &cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: realize.Wdir(), Usage: "Project base path"}, 54 | &cli.BoolFlag{Name: "fmt", Aliases: []string{"f"}, Value: false, Usage: "Enable go fmt"}, 55 | &cli.BoolFlag{Name: "vet", Aliases: []string{"v"}, Value: false, Usage: "Enable go vet"}, 56 | &cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test"}, 57 | &cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate"}, 58 | &cli.BoolFlag{Name: "install", Aliases: []string{"i"}, Value: false, Usage: "Enable go install"}, 59 | &cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build"}, 60 | &cli.BoolFlag{Name: "run", Aliases: []string{"nr"}, Value: false, Usage: "Enable go run"}, 61 | }, 62 | Action: add, 63 | }, 64 | { 65 | Name: "init", 66 | Category: "Configuration", 67 | Aliases: []string{"i"}, 68 | Description: "Make a new config file step by step.", 69 | Action: setup, 70 | }, 71 | { 72 | Name: "remove", 73 | Category: "Configuration", 74 | Aliases: []string{"r"}, 75 | Description: "Remove a project from an existing config.", 76 | Flags: []cli.Flag{ 77 | &cli.StringFlag{Name: "name", Aliases: []string{"n"}, Value: ""}, 78 | }, 79 | Action: remove, 80 | }, 81 | { 82 | Name: "clean", 83 | Category: "Configuration", 84 | Aliases: []string{"c"}, 85 | Description: "Remove " + strings.Title(realize.RPrefix) + " folder.", 86 | Action: func(c *cli.Context) error { 87 | return clean() 88 | }, 89 | }, 90 | { 91 | Name: "version", 92 | Aliases: []string{"v"}, 93 | Description: "Print " + strings.Title(realize.RPrefix) + " version.", 94 | Action: func(p *cli.Context) error { 95 | version() 96 | return nil 97 | }, 98 | }, 99 | }, 100 | } 101 | if err := app.Run(os.Args); err != nil { 102 | log.Fatal(err) 103 | } 104 | } 105 | 106 | // Version print current version 107 | func version() { 108 | log.Println(r.Prefix(realize.Green.Bold(realize.RVersion))) 109 | } 110 | 111 | // Clean remove realize file 112 | func clean() (err error) { 113 | if err := r.Settings.Remove(realize.RFile); err != nil { 114 | return err 115 | } 116 | log.Println(r.Prefix(realize.Green.Bold("folder successfully removed"))) 117 | return nil 118 | } 119 | 120 | // Add a project to an existing config or create a new one 121 | func add(c *cli.Context) (err error) { 122 | // read a config if exist 123 | err = r.Settings.Read(&r) 124 | if err != nil { 125 | return err 126 | } 127 | projects := len(r.Schema.Projects) 128 | // create and add a new project 129 | r.Schema.Add(r.Schema.New(c)) 130 | if len(r.Schema.Projects) > projects { 131 | // update config 132 | err = r.Settings.Write(r) 133 | if err != nil { 134 | return err 135 | } 136 | log.Println(r.Prefix(realize.Green.Bold("project successfully added"))) 137 | } else { 138 | log.Println(r.Prefix(realize.Green.Bold("project can't be added"))) 139 | } 140 | return nil 141 | } 142 | 143 | // Setup a new config step by step 144 | func setup(c *cli.Context) (err error) { 145 | interact.Run(&interact.Interact{ 146 | Before: func(context interact.Context) error { 147 | context.SetErr(realize.Red.Bold("INVALID INPUT")) 148 | context.SetPrfx(realize.Output, realize.Yellow.Regular("[")+time.Now().Format("15:04:05")+realize.Yellow.Regular("]")+realize.Yellow.Bold("[")+strings.ToUpper(realize.RPrefix)+realize.Yellow.Bold("]")) 149 | return nil 150 | }, 151 | Questions: []*interact.Question{ 152 | { 153 | Before: func(d interact.Context) error { 154 | if _, err := os.Stat(realize.RFile); err != nil { 155 | d.Skip() 156 | } 157 | d.SetDef(false, realize.Green.Regular("(n)")) 158 | return nil 159 | }, 160 | Quest: interact.Quest{ 161 | Options: realize.Yellow.Regular("[y/n]"), 162 | Msg: "Would you want to overwrite existing " + realize.Magenta.Regular(realize.RPrefix) + " config?", 163 | }, 164 | Action: func(d interact.Context) interface{} { 165 | val, err := d.Ans().Bool() 166 | if err != nil { 167 | return d.Err() 168 | } else if val { 169 | r := realize.Realize{} 170 | r.Server = realize.Server{Parent: &r, Status: false, Open: false, Port: realize.Port, Host: realize.Host} 171 | } 172 | return nil 173 | }, 174 | }, 175 | { 176 | Before: func(d interact.Context) error { 177 | d.SetDef(false, realize.Green.Regular("(n)")) 178 | return nil 179 | }, 180 | Quest: interact.Quest{ 181 | Options: realize.Yellow.Regular("[y/n]"), 182 | Msg: "Would you want to customize settings?", 183 | Resolve: func(d interact.Context) bool { 184 | val, _ := d.Ans().Bool() 185 | return val 186 | }, 187 | }, 188 | Subs: []*interact.Question{ 189 | { 190 | Before: func(d interact.Context) error { 191 | d.SetDef(0, realize.Green.Regular("(os default)")) 192 | return nil 193 | }, 194 | Quest: interact.Quest{ 195 | Options: realize.Yellow.Regular("[int]"), 196 | Msg: "Set max number of open files (root required)", 197 | }, 198 | Action: func(d interact.Context) interface{} { 199 | val, err := d.Ans().Int() 200 | if err != nil { 201 | return d.Err() 202 | } 203 | r.Settings.FileLimit = int32(val) 204 | return nil 205 | }, 206 | }, 207 | { 208 | Before: func(d interact.Context) error { 209 | d.SetDef(false, realize.Green.Regular("(n)")) 210 | return nil 211 | }, 212 | Quest: interact.Quest{ 213 | Options: realize.Yellow.Regular("[y/n]"), 214 | Msg: "Force polling watcher?", 215 | Resolve: func(d interact.Context) bool { 216 | val, _ := d.Ans().Bool() 217 | return val 218 | }, 219 | }, 220 | Subs: []*interact.Question{ 221 | { 222 | Before: func(d interact.Context) error { 223 | d.SetDef(100, realize.Green.Regular("(100ms)")) 224 | return nil 225 | }, 226 | Quest: interact.Quest{ 227 | Options: realize.Yellow.Regular("[int]"), 228 | Msg: "Set polling interval", 229 | }, 230 | Action: func(d interact.Context) interface{} { 231 | val, err := d.Ans().Int() 232 | if err != nil { 233 | return d.Err() 234 | } 235 | r.Settings.Legacy.Interval = time.Duration(int(val)) * time.Millisecond 236 | return nil 237 | }, 238 | }, 239 | }, 240 | Action: func(d interact.Context) interface{} { 241 | val, err := d.Ans().Bool() 242 | if err != nil { 243 | return d.Err() 244 | } 245 | r.Settings.Legacy.Force = val 246 | return nil 247 | }, 248 | }, 249 | { 250 | Before: func(d interact.Context) error { 251 | d.SetDef(false, realize.Green.Regular("(n)")) 252 | return nil 253 | }, 254 | Quest: interact.Quest{ 255 | Options: realize.Yellow.Regular("[y/n]"), 256 | Msg: "Enable logging files", 257 | }, 258 | Action: func(d interact.Context) interface{} { 259 | val, err := d.Ans().Bool() 260 | if err != nil { 261 | return d.Err() 262 | } 263 | r.Settings.Files.Errors = realize.Resource{Name: realize.FileErr, Status: val} 264 | r.Settings.Files.Outputs = realize.Resource{Name: realize.FileOut, Status: val} 265 | r.Settings.Files.Logs = realize.Resource{Name: realize.FileLog, Status: val} 266 | return nil 267 | }, 268 | }, 269 | { 270 | Before: func(d interact.Context) error { 271 | d.SetDef(false, realize.Green.Regular("(n)")) 272 | return nil 273 | }, 274 | Quest: interact.Quest{ 275 | Options: realize.Yellow.Regular("[y/n]"), 276 | Msg: "Enable web server", 277 | Resolve: func(d interact.Context) bool { 278 | val, _ := d.Ans().Bool() 279 | return val 280 | }, 281 | }, 282 | Subs: []*interact.Question{ 283 | { 284 | Before: func(d interact.Context) error { 285 | d.SetDef(realize.Port, realize.Green.Regular("("+strconv.Itoa(realize.Port)+")")) 286 | return nil 287 | }, 288 | Quest: interact.Quest{ 289 | Options: realize.Yellow.Regular("[int]"), 290 | Msg: "Server port", 291 | }, 292 | Action: func(d interact.Context) interface{} { 293 | val, err := d.Ans().Int() 294 | if err != nil { 295 | return d.Err() 296 | } 297 | r.Server.Port = int(val) 298 | return nil 299 | }, 300 | }, 301 | { 302 | Before: func(d interact.Context) error { 303 | d.SetDef(realize.Host, realize.Green.Regular("("+realize.Host+")")) 304 | return nil 305 | }, 306 | Quest: interact.Quest{ 307 | Options: realize.Yellow.Regular("[string]"), 308 | Msg: "Server host", 309 | }, 310 | Action: func(d interact.Context) interface{} { 311 | val, err := d.Ans().String() 312 | if err != nil { 313 | return d.Err() 314 | } 315 | r.Server.Host = val 316 | return nil 317 | }, 318 | }, 319 | { 320 | Before: func(d interact.Context) error { 321 | d.SetDef(false, realize.Green.Regular("(n)")) 322 | return nil 323 | }, 324 | Quest: interact.Quest{ 325 | Options: realize.Yellow.Regular("[y/n]"), 326 | Msg: "Open in current browser", 327 | }, 328 | Action: func(d interact.Context) interface{} { 329 | val, err := d.Ans().Bool() 330 | if err != nil { 331 | return d.Err() 332 | } 333 | r.Server.Open = val 334 | return nil 335 | }, 336 | }, 337 | }, 338 | Action: func(d interact.Context) interface{} { 339 | val, err := d.Ans().Bool() 340 | if err != nil { 341 | return d.Err() 342 | } 343 | r.Server.Status = val 344 | return nil 345 | }, 346 | }, 347 | }, 348 | Action: func(d interact.Context) interface{} { 349 | _, err := d.Ans().Bool() 350 | if err != nil { 351 | return d.Err() 352 | } 353 | return nil 354 | }, 355 | }, 356 | { 357 | Before: func(d interact.Context) error { 358 | d.SetDef(true, realize.Green.Regular("(y)")) 359 | d.SetEnd("!") 360 | return nil 361 | }, 362 | Quest: interact.Quest{ 363 | Options: realize.Yellow.Regular("[y/n]"), 364 | Msg: "Would you want to " + realize.Magenta.Regular("add a new project") + "? (insert '!' to stop)", 365 | Resolve: func(d interact.Context) bool { 366 | val, _ := d.Ans().Bool() 367 | if val { 368 | r.Schema.Add(r.Schema.New(c)) 369 | } 370 | return val 371 | }, 372 | }, 373 | Subs: []*interact.Question{ 374 | { 375 | Before: func(d interact.Context) error { 376 | d.SetDef(realize.Wdir(), realize.Green.Regular("("+realize.Wdir()+")")) 377 | return nil 378 | }, 379 | Quest: interact.Quest{ 380 | Options: realize.Yellow.Regular("[string]"), 381 | Msg: "Project name", 382 | }, 383 | Action: func(d interact.Context) interface{} { 384 | val, err := d.Ans().String() 385 | if err != nil { 386 | return d.Err() 387 | } 388 | r.Schema.Projects[len(r.Schema.Projects)-1].Name = val 389 | return nil 390 | }, 391 | }, 392 | { 393 | Before: func(d interact.Context) error { 394 | dir := realize.Wdir() 395 | d.SetDef(dir, realize.Green.Regular("("+dir+")")) 396 | return nil 397 | }, 398 | Quest: interact.Quest{ 399 | Options: realize.Yellow.Regular("[string]"), 400 | Msg: "Project path", 401 | }, 402 | Action: func(d interact.Context) interface{} { 403 | val, err := d.Ans().String() 404 | if err != nil { 405 | return d.Err() 406 | } 407 | r.Schema.Projects[len(r.Schema.Projects)-1].Path = filepath.Clean(val) 408 | return nil 409 | }, 410 | }, 411 | 412 | { 413 | Before: func(d interact.Context) error { 414 | d.SetDef(false, realize.Green.Regular("(n)")) 415 | return nil 416 | }, 417 | Quest: interact.Quest{ 418 | Options: realize.Yellow.Regular("[y/n]"), 419 | Msg: "Enable go vet", 420 | }, 421 | Subs: []*interact.Question{ 422 | { 423 | Before: func(d interact.Context) error { 424 | d.SetDef("", realize.Green.Regular("(none)")) 425 | return nil 426 | }, 427 | Quest: interact.Quest{ 428 | Options: realize.Yellow.Regular("[string]"), 429 | Msg: "Vet additional arguments", 430 | }, 431 | Action: func(d interact.Context) interface{} { 432 | val, err := d.Ans().String() 433 | if err != nil { 434 | return d.Err() 435 | } 436 | if val != "" { 437 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Vet.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Vet.Args, val) 438 | } 439 | return nil 440 | }, 441 | }, 442 | }, 443 | Action: func(d interact.Context) interface{} { 444 | val, err := d.Ans().Bool() 445 | if err != nil { 446 | return d.Err() 447 | } 448 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Vet.Status = val 449 | return nil 450 | }, 451 | }, 452 | { 453 | Before: func(d interact.Context) error { 454 | d.SetDef(false, realize.Green.Regular("(n)")) 455 | return nil 456 | }, 457 | Quest: interact.Quest{ 458 | Options: realize.Yellow.Regular("[y/n]"), 459 | Msg: "Enable go fmt", 460 | Resolve: func(d interact.Context) bool { 461 | val, _ := d.Ans().Bool() 462 | return val 463 | }, 464 | }, 465 | Subs: []*interact.Question{ 466 | { 467 | Before: func(d interact.Context) error { 468 | d.SetDef("", realize.Green.Regular("(none)")) 469 | return nil 470 | }, 471 | Quest: interact.Quest{ 472 | Options: realize.Yellow.Regular("[string]"), 473 | Msg: "Fmt additional arguments", 474 | }, 475 | Action: func(d interact.Context) interface{} { 476 | val, err := d.Ans().String() 477 | if err != nil { 478 | return d.Err() 479 | } 480 | if val != "" { 481 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Fmt.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Fmt.Args, val) 482 | } 483 | return nil 484 | }, 485 | }, 486 | }, 487 | Action: func(d interact.Context) interface{} { 488 | val, err := d.Ans().Bool() 489 | if err != nil { 490 | return d.Err() 491 | } 492 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Fmt.Status = val 493 | return nil 494 | }, 495 | }, 496 | { 497 | Before: func(d interact.Context) error { 498 | d.SetDef(false, realize.Green.Regular("(n)")) 499 | return nil 500 | }, 501 | Quest: interact.Quest{ 502 | Options: realize.Yellow.Regular("[y/n]"), 503 | Msg: "Enable go test", 504 | Resolve: func(d interact.Context) bool { 505 | val, _ := d.Ans().Bool() 506 | return val 507 | }, 508 | }, 509 | Subs: []*interact.Question{ 510 | { 511 | Before: func(d interact.Context) error { 512 | d.SetDef("", realize.Green.Regular("(none)")) 513 | return nil 514 | }, 515 | Quest: interact.Quest{ 516 | Options: realize.Yellow.Regular("[string]"), 517 | Msg: "Test additional arguments", 518 | }, 519 | Action: func(d interact.Context) interface{} { 520 | val, err := d.Ans().String() 521 | if err != nil { 522 | return d.Err() 523 | } 524 | if val != "" { 525 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Test.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Test.Args, val) 526 | } 527 | return nil 528 | }, 529 | }, 530 | }, 531 | Action: func(d interact.Context) interface{} { 532 | val, err := d.Ans().Bool() 533 | if err != nil { 534 | return d.Err() 535 | } 536 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Test.Status = val 537 | return nil 538 | }, 539 | }, 540 | { 541 | Before: func(d interact.Context) error { 542 | d.SetDef(false, realize.Green.Regular("(n)")) 543 | return nil 544 | }, 545 | Quest: interact.Quest{ 546 | Options: realize.Yellow.Regular("[y/n]"), 547 | Msg: "Enable go clean", 548 | Resolve: func(d interact.Context) bool { 549 | val, _ := d.Ans().Bool() 550 | return val 551 | }, 552 | }, 553 | Subs: []*interact.Question{ 554 | { 555 | Before: func(d interact.Context) error { 556 | d.SetDef("", realize.Green.Regular("(none)")) 557 | return nil 558 | }, 559 | Quest: interact.Quest{ 560 | Options: realize.Yellow.Regular("[string]"), 561 | Msg: "Clean additional arguments", 562 | }, 563 | Action: func(d interact.Context) interface{} { 564 | val, err := d.Ans().String() 565 | if err != nil { 566 | return d.Err() 567 | } 568 | if val != "" { 569 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Clean.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Clean.Args, val) 570 | } 571 | return nil 572 | }, 573 | }, 574 | }, 575 | Action: func(d interact.Context) interface{} { 576 | val, err := d.Ans().Bool() 577 | if err != nil { 578 | return d.Err() 579 | } 580 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Clean.Status = val 581 | return nil 582 | }, 583 | }, 584 | { 585 | Before: func(d interact.Context) error { 586 | d.SetDef(false, realize.Green.Regular("(n)")) 587 | return nil 588 | }, 589 | Quest: interact.Quest{ 590 | Options: realize.Yellow.Regular("[y/n]"), 591 | Msg: "Enable go generate", 592 | Resolve: func(d interact.Context) bool { 593 | val, _ := d.Ans().Bool() 594 | return val 595 | }, 596 | }, 597 | Subs: []*interact.Question{ 598 | { 599 | Before: func(d interact.Context) error { 600 | d.SetDef("", realize.Green.Regular("(none)")) 601 | return nil 602 | }, 603 | Quest: interact.Quest{ 604 | Options: realize.Yellow.Regular("[string]"), 605 | Msg: "Generate additional arguments", 606 | }, 607 | Action: func(d interact.Context) interface{} { 608 | val, err := d.Ans().String() 609 | if err != nil { 610 | return d.Err() 611 | } 612 | if val != "" { 613 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Generate.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Generate.Args, val) 614 | } 615 | return nil 616 | }, 617 | }, 618 | }, 619 | Action: func(d interact.Context) interface{} { 620 | val, err := d.Ans().Bool() 621 | if err != nil { 622 | return d.Err() 623 | } 624 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Generate.Status = val 625 | return nil 626 | }, 627 | }, 628 | { 629 | Before: func(d interact.Context) error { 630 | d.SetDef(true, realize.Green.Regular("(y)")) 631 | return nil 632 | }, 633 | Quest: interact.Quest{ 634 | Options: realize.Yellow.Regular("[y/n]"), 635 | Msg: "Enable go install", 636 | Resolve: func(d interact.Context) bool { 637 | val, _ := d.Ans().Bool() 638 | return val 639 | }, 640 | }, 641 | Subs: []*interact.Question{ 642 | { 643 | Before: func(d interact.Context) error { 644 | d.SetDef("", realize.Green.Regular("(none)")) 645 | return nil 646 | }, 647 | Quest: interact.Quest{ 648 | Options: realize.Yellow.Regular("[string]"), 649 | Msg: "Install additional arguments", 650 | }, 651 | Action: func(d interact.Context) interface{} { 652 | val, err := d.Ans().String() 653 | if err != nil { 654 | return d.Err() 655 | } 656 | if val != "" { 657 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Install.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Install.Args, val) 658 | } 659 | return nil 660 | }, 661 | }, 662 | }, 663 | Action: func(d interact.Context) interface{} { 664 | val, err := d.Ans().Bool() 665 | if err != nil { 666 | return d.Err() 667 | } 668 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Install.Status = val 669 | return nil 670 | }, 671 | }, 672 | { 673 | Before: func(d interact.Context) error { 674 | d.SetDef(false, realize.Green.Regular("(n)")) 675 | return nil 676 | }, 677 | Quest: interact.Quest{ 678 | Options: realize.Yellow.Regular("[y/n]"), 679 | Msg: "Enable go build", 680 | Resolve: func(d interact.Context) bool { 681 | val, _ := d.Ans().Bool() 682 | return val 683 | }, 684 | }, 685 | Subs: []*interact.Question{ 686 | { 687 | Before: func(d interact.Context) error { 688 | d.SetDef("", realize.Green.Regular("(none)")) 689 | return nil 690 | }, 691 | Quest: interact.Quest{ 692 | Options: realize.Yellow.Regular("[string]"), 693 | Msg: "Build additional arguments", 694 | }, 695 | Action: func(d interact.Context) interface{} { 696 | val, err := d.Ans().String() 697 | if err != nil { 698 | return d.Err() 699 | } 700 | if val != "" { 701 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Build.Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Build.Args, val) 702 | } 703 | return nil 704 | }, 705 | }, 706 | }, 707 | Action: func(d interact.Context) interface{} { 708 | val, err := d.Ans().Bool() 709 | if err != nil { 710 | return d.Err() 711 | } 712 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Build.Status = val 713 | return nil 714 | }, 715 | }, 716 | { 717 | Before: func(d interact.Context) error { 718 | d.SetDef(true, realize.Green.Regular("(y)")) 719 | return nil 720 | }, 721 | Quest: interact.Quest{ 722 | Options: realize.Yellow.Regular("[y/n]"), 723 | Msg: "Enable go run", 724 | }, 725 | Action: func(d interact.Context) interface{} { 726 | val, err := d.Ans().Bool() 727 | if err != nil { 728 | return d.Err() 729 | } 730 | r.Schema.Projects[len(r.Schema.Projects)-1].Tools.Run.Status = val 731 | return nil 732 | }, 733 | }, 734 | { 735 | Before: func(d interact.Context) error { 736 | d.SetDef(false, realize.Green.Regular("(n)")) 737 | return nil 738 | }, 739 | Quest: interact.Quest{ 740 | Options: realize.Yellow.Regular("[y/n]"), 741 | Msg: "Customize watching paths", 742 | Resolve: func(d interact.Context) bool { 743 | val, _ := d.Ans().Bool() 744 | if val { 745 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Paths = r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Paths[:len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Paths)-1] 746 | } 747 | return val 748 | }, 749 | }, 750 | Subs: []*interact.Question{ 751 | { 752 | Before: func(d interact.Context) error { 753 | d.SetEnd("!") 754 | return nil 755 | }, 756 | Quest: interact.Quest{ 757 | Options: realize.Yellow.Regular("[string]"), 758 | Msg: "Insert a path to watch (insert '!' to stop)", 759 | }, 760 | Action: func(d interact.Context) interface{} { 761 | val, err := d.Ans().String() 762 | if err != nil { 763 | return d.Err() 764 | } 765 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Paths = append(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Paths, val) 766 | d.Reload() 767 | return nil 768 | }, 769 | }, 770 | }, 771 | Action: func(d interact.Context) interface{} { 772 | _, err := d.Ans().Bool() 773 | if err != nil { 774 | return d.Err() 775 | } 776 | return nil 777 | }, 778 | }, 779 | { 780 | Before: func(d interact.Context) error { 781 | d.SetDef(false, realize.Green.Regular("(n)")) 782 | return nil 783 | }, 784 | Quest: interact.Quest{ 785 | Options: realize.Yellow.Regular("[y/n]"), 786 | Msg: "Customize ignore paths", 787 | Resolve: func(d interact.Context) bool { 788 | val, _ := d.Ans().Bool() 789 | if val { 790 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Ignore = r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Ignore[:len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Ignore)-1] 791 | } 792 | return val 793 | }, 794 | }, 795 | Subs: []*interact.Question{ 796 | { 797 | Before: func(d interact.Context) error { 798 | d.SetEnd("!") 799 | return nil 800 | }, 801 | Quest: interact.Quest{ 802 | Options: realize.Yellow.Regular("[string]"), 803 | Msg: "Insert a path to ignore (insert '!' to stop)", 804 | }, 805 | Action: func(d interact.Context) interface{} { 806 | val, err := d.Ans().String() 807 | if err != nil { 808 | return d.Err() 809 | } 810 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Ignore = append(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Ignore, val) 811 | d.Reload() 812 | return nil 813 | }, 814 | }, 815 | }, 816 | Action: func(d interact.Context) interface{} { 817 | _, err := d.Ans().Bool() 818 | if err != nil { 819 | return d.Err() 820 | } 821 | return nil 822 | }, 823 | }, 824 | { 825 | Before: func(d interact.Context) error { 826 | d.SetDef(false, realize.Green.Regular("(n)")) 827 | return nil 828 | }, 829 | Quest: interact.Quest{ 830 | Options: realize.Yellow.Regular("[y/n]"), 831 | Msg: "Add an additional argument", 832 | Resolve: func(d interact.Context) bool { 833 | val, _ := d.Ans().Bool() 834 | return val 835 | }, 836 | }, 837 | Subs: []*interact.Question{ 838 | { 839 | Before: func(d interact.Context) error { 840 | d.SetEnd("!") 841 | return nil 842 | }, 843 | Quest: interact.Quest{ 844 | Options: realize.Yellow.Regular("[string]"), 845 | Msg: "Add another argument (insert '!' to stop)", 846 | }, 847 | Action: func(d interact.Context) interface{} { 848 | val, err := d.Ans().String() 849 | if err != nil { 850 | return d.Err() 851 | } 852 | r.Schema.Projects[len(r.Schema.Projects)-1].Args = append(r.Schema.Projects[len(r.Schema.Projects)-1].Args, val) 853 | d.Reload() 854 | return nil 855 | }, 856 | }, 857 | }, 858 | Action: func(d interact.Context) interface{} { 859 | _, err := d.Ans().Bool() 860 | if err != nil { 861 | return d.Err() 862 | } 863 | return nil 864 | }, 865 | }, 866 | { 867 | Before: func(d interact.Context) error { 868 | d.SetDef(false, realize.Green.Regular("(none)")) 869 | d.SetEnd("!") 870 | return nil 871 | }, 872 | Quest: interact.Quest{ 873 | Options: realize.Yellow.Regular("[y/n]"), 874 | Msg: "Add a 'before' custom command (insert '!' to stop)", 875 | Resolve: func(d interact.Context) bool { 876 | val, _ := d.Ans().Bool() 877 | return val 878 | }, 879 | }, 880 | Subs: []*interact.Question{ 881 | { 882 | Before: func(d interact.Context) error { 883 | return nil 884 | }, 885 | Quest: interact.Quest{ 886 | Options: realize.Yellow.Regular("[string]"), 887 | Msg: "Insert a command", 888 | }, 889 | Action: func(d interact.Context) interface{} { 890 | val, err := d.Ans().String() 891 | if err != nil { 892 | return d.Err() 893 | } 894 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts = append(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts, realize.Command{Type: "before", Cmd: val}) 895 | return nil 896 | }, 897 | }, 898 | { 899 | Before: func(d interact.Context) error { 900 | d.SetDef("", realize.Green.Regular("(n)")) 901 | return nil 902 | }, 903 | Quest: interact.Quest{ 904 | Options: realize.Yellow.Regular("[string]"), 905 | Msg: "Launch from a specific path", 906 | }, 907 | Action: func(d interact.Context) interface{} { 908 | val, err := d.Ans().String() 909 | if err != nil { 910 | return d.Err() 911 | } 912 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Path = val 913 | return nil 914 | }, 915 | }, 916 | { 917 | Before: func(d interact.Context) error { 918 | d.SetDef(false, realize.Green.Regular("(n)")) 919 | return nil 920 | }, 921 | Quest: interact.Quest{ 922 | Options: realize.Yellow.Regular("[y/n]"), 923 | Msg: "Tag as global command", 924 | }, 925 | Action: func(d interact.Context) interface{} { 926 | val, err := d.Ans().Bool() 927 | if err != nil { 928 | return d.Err() 929 | } 930 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Global = val 931 | return nil 932 | }, 933 | }, 934 | { 935 | Before: func(d interact.Context) error { 936 | d.SetDef(false, realize.Green.Regular("(n)")) 937 | return nil 938 | }, 939 | Quest: interact.Quest{ 940 | Options: realize.Yellow.Regular("[y/n]"), 941 | Msg: "Display command output", 942 | }, 943 | Action: func(d interact.Context) interface{} { 944 | val, err := d.Ans().Bool() 945 | if err != nil { 946 | return d.Err() 947 | } 948 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Output = val 949 | return nil 950 | }, 951 | }, 952 | }, 953 | Action: func(d interact.Context) interface{} { 954 | val, err := d.Ans().Bool() 955 | if err != nil { 956 | return d.Err() 957 | } 958 | if val { 959 | d.Reload() 960 | } 961 | return nil 962 | }, 963 | }, 964 | { 965 | Before: func(d interact.Context) error { 966 | d.SetDef(false, realize.Green.Regular("(none)")) 967 | d.SetEnd("!") 968 | return nil 969 | }, 970 | Quest: interact.Quest{ 971 | Options: realize.Yellow.Regular("[y/n]"), 972 | Msg: "Add an 'after' custom commands (insert '!' to stop)", 973 | Resolve: func(d interact.Context) bool { 974 | val, _ := d.Ans().Bool() 975 | return val 976 | }, 977 | }, 978 | Subs: []*interact.Question{ 979 | { 980 | Before: func(d interact.Context) error { 981 | return nil 982 | }, 983 | Quest: interact.Quest{ 984 | Options: realize.Yellow.Regular("[string]"), 985 | Msg: "Insert a command", 986 | }, 987 | Action: func(d interact.Context) interface{} { 988 | val, err := d.Ans().String() 989 | if err != nil { 990 | return d.Err() 991 | } 992 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts = append(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts, realize.Command{Type: "after", Cmd: val}) 993 | return nil 994 | }, 995 | }, 996 | { 997 | Before: func(d interact.Context) error { 998 | d.SetDef("", realize.Green.Regular("(n)")) 999 | return nil 1000 | }, 1001 | Quest: interact.Quest{ 1002 | Options: realize.Yellow.Regular("[string]"), 1003 | Msg: "Launch from a specific path", 1004 | }, 1005 | Action: func(d interact.Context) interface{} { 1006 | val, err := d.Ans().String() 1007 | if err != nil { 1008 | return d.Err() 1009 | } 1010 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Path = val 1011 | return nil 1012 | }, 1013 | }, 1014 | { 1015 | Before: func(d interact.Context) error { 1016 | d.SetDef(false, realize.Green.Regular("(n)")) 1017 | return nil 1018 | }, 1019 | Quest: interact.Quest{ 1020 | Options: realize.Yellow.Regular("[y/n]"), 1021 | Msg: "Tag as global command", 1022 | }, 1023 | Action: func(d interact.Context) interface{} { 1024 | val, err := d.Ans().Bool() 1025 | if err != nil { 1026 | return d.Err() 1027 | } 1028 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Global = val 1029 | return nil 1030 | }, 1031 | }, 1032 | { 1033 | Before: func(d interact.Context) error { 1034 | d.SetDef(false, realize.Green.Regular("(n)")) 1035 | return nil 1036 | }, 1037 | Quest: interact.Quest{ 1038 | Options: realize.Yellow.Regular("[y/n]"), 1039 | Msg: "Display command output", 1040 | }, 1041 | Action: func(d interact.Context) interface{} { 1042 | val, err := d.Ans().Bool() 1043 | if err != nil { 1044 | return d.Err() 1045 | } 1046 | r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts[len(r.Schema.Projects[len(r.Schema.Projects)-1].Watcher.Scripts)-1].Output = val 1047 | return nil 1048 | }, 1049 | }, 1050 | }, 1051 | Action: func(d interact.Context) interface{} { 1052 | val, err := d.Ans().Bool() 1053 | if err != nil { 1054 | return d.Err() 1055 | } 1056 | if val { 1057 | d.Reload() 1058 | } 1059 | return nil 1060 | }, 1061 | }, 1062 | { 1063 | Before: func(d interact.Context) error { 1064 | d.SetDef("", realize.Green.Regular("(none)")) 1065 | return nil 1066 | }, 1067 | Quest: interact.Quest{ 1068 | Options: realize.Yellow.Regular("[string]"), 1069 | Msg: "Set an error output pattern", 1070 | }, 1071 | Action: func(d interact.Context) interface{} { 1072 | val, err := d.Ans().String() 1073 | if err != nil { 1074 | return d.Err() 1075 | } 1076 | r.Schema.Projects[len(r.Schema.Projects)-1].ErrPattern = val 1077 | return nil 1078 | }, 1079 | }, 1080 | }, 1081 | Action: func(d interact.Context) interface{} { 1082 | if val, err := d.Ans().Bool(); err != nil { 1083 | return d.Err() 1084 | } else if val { 1085 | d.Reload() 1086 | } 1087 | return nil 1088 | }, 1089 | }, 1090 | }, 1091 | After: func(d interact.Context) error { 1092 | if val, _ := d.Qns().Get(0).Ans().Bool(); val { 1093 | err := r.Settings.Remove(realize.RFile) 1094 | if err != nil { 1095 | return err 1096 | } 1097 | } 1098 | return nil 1099 | }, 1100 | }) 1101 | // create config 1102 | err = r.Settings.Write(r) 1103 | if err != nil { 1104 | return err 1105 | } 1106 | log.Println(r.Prefix(realize.Green.Bold("Config successfully created"))) 1107 | return nil 1108 | } 1109 | 1110 | // Start realize workflow 1111 | func start(c *cli.Context) (err error) { 1112 | // set legacy watcher 1113 | if c.Bool("legacy") { 1114 | r.Settings.Legacy.Set(c.Bool("legacy"), 1) 1115 | } 1116 | // set server 1117 | if c.Bool("server") { 1118 | r.Server.Set(c.Bool("server"), c.Bool("open"), realize.Port, realize.Host) 1119 | } 1120 | 1121 | // check no-config and read 1122 | if !c.Bool("no-config") { 1123 | // read a config if exist 1124 | r.Settings.Read(&r) 1125 | if c.String("name") != "" { 1126 | // filter by name flag if exist 1127 | r.Schema.Projects = r.Schema.Filter("Name", c.String("name")) 1128 | } 1129 | // increase file limit 1130 | if r.Settings.FileLimit != 0 { 1131 | if err = r.Settings.Flimit(); err != nil { 1132 | return err 1133 | } 1134 | } 1135 | 1136 | } 1137 | // check project list length 1138 | if len(r.Schema.Projects) == 0 { 1139 | // create a new project based on given params 1140 | project := r.Schema.New(c) 1141 | // Add to projects list 1142 | r.Schema.Add(project) 1143 | // save config 1144 | if !c.Bool("no-config") { 1145 | err = r.Settings.Write(r) 1146 | if err != nil { 1147 | return err 1148 | } 1149 | } 1150 | } 1151 | // Start web server 1152 | if r.Server.Status { 1153 | r.Server.Parent = &r 1154 | err = r.Server.Start() 1155 | if err != nil { 1156 | return err 1157 | } 1158 | err = r.Server.OpenURL() 1159 | if err != nil { 1160 | return err 1161 | } 1162 | } 1163 | // start workflow 1164 | return r.Start() 1165 | } 1166 | 1167 | // Remove a project from an existing config 1168 | func remove(c *cli.Context) (err error) { 1169 | // read a config if exist 1170 | err = r.Settings.Read(&r) 1171 | if err != nil { 1172 | return err 1173 | } 1174 | if c.String("name") != "" { 1175 | err := r.Schema.Remove(c.String("name")) 1176 | if err != nil { 1177 | return err 1178 | } 1179 | // update config 1180 | err = r.Settings.Write(r) 1181 | if err != nil { 1182 | return err 1183 | } 1184 | log.Println(r.Prefix(realize.Green.Bold("project successfully removed"))) 1185 | } else { 1186 | log.Println(r.Prefix(realize.Green.Bold("project name not found"))) 1187 | } 1188 | return nil 1189 | } 1190 | --------------------------------------------------------------------------------