github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/shelltemplate.go (about)

     1  /*
     2  Copyright 2018 Mirantis
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package utils
    18  
    19  import (
    20  	"bytes"
    21  	"log"
    22  	"text/template"
    23  
    24  	"github.com/kballard/go-shellquote"
    25  )
    26  
    27  // ShellTemplate denotes a simple template used to generate shell
    28  // commands. It adds 'shellquote' function to go-template that can be
    29  // used to quote string values for the shell.
    30  type ShellTemplate struct {
    31  	*template.Template
    32  }
    33  
    34  // NewShellTemplate returns a new shell template using the specified
    35  // text. It panics if the template doesn't compile.
    36  func NewShellTemplate(text string) *ShellTemplate {
    37  	funcs := map[string]interface{}{
    38  		"shq": func(text string) string {
    39  			return shellquote.Join(text)
    40  		},
    41  	}
    42  	return &ShellTemplate{
    43  		template.Must(template.New("script").Funcs(funcs).Parse(text)),
    44  	}
    45  }
    46  
    47  // ExecuteToString executes the template using the specified data and
    48  // returns the result as a string.
    49  func (t *ShellTemplate) ExecuteToString(data interface{}) (string, error) {
    50  	var buf bytes.Buffer
    51  	err := t.Template.Execute(&buf, data)
    52  	if err != nil {
    53  		return "", err
    54  	}
    55  	return buf.String(), nil
    56  }
    57  
    58  // MustExecuteToString executes the template using the specified data
    59  // and returns the result as a string. It panics upon an error
    60  func (t *ShellTemplate) MustExecuteToString(data interface{}) string {
    61  	r, err := t.ExecuteToString(data)
    62  	if err != nil {
    63  		log.Panicf("Error executing template: %v", err)
    64  	}
    65  	return r
    66  }