You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

  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. package zip
  15. import (
  16. "archive/zip"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. )
  21. // A StreamArchive represents a streamable archive.
  22. type StreamArchive struct {
  23. *zip.Writer
  24. }
  25. // NewStreamArachive returns a new streamable archive with given io.Writer.
  26. // It's caller's responsibility to close io.Writer and streamer after operation.
  27. func NewStreamArachive(w io.Writer) *StreamArchive {
  28. return &StreamArchive{zip.NewWriter(w)}
  29. }
  30. // StreamFile streams a file or directory entry into StreamArchive.
  31. func (s *StreamArchive) StreamFile(relPath string, fi os.FileInfo, data []byte) error {
  32. if fi.IsDir() {
  33. fh, err := zip.FileInfoHeader(fi)
  34. if err != nil {
  35. return err
  36. }
  37. fh.Name = relPath + "/"
  38. if _, err = s.Writer.CreateHeader(fh); err != nil {
  39. return err
  40. }
  41. } else {
  42. fh, err := zip.FileInfoHeader(fi)
  43. if err != nil {
  44. return err
  45. }
  46. fh.Name = filepath.Join(relPath, fi.Name())
  47. fh.Method = zip.Deflate
  48. fw, err := s.Writer.CreateHeader(fh)
  49. if err != nil {
  50. return err
  51. } else if _, err = fw.Write(data); err != nil {
  52. return err
  53. }
  54. }
  55. return nil
  56. }
  57. // StreamReader streams data from io.Reader to StreamArchive.
  58. func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) {
  59. fh, err := zip.FileInfoHeader(fi)
  60. if err != nil {
  61. return err
  62. }
  63. fh.Name = filepath.Join(relPath, fi.Name())
  64. fw, err := s.Writer.CreateHeader(fh)
  65. if err != nil {
  66. return err
  67. }
  68. _, err = io.Copy(fw, r)
  69. return err
  70. }