mirror of
https://github.com/mikefarah/yq.git
synced 2026-09-07 02:48:27 +08:00
Added shell string encoder (@sh) #1526
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package yqlib
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var pattern = regexp.MustCompile(`[^\w@%+=:,./-]`)
|
||||
|
||||
type shEncoder struct {
|
||||
}
|
||||
|
||||
func NewShEncoder() Encoder {
|
||||
return &shEncoder{}
|
||||
}
|
||||
|
||||
func (e *shEncoder) CanHandleAliases() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *shEncoder) PrintDocumentSeparator(writer io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *shEncoder) PrintLeadingContent(writer io.Writer, content string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *shEncoder) Encode(writer io.Writer, originalNode *yaml.Node) error {
|
||||
node := unwrapDoc(originalNode)
|
||||
if guessTagFromCustomType(node) != "!!str" {
|
||||
return fmt.Errorf("cannot encode %v as URI, can only operate on strings. Please first pipe through another encoding operator to convert the value to a string", node.Tag)
|
||||
}
|
||||
|
||||
value := originalNode.Value
|
||||
if pattern.MatchString(value) {
|
||||
value = "'" + strings.ReplaceAll(value, "'", "\\'") + "'"
|
||||
}
|
||||
return writeString(writer, value)
|
||||
}
|
||||
Reference in New Issue
Block a user