forked from cdnjs/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request cdnjs#78 from tc80/brotli_cli
brotli and gzip native/cli approaches
- Loading branch information
Showing
4 changed files
with
67 additions
and
70 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package compress | ||
|
||
import ( | ||
"bytes" | ||
"compress/gzip" | ||
"fmt" | ||
"os/exec" | ||
|
||
"github.com/cdnjs/tools/util" | ||
) | ||
|
||
// 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) | ||
} | ||
|
||
// Gzip9Native returns a gzip compressed file as bytes | ||
// at optimal compression (level 9). | ||
func Gzip9Native(uncompressed []byte) []byte { | ||
var b bytes.Buffer | ||
|
||
w, err := gzip.NewWriterLevel(&b, gzip.BestCompression) | ||
util.Check(err) | ||
|
||
_, err = w.Write(uncompressed) | ||
util.Check(err) | ||
util.Check(w.Close()) | ||
|
||
return b.Bytes() | ||
} |
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
Oops, something went wrong.