tar 包

import "archive/tar"

概览

Package tar implements access to tar archives. It aims to cover most of the variations, including those produced by GNU and BSD tars.
tar 包实现了对 tar 归档文件的访问。它旨在提供较强的通用性,包括对GNU和BSD生成的tar文件的访问。

引用文章:

http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
http://www.gnu.org/software/tar/manual/html_node/Standard.html
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html

示例

package main

import (
	"archive/tar"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {
	// Create a buffer to write our archive to.
	buf := new(bytes.Buffer)

	// Create a new tar archive.
	tw := tar.NewWriter(buf)

	// Add some files to the archive.
	var files = []struct {
		Name, Body string
	}{
		{"readme.txt", "This archive contains some text files."},
		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
		{"todo.txt", "Get animal handling license."},
	}
	for _, file := range files {
		hdr := &tar.Header{
			Name: file.Name,
			Mode: 0600,
			Size: int64(len(file.Body)),
		}
		if err := tw.WriteHeader(hdr); err != nil {
			log.Fatalln(err)
		}
		if _, err := tw.Write([]byte(file.Body)); err != nil {
			log.Fatalln(err)
		}
	}
	// Make sure to check the error on Close.
	if err := tw.Close(); err != nil {
		log.Fatalln(err)
	}

	// Open the tar archive for reading.
	r := bytes.NewReader(buf.Bytes())
	tr := tar.NewReader(r)

	// Iterate through the files in the archive.
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		if err != nil {
			log.Fatalln(err)
		}
		fmt.Printf("Contents of %s:\n", hdr.Name)
		if _, err := io.Copy(os.Stdout, tr); err != nil {
			log.Fatalln(err)
		}
		fmt.Println()
	}

}
Contents of readme.txt:
This archive contains some text files.
Contents of gopher.txt:
Gopher names:
George
Geoffrey
Gonzo
Contents of todo.txt:
Get animal handling license.

索引

Constants

Header type flags.

const (
        TypeReg           = '0'    // regular file
        TypeRegA          = '\x00' // regular file
        TypeLink          = '1'    // hard link
        TypeSymlink       = '2'    // symbolic link
        TypeChar          = '3'    // character device node
        TypeBlock         = '4'    // block device node
        TypeDir           = '5'    // directory
        TypeFifo          = '6'    // fifo node
        TypeCont          = '7'    // reserved
        TypeXHeader       = 'x'    // extended header
        TypeXGlobalHeader = 'g'    // global extended header
        TypeGNULongName   = 'L'    // Next file has a long name
        TypeGNULongLink   = 'K'    // Next file symlinks to a file w/ a long name
        TypeGNUSparse     = 'S'    // sparse file
)

Variables

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

type Header

A Header represents a single header in a tar archive. Some fields may not be populated.
Header表示tar归档文件的信息头,其包含的字段可以不被填充。

type Header struct {
        Name       string    // name of header file entry
        Mode       int64     // permission and mode bits
        Uid        int       // user id of owner
        Gid        int       // group id of owner
        Size       int64     // length in bytes
        ModTime    time.Time // modified time
        Typeflag   byte      // type of header entry
        Linkname   string    // target name of link
        Uname      string    // user name of owner
        Gname      string    // group name of owner
        Devmajor   int64     // major number of character or block device
        Devminor   int64     // minor number of character or block device
        AccessTime time.Time // access time
        ChangeTime time.Time // status change time
        Xattrs     map[string]string
}

func FileInfoHeader

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. Because os.FileInfo's Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file.
FileInfoHeader函数根据传入的fi创建了一个部分填充的Header。如果fi描述了一个文件链接,则FileInfoHeader将其记录为链接目标。 如果fi描述一个目录,则会在该名称后附加一个斜杠。由于os.FileInfo的Name方法只返回它描述的文件的基本名称,所以可能需要修改Header返回值的Name字段以提供文件的完整路径名。

func (*Header) FileInfo

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

FileInfo returns an os.FileInfo for the Header.
FileInfo函数返回了h的os.FileInfo信息。

type Reader

A Reader provides sequential access to the contents of a tar archive. A tar archive consists of a sequence of files. The Next method advances to the next file in the archive (including the first), and then it can be treated as an io.Reader to access the file's data.
Reader对tar的归档内容提供了序列化访问。tr由一系列文件组成。 Next方法指向tar中的下一个文件(包括第一个文件),然后可以将其视为一个io.Reader以访问该文件的数据。

type Reader struct {
        // contains filtered or unexported fields
}

func NewReader

func NewReader(r io.Reader) *Reader

NewReader creates a new Reader reading from r.
NewReader函数根据r建立一个新的Reader。

func (*Reader) Next

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

Next advances to the next entry in the tar archive.
Next函数将读取游标指向下一个tar中的归档文件实体。

io.EOF is returned at the end of the input.
没有下一个文件将返回io.EOF。

func (*Reader) Read

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

Read reads from the current entry in the tar archive. It returns 0, io.EOF when it reaches the end of that entry, until Next is called to advance to the next entry.
Read函数读取当前tar中的归档文件实体。如果最后一个文件读取结束,继续执行Next函数将返回0,io.EOF。

Calling Read on special types like TypeLink, TypeSymLink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns 0, io.EOF regardless of what the Header.Size claims.
在TypeLink,TypeSymLink,TypeChar,TypeBlock,TypeDir和TypeFifo之类的特殊类型上调用Read,无论Header.Size声明如何,都会返回0,io.EOF。

type Writer

A Writer provides sequential writing of a tar archive in POSIX.1 format. A tar archive consists of a sequence of files. Call WriteHeader to begin a new file, and then call Write to supply that file's data, writing at most hdr.Size bytes in total.
Writer提供POSIX.1格式的对tar文件的连续写入。tar由一系列文件组成。调用WriteHeader开始一个新文件操作,然后调用Write来提供该文件的数据,总共写入最多hdr.Size字节。

type Writer struct {
        // contains filtered or unexported fields
}

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer writing to w.
NewWriter函数建立一个新的Writer以写入w。

func (*Writer) Close

func (tw *Writer) Close() error

Close closes the tar archive, flushing any unwritten data to the underlying writer.
Close函数关闭tar操作,刷新任何未写入的数据到底层的writer。

func (*Writer) Flush

func (tw *Writer) Flush() error

Flush finishes writing the current file (optional).
Flush函数结束对当前文件的写入操作(可选)。

func (*Writer) Write

func (tw *Writer) Write(b []byte) (n int, err error)

Write writes to the current entry in the tar archive. Write returns the error ErrWriteTooLong if more than hdr.Size bytes are written after WriteHeader.
Write函数将当前文件实体写入tar。如果在WriteHeader之后写入超过hdr.Size字节,将返回ErrWriteTooLong错误。

func (*Writer) WriteHeader

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

WriteHeader writes hdr and prepares to accept the file's contents. WriteHeader calls Flush if it is not the first header. Calling after a Close will return ErrWriteAfterClose.
WriteHeader函数写入hdr并准备接受文件的内容。如果WriteHeader时发现不是第一个Header,则调用Flush。调用Clost后将返回ErrWriteAfterClose。