go - tar typeflag directory or file when tar'ing directories in golang -
i'm not sure how set header.typeflag when tar'ing directory files , subdirectories. know if add
header.typeflag = '0'
it tar files not directories. how set typeflag when file or directory when untar'ing can pass in case statement tar.typedir
example taken https://www.socketloop.com/tutorials/golang-archive-directory-with-tar-and-gzip
package main import ( "archive/tar" "compress/gzip" "flag" "fmt" "io" "os" "strings" "path/filepath" ) func checkerror(err error) { if err != nil { fmt.println(err) os.exit(1) } } func main() { flag.parse() // arguments command line destinationfile := flag.arg(0) if destinationfile == "" { fmt.println("usage : gotar destinationfile.tar.gz source") os.exit(1) } sourcedir := flag.arg(1) if sourcedir == "" { fmt.println("usage : gotar destinationfile.tar.gz source-directory") os.exit(1) } dir, err := os.open(sourcedir) checkerror(err) defer dir.close() files, err := dir.readdir(0) // grab files list checkerror(err) tarfile, err := os.create(destinationfile) checkerror(err) defer tarfile.close() var filewriter io.writecloser = tarfile if strings.hassuffix(destinationfile, ".gz") { filewriter = gzip.newwriter(tarfile) // add gzip filter defer filewriter.close() // if user add .gz in destination filename } tarfilewriter := tar.newwriter(filewriter) defer tarfilewriter.close() _, fileinfo := range files { if fileinfo.isdir() { continue } // see https://www.socketloop.com/tutorials/go-file-path-independent-of-operating-system file, err := os.open(dir.name() + string(filepath.separator) + fileinfo.name()) checkerror(err) defer file.close() // prepare tar header header := new(tar.header) header.name = file.name() header.size = fileinfo.size() header.mode = int64(fileinfo.mode()) header.modtime = fileinfo.modtime() err = tarfilewriter.writeheader(header) checkerror(err) _, err = io.copy(tarfilewriter, file) checkerror(err) } }
if files on disk, looks are, part done you. have @ fileinfoheader. set typeflag based on can extrapolate resource (directory or file in case.)
for complete list of available options see the tar standard docs
Comments
Post a Comment