Add ParseFromReader function

dev
shubhamrasal 2022-12-13 12:57:47 +05:30
parent a5b39dcaa5
commit 198d84ec25
1 changed files with 54 additions and 0 deletions

View File

@ -2,6 +2,8 @@ package templates
import (
"fmt"
"io"
"io/ioutil"
"reflect"
"github.com/pkg/errors"
@ -221,3 +223,55 @@ mainLoop:
template.Executer = executer.NewExecuter([]protocols.Request{&offlinehttp.Request{}}, &options)
}
}
// ParseFromReader reads the template from reader
// returns the parsed template
func ParseFromReader(reader io.Reader, options protocols.ExecuterOptions) (*Template, error) {
template := &Template{}
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(data, template); err != nil {
return nil, err
}
if utils.IsBlank(template.Info.Name) {
return nil, errors.New("no template name field provided")
}
if template.Info.Authors.IsEmpty() {
return nil, errors.New("no template author field provided")
}
// Setting up variables regarding template metadata
options.TemplateID = template.ID
options.TemplateInfo = template.Info
options.StopAtFirstMatch = template.StopAtFirstMatch
if template.Variables.Len() > 0 {
options.Variables = template.Variables
}
// If no requests, and it is also not a workflow, return error.
if template.Requests() == 0 {
return nil, fmt.Errorf("no requests defined for %s", template.ID)
}
if err := template.compileProtocolRequests(options); err != nil {
return nil, err
}
if template.Executer != nil {
if err := template.Executer.Compile(); err != nil {
return nil, errors.Wrap(err, "could not compile request")
}
template.TotalRequests = template.Executer.Requests()
}
if template.Executer == nil && template.CompiledWorkflow == nil {
return nil, ErrCreateTemplateExecutor
}
template.parseSelfContainedRequests()
return template, nil
}