Esempio n. 1
0
func parseNode(value interface{}) (MapNode, error) {
	switch v := value.(type) {
	case string:
		t, err := pongo2.FromString(v)
		if err != nil {
			return nil, err
		}
		return &mapNodeTemplate{template: t}, nil
	case map[string]string:
		res := make(Map)
		for key, mvalue := range v {
			t, err := pongo2.FromString(mvalue)
			if err != nil {
				return nil, err
			}
			res[key] = &mapNodeTemplate{template: t}
		}
		return &mapNodeMap{nodes: res}, nil
	case map[string]interface{}:
		res, err := ParseMap(Context(v))
		if err != nil {
			return nil, err
		}
		return &mapNodeMap{nodes: res}, nil
	case Context:
		res, err := ParseMap(v)
		if err != nil {
			return nil, err
		}
		return &mapNodeMap{nodes: res}, nil
	case map[interface{}]interface{}:
		res := make(Map)
		for k, mvalue := range v {
			key, ok := k.(string)
			if !ok {
				return nil, fmt.Errorf("Invalid key %#v in templates map. All keys must be strings.", k)
			}
			n, err := parseNode(mvalue)
			if err != nil {
				return nil, err
			}
			res[key] = n
		}
		return &mapNodeMap{nodes: res}, nil
	case []interface{}:
		res := new(mapNodeSlice)
		for _, svalue := range v {
			n, err := parseNode(svalue)
			if err != nil {
				return nil, err
			}
			res.nodes = append(res.nodes, n)
		}
		return res, nil
	}
	return &mapNodeInterface{value: value}, nil
}
Esempio n. 2
0
func renderVarsHelper(varsMap VarsMap, ctxt pongo2.Context) error {
	for key, value := range varsMap {
		switch v := value.(type) {
		case map[string]interface{}:
			if err := renderVarsHelper(varsMap, ctxt); err != nil {
				return HenchErr(err, map[string]interface{}{
					"value_map": value,
					"solution":  "Refer to wiki for proper pongo2 formatting",
				}, "While templating")
			}
		case string:
			tmpl, err := pongo2.FromString(v)
			if err != nil {
				return HenchErr(err, map[string]interface{}{
					"value":    value,
					"solution": "Refer to wiki for proper pongo2 formatting",
				}, "While templating")
			}
			out, err := tmpl.Execute(ctxt)
			if err != nil {
				return HenchErr(err, map[string]interface{}{
					"value":    value,
					"context":  ctxt,
					"solution": "Refer to wiki for proper pongo2 formatting",
				}, "While executing")
			}
			varsMap[key] = out
		}
	}

	return nil
}
Esempio n. 3
0
func (s *TestSuite) TestImplicitExecCtx(c *C) {
	tpl, err := pongo2.FromString("{{ ImplicitExec }}")
	if err != nil {
		c.Fatalf("Error in FromString: %v", err)
	}

	val := "a stringy thing"

	res, err := tpl.Execute(pongo2.Context{
		"Value": val,
		"ImplicitExec": func(ctx *pongo2.ExecutionContext) string {
			return ctx.Public["Value"].(string)
		},
	})

	if err != nil {
		c.Fatalf("Error executing template: %v", err)
	}

	c.Check(res, Equals, val)

	// The implicit ctx should not be persisted from call-to-call
	res, err = tpl.Execute(pongo2.Context{
		"ImplicitExec": func() string {
			return val
		},
	})

	if err != nil {
		c.Fatalf("Error executing template: %v", err)
	}

	c.Check(res, Equals, val)
}
Esempio n. 4
0
// change this to be a non-plan function
// come back to context variable stuff after getting include done
// look at diagram
// renders Task list, uses vars and machine for context
func PrepareTasks(tasks []*Task, vars TaskVars, machine Machine) ([]*Task, error) {
	// changes Task array back to yaml form to be rendered
	var newTasks = []*Task{}
	tasksBuf, err := yaml.Marshal(&tasks)
	if err != nil {
		return nil, err
	}

	// convert tasks to a pongo2 template
	tmpl, err := pongo2.FromString(string(tasksBuf))
	if err != nil {
		return nil, err
	}

	// add context and render
	ctxt := pongo2.Context{"vars": vars, "machine": machine}
	out, err := tmpl.Execute(ctxt)
	if err != nil {
		return nil, err
	}

	// change the newly rendered yaml format array back to a struct
	err = yaml.Unmarshal([]byte(out), &newTasks)
	if err != nil {
		return nil, err
	}

	return newTasks, nil
}
Esempio n. 5
0
func (c *IFMapClient) arcPoll(callback PollCallback) error {
	tpl, err := pongo2.FromString(ifmapPollRequest)
	if err != nil {
		return err
	}
	requestString, err := tpl.Execute(pongo2.Context{"session_id": c.sessionID})
	if err != nil {
		return err
	}
	err = c.request(c.arc, "poll", requestString)
	if err != nil {
		return err
	}

	output, err := response(c.arc)
	if err != nil {
		return err
	}
	fmt.Println()
	e := PollResult{}
	err = xml.Unmarshal([]byte(output), &e)
	for _, resultItem := range e.SearchItems {
		callback.Search(resultItem.toMap())
	}
	for _, resultItem := range e.UpdateItems {
		callback.Update(resultItem.toMap())
	}
	for _, resultItem := range e.DeleteItems {
		callback.Delete(resultItem.toMap())
	}

	return nil
}
Esempio n. 6
0
// FromString - Creates a new template structure from string.
func FromString(body string) (t Template, err error) {
	template, err := pongo2.FromString(body)
	if err != nil {
		return
	}
	return &pongoTemplate{Template: template}, nil
}
Esempio n. 7
0
func prepareTemplate(data string, vars *TaskVars, machine *Machine) (string, error) {
	tmpl, err := pongo2.FromString(data)
	if err != nil {
		panic(err)
	}
	ctxt := pongo2.Context{"vars": vars, "machine": machine}
	return tmpl.Execute(ctxt)
}
Esempio n. 8
0
func executeTemplate(template string, vars PlanVars) (string, error) {
	tmpl, err := pongo2.FromString(template)
	if err != nil {
		return "", err
	}

	return tmpl.Execute(pongo2.Context(vars))
}
func TestExecutionErrors(t *testing.T) {
	//debug = true

	matches, err := filepath.Glob("./template_tests/*-execution.err")
	if err != nil {
		t.Fatal(err)
	}
	for idx, match := range matches {
		t.Logf("[Errors %3d] Testing '%s'", idx+1, match)

		testData, err := ioutil.ReadFile(match)
		tests := strings.Split(string(testData), "\n")

		checkFilename := fmt.Sprintf("%s.out", match)
		checkData, err := ioutil.ReadFile(checkFilename)
		if err != nil {
			t.Fatalf("Error on ReadFile('%s'): %s", checkFilename, err.Error())
		}
		checks := strings.Split(string(checkData), "\n")

		if len(checks) != len(tests) {
			t.Fatal("Template lines != Checks lines")
		}

		for idx, test := range tests {
			if strings.TrimSpace(test) == "" {
				continue
			}
			if strings.TrimSpace(checks[idx]) == "" {
				t.Fatalf("[%s Line %d] Check is empty (must contain an regular expression).",
					match, idx+1)
			}

			tpl, err := pongo2.FromString(test)
			if err != nil {
				t.Fatalf("Error on FromString('%s'): %s", test, err.Error())
			}

			tpl, err = pongo2.FromBytes([]byte(test))
			if err != nil {
				t.Fatalf("Error on FromBytes('%s'): %s", test, err.Error())
			}

			_, err = tpl.ExecuteBytes(tplContext)
			if err == nil {
				t.Fatalf("[%s Line %d] Expected error for (got none): %s",
					match, idx+1, tests[idx])
			}

			re := regexp.MustCompile(fmt.Sprintf("^%s$", checks[idx]))
			if !re.MatchString(err.Error()) {
				t.Fatalf("[%s Line %d] Error for '%s' (err = '%s') does not match the (regexp-)check: %s",
					match, idx+1, test, err.Error(), checks[idx])
			}
		}
	}
}
Esempio n. 10
0
func handleViewer(res http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	tplData, _ := Asset("viewer.html")
	tpl := pongo2.Must(pongo2.FromString(string(tplData)))
	tpl.ExecuteWriter(pongo2.Context{
		"ipfs_hash": vars["ipfs_hash"],
		"branding":  cfg.Branding,
	}, res)
}
Esempio n. 11
0
//GenerateCustomPath - returns custom path based on sync_key_template
func (schema *Schema) GenerateCustomPath(data map[string]interface{}) (path string, err error) {
	syncKeyTemplate, ok := schema.SyncKeyTemplate()
	if !ok {
		err = fmt.Errorf("Failed to read sync_key_template from schema %v", schema.URL)
		return
	}
	tpl, err := pongo2.FromString(syncKeyTemplate)
	if err != nil {
		return
	}
	path, err = tpl.Execute(pongo2.Context{}.Update(data))
	return
}
Esempio n. 12
0
func htmlHandler(res http.ResponseWriter, r *http.Request) {
	tplsrc, _ := Asset("display.html")

	template, err := pongo2.FromString(string(tplsrc))
	if err != nil {
		log.Fatal(err)
	}

	template.ExecuteWriter(pongo2.Context{
		"results":                probeMonitors,
		"certificateOK":          certificateOK,
		"certificateExpiresSoon": certificateExpiresSoon,
		"version":                version,
	}, res)
}
Esempio n. 13
0
// Builds pxe config to be sent to pixiecore
func (m Machine) pixieInit(config Config) (PixieConfig, error) {
	pixieConfig := PixieConfig{}
	tpl, err := pongo2.FromString(defaultString(m.Cmdline, config.DefaultCmdline))
	if err != nil {
		return pixieConfig, err
	}
	cmdline, err := tpl.Execute(pongo2.Context{"BaseURL": config.BaseURL, "Hostname": m.Hostname, "Token": m.Token})
	if err != nil {
		return pixieConfig, err
	}
	pixieConfig.Kernel = defaultString(m.ImageURL+m.Kernel, config.DefaultImageURL+config.DefaultKernel)
	pixieConfig.Initrd = []string{defaultString(m.ImageURL+m.Initrd, config.DefaultImageURL+config.DefaultInitrd)}
	pixieConfig.Cmdline = cmdline
	return pixieConfig, nil
}
Esempio n. 14
0
func (task *Task) renderValue(value string) (string, error) {
	tmpl, err := pongo2.FromString(value)
	if err != nil {
		log.Println("tmpl error")
		return "", err
	}
	// NOTE: add an update context when regMap is passed in
	ctxt := pongo2.Context{"vars": task.Vars} //, "machine": machine}
	out, err := tmpl.Execute(ctxt)
	if err != nil {
		log.Println("execute error")
		return "", err
	}
	return out, nil

}
Esempio n. 15
0
func doTemplate(c *cli.Context) {
	template := c.String("template")
	manager := schema.GetManager()
	configFile := c.String("config-file")
	config := util.GetConfig()
	err := config.ReadConfig(configFile)
	if err != nil {
		util.ExitFatal(err)
		return
	}
	templateCode, err := util.GetContent(template)
	if err != nil {
		util.ExitFatal(err)
		return
	}
	pwd, _ := os.Getwd()
	os.Chdir(path.Dir(configFile))
	schemaFiles := config.GetStringList("schemas", nil)
	if schemaFiles == nil {
		util.ExitFatal("No schema specified in configuraion")
	} else {
		err = manager.LoadSchemasFromFiles(schemaFiles...)
		if err != nil {
			util.ExitFatal(err)
			return
		}
	}
	schemas := manager.OrderedSchemas()

	if err != nil {
		util.ExitFatal(err)
		return
	}
	tpl, err := pongo2.FromString(string(templateCode))
	if err != nil {
		util.ExitFatal(err)
		return
	}
	output, err := tpl.Execute(pongo2.Context{"schemas": schemas})
	if err != nil {
		util.ExitFatal(err)
		return
	}
	os.Chdir(pwd)
	fmt.Println(output)
}
Esempio n. 16
0
// Builds pxe config to be sent to pixiecore
func (m Machine) pixieInit(config Config) (Pixie, error) {
	var p Pixie

	p.Kernel = m.ImageURL + m.Kernel
	p.Initrd = []string{m.ImageURL + m.Initrd}

	tpl, err := pongo2.FromString(m.Cmdline)
	if err != nil {
		return Pixie{}, err
	}
	out, err := tpl.Execute(pongo2.Context{"BaseURL": config.BaseURL, "Hostname": m.Hostname, "Token": m.Token})
	if err != nil {
		return Pixie{}, err
	}
	p.Cmdline = out

	return p, nil
}
Esempio n. 17
0
func BenchmarkCompileAndExecuteComplexWithSandboxActive(b *testing.B) {
	buf, err := ioutil.ReadFile("template_tests/complex.tpl")
	if err != nil {
		b.Fatal(err)
	}
	preloadedTpl := string(buf)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		tpl, err := pongo2.FromString(preloadedTpl)
		if err != nil {
			b.Fatal(err)
		}

		err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
		if err != nil {
			b.Fatal(err)
		}
	}
}
Esempio n. 18
0
//CacheTemplate caches template to the statement
func CacheTemplate(arg interface{}, templates map[string]*pongo2.Template, minigos map[string]*MiniGo) error {
	switch a := arg.(type) {
	case string:
		if a == "" {
			return nil
		}
		if a[0] == '$' {
			miniGoValue, err := NewMiniGoValue(a)
			if err != nil {
				return err
			}
			minigos[a] = miniGoValue.minigo
		} else {
			tpl, err := pongo2.FromString(a)
			if err != nil {
				return err
			}
			templates[a] = tpl
		}
	case []interface{}:
		for _, item := range a {
			err := CacheTemplate(item, templates, minigos)
			if err != nil {
				return err
			}
		}
	case map[string]interface{}:
		for key, item := range a {
			err := CacheTemplate(key, templates, minigos)
			if err != nil {
				return err
			}
			err = CacheTemplate(item, templates, minigos)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
Esempio n. 19
0
// prepareTmpl takes the loaded template and merges all params available
// on the client into the template
func (c *Client) prepareTmpl() (string, error) {
	// load local template file into memory
	body, err := loadTmpl(fmt.Sprintf("%s%s.html", Conf["template"]["path"], c.Template))
	if err != nil {
		c.context.Errorf("Unable to load template: %v", err)
		return "", err
	}

	tmpl, err := pongo2.FromString(body)
	if err != nil {
		c.context.Errorf("Unable to prepare body of template for pongo: %v", err)
		return "", err
	}

	output, err := tmpl.Execute(c.Params)
	if err != nil {
		c.context.Errorf("Unable to merge variables with pongo template: %v", err)
		return "", err
	}

	return output, nil
}
Esempio n. 20
0
// strings will be evaluated using pongo2 templating with context of
// VarsMap and RegisterMap
func renderValue(value string, varsMap VarsMap, registerMap map[string]interface{}) (string, error) {
	tmpl, err := pongo2.FromString(value)
	if err != nil {
		return "", HenchErr(err, map[string]interface{}{
			"value":    value,
			"solution": "Refer to wiki for proper pongo2 formatting",
		}, "While templating")
	}

	ctxt := pongo2.Context{"vars": varsMap}
	ctxt = ctxt.Update(registerMap)

	out, err := tmpl.Execute(ctxt)
	if err != nil {
		return "", HenchErr(err, map[string]interface{}{
			"value":    value,
			"context":  ctxt,
			"solution": "Refer to wiki for proper pongo2 formatting",
		}, "While executing")
	}
	return out, nil
}
Esempio n. 21
0
func (c *IFMapClient) subcribe() error {
	tpl, err := pongo2.FromString(ifmapSubribeRequest)
	if err != nil {
		return err
	}
	requestString, err := tpl.Execute(pongo2.Context{"session_id": c.sessionID})
	if err != nil {
		return err
	}
	err = c.request(c.ssrc, "subscribe", requestString)
	if err != nil {
		return nil
	}
	if err != nil {
		return nil
	}
	_, err = response(c.ssrc)
	if err != nil {
		return nil
	}
	return nil
}
Esempio n. 22
0
func handleMap(res http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	usr, ok := users.Users[vars["user"]]
	if !ok {
		http.Error(res, "User not found.", http.StatusNotFound)
		return
	}

	if usr.Protected && usr.ViewToken != r.URL.Query().Get("token") {
		http.Error(res, "User not found.", http.StatusNotFound)
		return
	}

	tplString, err := Asset("assets/map.html")
	if err != nil {
		fmt.Printf("Unable to load asset map.html: %s\n", err)
		http.Error(res, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	tpl, err := pongo2.FromString(string(tplString))
	if err != nil {
		fmt.Printf("Unable to parse map.html: %s\n", err)
		http.Error(res, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	data, err := tpl.Execute(pongo2.Context{
		"user": usr.Name,
	})
	if err != nil {
		fmt.Printf("Unable to execute map.html: %s\n", err)
		http.Error(res, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	res.Write([]byte(data))
}
Esempio n. 23
0
func (p *Render) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := "templates/" + data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		if options.Debug {
			tmpl, err := pongo2.FromFile(file)
			if err != nil {
				return err
			}
			t = tmpl
		} else {
			buff, err := server.Asset(file)
			if err == nil {
				tmpl, err := pongo2.FromString(string(buff))
				if err != nil {
					return err
				}
				t = tmpl
			} else {
				tmpl, err := pongo2.FromFile(file)
				if err != nil {
					return err
				}
				t = tmpl
			}

		}
		p.cache[file] = t
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteWriter(ctx, w)
}
Esempio n. 24
0
// NewPongo2ReportRunnerFromString constructor with template string
func NewPongo2ReportRunnerFromString(TemplateString string) *Pongo2ReportRunner {
	var template = pongo2.Must(pongo2.FromString(TemplateString))
	return &Pongo2ReportRunner{
		Template: *template,
	}
}
Esempio n. 25
0
func (server *IFMapServer) handleNewSession(conn net.Conn, body string) {
	tpl, _ := pongo2.FromString(ifmapNewSessionResponse)
	sessionID := uuid.NewV4()
	requestString, _ := tpl.Execute(pongo2.Context{"session_id": sessionID.String()})
	server.serverResponse(conn, requestString)
}