Beispiel #1
0
func (ctx *TemplateContext) Transform(writer io.Writer, descriptor string) error {
	var t *template.Template

	if b, err := ioutil.ReadFile(descriptor); err != nil {
		return err
	} else {
		var e error
		t = template.New(descriptor).Funcs(Funcs)
		t, e = t.Parse(string(b))
		if e != nil {
			return e
		}
		if matches, err := filepath.Glob("./**/*.tmpl"); err == nil && len(matches) > 0 {
			if t, e = t.ParseFiles(matches...); err != nil {
				return err
			}
		}
	}
	environment := viper.GetString(ENV_NAME)
	m := ctx.mergeAppWithDefault(strings.ToLower(environment))

	if err := t.Execute(writer, m); err != nil {
		return err
	}
	return nil
}
Beispiel #2
0
// Render updates the given destinationPath according to the given template and options.
// Returns true if the file was created or changed, false if nothing has changed.
func Render(templateName, destinationPath string, options interface{}, destinationFileMode os.FileMode) (bool, error) {
	asset, err := Asset(templateName)
	if err != nil {
		return false, maskAny(err)
	}

	// parse template
	var tmpl *template.Template
	tmpl = template.New(templateName)
	funcMap := template.FuncMap{
		"escape": escape,
		"quote":  strconv.Quote,
	}
	tmpl.Funcs(funcMap)
	_, err = tmpl.Parse(string(asset))
	if err != nil {
		return false, maskAny(err)
	}
	// execute template to buffer
	buf := &bytes.Buffer{}
	tmpl.Funcs(funcMap)
	err = tmpl.Execute(buf, options)
	if err != nil {
		return false, maskAny(err)
	}

	// Update file
	changed, err := util.UpdateFile(destinationPath, buf.Bytes(), destinationFileMode)
	return changed, maskAny(err)
}
Beispiel #3
0
func applyTemplate(t *template.Template, name string, data interface{}) []byte {
	var buf bytes.Buffer
	if err := t.Execute(&buf, data); err != nil {
		log.Printf("%s.Execute: %s", name, err)
	}
	return buf.Bytes()
}
Beispiel #4
0
/*
 * Render page
 *
 * @param pageFilePath (string)
 * @param w            (http.ResponseWriter)
 *
 * @return (error)
 */
