tar.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "archive/tar"
  16. "compress/gzip"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "github.com/pkg/errors"
  22. )
  23. // tarDir takes a source and variable writers and walks 'source' writing each file
  24. // found to the tar writer.
  25. func tarDir(dir, outpath string) error {
  26. // ensure the src actually exists before trying to tar it
  27. if _, err := os.Stat(dir); err != nil {
  28. return errors.Wrapf(err, "tar unable to stat directory %v", dir)
  29. }
  30. outfile, err := os.Create(outpath)
  31. if err != nil {
  32. return errors.Wrapf(err, "creating tarball %v", outpath)
  33. }
  34. defer outfile.Close()
  35. gzw := gzip.NewWriter(outfile)
  36. defer gzw.Close()
  37. tw := tar.NewWriter(gzw)
  38. defer tw.Close()
  39. return filepath.Walk(dir, func(file string, fi os.FileInfo, err error) error {
  40. // Return on any error.
  41. if err != nil {
  42. return err
  43. }
  44. // Only write regular files and don't include the archive itself.
  45. if !fi.Mode().IsRegular() || filepath.Join(dir, fi.Name()) == outpath {
  46. return nil
  47. }
  48. // Create a new dir/file header.
  49. header, err := tar.FileInfoHeader(fi, fi.Name())
  50. if err != nil {
  51. return errors.Wrapf(err, "creating file info header %v", fi.Name())
  52. }
  53. // Update the name to correctly reflect the desired destination when untaring.
  54. header.Name = strings.TrimPrefix(strings.Replace(file, dir, "", -1), string(filepath.Separator))
  55. if err := tw.WriteHeader(header); err != nil {
  56. return errors.Wrapf(err, "writing header for tarball %v", header.Name)
  57. }
  58. // Open files, copy into tarfile, and close.
  59. f, err := os.Open(file)
  60. if err != nil {
  61. return errors.Wrapf(err, "opening file %v for writing into tarball", file)
  62. }
  63. defer f.Close()
  64. _, err = io.Copy(tw, f)
  65. return errors.Wrapf(err, "creating file %v contents into tarball", file)
  66. })
  67. }