Beispiel #1
0
func Run(uni *context.Uni, commands string) (string, error) {
	if !scut.IsAdmin(uni.Dat["_user"]) {
		return "", fmt.Errorf("Currently only admins can use this.")
	}
	lines := strings.Split(commands, "\n")
	for i, v := range lines {
		// This hack...
		if len(v) > 0 && v[0] != '#' {
			lines[i] = "{{" + v + "}}"
		}
	}
	whole_file := strings.Join(lines, "\n")
	funcMap := template.FuncMap(builtins(uni))
	t, err := template.New("shell").Funcs(funcMap).Parse(string(whole_file))
	if err != nil {
		return "", strip(err)
	}
	context := map[string]interface{}{"dat": uni.Dat, "opt": uni.Opt}
	var buffer bytes.Buffer
	err = t.Execute(&buffer, context) // TODO: watch for errors in execution.
	if err != nil {
		return "", strip(err)
	}
	output_lines := strings.Split(buffer.String(), "\n")
	output_lines = stripComments(output_lines)
	return strings.Join(output_lines, "\n"), nil
}
Beispiel #2
0
func main() {
	tpl := template.New(flag.Arg(0))
	tpl.Funcs(template.FuncMap(map[string]interface{}{
		"string": func(filename string) (string, error) {
			buf, err := ioutil.ReadFile(filename)
			if err != nil {
				return "", err
			}

			return strconv.Quote(string(buf)), nil
		},
		"bytes": func(filename string) (string, error) {
			buf, err := ioutil.ReadFile(filename)
			if err != nil {
				return "", err
			}

			return fmt.Sprintf("%#v", buf), nil
		},
	}))
	_, err := tpl.ParseFiles(flag.Arg(0))
	catch(err)

	file, err := os.Create(regexp.MustCompile("\\.got$").ReplaceAllString(flag.Arg(0), "") + ".go")
	catch(err)
	defer file.Close()

	err = tpl.Execute(file, nil)
	catch(err)
}
Beispiel #3
0
// Creates TEXT template with predefined functions
func NewText(name string) *template.Template {
	tmpl := template.New(name)

	extends := template.FuncMap(map[string]interface{}{
		"extends": func(name string, data interface{}) (text string, err error) {
			buf := bytes.NewBuffer([]byte{})

			if err = tmpl.ExecuteTemplate(buf, name, data); err == nil {
				text = buf.String()
			}

			return
		},
	})

	return tmpl.Funcs(template.FuncMap(coreFuncs)).Funcs(extends)
}
Beispiel #4
0
func loadEmail() {
	contents, _ := ioutil.ReadDir("tmpl/email")
	templatePaths := make([]string, 0)
	for _, fileInfo := range contents {
		if fileInfo.Mode().IsRegular() && strings.HasSuffix(fileInfo.Name(), ".txt") {
			templatePaths = append(templatePaths, "tmpl/email/"+fileInfo.Name())
		}
	}
	emailTemplate = template.Must(template.New("").Funcs(template.FuncMap(templateFuncMap())).ParseFiles(templatePaths...))
}
Beispiel #5
0
// Funcs returns the functions that can be used for interpolation given
// a context.
func Funcs(ctx *Context) template.FuncMap {
	result := make(map[string]interface{})
	for k, v := range FuncGens {
		result[k] = v(ctx)
	}
	if ctx != nil {
		for k, v := range ctx.Funcs {
			result[k] = v
		}
	}

	return template.FuncMap(result)
}
Beispiel #6
0
func main() {

	settings := evergreen.GetSettingsOrExit()
	home := evergreen.FindEvergreenHome()
	uis, err := ui.New(settings, home)
	if err != nil {
		fmt.Println("Failed to create ui server: %v", err)
		os.Exit(1)
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(uis.Home, "public")

	functionOptions := ui.FuncOptions{webHome, uis.Settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, uis.Settings.SuperUsers)
	htmlFunctions := htmlTemplate.FuncMap(functions)
	textFunctions := textTemplate.FuncMap(functions)

	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(uis.Home, ui.WebRootPath, ui.Templates),
		DisableCache: !uis.Settings.Ui.CacheTemplates,
		HtmlFuncs:    htmlFunctions,
		TextFuncs:    textFunctions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(uis.UserManager)))
	n.UseHandler(router)
	graceful.Run(uis.Settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
Beispiel #7
0
func (this *SunnyPublisher) Publish(wr io.Writer, name string, data interface{}) {
	// TODO: use sync.Pool instead once GAE supports 1.3

	// get cloned template from pool
	// add contextual funcmap to the template

	if strings.HasSuffix(name, ".html") {
		ht, err := this.htmpl.Clone()
		ht.Funcs(htemplate.FuncMap(this.fmap))

		if err == nil {
			ht = ht.Lookup(name)
			if ht != nil {
				ht.Execute(wr, data)
			} else {
				goto renderer
			}
		} else {
			goto renderer
		}
	} else {
		ht, err := this.tmpl.Clone()
		ht.Funcs(template.FuncMap(this.fmap))

		if err == nil {
			if ht != nil {
				ht.Execute(wr, data)
			} else {
				goto renderer
			}
		} else {
			goto renderer
		}
	}

	return

renderer:
	ext := ".html"
	b, err := this.renderer[ext](name, data)
	if err == nil {
		wr.Write(b)
	}
}
//newTtemplate adds funcmap to template var and parse files.
func newTtemplate(templateDir string) *Ttemplate {
	t := &Ttemplate{textTemplate.New("")}
	t.Funcs(textTemplate.FuncMap(funcMap))
	templateFiles := filepath.Join(templateDir, "rss1.txt")
	if util.IsFile(templateFiles) {
		_, err := t.ParseFiles(templateFiles)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		cont, err := util.Asset(path.Join("gou_template", "rss1.txt"))
		if err != nil {
			log.Fatal(err)
		}
		_, err = t.Parse(string(cont))
		if err != nil {
			log.Fatal(err)
		}
	}
	return t
}
Beispiel #9
0
// FromGlobs calls ParseGlob on all path globs provided and returns the
// resulting Template.
func FromGlobs(paths ...string) (*Template, error) {
	t := &Template{
		text: tmpltext.New("").Option("missingkey=zero"),
		html: tmplhtml.New("").Option("missingkey=zero"),
	}
	var err error

	t.text = t.text.Funcs(tmpltext.FuncMap(DefaultFuncs))
	t.html = t.html.Funcs(tmplhtml.FuncMap(DefaultFuncs))

	b, err := deftmpl.Asset("template/default.tmpl")
	if err != nil {
		return nil, err
	}
	if t.text, err = t.text.Parse(string(b)); err != nil {
		return nil, err
	}
	if t.html, err = t.html.Parse(string(b)); err != nil {
		return nil, err
	}

	for _, tp := range paths {
		// ParseGlob in the template packages errors if not at least one file is
		// matched. We want to allow empty matches that may be populated later on.
		p, err := filepath.Glob(tp)
		if err != nil {
			return nil, err
		}
		if len(p) > 0 {
			if t.text, err = t.text.ParseGlob(tp); err != nil {
				return nil, err
			}
			if t.html, err = t.html.ParseGlob(tp); err != nil {
				return nil, err
			}
		}
	}
	return t, nil
}
Beispiel #10
0
func (r *TextTemplateRenderer) Render(name string, vars librenderer.M) ([]byte, error) {
	if r.memcache == nil {
		r.memcache = make(map[string]*template.Template)
	}

	if r.memlock == nil {
		r.memlock = new(sync.Mutex)
	}

	r.memlock.Lock()
	defer r.memlock.Unlock()

	tpl, exists := r.memcache[name]
	if !exists {
		src, err := r.Assets.Asset(name)
		if err != nil {
			return []byte{}, err
		}

		tpl, err = template.New(name).Parse(string(src))
		if err != nil {
			return []byte{}, err
		}

		if r.Funcs != nil {
			tpl = tpl.Funcs(template.FuncMap(r.Funcs))
		}

		r.memcache[name] = tpl
	}

	b := new(bytes.Buffer)
	if err := tpl.Execute(b, vars); err != nil {
		return []byte{}, err
	}

	return b.Bytes(), nil
}
Beispiel #11
0
// Setup runs before parsing templates
func (t *TextTemplate) Setup(helpers FuncMap) error {
	textTemplateSet = got.New("").Funcs(got.FuncMap(helpers))
	return nil
}
Beispiel #12
0
}

