github.com/chrislusf/greenpack@v3.7.1-0.20170911073826-ad5bd10b7c47+incompatible/cmd/addzid/tdir.go (about) 1 package main 2 3 import ( 4 "io/ioutil" 5 "os" 6 "os/exec" 7 ) 8 9 type TempDir struct { 10 OrigDir string 11 DirPath string 12 Files map[string]*os.File 13 } 14 15 func NewTempDir() *TempDir { 16 dirname, err := ioutil.TempDir(".", "testdir_") 17 if err != nil { 18 panic(err) 19 } 20 origdir, err := os.Getwd() 21 if err != nil { 22 panic(err) 23 } 24 25 // add files needed for capnpc -ogo compilation 26 exec.Command("/bin/cp", "go.capnp", dirname).Run() 27 28 return &TempDir{ 29 OrigDir: origdir, 30 DirPath: dirname, 31 Files: make(map[string]*os.File), 32 } 33 } 34 35 func (d *TempDir) MoveTo() { 36 err := os.Chdir(d.DirPath) 37 if err != nil { 38 panic(err) 39 } 40 } 41 42 func (d *TempDir) Close() { 43 for _, f := range d.Files { 44 f.Close() 45 } 46 } 47 48 func (d *TempDir) Cleanup() { 49 d.Close() 50 err := os.RemoveAll(d.DirPath) 51 if err != nil { 52 panic(err) 53 } 54 err = os.Chdir(d.OrigDir) 55 if err != nil { 56 panic(err) 57 } 58 } 59 60 func (d *TempDir) TempFile() *os.File { 61 62 f, err := ioutil.TempFile(d.DirPath, "testfile.") 63 if err != nil { 64 panic(err) 65 } 66 d.Files[f.Name()] = f 67 return f 68 }