Skip to content

Commit

Permalink
add native and cli approaches
Browse files Browse the repository at this point in the history
  • Loading branch information
tc80 committed Jul 7, 2020
1 parent 0cf4923 commit 969c504
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions compress/algorithm.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,47 @@ package compress
import (
"bytes"
"compress/gzip"
"fmt"
"os/exec"

"github.com/andybalholm/brotli"
"github.com/cdnjs/tools/util"
)

// Brotli11 returns a brotli compressed file as bytes
// Runs an algorithm with a set of arguments,
// and returns its stdout as bytes.
// Note, this function will panic if anything is
// output to stderr.
func runAlgorithm(alg string, args ...string) []byte {
cmd := exec.Command(alg, args...)
var stdOut, stdErr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdOut, &stdErr

err := cmd.Run()
util.Check(err)

if stdErr.Len() > 0 {
panic(fmt.Sprintf("%s failed: %s", alg, stdErr.String()))
}

return stdOut.Bytes()
}

// Brotli11CLI returns a brotli compressed file as bytes
// at optimal compression (quality 11).
func Brotli11CLI(filePath string) []byte {
return runAlgorithm("brotli", "-c", "-q", "11", filePath)
}

// Gzip9CLI returns a gzip compressed file as bytes
// at optimal compression (level 9).
func Gzip9CLI(filePath string) []byte {
return runAlgorithm("gzip", "-c", "-9", filePath)
}

// Brotli11Native returns a brotli compressed file as bytes
// at optimal compression (quality 11).
func Brotli11(uncompressed []byte) []byte {
func Brotli11Native(uncompressed []byte) []byte {
var b bytes.Buffer

w := brotli.NewWriterLevel(&b, brotli.BestCompression)
Expand All @@ -22,9 +55,9 @@ func Brotli11(uncompressed []byte) []byte {
return b.Bytes()
}

// Gzip9 returns a gzip compressed file as bytes
// Gzip9Native returns a gzip compressed file as bytes
// at optimal compression (level 9).
func Gzip9(uncompressed []byte) []byte {
func Gzip9Native(uncompressed []byte) []byte {
var b bytes.Buffer

w, err := gzip.NewWriterLevel(&b, gzip.BestCompression)
Expand Down

0 comments on commit 969c504

Please sign in to comment.