configui/util.go

84 lines
1.5 KiB
Go
Raw Normal View History

package configui
2021-10-18 10:59:09 +00:00
import (
"archive/tar"
"compress/gzip"
"io"
"os"
2021-11-12 09:25:44 +00:00
"path/filepath"
2021-10-18 15:53:49 +00:00
"strings"
2021-10-18 10:59:09 +00:00
)
func bundle(buf io.Writer, paths []string, rootDir string, flat bool) error {
2021-10-18 10:59:09 +00:00
gw := gzip.NewWriter(buf)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
for _, file := range paths {
if err := func(file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
// Use full path as name (FileInfoHeader only takes the basename)
// If we don't do this the directory strucuture would
// not be preserved
// https://golang.org/src/archive/tar/common.go?#L626
if !flat {
2021-10-18 15:53:49 +00:00
if !strings.HasPrefix(file, "/") {
file = rootDir + "/" + file
2021-10-18 15:53:49 +00:00
} else {
file = rootDir + file
2021-10-18 15:53:49 +00:00
}
2021-10-18 10:59:09 +00:00
header.Name = file
}
// Write file header to the tar archive
err = tw.WriteHeader(header)
if err != nil {
return err
}
// Copy file content to tar archive
_, err = io.Copy(tw, f)
if err != nil {
return err
}
return nil
}(file); err != nil {
return err
}
}
return nil
}
2021-11-12 09:25:44 +00:00
func mkdir(args ...interface{}) error {
var path string
var mode os.FileMode
mode = 0755
for _, arg := range args {
switch arg := arg.(type) {
case string:
path = filepath.Join(path, arg)
case os.FileMode:
mode = arg
}
}
return os.MkdirAll(path, mode)
}