func (page *Page) Render(pageFilePath string, w http.ResponseWriter) (err error) {
	columnFilePath := page.PageSetting.Layout + ".html"
	mainFilePath := "main.html"
	contentFilePath := pageFilePath + ".html"
	sidebarFilePath := "sidebar.html"

	var tmpl *template.Template

	switch page.PageSetting.ShowSidebar {
	case true:
		tmpl, err = template.ParseFiles(
			LAYOUT_FOLDER+mainFilePath,
			LAYOUT_FOLDER+columnFilePath,
			LAYOUT_FOLDER+sidebarFilePath,
			STATIC_FOLDER+contentFilePath)
	case false:
		tmpl, err = template.ParseFiles(
			LAYOUT_FOLDER+mainFilePath,
			LAYOUT_FOLDER+columnFilePath,
			STATIC_FOLDER+contentFilePath)

	}

	if err != nil {
		return
	}

	tmpl.Execute(w, page)
	return
}
Beispiel #5
0
// execTmpl executes the provided template on the data, emitting the string.
// It presumes that the input data is semantically correct for the template.
func execTmpl(t *template.Template, data interface{}) string {
	var b bytes.Buffer
	if err := t.Execute(&b, data); err != nil {
		panic("drum: " + err.Error())
	}
	return b.String()
}
Beispiel #6
0
func getServiceURLWithClient(client *unversioned.Client, ip, namespace, service string, t *template.Template) (string, error) {
	port, err := getServicePort(client, namespace, service)
	if err != nil {
		return "", err
	}

	var doc bytes.Buffer
	err = t.Execute(&doc, ipPort{ip, port})
	if err != nil {
		return "", err
	}

	u, err := url.Parse(doc.String())
	if err != nil {
		return "", err
	}

	annotations, err := getServiceAnnotations(client, namespace, service)
	if err != nil {
		return "", err
	}

	if scheme, ok := annotations[serviceAPIAnnotationScheme]; ok {
		u.Scheme = scheme
	}
	if path, ok := annotations[serviceAPIAnnotationPath]; ok && len(u.Path) == 0 {
		u.Path = path
	}

	return u.String(), nil
}
Beispiel #7
0
func generateCode(outputFile string, tmpl *template.Template, pkg string, parsed *parser.Thrift) error {
	wrappedServices, err := wrapServices(parsed)
	if err != nil {
		log.Fatalf("Service parsing error: %v", err)
	}

	buf := &bytes.Buffer{}

	td := TemplateData{
		Package:        pkg,
		Services:       wrappedServices,
		ThriftImport:   *apacheThriftImport,
		TChannelImport: tchannelThriftImport,
	}
	if err := tmpl.Execute(buf, td); err != nil {
		return fmt.Errorf("failed to execute template: %v", err)
	}

	generated := cleanGeneratedCode(buf.Bytes())
	if err := ioutil.WriteFile(outputFile, generated, 0666); err != nil {
		return fmt.Errorf("cannot write output file %s: %v", outputFile, err)
	}

	// Run gofmt on the file (ignore any errors)
	exec.Command("gofmt", "-w", outputFile).Run()
	return nil
}
Beispiel #8
0
func diffOutput(got string, wantTmpl *template.Template) (string, error) {
	got = filepath.ToSlash(got)

	wantBuf := new(bytes.Buffer)
	data := outputData{
		NDK:         ndkVersion,
		GOOS:        goos,
		GOARCH:      goarch,
		GOPATH:      gopath,
		NDKARCH:     ndkarch,
		BuildScript: unixBuildScript,
	}
	if goos == "windows" {
		data.EXE = ".exe"
		data.BuildScript = windowsBuildScript
	}
	if err := wantTmpl.Execute(wantBuf, data); err != nil {
		return "", err
	}
	want := wantBuf.String()
	if got != want {
		return diff(got, want)
	}
	return "", nil
}
Beispiel #9
0
func (blankPanel blankPanel) generate(terminal, packageName string, employee Employee) []byte {

	var t *template.Template

	var buf bytes.Buffer

	t = template.New("blankpanel.html")

	t, err := t.ParseFiles("../lessgo/template/component/" + terminal + "/blankpanel.html")

	if err != nil {
		Log.Error(err.Error())
		return []byte{}
	}

	data := make(map[string]interface{})

	data["BlankPanel"] = blankPanel
	data["Terminal"] = terminal
	data["Employee"] = employee

	err = t.Execute(&buf, data)

	if err != nil {
		Log.Error(err.Error())
		return []byte{}
	}

	return buf.Bytes()

}
Beispiel #10
0
/**
 * 単語学習ページの表示
 * play.html 学習ページ全体のテンプレート
 */
func play(w http.ResponseWriter, r *http.Request) {
	type Contents struct {
		Words string
	}

	var c appengine.Context
	var u *user.User
	var contents *Contents
	var err error
	var page *template.Template
	var entities []Entity
	var bytes []byte

	c = appengine.NewContext(r)
	u = user.Current(c)

	// 単語一覧を取得
	entities = get(c, u)

	// JSONに変換
	bytes, err = json.Marshal(entities)
	Check(c, err)
	contents = new(Contents)
	contents.Words = string(bytes)

	// ページテンプレート取得
	page, err = template.ParseFiles("server/play.html")
	Check(c, err)

	// 表示
	page.Execute(w, contents)
}
Beispiel #11
0
// ShowMessage opens a message dialog to show the user a message.
func (w *Workflow) ShowMessage(message string) (err error) {
	script :=
		`tell application "Alfred {{.Version}}"
			  activate
			  set alfredPath to (path to application "Alfred {{.Version}}")
			  set alfredIcon to path to resource "appicon.icns" in bundle (alfredPath as alias)
			  display dialog "{{.Prompt}}" with title "{{.Title}}" buttons {"Ok"} default button "Ok" with icon alfredIcon
		  end tell`

	data := struct {
		Version string
		Prompt  string
		Title   string
	}{os.Getenv("alfred_short_version"), message, w.name}

	var tmpl *template.Template
	tmpl, err = template.New("script").Parse(script)
	if err != nil {
		return
	}

	var buf bytes.Buffer
	err = tmpl.Execute(&buf, data)
	if err != nil {
		return
	}

	script = buf.String()
	_, err = RunScript(script)
	return
}
Beispiel #12
0
func (slConfig *SyslogConfig) logrotateRender(t *template.Template) ([]byte, error) {
	var buffer bytes.Buffer
	if err := t.Execute(&buffer, slConfig); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}
