diff --git a/v2/pkg/templates/compile.go b/v2/pkg/templates/compile.go index c3a60fff..dca27e0e 100644 --- a/v2/pkg/templates/compile.go +++ b/v2/pkg/templates/compile.go @@ -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 +}