version: 1.10

package tar

import "archive/tar"

Overview

Package tar implements access to tar archives.

Tape archives (tar) are a file format for storing a sequence of files that can
be read and written in a streaming manner. This package aims to cover most
variations of the format, including those produced by GNU and BSD tar tools.


Example:

  1. // Create and add some files to the archive.
  2. var buf bytes.Buffer
  3. tw := tar.NewWriter(&buf)
  4. var files = []struct {
  5. Name, Body string
  6. }{
  7. {"readme.txt", "This archive contains some text files."},
  8. {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
  9. {"todo.txt", "Get animal handling license."},
  10. }
  11. for _, file := range files {
  12. hdr := &tar.Header{
  13. Name: file.Name,
  14. Mode: 0600,
  15. Size: int64(len(file.Body)),
  16. }
  17. if err := tw.WriteHeader(hdr); err != nil {
  18. log.Fatal(err)
  19. }
  20. if _, err := tw.Write([]byte(file.Body)); err != nil {
  21. log.Fatal(err)
  22. }
  23. }
  24. if err := tw.Close(); err != nil {
  25. log.Fatal(err)
  26. }
  27. // Open and iterate through the files in the archive.
  28. tr := tar.NewReader(&buf)
  29. for {
  30. hdr, err := tr.Next()
  31. if err == io.EOF {
  32. break // End of archive
  33. }
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. fmt.Printf("Contents of %s:\n", hdr.Name)
  38. if _, err := io.Copy(os.Stdout, tr); err != nil {
  39. log.Fatal(err)
  40. }
  41. fmt.Println()
  42. }
  43. // Output:
  44. // Contents of readme.txt:
  45. // This archive contains some text files.
  46. // Contents of gopher.txt:
  47. // Gopher names:
  48. // George
  49. // Geoffrey
  50. // Gonzo
  51. // Contents of todo.txt:
  52. // Get animal handling license.

Index

Examples

Package files

common.go format.go reader.go stat_actime1.go stat_unix.go strconv.go writer.go

Constants

  1. const (
  2. // Type '0' indicates a regular file.
  3. TypeReg = '0'
  4. TypeRegA = '\x00' // For legacy support; use TypeReg instead
  5.  
  6. // Type '1' to '6' are header-only flags and may not have a data body.
  7. TypeLink = '1' // Hard link
  8. TypeSymlink = '2' // Symbolic link
  9. TypeChar = '3' // Character device node
  10. TypeBlock = '4' // Block device node
  11. TypeDir = '5' // Directory
  12. TypeFifo = '6' // FIFO node
  13.  
  14. // Type '7' is reserved.
  15. TypeCont = '7'
  16.  
  17. // Type 'x' is used by the PAX format to store key-value records that
  18. // are only relevant to the next file.
  19. // This package transparently handles these types.
  20. TypeXHeader = 'x'
  21.  
  22. // Type 'g' is used by the PAX format to store key-value records that
  23. // are relevant to all subsequent files.
  24. // This package only supports parsing and composing such headers,
  25. // but does not currently support persisting the global state across files.
  26. TypeXGlobalHeader = 'g'
  27.  
  28. // Type 'S' indicates a sparse file in the GNU format.
  29. TypeGNUSparse = 'S'
  30.  
  31. // Types 'L' and 'K' are used by the GNU format for a meta file
  32. // used to store the path or link name for the next file.
  33. // This package transparently handles these types.
  34. TypeGNULongName = 'L'
  35. TypeGNULongLink = 'K'
  36. )

Type flags for Header.Typeflag.

Variables

  1. var (
  2. ErrHeader = errors.New("archive/tar: invalid tar header")
  3. ErrWriteTooLong = errors.New("archive/tar: write too long")
  4. ErrFieldTooLong = errors.New("archive/tar: header field too long")
  5. ErrWriteAfterClose = errors.New("archive/tar: write after close")
  6. )

type Format

  1. type Format int

Format represents the tar archive format.

The original tar format was introduced in Unix V7. Since then, there have been
multiple competing formats attempting to standardize or extend the V7 format to
overcome its limitations. The most common formats are the USTAR, PAX, and GNU
formats, each with their own advantages and limitations.

The following table captures the capabilities of each format:

  1. | USTAR | PAX | GNU
  2. ------------------+--------+-----------+----------
  3. Name | 256B | unlimited | unlimited
  4. Linkname | 100B | unlimited | unlimited
  5. Size | uint33 | unlimited | uint89
  6. Mode | uint21 | uint21 | uint57
  7. Uid/Gid | uint21 | unlimited | uint57
  8. Uname/Gname | 32B | unlimited | 32B
  9. ModTime | uint33 | unlimited | int89
  10. AccessTime | n/a | unlimited | int89
  11. ChangeTime | n/a | unlimited | int89
  12. Devmajor/Devminor | uint21 | uint21 | uint57
  13. ------------------+--------+-----------+----------
  14. string encoding | ASCII | UTF-8 | binary
  15. sub-second times | no | yes | no
  16. sparse files | no | yes | yes

The table’s upper portion shows the Header fields, where each format reports the
maximum number of bytes allowed for each string field and the integer type used
to store each numeric field (where timestamps are stored as the number of
seconds since the Unix epoch).

The table’s lower portion shows specialized features of each format, such as
supported string encodings, support for sub-second timestamps, or support for
sparse files.

The Writer currently provides no support for sparse files.

  1. const (
  2.  
  3. // FormatUnknown indicates that the format is unknown.
  4. FormatUnknown Format
  5.  
  6. // FormatUSTAR represents the USTAR header format defined in POSIX.1-1988.
  7. //
  8. // While this format is compatible with most tar readers,
  9. // the format has several limitations making it unsuitable for some usages.
  10. // Most notably, it cannot support sparse files, files larger than 8GiB,
  11. // filenames larger than 256 characters, and non-ASCII filenames.
  12. //
  13. // Reference:
  14. // http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06
  15. FormatUSTAR
  16.  
  17. // FormatPAX represents the PAX header format defined in POSIX.1-2001.
  18. //
  19. // PAX extends USTAR by writing a special file with Typeflag TypeXHeader
  20. // preceding the original header. This file contains a set of key-value
  21. // records, which are used to overcome USTAR's shortcomings, in addition to
  22. // providing the ability to have sub-second resolution for timestamps.
  23. //
  24. // Some newer formats add their own extensions to PAX by defining their
  25. // own keys and assigning certain semantic meaning to the associated values.
  26. // For example, sparse file support in PAX is implemented using keys
  27. // defined by the GNU manual (e.g., "GNU.sparse.map").
  28. //
  29. // Reference:
  30. // http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
  31. FormatPAX
  32.  
  33. // FormatGNU represents the GNU header format.
  34. //
  35. // The GNU header format is older than the USTAR and PAX standards and
  36. // is not compatible with them. The GNU format supports
  37. // arbitrary file sizes, filenames of arbitrary encoding and length,
  38. // sparse files, and other features.
  39. //
  40. // It is recommended that PAX be chosen over GNU unless the target
  41. // application can only parse GNU formatted archives.
  42. //
  43. // Reference:
  44. // http://www.gnu.org/software/tar/manual/html_node/Standard.html
  45. FormatGNU
  46. )

Constants to identify various tar formats.

func (Format) String

  1. func (f Format) String() string

  1. type Header struct {
  2. Typeflag byte // Type of header entry (should be TypeReg for most files)
  3.  
  4. Name string // Name of file entry
  5. Linkname string // Target name of link (valid for TypeLink or TypeSymlink)
  6.  
  7. Size int64 // Logical file size in bytes
  8. Mode int64 // Permission and mode bits
  9. Uid int // User ID of owner
  10. Gid int // Group ID of owner
  11. Uname string // User name of owner
  12. Gname string // Group name of owner
  13.  
  14. // If the Format is unspecified, then Writer.WriteHeader rounds ModTime
  15. // to the nearest second and ignores the AccessTime and ChangeTime fields.
  16. //
  17. // To use AccessTime or ChangeTime, specify the Format as PAX or GNU.
  18. // To use sub-second resolution, specify the Format as PAX.
  19. ModTime time.Time // Modification time
  20. AccessTime time.Time // Access time (requires either PAX or GNU support)
  21. ChangeTime time.Time // Change time (requires either PAX or GNU support)
  22.  
  23. Devmajor int64 // Major device number (valid for TypeChar or TypeBlock)
  24. Devminor int64 // Minor device number (valid for TypeChar or TypeBlock)
  25.  
  26. // Xattrs stores extended attributes as PAX records under the
  27. // "SCHILY.xattr." namespace.
  28. //
  29. // The following are semantically equivalent:
  30. // h.Xattrs[key] = value
  31. // h.PAXRecords["SCHILY.xattr."+key] = value
  32. //
  33. // When Writer.WriteHeader is called, the contents of Xattrs will take
  34. // precedence over those in PAXRecords.
  35. //
  36. // Deprecated: Use PAXRecords instead.
  37. Xattrs map[string]string
  38.  
  39. // PAXRecords is a map of PAX extended header records.
  40. //
  41. // User-defined records should have keys of the following form:
  42. // VENDOR.keyword
  43. // Where VENDOR is some namespace in all uppercase, and keyword may
  44. // not contain the '=' character (e.g., "GOLANG.pkg.version").
  45. // The key and value should be non-empty UTF-8 strings.
  46. //
  47. // When Writer.WriteHeader is called, PAX records derived from the
  48. // the other fields in Header take precedence over PAXRecords.
  49. PAXRecords map[string]string
  50.  
  51. // Format specifies the format of the tar header.
  52. //
  53. // This is set by Reader.Next as a best-effort guess at the format.
  54. // Since the Reader liberally reads some non-compliant files,
  55. // it is possible for this to be FormatUnknown.
  56. //
  57. // If the format is unspecified when Writer.WriteHeader is called,
  58. // then it uses the first format (in the order of USTAR, PAX, GNU)
  59. // capable of encoding this Header (see Format).
  60. Format Format
  61. }

A Header represents a single header in a tar archive. Some fields may not be
populated.

For forward compatibility, users that retrieve a Header from Reader.Next, mutate
it in some ways, and then pass it back to Writer.WriteHeader should do so by
creating a new Header and copying the fields that they are interested in
preserving.

func FileInfoHeader

  1. func FileInfoHeader(fi os.FileInfo, link string) (*Header, error)

FileInfoHeader creates a partially-populated Header from fi. If fi describes a
symlink, FileInfoHeader records link as the link target. If fi describes a
directory, a slash is appended to the name.

Since os.FileInfo’s Name method only returns the base name of the file it
describes, it may be necessary to modify Header.Name to provide the full path
name of the file.

func (*Header) FileInfo

  1. func (h *Header) FileInfo() os.FileInfo

FileInfo returns an os.FileInfo for the Header.

type Reader

  1. type Reader struct {
  2. // contains filtered or unexported fields
  3. }

Reader provides sequential access to the contents of a tar archive. Reader.Next
advances to the next file in the archive (including the first), and then Reader
can be treated as an io.Reader to access the file’s data.

func NewReader

  1. func NewReader(r io.Reader) *Reader

NewReader creates a new Reader reading from r.

func (*Reader) Next

  1. func (tr *Reader) Next() (*Header, error)

Next advances to the next entry in the tar archive. The Header.Size determines
how many bytes can be read for the next file. Any remaining data in the current
file is automatically discarded.

io.EOF is returned at the end of the input.

func (*Reader) Read

  1. func (tr *Reader) Read(b []byte) (int, error)

Read reads from the current file in the tar archive. It returns (0, io.EOF) when
it reaches the end of that file, until Next is called to advance to the next
file.

If the current file is sparse, then the regions marked as a hole are read back
as NUL-bytes.

Calling Read on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock,
TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the Header.Size
claims.

type Writer

  1. type Writer struct {
  2. // contains filtered or unexported fields
  3. }

Writer provides sequential writing of a tar archive. Write.WriteHeader begins a
new file with the provided Header, and then Writer can be treated as an
io.Writer to supply that file’s data.

func NewWriter

  1. func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer writing to w.

func (*Writer) Close

  1. func (tw *Writer) Close() error

Close closes the tar archive by flushing the padding, and writing the footer. If
the current file (from a prior call to WriteHeader) is not fully written, then
this returns an error.

func (*Writer) Flush

  1. func (tw *Writer) Flush() error

Flush finishes writing the current file’s block padding. The current file must
be fully written before Flush can be called.

This is unnecessary as the next call to WriteHeader or Close will implicitly
flush out the file’s padding.

func (*Writer) Write

  1. func (tw *Writer) Write(b []byte) (int, error)

Write writes to the current file in the tar archive. Write returns the error
ErrWriteTooLong if more than Header.Size bytes are written after WriteHeader.

Calling Write on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock,
TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of what the
Header.Size claims.

func (*Writer) WriteHeader

  1. func (tw *Writer) WriteHeader(hdr *Header) error

WriteHeader writes hdr and prepares to accept the file’s contents. The
Header.Size determines how many bytes can be written for the next file. If the
current file is not fully written, then this returns an error. This implicitly
flushes any padding necessary before writing the header.