From 518521018b191cef658b5bd66a4a6850b59614a6 Mon Sep 17 00:00:00 2001 From: Vincent Chenal Date: Fri, 13 Sep 2024 10:05:59 +0200 Subject: [PATCH] feat: add gzip and ungzip functions --- crypto.go | 35 +++++++++++++++++++++++++++++++++++ crypto_test.go | 7 +++++++ functions.go | 2 ++ 3 files changed, 44 insertions(+) diff --git a/crypto.go b/crypto.go index 75fe027e..07a78a50 100644 --- a/crypto.go +++ b/crypto.go @@ -2,6 +2,7 @@ package sprig import ( "bytes" + "compress/gzip" "crypto" "crypto/aes" "crypto/cipher" @@ -657,3 +658,37 @@ func decryptAES(password string, crypt64 string) (string, error) { return string(decrypted[:len(decrypted)-int(decrypted[len(decrypted)-1])]), nil } + +func gzipCompress(input string) (string, error) { + var buffer bytes.Buffer + gzipWriter := gzip.NewWriter(&buffer) + _, err := gzipWriter.Write([]byte(input)) + if err != nil { + return "", err + } + + if err := gzipWriter.Close(); err != nil { + return "", err + } + + return buffer.String(), nil +} + +func gzipDecompress(input string) (string, error) { + gzipReader, err := gzip.NewReader(bytes.NewReader([]byte(input))) + if err != nil { + return "", err + } + + var buffer bytes.Buffer + _, err = buffer.ReadFrom(gzipReader) + if err != nil { + return "", err + } + + if err := gzipReader.Close(); err != nil { + return "", err + } + + return buffer.String(), nil +} diff --git a/crypto_test.go b/crypto_test.go index ac3f43b9..a01bea5c 100644 --- a/crypto_test.go +++ b/crypto_test.go @@ -430,3 +430,10 @@ func TestEncryptDecryptAES(t *testing.T) { t.Error(err) } } + +func TestCompressDecompressGzip(t *testing.T) { + tpl := `{{"plaintext" | gzip | ungzip }}` + if err := runt(tpl, "plaintext"); err != nil { + t.Error(err) + } +} diff --git a/functions.go b/functions.go index cda47d26..8bb01cb9 100644 --- a/functions.go +++ b/functions.go @@ -353,6 +353,8 @@ var genericMap = map[string]interface{}{ "encryptAES": encryptAES, "decryptAES": decryptAES, "randBytes": randBytes, + "gzip": gzipCompress, + "ungzip": gzipDecompress, // UUIDs: "uuidv4": uuidv4,