github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/archive/zip_archiver.go (about) 1 package archive 2 3 import ( 4 "archive/zip" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 ) 10 11 type ZipArchiver struct { 12 filepath string 13 filewriter *os.File 14 writer *zip.Writer 15 } 16 17 func NewZipArchiver(filepath string) Archiver { 18 return &ZipArchiver{ 19 filepath: filepath, 20 } 21 } 22 23 func (a *ZipArchiver) ArchiveContent(content []byte, infilename string) error { 24 if err := a.open(); err != nil { 25 return err 26 } 27 defer a.close() 28 29 f, err := a.writer.Create(infilename) 30 if err != nil { 31 return err 32 } 33 34 _, err = f.Write(content) 35 return err 36 } 37 38 func (a *ZipArchiver) ArchiveFile(infilename string) error { 39 fi, err := assertValidFile(infilename) 40 if err != nil { 41 return err 42 } 43 44 content, err := ioutil.ReadFile(infilename) 45 if err != nil { 46 return err 47 } 48 49 return a.ArchiveContent(content, fi.Name()) 50 } 51 52 func (a *ZipArchiver) ArchiveDir(indirname string) error { 53 _, err := assertValidDir(indirname) 54 if err != nil { 55 return err 56 } 57 58 if err := a.open(); err != nil { 59 return err 60 } 61 defer a.close() 62 63 return filepath.Walk(indirname, func(path string, info os.FileInfo, err error) error { 64 if info.IsDir() { 65 return nil 66 } 67 if err != nil { 68 return err 69 } 70 relname, err := filepath.Rel(indirname, path) 71 if err != nil { 72 return fmt.Errorf("error relativizing file for archival: %s", err) 73 } 74 f, err := a.writer.Create(relname) 75 if err != nil { 76 return fmt.Errorf("error creating file inside archive: %s", err) 77 } 78 content, err := ioutil.ReadFile(path) 79 if err != nil { 80 return fmt.Errorf("error reading file for archival: %s", err) 81 } 82 _, err = f.Write(content) 83 return err 84 }) 85 86 } 87 88 func (a *ZipArchiver) open() error { 89 f, err := os.Create(a.filepath) 90 if err != nil { 91 return err 92 } 93 a.filewriter = f 94 a.writer = zip.NewWriter(f) 95 return nil 96 } 97 98 func (a *ZipArchiver) close() { 99 if a.writer != nil { 100 a.writer.Close() 101 a.writer = nil 102 } 103 if a.filewriter != nil { 104 a.filewriter.Close() 105 a.filewriter = nil 106 } 107 }