// firstMatch executes the query q and loads the first entity into v.
func firstMatch(c appengine.Context, q *datastore.Query, v interface{}) error {
	t := q.Limit(1).Run(c)
	_, err := t.Next(v)
	if err == datastore.Done {
		err = datastore.ErrNoSuchEntity
	}
	return err
}

var (
	notifyLater = delay.Func("notify", notify)
	notifyTmpl  = template.Must(template.New("notify.txt").
			Funcs(template.FuncMap(tmplFuncs)).ParseFiles("build/notify.txt"))
)

// notify tries to update the CL for the given Commit with a failure message.
// If it doesn't succeed, it sends a failure email to golang-dev.
func notify(c appengine.Context, com *Commit, builder, logHash string) {
	var msg bytes.Buffer
	err := notifyTmpl.Execute(&msg, struct {
		Builder  string
		LogHash  string
		Hostname string
	}{builder, logHash, domain})
	if err != nil {
		c.Criticalf("couldn't render template: %v", err)
		return
	}
Beispiel #13
0
func (t textTemp) Funcs(funcMap FuncMap) {
	t.Template.Funcs(template.FuncMap(funcMap))
}
Beispiel #14
0
func GetTextFuncMap() (fc txtemplate.FuncMap) {
	return txtemplate.FuncMap(GetFuncMap())
}
Beispiel #15
0
// firstMatch executes the query q and loads the first entity into v.
func firstMatch(c appengine.Context, q *datastore.Query, v interface{}) error {
	t := q.Limit(1).Run(c)
	_, err := t.Next(v)
	if err == datastore.Done {
		err = datastore.ErrNoSuchEntity
	}
	return err
}

var (
	sendFailMailLater = delay.Func("sendFailMail", sendFailMail)
	sendFailMailTmpl  = template.Must(
		template.New("notify.txt").
			Funcs(template.FuncMap(tmplFuncs)).
			ParseFiles("build/notify.txt"),
	)
)

func init() {
	gob.Register(&Commit{}) // for delay
}

// sendFailMail sends a mail notification that the build failed on the
// provided commit and builder.
func sendFailMail(c appengine.Context, com *Commit, builder string) {
	// TODO(adg): handle packages

	// get Result
	r := com.Result(builder, "")
Beispiel #16
0
package tpl

import (
	"os"
	"text/template"
)

var Funcs = template.FuncMap(map[string]interface{}{
	"PWD": func() (string, error) { return os.Getwd() },
})
Beispiel #17
0
Datei: main.go Projekt: kr/blog
	Path     string
	Id       string
	Content  template.HTML
	Date     time.Time
	Articles []Page
}

var dstDir string

var (
	baseLayout *template.Template
	htmlfuncs  = template.FuncMap{
		"rev":     rev,
		"datauri": datauri,
	}
	textfuncs = ttemplate.FuncMap(htmlfuncs)
)

func mustGetOutput(c *exec.Cmd) []byte {
	b, err := c.Output()
	if err != nil {
		panic(err)
	}
	return b
}

func lines(b []byte) []string {
	a := bytes.Split(b, []byte("\n"))
	s := make([]string, len(a))
	for i := range a {
		s[i] = string(a[i])
Beispiel #18
0
// Funcs adds the elements of the argument map to the template's function map.
// It panics if a value in the map is not a function with appropriate return
// type. However, it is legal to overwrite elements of the map. The return
// value is the template, so calls can be chained.
func (t *Template) Funcs(funcMap FuncMap) *Template {
	t.text.Funcs(template.FuncMap(funcMap))
	return t
}
func FunctionsMap() template.FuncMap {
	return template.FuncMap(fmap)
}
Beispiel #20
0
// TextFuncMap returns a 'text/template'.FuncMap
func TxtFuncMap() ttemplate.FuncMap {
	return ttemplate.FuncMap(genericMap)
}
Beispiel #21
0
func main() {
	settings := evergreen.GetSettingsOrExit()
	if settings.Ui.LogFile != "" {
		evergreen.SetLogger(settings.Ui.LogFile)
	}
	db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(settings))

	home := evergreen.FindEvergreenHome()

	userManager, err := auth.LoadUserManager(settings.AuthConfig)
	if err != nil {
		fmt.Println("Failed to create user manager:", err)
		os.Exit(1)
	}

	cookieStore := sessions.NewCookieStore([]byte(settings.Ui.Secret))

	uis := ui.UIServer{
		nil,             // render
		settings.Ui.Url, // RootURL
		userManager,     // User Manager
		*settings,       // mci settings
		cookieStore,     // cookiestore
		nil,             // plugin panel manager
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(home, "public")

	functionOptions := ui.FuncOptions{webHome, settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, settings.SuperUsers)
	htmlFunctions := htmlTemplate.FuncMap(functions)
	textFunctions := textTemplate.FuncMap(functions)

	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, ui.WebRootPath, ui.Templates),
		DisableCache: !settings.Ui.CacheTemplates,
		HtmlFuncs:    htmlFunctions,
		TextFuncs:    textFunctions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(userManager)))
	n.UseHandler(router)
	graceful.Run(settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
Beispiel #22
0
func main() {
	var (
		outputFile  string
		definesFile string
		prettyPrint bool
		jscriptMode bool
	)

	for _, name := range []string{"o", "output"} {
		flag.StringVar(&outputFile, name, "", "Output file")
	}
	for _, name := range []string{"d", "defines"} {
		flag.StringVar(&definesFile, name, "", "Defines file")
	}
	for _, name := range []string{"pp", "prettyprint"} {
		flag.BoolVar(&prettyPrint, name, false, "Pretty print")
	}
	for _, name := range []string{"j", "javascript"} {
		flag.BoolVar(&jscriptMode, name, false, "Javascript mode")
	}

	flag.Parse()
	inputFile := flag.Arg(0)

	if inputFile == "" {
		fmt.Fprintf(os.Stderr, "No input file specified.")
		flag.Usage()
		os.Exit(2)
	}

	inputText := ""
	if definesFile != "" {
		b, err := ioutil.ReadFile(definesFile)
		check(err)
		inputText += compile(b, prettyPrint, jscriptMode)
		if inputText[len(inputText)-1] == '\n' { // amber does add this '\n', which is fine for the end of a file, which inputText is not
			inputText = inputText[:len(inputText)-1]
		}
	}
	b, err := ioutil.ReadFile(inputFile)
	check(err)
	inputText += compile(b, prettyPrint, jscriptMode)

	fstplate, err := template.New("fst").Funcs(dotFuncs).Delims("[[", "]]").Parse(inputText)
	check(err)
	fst := execute(fstplate, hash{})

	if !jscriptMode {
		writeFile(outputFile, fst)
		return
	}

	sndplate, err := template.New("snd").Funcs(template.FuncMap(amber.FuncMap)).Parse(fst)
	check(err)

	m := data(sndplate.Tree, jscriptMode) //; fmt.Printf("data => %+v\nstring_hash(data) => %+v", m, string_hash(m))
	snd := execute(sndplate, m)
	snd = regexp.MustCompile("</?script>").ReplaceAllLiteralString(snd, "")

	writeFile(outputFile, snd)
}