github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/Unknwon/cae/tz/stream.go (about) 1 // Copyright 2014 Unknown 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations 13 // under the License. 14 15 package tz 16 17 import ( 18 "archive/tar" 19 "compress/gzip" 20 "io" 21 "os" 22 "path/filepath" 23 ) 24 25 // A StreamArchive represents a streamable archive. 26 type StreamArchive struct { 27 *tar.Writer 28 gw *gzip.Writer 29 } 30 31 func (s *StreamArchive) Close() (err error) { 32 if err = s.Writer.Close(); err != nil { 33 return err 34 } 35 return s.gw.Close() 36 } 37 38 // NewStreamArachive returns a new streamable archive with given io.Writer. 39 // It's caller's responsibility to close io.Writer and streamer after operation. 40 func NewStreamArachive(w io.Writer) *StreamArchive { 41 s := &StreamArchive{} 42 s.gw = gzip.NewWriter(w) 43 s.Writer = tar.NewWriter(s.gw) 44 return s 45 } 46 47 // StreamFile streams a file or directory entry into StreamArchive. 48 func (s *StreamArchive) StreamFile(relPath string, fi os.FileInfo, data []byte) error { 49 if fi.IsDir() { 50 fh, err := tar.FileInfoHeader(fi, "") 51 if err != nil { 52 return err 53 } 54 fh.Name = relPath + "/" 55 if err = s.Writer.WriteHeader(fh); err != nil { 56 return err 57 } 58 } else { 59 target := "" 60 if fi.Mode()&os.ModeSymlink != 0 { 61 target = string(data) 62 } 63 64 fh, err := tar.FileInfoHeader(fi, target) 65 if err != nil { 66 return err 67 } 68 fh.Name = filepath.Join(relPath, fi.Name()) 69 if err = s.Writer.WriteHeader(fh); err != nil { 70 return err 71 } 72 73 if _, err = s.Writer.Write(data); err != nil { 74 return err 75 } 76 } 77 return nil 78 } 79 80 // StreamReader streams data from io.Reader to StreamArchive. 81 func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) { 82 fh, err := tar.FileInfoHeader(fi, "") 83 if err != nil { 84 return err 85 } 86 fh.Name = filepath.Join(relPath, fi.Name()) 87 if err = s.Writer.WriteHeader(fh); err != nil { 88 return err 89 } 90 _, err = io.Copy(s.Writer, r) 91 return err 92 }