github.com/mailru/activerecord@v1.12.2/internal/pkg/testutil/app.go (about) 1 package testutil 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "runtime" 8 "strings" 9 "time" 10 11 "github.com/mailru/activerecord/internal/pkg/ds" 12 ) 13 14 var TestAppInfo = *ds.NewAppInfo(). 15 WithBuildOS(runtime.GOOS). 16 WithBuildTime(time.Now().String()). 17 WithVersion("1.0"). 18 WithBuildCommit("nocommit") 19 20 type Tmps struct { 21 dirs []string 22 } 23 24 func InitTmps() *Tmps { 25 return &Tmps{ 26 dirs: []string{}, 27 } 28 } 29 30 func (tmp *Tmps) AddTempDir(basepath ...string) (string, error) { 31 rootTmpDir := os.TempDir() 32 if len(basepath) > 0 { 33 rootTmpDir = basepath[0] 34 } 35 36 newTempDir, err := os.MkdirTemp(rootTmpDir, "argen_testdir*") 37 if err != nil { 38 return "", fmt.Errorf("can't create temp dir for test: %s", err) 39 } 40 41 tmp.dirs = append(tmp.dirs, newTempDir) 42 43 return newTempDir, nil 44 } 45 46 const ( 47 EmptyDstDir uint32 = 1 << iota 48 NonExistsDstDir 49 NonExistsSrcDir 50 ) 51 52 func (tmp *Tmps) CreateDirs(flags uint32) (string, string, error) { 53 projectDir, err := tmp.AddTempDir() 54 if err != nil { 55 return "", "", fmt.Errorf("can't create root test dir: %w", err) 56 } 57 58 srcDir := filepath.Join(projectDir, "src") 59 if flags&NonExistsSrcDir != NonExistsSrcDir { 60 if err := os.MkdirAll(srcDir, 0750); err != nil { 61 return "", "", fmt.Errorf("can't create temp src dir: %w", err) 62 } 63 } 64 65 dstDir := "" 66 67 switch { 68 case flags&NonExistsDstDir == NonExistsDstDir: 69 dstDir = filepath.Join(projectDir, "nonexistsdst") 70 case flags&EmptyDstDir == EmptyDstDir: 71 dstDir = filepath.Join(projectDir, "dst") 72 if err := os.MkdirAll(dstDir, 0750); err != nil { 73 return "", "", fmt.Errorf("can't create temp dst dir: %w", err) 74 } 75 76 if err := os.WriteFile(filepath.Join(dstDir, ".argen"), []byte("test argen special file"), 0600); err != nil { 77 return "", "", fmt.Errorf("can't create special file into dst") 78 } 79 } 80 81 return srcDir, dstDir, nil 82 } 83 84 func (tmp *Tmps) Defer() { 85 for _, dir := range tmp.dirs { 86 os.RemoveAll(dir) 87 } 88 } 89 90 func GetPathToSrc() string { 91 _, filename, _, _ := runtime.Caller(0) 92 filenameSplit := strings.Split(filename, string(filepath.Separator)) 93 94 return string(filepath.Separator) + filepath.Join(filenameSplit[:len(filenameSplit)-4]...) 95 }