Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mholt committed Apr 8, 2016
0 parents commit 1d6c7f7
Show file tree
Hide file tree
Showing 10 changed files with 416 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2016 Matthew Holt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
archiver
========

Package archiver makes it trivially easy to make .zip and .tar.gz files. Simply give the output filename and a list of files/folders you want included in the archive.

The goal of this package is to make it as easy for Go programmers to make archives as it is for a computer user who just right-clicks and chooses something like "Compress".

Files are put into the root of the archive; directories are recursively added.


## Install

```bash
go get github.com/mholt/archiver
```


## Use

Create a .zip file:

```go
err := archiver.Zip("output.zip", []string{"file.txt", "folder"})
```

Create a .tar.gz file:

```go
err := archiver.TarGz("output.tar.gz", []string{"file.txt", "folder"})
```


## FAQ

#### Can it unzip and untar?

No, because I haven't needed that yet. But if there's enough demand, we can add it. Pull requests welcome! **Remember: a pull request, with test, is best.**


#### Can I list a file to go in a different folder in the archive?

No, because I didn't need it to do that. Just structure your source files to mirror the structure in the archive, like you would normally do when you make an archive using your OS.

92 changes: 92 additions & 0 deletions targz.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package archiver

import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)

// TarGz creates a .tar.gz file at targzPath containing
// the contents of files listed in filePaths. File paths
// can be those of regular files or directories. Regular
// files are stored at the 'root' of the archive, and
// directories are recursively added.
func TarGz(targzPath string, filePaths []string) error {
out, err := os.Create(targzPath)
if err != nil {
return fmt.Errorf("error creating %s: %v", targzPath, err)
}
defer out.Close()

gzWriter := gzip.NewWriter(out)
defer gzWriter.Close()

tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()

for _, fpath := range filePaths {
err := tarGzFile(tarWriter, fpath)
if err != nil {
return err
}
}

return nil
}

func tarGzFile(tarWriter *tar.Writer, source string) error {
sourceInfo, err := os.Stat(source)
if err != nil {
return fmt.Errorf("error stat'ing %s: %v", source, err)
}

var baseDir string
if sourceInfo.IsDir() {
baseDir = filepath.Base(source)
}

return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error walking to %s: %v", path, err)
}

header, err := tar.FileInfoHeader(info, path)
if err != nil {
return fmt.Errorf("error making header for %s: %v", path, err)
}

if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}

if info.IsDir() {
header.Name += "/"
}

err = tarWriter.WriteHeader(header)
if err != nil {
return fmt.Errorf("error writing header for %s: %v", path, err)
}

if info.IsDir() {
return nil
}

file, err := os.Open(path)
if err != nil {
return fmt.Errorf("error opening %s: %v", path, err)
}
defer file.Close()

_, err = io.Copy(tarWriter, file)
if err != nil {
return fmt.Errorf("error copying contents of %s: %v", path, err)
}

return nil
})
}
87 changes: 87 additions & 0 deletions targz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package archiver

import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
)

func TestTarGz(t *testing.T) {
tmp, err := ioutil.TempDir("", "archiver")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)

outfile := filepath.Join(tmp, "test.tar.gz")
err = TarGz(outfile, []string{
"testdata",
})
if err != nil {
t.Errorf("Didn't expect an error, but got: %v", err)
}

var fileCount int
filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
fileCount++
return nil
})

f, err := os.Open(outfile)
if err != nil {
t.Fatalf("%s: Failed to open archive: %v", outfile, err)
}
defer f.Close()

gzf, err := gzip.NewReader(f)
if err != nil {
t.Fatalf("Failed to create new gzip reader: %v", err)
}

tr := tar.NewReader(gzf)

i := 0
for {
header, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
t.Fatalf("Error advancing to next: %v", err)
}
i++

switch header.Typeflag {
case tar.TypeDir:
// stat dir instead of read file
_, err := os.Stat(header.Name)
if err != nil {
t.Fatalf("%s: Couldn't stat directory: %v", header.Name, err)
}
continue
case tar.TypeReg:
expected, err := ioutil.ReadFile(header.Name)
if err != nil {
t.Fatalf("%s: Couldn't open from disk: %v", header.Name, err)
}
actual := new(bytes.Buffer)
_, err = io.Copy(actual, tr)
if err != nil {
t.Fatalf("%s: Couldn't read contents of compressed file: %v", header.Name, err)
}
if !bytes.Equal(expected, actual.Bytes()) {
t.Fatalf("%s: File contents differed between on disk and compressed", header.Name)
}
default:
t.Fatalf("%s: Unknown type flag: %c", header.Name, header.Typeflag)
}
}

if i != fileCount {
t.Fatalf("Expected %d files in archive, got %d", fileCount, i)
}
}
2 changes: 2 additions & 0 deletions testdata/proverbs/extra/proverb3.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"interface{} says nothing."
- Rob Pike
2 changes: 2 additions & 0 deletions testdata/proverbs/proverb1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"Channels orchestrate; mutexes serialize."
- Rob Pike
2 changes: 2 additions & 0 deletions testdata/proverbs/proverb2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"A little copying is better than a little dependency."
- Rob Pike
2 changes: 2 additions & 0 deletions testdata/quote1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"Go has generics; they're called interfaces."
- Matt Holt
90 changes: 90 additions & 0 deletions zip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Package archiver makes it super easy to create .zip and .tar.gz archives.
package archiver

import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)

// Zip creates a .zip file in the location zipPath containing
// the contents of files listed in filePaths. File paths
// can be those of regular files or directories. Regular
// files are stored at the 'root' of the archive, and
// directories are recursively added.
func Zip(zipPath string, filePaths []string) error {
out, err := os.Create(zipPath)
if err != nil {
return fmt.Errorf("error creating %s: %v", zipPath, err)
}
defer out.Close()

w := zip.NewWriter(out)
for _, fpath := range filePaths {
err = zipFile(w, fpath)
if err != nil {
w.Close()
return err
}
}

return w.Close()
}

func zipFile(w *zip.Writer, source string) error {
sourceInfo, err := os.Stat(source)
if err != nil {
return fmt.Errorf("error stat'ing %s: %v", source, err)
}

var baseDir string
if sourceInfo.IsDir() {
baseDir = filepath.Base(source)
}

return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error walking to %s: %v", path, err)
}

header, err := zip.FileInfoHeader(info)
if err != nil {
return fmt.Errorf("error making header for %s: %v", path, err)
}

if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}

if info.IsDir() {
header.Name += string(filepath.Separator)
} else {
header.Method = zip.Deflate
}

writer, err := w.CreateHeader(header)
if err != nil {
return fmt.Errorf("error making header for %s: %v", path, err)
}

if info.IsDir() {
return nil
}

file, err := os.Open(path)
if err != nil {
return fmt.Errorf("error opening %s: %v", path, err)
}
defer file.Close()

_, err = io.Copy(writer, file)
if err != nil {
return fmt.Errorf("error copying contents of %s: %v", path, err)
}

return nil
})
}
Loading

0 comments on commit 1d6c7f7

Please sign in to comment.