github.com/saymoon/flop@v0.1.6-0.20201205092451-00912199cc96/util_test.go (about) 1 package flop 2 3 import ( 4 "fmt" 5 "github.com/rs/zerolog" 6 "github.com/rs/zerolog/log" 7 "io/ioutil" 8 "os" 9 "path" 10 "path/filepath" 11 "strings" 12 ) 13 14 // memoizeTmpDir holds memoization info for the temporary directory 15 var memoizeTmpDir string 16 17 // unusedFileNum tracks a unique file identifier 18 var unusedFileNum int 19 20 // unusedDirNum tracks a unique dir identifier 21 var unusedDirNum int 22 23 // tmpDirPath gets the path of a temporary directory on the system 24 func tmpDirPath() string { 25 // memoize 26 if memoizeTmpDir != "" { 27 return memoizeTmpDir 28 } 29 30 d, _ := ioutil.TempDir("", "") 31 return d 32 } 33 34 // tmpDirPathUnused returns the path for a temp directory that does not exist yet 35 func tmpDirPathUnused() string { 36 d, err := ioutil.TempDir("", "") 37 if err != nil { 38 panic(err) 39 } 40 41 for { 42 d = filepath.Join(d, fmt.Sprintf("%s%d", "dir", unusedDirNum)) 43 // we expect to see an error if the dir path is unused 44 if _, err := os.Stat(d); err == nil { 45 // bump file number if the file created with that number exists 46 unusedDirNum += 1 47 } else { 48 return d 49 } 50 } 51 } 52 53 // tmpFile creates a new, empty temporary file and returns the full path 54 func tmpFile() string { 55 src, err := ioutil.TempFile("", "*.txt") 56 if err != nil { 57 panic(fmt.Sprintf("temp file creation failed: %s", err)) 58 } 59 defer func() { 60 _ = src.Close() 61 }() 62 63 return src.Name() 64 } 65 66 // tmpFilePathUnused returns the path for a temp file that does not yet exist 67 func tmpFilePathUnused() string { 68 d, err := ioutil.TempDir("", "") 69 if err != nil { 70 panic(err) 71 } 72 73 // derive file name of potentially unused file 74 tmpFile := func() string { 75 return path.Join(d, fmt.Sprintf("%s%d", "file", unusedFileNum)) 76 } 77 78 for { 79 // we expect to see an error if the file path is unused 80 if _, err := os.Stat(tmpFile()); err == nil { 81 // bump file number if the file created with that number exists 82 unusedFileNum += 1 83 } else { 84 return tmpFile() 85 } 86 } 87 } 88 89 func errContains(err error, substring string) bool { 90 errString := fmt.Sprintf("%s", err) 91 if strings.Contains(errString, substring) { 92 return true 93 } 94 fmt.Println("error:", errString) 95 fmt.Println("substring:", substring) 96 return false 97 } 98 99 func debugLogger(msg string) { 100 if debug { 101 log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 102 log.Debug().Msg(msg) 103 } 104 } 105 106 func infoLogger(msg string) { 107 if debug { 108 log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) 109 log.Info().Msg(msg) 110 } 111 }