github.com/windmilleng/wat@v0.0.2-0.20180626175338-9349b638e250/cli/wat/ignore.go (about) 1 package wat 2 3 import ( 4 "fmt" 5 "os" 6 7 "strings" 8 9 "io/ioutil" 10 11 "path/filepath" 12 13 "github.com/monochromegane/go-gitignore" 14 ) 15 16 var defaultIgnores = []string{ 17 "# WAT DEFAULT IGNORES", // just a comment... 18 ".git", 19 ".wat", 20 21 // language-specific 22 "node_modules", 23 "vendor", 24 "*.pyc", 25 26 // editor-specific 27 ".idea", 28 29 // ...windmill specific -- TODO: remove 30 "frontend", 31 "build", 32 "sphinx", 33 } 34 35 func MakeWatIgnore(root string) error { 36 contents, err := makeWatIgnoreContents(root, defaultIgnores) 37 if err != nil { 38 return err 39 } 40 41 watIgnorePath := filepath.Join(root, fnameWatIgnore) 42 return ioutil.WriteFile(watIgnorePath, []byte(contents), permFile) 43 } 44 45 func makeWatIgnoreContents(root string, defaults []string) (string, error) { 46 gitIgnorePath := filepath.Join(root, fnameGitIgnore) 47 48 // populate .watignore w/ contents of .gitignore 49 existing, err := ioutil.ReadFile(gitIgnorePath) 50 if err != nil { 51 if os.IsNotExist(err) { 52 // .gitignore doesn't exist, populate .watignore with defaults stuff 53 return strings.Join(defaults, "\n"), nil 54 } 55 return "", fmt.Errorf("ioutil.ReadFile(%s): %v", gitIgnorePath, err) 56 } 57 lines := strings.Split(string(existing), "\n") 58 59 // add defaults (deduped against existing lines) 60 defaultsToAdd := dedupeAgainst(defaults, lines) 61 if len(defaultsToAdd) > 0 { 62 lines = append(lines, "") // line break 63 lines = append(lines, defaultsToAdd...) 64 } 65 66 return strings.Join(lines, "\n"), nil 67 } 68 69 func watIgnoreOrDummy(ignorePath string) matcher { 70 // if file doesn't exist (or we can't parse it for some reason), return a dummy 71 ignore, err := gitignore.NewGitIgnore(ignorePath) 72 if err != nil { 73 if !os.IsNotExist(err) { 74 // File exists, something weird is going on 75 fmt.Fprintf(os.Stderr, 76 "ERROR: ignore file at %s exists, but err calling NewGitIgnore: %v", 77 ignorePath, err) 78 } 79 return dummyWatIgnore{} 80 } 81 return ignore 82 } 83 84 type matcher interface { 85 Match(string, bool) bool 86 } 87 88 type dummyWatIgnore struct{} 89 90 // Dummy Wat Ignore doesn't match any files (i.e. doesn't ignore anything) 91 func (dummyWatIgnore) Match(string, bool) bool { 92 return false 93 }