templates.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package templates
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "text/template"
  8. "github.com/Masterminds/sprig/v3"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/cli/config"
  11. "github.com/smallstep/cli/utils"
  12. )
  13. // TemplateType defines how a template will be written in disk.
  14. type TemplateType string
  15. const (
  16. // Snippet will mark a template as a part of a file.
  17. Snippet TemplateType = "snippet"
  18. // File will mark a templates as a full file.
  19. File TemplateType = "file"
  20. // Directory will mark a template as a directory.
  21. Directory TemplateType = "directory"
  22. )
  23. // Templates is a collection of templates and variables.
  24. type Templates struct {
  25. SSH *SSHTemplates `json:"ssh,omitempty"`
  26. Data map[string]interface{} `json:"data,omitempty"`
  27. }
  28. // Validate returns an error if a template is not valid.
  29. func (t *Templates) Validate() (err error) {
  30. if t == nil {
  31. return nil
  32. }
  33. // Validate members
  34. if err = t.SSH.Validate(); err != nil {
  35. return
  36. }
  37. // Do not allow "Step" and "User"
  38. if t.Data != nil {
  39. if _, ok := t.Data["Step"]; ok {
  40. return errors.New("templates variables cannot contain 'Step' as a property")
  41. }
  42. if _, ok := t.Data["User"]; ok {
  43. return errors.New("templates variables cannot contain 'User' as a property")
  44. }
  45. }
  46. return nil
  47. }
  48. // LoadAll preloads all templates in memory. It returns an error if an error is
  49. // found parsing at least one template.
  50. func LoadAll(t *Templates) (err error) {
  51. if t != nil {
  52. if t.SSH != nil {
  53. for _, tt := range t.SSH.User {
  54. if err = tt.Load(); err != nil {
  55. return
  56. }
  57. }
  58. for _, tt := range t.SSH.Host {
  59. if err = tt.Load(); err != nil {
  60. return
  61. }
  62. }
  63. }
  64. }
  65. return
  66. }
  67. // SSHTemplates contains the templates defining ssh configuration files.
  68. type SSHTemplates struct {
  69. User []Template `json:"user"`
  70. Host []Template `json:"host"`
  71. }
  72. // Validate returns an error if a template is not valid.
  73. func (t *SSHTemplates) Validate() (err error) {
  74. if t == nil {
  75. return nil
  76. }
  77. for _, tt := range t.User {
  78. if err = tt.Validate(); err != nil {
  79. return
  80. }
  81. }
  82. for _, tt := range t.Host {
  83. if err = tt.Validate(); err != nil {
  84. return
  85. }
  86. }
  87. return
  88. }
  89. // Template represents on template file.
  90. type Template struct {
  91. *template.Template
  92. Name string `json:"name"`
  93. Type TemplateType `json:"type"`
  94. TemplatePath string `json:"template"`
  95. Path string `json:"path"`
  96. Comment string `json:"comment"`
  97. }
  98. // Validate returns an error if the template is not valid.
  99. func (t *Template) Validate() error {
  100. switch {
  101. case t == nil:
  102. return nil
  103. case t.Name == "":
  104. return errors.New("template name cannot be empty")
  105. case t.Type != Snippet && t.Type != File && t.Type != Directory:
  106. return errors.Errorf("invalid template type %s, it must be %s, %s, or %s", t.Type, Snippet, File, Directory)
  107. case t.TemplatePath == "" && t.Type != Directory:
  108. return errors.New("template template cannot be empty")
  109. case t.TemplatePath != "" && t.Type == Directory:
  110. return errors.New("template template must be empty with directory type")
  111. case t.Path == "":
  112. return errors.New("template path cannot be empty")
  113. }
  114. if t.TemplatePath != "" {
  115. // Check for file
  116. st, err := os.Stat(config.StepAbs(t.TemplatePath))
  117. if err != nil {
  118. return errors.Wrapf(err, "error reading %s", t.TemplatePath)
  119. }
  120. if st.IsDir() {
  121. return errors.Errorf("error reading %s: is not a file", t.TemplatePath)
  122. }
  123. // Defaults
  124. if t.Comment == "" {
  125. t.Comment = "#"
  126. }
  127. }
  128. return nil
  129. }
  130. // Load loads the template in memory, returns an error if the parsing of the
  131. // template fails.
  132. func (t *Template) Load() error {
  133. if t.Template == nil && t.Type != Directory {
  134. filename := config.StepAbs(t.TemplatePath)
  135. b, err := ioutil.ReadFile(filename)
  136. if err != nil {
  137. return errors.Wrapf(err, "error reading %s", filename)
  138. }
  139. tmpl, err := template.New(t.Name).Funcs(sprig.TxtFuncMap()).Parse(string(b))
  140. if err != nil {
  141. return errors.Wrapf(err, "error parsing %s", filename)
  142. }
  143. t.Template = tmpl
  144. }
  145. return nil
  146. }
  147. // Render executes the template with the given data and returns the rendered
  148. // version.
  149. func (t *Template) Render(data interface{}) ([]byte, error) {
  150. if t.Type == Directory {
  151. return nil, nil
  152. }
  153. if err := t.Load(); err != nil {
  154. return nil, err
  155. }
  156. buf := new(bytes.Buffer)
  157. if err := t.Execute(buf, data); err != nil {
  158. return nil, errors.Wrapf(err, "error executing %s", t.TemplatePath)
  159. }
  160. return buf.Bytes(), nil
  161. }
  162. // Output renders the template and returns a template.Output struct or an error.
  163. func (t *Template) Output(data interface{}) (Output, error) {
  164. b, err := t.Render(data)
  165. if err != nil {
  166. return Output{}, err
  167. }
  168. return Output{
  169. Name: t.Name,
  170. Type: t.Type,
  171. Path: t.Path,
  172. Comment: t.Comment,
  173. Content: b,
  174. }, nil
  175. }
  176. // Output represents the text representation of a rendered template.
  177. type Output struct {
  178. Name string `json:"name"`
  179. Type TemplateType `json:"type"`
  180. Path string `json:"path"`
  181. Comment string `json:"comment"`
  182. Content []byte `json:"content"`
  183. }
  184. // Write writes the Output to the filesystem as a directory, file or snippet.
  185. func (o *Output) Write() error {
  186. path := config.StepAbs(o.Path)
  187. if o.Type == Directory {
  188. return mkdir(path, 0700)
  189. }
  190. dir := filepath.Dir(path)
  191. if err := mkdir(dir, 0700); err != nil {
  192. return err
  193. }
  194. if o.Type == File {
  195. return utils.WriteFile(path, o.Content, 0600)
  196. }
  197. return utils.WriteSnippet(path, o.Content, 0600)
  198. }
  199. func mkdir(path string, perm os.FileMode) error {
  200. if err := os.MkdirAll(path, perm); err != nil {
  201. return errors.Wrapf(err, "error creating %s", path)
  202. }
  203. return nil
  204. }