2018-02-05 16:05:59 -05:00
|
|
|
package archive // import "github.com/docker/docker/pkg/archive"
|
2014-02-12 18:10:41 -05:00
|
|
|
|
|
|
|
import (
|
2015-05-01 18:01:10 -04:00
|
|
|
"archive/tar"
|
2014-02-12 18:10:41 -05:00
|
|
|
"bytes"
|
2016-10-20 19:40:59 -04:00
|
|
|
"io"
|
2014-02-12 18:10:41 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Generate generates a new archive from the content provided
|
|
|
|
// as input.
|
|
|
|
//
|
|
|
|
// `files` is a sequence of path/content pairs. A new file is
|
|
|
|
// added to the archive for each pair.
|
|
|
|
// If the last pair is incomplete, the file is created with an
|
|
|
|
// empty content. For example:
|
|
|
|
//
|
|
|
|
// Generate("foo.txt", "hello world", "emptyfile")
|
|
|
|
//
|
|
|
|
// The above call will return an archive with 2 files:
|
2022-07-08 12:27:07 -04:00
|
|
|
// - ./foo.txt with content "hello world"
|
|
|
|
// - ./empty with empty content
|
2014-02-12 18:10:41 -05:00
|
|
|
//
|
|
|
|
// FIXME: stream content instead of buffering
|
|
|
|
// FIXME: specify permissions and other archive metadata
|
2016-10-20 19:40:59 -04:00
|
|
|
func Generate(input ...string) (io.Reader, error) {
|
2014-02-12 18:10:41 -05:00
|
|
|
files := parseStringPairs(input...)
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
tw := tar.NewWriter(buf)
|
|
|
|
for _, file := range files {
|
|
|
|
name, content := file[0], file[1]
|
|
|
|
hdr := &tar.Header{
|
|
|
|
Name: name,
|
|
|
|
Size: int64(len(content)),
|
|
|
|
}
|
|
|
|
if err := tw.WriteHeader(hdr); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if _, err := tw.Write([]byte(content)); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := tw.Close(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-10-20 19:40:59 -04:00
|
|
|
return buf, nil
|
2014-02-12 18:10:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func parseStringPairs(input ...string) (output [][2]string) {
|
|
|
|
output = make([][2]string, 0, len(input)/2+1)
|
|
|
|
for i := 0; i < len(input); i += 2 {
|
|
|
|
var pair [2]string
|
|
|
|
pair[0] = input[i]
|
|
|
|
if i+1 < len(input) {
|
|
|
|
pair[1] = input[i+1]
|
|
|
|
}
|
|
|
|
output = append(output, pair)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|