Created
July 24, 2015 20:35
-
-
Save iamralch/dc27b7fb04c2549e3ada to your computer and use it in GitHub Desktop.
Tar packages in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"archive/tar" | |
"fmt" | |
"io" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func tarit(source, target string) error { | |
filename := filepath.Base(source) | |
target = filepath.Join(target, fmt.Sprintf("%s.tar", filename)) | |
tarfile, err := os.Create(target) | |
if err != nil { | |
return err | |
} | |
defer tarfile.Close() | |
tarball := tar.NewWriter(tarfile) | |
defer tarball.Close() | |
info, err := os.Stat(source) | |
if err != nil { | |
return nil | |
} | |
var baseDir string | |
if info.IsDir() { | |
baseDir = filepath.Base(source) | |
} | |
return filepath.Walk(source, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
header, err := tar.FileInfoHeader(info, info.Name()) | |
if err != nil { | |
return err | |
} | |
if baseDir != "" { | |
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) | |
} | |
if err := tarball.WriteHeader(header); err != nil { | |
return err | |
} | |
if info.IsDir() { | |
return nil | |
} | |
file, err := os.Open(path) | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
_, err = io.Copy(tarball, file) | |
return err | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"archive/tar" | |
"fmt" | |
"io" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func untar(tarball, target string) error { | |
reader, err := os.Open(tarball) | |
if err != nil { | |
return err | |
} | |
defer reader.Close() | |
tarReader := tar.NewReader(reader) | |
for { | |
header, err := tarReader.Next() | |
if err == io.EOF { | |
break | |
} else if err != nil { | |
return err | |
} | |
path := filepath.Join(target, header.Name) | |
info := header.FileInfo() | |
if info.IsDir() { | |
if err = os.MkdirAll(path, info.Mode()); err != nil { | |
return err | |
} | |
continue | |
} | |
file, err:= os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode()) | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
_, err =io.Copy(file, tarReader) | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Svetlin, we are going to use your untar code on a GPL licensed project, here. Please let us know if the use is OK. Thank you :)