Skip to content

Commit

Permalink
implement format strings base64, base64d (ref: #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Jan 2, 2020
1 parent 251e9f2 commit d909b34
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
16 changes: 16 additions & 0 deletions cli/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3211,6 +3211,22 @@
expected: |
"{"foo":"\\u003cdiv\\u003e\\u0026'\\"\\u003c/div\\u003e"}"
- name: format strings @base64
args:
- '@base64'
input: |
{"foo": "bar"}
expected: |
"eyJmb28iOiJiYXIifQ=="
- name: format strings @base64d
args:
- -R
- '@base64d'
input: eyJmb28iOiJiYXIifQ==
expected: |
"{\"foo\":\"bar\"}"
- name: destructuring alternative operator
args:
- '.[] | . as {a:$a} ?// [$a] ?// $a | $a'
Expand Down
4 changes: 4 additions & 0 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,10 @@ func (c *compiler) compileFormat(fmt string) error {
return c.compileFunc(&Func{Name: "tojson"})
case "@html":
return c.compileFunc(&Func{Name: "_tohtml"})
case "@base64":
return c.compileFunc(&Func{Name: "_tobase64"})
case "@base64d":
return c.compileFunc(&Func{Name: "_tobase64d"})
default:
return &formatNotFoundError{fmt}
}
Expand Down
25 changes: 25 additions & 0 deletions func.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gojq

import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -58,6 +59,8 @@ func init() {
"tojson": argFunc0(funcToJSON),
"fromjson": argFunc0(funcFromJSON),
"_tohtml": argFunc0(funcToHTML),
"_tobase64": argFunc0(funcToBase64),
"_tobase64d": argFunc0(funcToBase64d),
"_index": argFunc2(funcIndex),
"_slice": argFunc3(funcSlice),
"_break": argFunc0(funcBreak),
Expand Down Expand Up @@ -499,6 +502,28 @@ func funcToHTML(v interface{}) interface{} {
}
}

func funcToBase64(v interface{}) interface{} {
switch x := funcToString(v).(type) {
case string:
return base64.StdEncoding.EncodeToString([]byte(x))
default:
return x
}
}

func funcToBase64d(v interface{}) interface{} {
switch x := funcToString(v).(type) {
case string:
y, err := base64.StdEncoding.DecodeString(x)
if err != nil {
return err
}
return string(y)
default:
return x
}
}

func funcIndex(_, v, x interface{}) interface{} {
switch x := x.(type) {
case string:
Expand Down

0 comments on commit d909b34

Please sign in to comment.