Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add gzip api #2

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkg/yttlibrary/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func NewAPI(
"url": URLAPI,
"ip": IPAPI,

// Compression
"gzip": GzipAPI,

// Templating
"template": NewTemplateModule(replaceNodeFunc).AsModule(),
"data": dataMod.AsModule(),
Expand Down
81 changes: 81 additions & 0 deletions pkg/yttlibrary/gzip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0

package yttlibrary

import (
"bytes"
"compress/gzip"
"fmt"

"github.com/k14s/starlark-go/starlark"
"github.com/k14s/starlark-go/starlarkstruct"
"github.com/vmware-tanzu/carvel-ytt/pkg/template/core"
)

var (
GzipAPI = starlark.StringDict{
"gzip": &starlarkstruct.Module{
Name: "gzip",
Members: starlark.StringDict{
"compress": starlark.NewBuiltin("gzip.compress", core.ErrWrapper(gzipModule{}.Compress)),
"decompress": starlark.NewBuiltin("gzip.decompress", core.ErrWrapper(gzipModule{}.Decompress)),
},
},
}
)

type gzipModule struct{}

func (b gzipModule) Compress(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if args.Len() != 1 {
return starlark.None, fmt.Errorf("expected exactly one argument")
}

val, err := core.NewStarlarkValue(args.Index(0)).AsString()
if err != nil {
return starlark.None, err
}

var buf bytes.Buffer
gz := gzip.NewWriter(&buf)

if _, err := gz.Write([]byte(val)); err != nil {
return nil, err
}

if err := gz.Close(); err != nil {
return nil, err
}

return starlark.String(buf.String()), nil
}

func (b gzipModule) Decompress(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if args.Len() != 1 {
return starlark.None, fmt.Errorf("expected exactly one argument")
}

val, err := core.NewStarlarkValue(args.Index(0)).AsString()
if err != nil {
return starlark.None, err
}

buf := bytes.NewBufferString(val)

gz, err := gzip.NewReader(buf)
if err != nil {
return nil, err
}

var out bytes.Buffer
if _, err := out.ReadFrom(gz); err != nil {
return nil, err
}

if err := gz.Close(); err != nil {
return nil, err
}

return starlark.String(out.String()), nil
}