github.com/alkemics/goflow@v0.2.1/run.go (about) 1 package goflow 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path" 8 "strings" 9 "time" 10 ) 11 12 // WriteFile writes content into a file called filename. It updates the file only 13 // if there is a difference between the current content of the file and what is 14 // passed in content. 15 // 16 // It also logs the time taken since start, because why not. 17 func WriteFile(content, filename string, start time.Time) error { 18 before, err := ioutil.ReadFile(filename) 19 if err != nil && !os.IsNotExist(err) { 20 return err 21 } 22 if string(before) == content { 23 // Do not write file if there is nothing new to write... 24 return nil 25 } 26 27 created := os.IsNotExist(err) 28 29 wf, err := os.OpenFile(filename, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0o600) 30 if err != nil { 31 return err 32 } 33 defer wf.Close() 34 35 if _, err := wf.WriteString(content); err != nil { 36 return err 37 } 38 39 action := "updated" 40 if created { 41 action = "created" 42 } 43 fmt.Println(filename, action, "in", time.Since(start)) 44 45 return nil 46 } 47 48 func FindGraphFileNames(dir string) ([]string, error) { 49 files, err := ioutil.ReadDir(dir) 50 if err != nil { 51 return nil, err 52 } 53 54 graphNames := make([]string, 0) 55 for _, file := range files { 56 if file.IsDir() && file.Name() != "vendor" { 57 subs, err := FindGraphFileNames(path.Join(dir, file.Name())) 58 if err != nil { 59 return nil, err 60 } 61 graphNames = append(graphNames, subs...) 62 } else if strings.HasSuffix(file.Name(), ".yml") { 63 graphNames = append(graphNames, path.Join(dir, file.Name())) 64 } 65 } 66 67 return graphNames, nil 68 }