Beispiel #13
0
func (pw PackageWrapper) writePri(filename string, tpl *template.Template, data interface{}) error {

	var file *os.File
	var err error

	// create the vendor directory if needed
	if _, err = os.Stat(core.Vendor); err != nil {
		err = os.Mkdir(core.Vendor, 0755)
	}

	// re-create the .pri file
	file, err = os.Create(filename)

	if err != nil {
		return err
	}
	defer file.Close()

	err = tpl.Execute(file, data)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #14
0
// Generate a dockerfile for the given deployment
func createDockerfile(d *DeployInfo) ([]byte, error) {
	// use de-reference to create a copy
	info := *d

	var buf bytes.Buffer
	var tmpl *template.Template
	switch d.Lang {
	case Python2:
		tmpl = pyTmpl

		if info.BaseImage == "" {
			info.BaseImage = "yhat/scienceops-python:0.0.2"
		}

	case R:
		if d.CRANMirror == "" {
			// Create a copy of the DeployInfo to appease the race detector.
			info.CRANMirror = YhatCRANMirror
		}
		if info.BaseImage == "" {
			info.BaseImage = "yhat/scienceops-r:0.0.2"
		}

		tmpl = rTmpl
	default:
		return nil, fmt.Errorf("unrecognized language passed to dockerfile generation '%s'", d.Lang)
	}
	if err := tmpl.Execute(&buf, &info); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Beispiel #15
0
func genConfig(appPath string, data map[string]string) error {
	var src, dest *os.File
	var fileContent []byte
	var err error
	var tmpl *template.Template
	name := filepath.Join(appPath, "conf", "app.cnf.template")

	if src, err = os.Open(name); err != nil {
		return err
	}
	tmpfile := name
	defer func() { src.Close(); os.Remove(tmpfile) }()
	name = filepath.Join(appPath, "conf", "app.cnf")
	if dest, err = os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0666); err != nil {
		return nil
	}
	defer dest.Close()
	if fileContent, err = ioutil.ReadAll(src); err != nil {
		return err
	}
	if tmpl, err = template.New("").Parse(string(fileContent)); err != nil {
		return err
	}
	return tmpl.Execute(dest, data)
}
Beispiel #16
0
func writeTmpl(tmpl *template.Template, vmConfigs []vm) {
	file, err := os.Create(tmpl.Name())
	checkError(err)
	defer file.Close()
	err = tmpl.Execute(file, vmConfigs)
	checkError(err)
}
Beispiel #17
0
func (suite *ExamplesSuite) executeTemplate(tmpl *template.Template) {
	cqlshCmd := exec.Command("cqlsh")

	inPipe, inPipeErr := cqlshCmd.StdinPipe()
	if nil != inPipeErr {
		panic(inPipeErr.Error())
	}

	if startErr := cqlshCmd.Start(); nil != startErr {
		panic(startErr.Error())
	}

	data := struct {
		Keyspace string
		Id       gocql.UUID
	}{
		Keyspace: cassandraConfig.Keyspace,
		Id:       suite.id,
	}

	if renderErr := tmpl.Execute(inPipe, data); nil != renderErr {
		panic(renderErr.Error())
	}
	inPipe.Close()

	if waitErr := cqlshCmd.Wait(); nil != waitErr {
		panic(waitErr.Error())
	}
}
Beispiel #18
0
func waitForWatcher(ctx context.Context, watcher *inotify.Watcher, match matcherFunc, tpl *template.Template, monitor bool) {
	defer watcher.Close()

	for {
		select {
		case <-ctx.Done(): // Timeout
			os.Exit(2)
			return

		case ev := <-watcher.Event:
			if !match(ev) {
				break
			}
			if tpl != nil {
				tpl.Execute(os.Stdout, ev)
				log.Infoln()
			} else {
				log.Infoln(ev)
			}
			// Finish if not monitoring mode.
			if !monitor {
				return
			}

		case err := <-watcher.Error:
			log.Fatal(err)
		}
	}
}
Beispiel #19
0
func RunTemplate(reportFilename, templateFile, templateText string, out *os.File, data interface{}, format string) (err error) {
	var tmpl *template.Template
	var htmpl *htemplate.Template
	if templateFile != "" {
		if format == "html" {
			htmpl, err = htemplate.New(templateFile).ParseGlob(templateFile)
		} else {
			tmpl, err = template.New(templateFile).ParseGlob(templateFile)
		}
	} else {
		if format == "html" {
			htmpl, err = htemplate.New(reportFilename).Parse(templateText)
		} else {
			tmpl, err = template.New(reportFilename).Parse(templateText)
		}
	}
	if err != nil {
		return err
	}
	if format == "html" {
		err = htmpl.Execute(out, data)
	} else {
		err = tmpl.Execute(out, data)
	}
	if err != nil {
		return err
	}

	return err
}
Beispiel #20
0
// respond responds to a request by executing the html template t with data.
func Respond(w http.ResponseWriter, t *template.Template, data interface{}) {
	fmt.Println("Respond")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := t.Execute(w, data); err != nil {
		log.Print(err)
	}
}
Beispiel #21
0
func WriteTemplate(temp *template.Template, out string, data interface{}) {
	file, err := os.Create(path.Clean(out))
	defer file.Close()
	HandleError(err)

	HandleError(temp.Execute(file, data))
}
func executeTemplate(tmpl *template.Template, data interface{}) (string, error) {
	var cmdBuffer bytes.Buffer
	if err := tmpl.Execute(&cmdBuffer, data); err != nil {
		return "", err
	}
	return cmdBuffer.String(), nil
}
func generatePage(t *template.Template, data interface{}) ([]byte, error) {
	buffer := bytes.NewBuffer(nil)
	if err := t.Execute(buffer, data); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}
Beispiel #24
0
func (c *Config) writePlaylist(mount, ext string, t *template.Template) error {
	for i, s := range c.Server {
		if s.Kind == "master" {
			continue
		}
		url := fmt.Sprintf("%s%s", c.ServerURL(s), mount)
		servers := []string{url}
		for j, s := range c.Server {
			if s.Kind == "master" || i == j {
				continue
			}
			url := fmt.Sprintf("%s%s", c.ServerURL(s), mount)
			servers = append(servers, url)
		}
		name := fmt.Sprintf("%s-%s.%s", mount, s.Name, ext)
		f, err := os.Create(name)
		if err != nil {
			return err
		}
		if err := t.Execute(f, servers); err != nil {
			return err
		}
		f.Close()
	}
	return nil
}
Beispiel #25
0
// execute runs the given go-template over the given context.
func (temp *Templater) Execute(name string, templateStr string, context interface{}) string {
	var parsed *template.Template = nil

	// Check the cache.
	cached, isCached := temp.templateCache.Get(templateStr)
	if !isCached {
		t := template.New(name)
		parsedTemplate, err := t.Parse(templateStr)
		if err != nil {
			panic(err)
		}

		temp.templateCache.Set(templateStr, parsedTemplate)
		parsed = parsedTemplate
	} else {
		parsed = cached.(*template.Template)
	}

	// Execute the template.
	var source bytes.Buffer
	eerr := parsed.Execute(&source, context)
	if eerr != nil {
		panic(eerr)
	}

	return source.String()
}
Beispiel #26
0
func exportTileset(filename string, tmpl *template.Template) {
	fmt.Printf("Processing %s\n", filename)

	file, err := os.Open(filename)

	if err != nil {
		log.Fatal(err)
	}

	tileset, err := tmx.Read(file)

	if err != nil {
		log.Fatal(err)
	}

	luaFilename := strings.Replace(filepath.Base(filename), filepath.Ext(filename), ".lua", 1)
	outputPath := filepath.Join(filepath.Dir(filename), luaFilename)

	output, err := os.Create(outputPath)

	if err != nil {
		log.Fatal(err)
	}

	err = tmpl.Execute(output, tileset)

	if err != nil {
		log.Fatal(err)
	}
}
Beispiel #27
0
func diffOutput(got string, wantTmpl *template.Template) (string, error) {
	got = filepath.ToSlash(got)

	wantBuf := new(bytes.Buffer)
	data := outputData{
		NDK:       ndkVersion,
		GOOS:      goos,
		GOARCH:    goarch,
		GOPATH:    gopath,
		NDKARCH:   ndkarch,
		Xproj:     projPbxproj,
		Xcontents: contentsJSON,
		Xinfo:     infoplistTmplData{Name: "Basic"},
		NumCPU:    strconv.Itoa(runtime.NumCPU()),
	}
	if goos == "windows" {
		data.EXE = ".exe"
	}
	if err := wantTmpl.Execute(wantBuf, data); err != nil {
		return "", err
	}
	want := wantBuf.String()
	if got != want {
		return diff(got, want)
	}
	return "", nil
}
Beispiel #28
0
func Render(templateName string, options interface{}) (string, error) {
	asset, err := Asset(templateName)
	if err != nil {
		return "", maskAny(err)
	}

	// parse template
	var tmpl *template.Template
	tmpl = template.New(templateName)
	funcMap := template.FuncMap{
		"escape":     escape,
		"quote":      strconv.Quote,
		"yamlPrefix": yamlPrefix,
	}
	tmpl.Funcs(funcMap)
	_, err = tmpl.Parse(string(asset))
	if err != nil {
		return "", maskAny(err)
	}
	// write file to buffer
	tmpl.Funcs(funcMap)
	buffer := &bytes.Buffer{}
	err = tmpl.Execute(buffer, options)
	if err != nil {
		return "", maskAny(err)
	}

	return buffer.String(), nil
}
Beispiel #29
0
// write writes the configuration file, will write to stdout if dryRun == true
func (cfg *loadBalancerConfig) write(services map[string][]service, dryRun bool) (err error) {
	var w io.Writer
	if dryRun {
		w = os.Stdout
	} else {
		w, err = os.Create(cfg.Config)
		if err != nil {
			return
		}
	}
	var t *template.Template
	t, err = template.ParseFiles(cfg.Template)
	if err != nil {
		return
	}

	conf := make(map[string]interface{})
	conf["startSyslog"] = strconv.FormatBool(cfg.startSyslog)
	conf["services"] = services

	// default load balancer algorithm is roundrobin
	conf["defLbAlgorithm"] = lbDefAlgorithm
	if cfg.lbDefAlgorithm != "" {
		conf["defLbAlgorithm"] = cfg.lbDefAlgorithm
	}

	err = t.Execute(w, conf)
	return
}
Beispiel #30
0
// formatErrorDescription takes a string in the default text/template
// format and converts it to a string with replacements. The fields come
// from the ErrorDetails struct and vary for each type of error.
func formatErrorDescription(s string, details ErrorDetails) string {

	var tpl *template.Template
	var descrAsBuffer bytes.Buffer
	var err error

	if errorTemplates == nil {
		errorTemplates = template.New("all-errors")
	}

	tpl = errorTemplates.Lookup(s)
	if tpl == nil {
		tpl = errorTemplates.New(s)
		tpl, err = tpl.Parse(s)
		if err != nil {
			return err.Error()
		}
	}

	err = tpl.Execute(&descrAsBuffer, details)
	if err != nil {
		return err.Error()
	}

	return descrAsBuffer.String()
}