| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
 | <h1> Package tar  </h1>     <ul id="short-nav">
<li><code>import "archive/tar"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package tar implements access to tar archives. </p>
<p>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. </p>   <h4 id="example__minimal"> <span class="text">Example (Minimal)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// Create and add some files to the archive.
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
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.Fatal(err)
    }
    if _, err := tw.Write([]byte(file.Body)); err != nil {
        log.Fatal(err)
    }
}
if err := tw.Close(); err != nil {
    log.Fatal(err)
}
// Open and iterate through the files in the archive.
tr := tar.NewReader(&buf)
for {
    hdr, err := tr.Next()
    if err == io.EOF {
        break // End of archive
    }
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Contents of %s:\n", hdr.Name)
    if _, err := io.Copy(os.Stdout, tr); err != nil {
        log.Fatal(err)
    }
    fmt.Println()
}
</pre> <p>Output:</p> <pre class="output" data-language="go">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.
</pre>        <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-constants">Constants</a></li>
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#Format">type Format</a></li>
<li> <a href="#Format.String">func (f Format) String() string</a>
</li>
<li><a href="#Header">type Header</a></li>
<li> <a href="#FileInfoHeader">func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)</a>
</li>
<li> <a href="#Header.FileInfo">func (h *Header) FileInfo() fs.FileInfo</a>
</li>
<li><a href="#Reader">type Reader</a></li>
<li> <a href="#NewReader">func NewReader(r io.Reader) *Reader</a>
</li>
<li> <a href="#Reader.Next">func (tr *Reader) Next() (*Header, error)</a>
</li>
<li> <a href="#Reader.Read">func (tr *Reader) Read(b []byte) (int, error)</a>
</li>
<li><a href="#Writer">type Writer</a></li>
<li> <a href="#NewWriter">func NewWriter(w io.Writer) *Writer</a>
</li>
<li> <a href="#Writer.AddFS">func (tw *Writer) AddFS(fsys fs.FS) error</a>
</li>
<li> <a href="#Writer.Close">func (tw *Writer) Close() error</a>
</li>
<li> <a href="#Writer.Flush">func (tw *Writer) Flush() error</a>
</li>
<li> <a href="#Writer.Write">func (tw *Writer) Write(b []byte) (int, error)</a>
</li>
<li> <a href="#Writer.WriteHeader">func (tw *Writer) WriteHeader(hdr *Header) error</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example__minimal">Package (Minimal)</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>common.go</span> <span>format.go</span> <span>reader.go</span> <span>stat_actime1.go</span> <span>stat_unix.go</span> <span>strconv.go</span> <span>writer.go</span>  </p>   <h2 id="pkg-constants">Constants</h2> <p>Type flags for Header.Typeflag. </p>
<pre data-language="go">const (
    // Type '0' indicates a regular file.
    TypeReg = '0'
    // Deprecated: Use TypeReg instead.
    TypeRegA = '\x00'
    // Type '1' to '6' are header-only flags and may not have a data body.
    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
    // Type '7' is reserved.
    TypeCont = '7'
    // Type 'x' is used by the PAX format to store key-value records that
    // are only relevant to the next file.
    // This package transparently handles these types.
    TypeXHeader = 'x'
    // Type 'g' is used by the PAX format to store key-value records that
    // are relevant to all subsequent files.
    // This package only supports parsing and composing such headers,
    // but does not currently support persisting the global state across files.
    TypeXGlobalHeader = 'g'
    // Type 'S' indicates a sparse file in the GNU format.
    TypeGNUSparse = 'S'
    // Types 'L' and 'K' are used by the GNU format for a meta file
    // used to store the path or link name for the next file.
    // This package transparently handles these types.
    TypeGNULongName = 'L'
    TypeGNULongLink = 'K'
)</pre> <h2 id="pkg-variables">Variables</h2> <pre data-language="go">var (
    ErrHeader          = errors.New("archive/tar: invalid tar header")
    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")
    ErrInsecurePath    = errors.New("archive/tar: insecure file path")
)</pre> <h2 id="Format">type <span>Format</span>  <span title="Added in Go 1.10">1.10</span> </h2> <p>Format represents the tar archive format. </p>
<p>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. </p>
<p>The following table captures the capabilities of each format: </p>
<pre data-language="go">                  |  USTAR |       PAX |       GNU
------------------+--------+-----------+----------
Name              |   256B | unlimited | unlimited
Linkname          |   100B | unlimited | unlimited
Size              | uint33 | unlimited |    uint89
Mode              | uint21 |    uint21 |    uint57
Uid/Gid           | uint21 | unlimited |    uint57
Uname/Gname       |    32B | unlimited |       32B
ModTime           | uint33 | unlimited |     int89
AccessTime        |    n/a | unlimited |     int89
ChangeTime        |    n/a | unlimited |     int89
Devmajor/Devminor | uint21 |    uint21 |    uint57
------------------+--------+-----------+----------
string encoding   |  ASCII |     UTF-8 |    binary
sub-second times  |     no |       yes |        no
sparse files      |     no |       yes |       yes
</pre> <p>The table's upper portion shows the <a href="#Header">Header</a> 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). </p>
<p>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. </p>
<p>The Writer currently provides no support for sparse files. </p>
<pre data-language="go">type Format int</pre> <p>Constants to identify various tar formats. </p>
<pre data-language="go">const (
    // FormatUnknown indicates that the format is unknown.
    FormatUnknown Format
    // FormatUSTAR represents the USTAR header format defined in POSIX.1-1988.
    //
    // While this format is compatible with most tar readers,
    // the format has several limitations making it unsuitable for some usages.
    // Most notably, it cannot support sparse files, files larger than 8GiB,
    // filenames larger than 256 characters, and non-ASCII filenames.
    //
    // Reference:
    //	http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06
    FormatUSTAR
    // FormatPAX represents the PAX header format defined in POSIX.1-2001.
    //
    // PAX extends USTAR by writing a special file with Typeflag TypeXHeader
    // preceding the original header. This file contains a set of key-value
    // records, which are used to overcome USTAR's shortcomings, in addition to
    // providing the ability to have sub-second resolution for timestamps.
    //
    // Some newer formats add their own extensions to PAX by defining their
    // own keys and assigning certain semantic meaning to the associated values.
    // For example, sparse file support in PAX is implemented using keys
    // defined by the GNU manual (e.g., "GNU.sparse.map").
    //
    // Reference:
    //	http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
    FormatPAX
    // FormatGNU represents the GNU header format.
    //
    // The GNU header format is older than the USTAR and PAX standards and
    // is not compatible with them. The GNU format supports
    // arbitrary file sizes, filenames of arbitrary encoding and length,
    // sparse files, and other features.
    //
    // It is recommended that PAX be chosen over GNU unless the target
    // application can only parse GNU formatted archives.
    //
    // Reference:
    //	https://www.gnu.org/software/tar/manual/html_node/Standard.html
    FormatGNU
)</pre> <h3 id="Format.String">func (Format) <span>String</span>  <span title="Added in Go 1.10">1.10</span> </h3> <pre data-language="go">func (f Format) String() string</pre> <h2 id="Header">type <span>Header</span>  </h2> <p>A Header represents a single header in a tar archive. Some fields may not be populated. </p>
<p>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. </p>
<pre data-language="go">type Header struct {
    // Typeflag is the type of header entry.
    // The zero value is automatically promoted to either TypeReg or TypeDir
    // depending on the presence of a trailing slash in Name.
    Typeflag byte
    Name     string // Name of file entry
    Linkname string // Target name of link (valid for TypeLink or TypeSymlink)
    Size  int64  // Logical file size in bytes
    Mode  int64  // Permission and mode bits
    Uid   int    // User ID of owner
    Gid   int    // Group ID of owner
    Uname string // User name of owner
    Gname string // Group name of owner
    // If the Format is unspecified, then Writer.WriteHeader rounds ModTime
    // to the nearest second and ignores the AccessTime and ChangeTime fields.
    //
    // To use AccessTime or ChangeTime, specify the Format as PAX or GNU.
    // To use sub-second resolution, specify the Format as PAX.
    ModTime    time.Time // Modification time
    AccessTime time.Time // Access time (requires either PAX or GNU support)
    ChangeTime time.Time // Change time (requires either PAX or GNU support)
    Devmajor int64 // Major device number (valid for TypeChar or TypeBlock)
    Devminor int64 // Minor device number (valid for TypeChar or TypeBlock)
    // Xattrs stores extended attributes as PAX records under the
    // "SCHILY.xattr." namespace.
    //
    // The following are semantically equivalent:
    //  h.Xattrs[key] = value
    //  h.PAXRecords["SCHILY.xattr."+key] = value
    //
    // When Writer.WriteHeader is called, the contents of Xattrs will take
    // precedence over those in PAXRecords.
    //
    // Deprecated: Use PAXRecords instead.
    Xattrs map[string]string // Go 1.3
    // PAXRecords is a map of PAX extended header records.
    //
    // User-defined records should have keys of the following form:
    //	VENDOR.keyword
    // Where VENDOR is some namespace in all uppercase, and keyword may
    // not contain the '=' character (e.g., "GOLANG.pkg.version").
    // The key and value should be non-empty UTF-8 strings.
    //
    // When Writer.WriteHeader is called, PAX records derived from the
    // other fields in Header take precedence over PAXRecords.
    PAXRecords map[string]string // Go 1.10
    // Format specifies the format of the tar header.
    //
    // This is set by Reader.Next as a best-effort guess at the format.
    // Since the Reader liberally reads some non-compliant files,
    // it is possible for this to be FormatUnknown.
    //
    // If the format is unspecified when Writer.WriteHeader is called,
    // then it uses the first format (in the order of USTAR, PAX, GNU)
    // capable of encoding this Header (see Format).
    Format Format // Go 1.10
}
</pre> <h3 id="FileInfoHeader">func <span>FileInfoHeader</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)</pre> <p>FileInfoHeader creates a partially-populated <a href="#Header">Header</a> 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. </p>
<p>Since fs.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. </p>
<h3 id="Header.FileInfo">func (*Header) <span>FileInfo</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (h *Header) FileInfo() fs.FileInfo</pre> <p>FileInfo returns an fs.FileInfo for the Header. </p>
<h2 id="Reader">type <span>Reader</span>  </h2> <p>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. </p>
<pre data-language="go">type Reader struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewReader">func <span>NewReader</span>  </h3> <pre data-language="go">func NewReader(r io.Reader) *Reader</pre> <p>NewReader creates a new <a href="#Reader">Reader</a> reading from r. </p>
<h3 id="Reader.Next">func (*Reader) <span>Next</span>  </h3> <pre data-language="go">func (tr *Reader) Next() (*Header, error)</pre> <p>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. At the end of the archive, Next returns the error io.EOF. </p>
<p>If Next encounters a non-local name (as defined by <span>filepath.IsLocal</span>) and the GODEBUG environment variable contains `tarinsecurepath=0`, Next returns the header with an <a href="#ErrInsecurePath">ErrInsecurePath</a> error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the <a href="#ErrInsecurePath">ErrInsecurePath</a> error and use the returned header. </p>
<h3 id="Reader.Read">func (*Reader) <span>Read</span>  </h3> <pre data-language="go">func (tr *Reader) Read(b []byte) (int, error)</pre> <p>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. </p>
<p>If the current file is sparse, then the regions marked as a hole are read back as NUL-bytes. </p>
<p>Calling Read on special types like <a href="#TypeLink">TypeLink</a>, <a href="#TypeSymlink">TypeSymlink</a>, <a href="#TypeChar">TypeChar</a>, <a href="#TypeBlock">TypeBlock</a>, <a href="#TypeDir">TypeDir</a>, and <a href="#TypeFifo">TypeFifo</a> returns (0, <span>io.EOF</span>) regardless of what the [Header.Size] claims. </p>
<h2 id="Writer">type <span>Writer</span>  </h2> <p>Writer provides sequential writing of a tar archive. <a href="#Writer.WriteHeader">Writer.WriteHeader</a> begins a new file with the provided <a href="#Header">Header</a>, and then Writer can be treated as an io.Writer to supply that file's data. </p>
<pre data-language="go">type Writer struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewWriter">func <span>NewWriter</span>  </h3> <pre data-language="go">func NewWriter(w io.Writer) *Writer</pre> <p>NewWriter creates a new Writer writing to w. </p>
<h3 id="Writer.AddFS">func (*Writer) <span>AddFS</span>  <span title="Added in Go 1.22">1.22</span> </h3> <pre data-language="go">func (tw *Writer) AddFS(fsys fs.FS) error</pre> <p>AddFS adds the files from fs.FS to the archive. It walks the directory tree starting at the root of the filesystem adding each file to the tar archive while maintaining the directory structure. </p>
<h3 id="Writer.Close">func (*Writer) <span>Close</span>  </h3> <pre data-language="go">func (tw *Writer) Close() error</pre> <p>Close closes the tar archive by flushing the padding, and writing the footer. If the current file (from a prior call to <a href="#Writer.WriteHeader">Writer.WriteHeader</a>) is not fully written, then this returns an error. </p>
<h3 id="Writer.Flush">func (*Writer) <span>Flush</span>  </h3> <pre data-language="go">func (tw *Writer) Flush() error</pre> <p>Flush finishes writing the current file's block padding. The current file must be fully written before Flush can be called. </p>
<p>This is unnecessary as the next call to <a href="#Writer.WriteHeader">Writer.WriteHeader</a> or <a href="#Writer.Close">Writer.Close</a> will implicitly flush out the file's padding. </p>
<h3 id="Writer.Write">func (*Writer) <span>Write</span>  </h3> <pre data-language="go">func (tw *Writer) Write(b []byte) (int, error)</pre> <p>Write writes to the current file in the tar archive. Write returns the error <a href="#ErrWriteTooLong">ErrWriteTooLong</a> if more than Header.Size bytes are written after <a href="#Writer.WriteHeader">Writer.WriteHeader</a>. </p>
<p>Calling Write on special types like <a href="#TypeLink">TypeLink</a>, <a href="#TypeSymlink">TypeSymlink</a>, <a href="#TypeChar">TypeChar</a>, <a href="#TypeBlock">TypeBlock</a>, <a href="#TypeDir">TypeDir</a>, and <a href="#TypeFifo">TypeFifo</a> returns (0, <a href="#ErrWriteTooLong">ErrWriteTooLong</a>) regardless of what the [Header.Size] claims. </p>
<h3 id="Writer.WriteHeader">func (*Writer) <span>WriteHeader</span>  </h3> <pre data-language="go">func (tw *Writer) WriteHeader(hdr *Header) error</pre> <p>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. </p><div class="_attribution">
  <p class="_attribution-p">
    © Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/archive/tar/" class="_attribution-link">http://golang.org/pkg/archive/tar/</a>
  </p>
</div>
 |