Ejemplo n.º 1
1
// ExecuteTemplate executes a template on the source TeX files.
func (t *CompileTask) ExecuteTemplate(templ *template.Template, data interface{}, inputFilename string, outputFilename string) {
	sc := t.context()

	useTempFile := outputFilename == ""
	if useTempFile {
		outputFilename = sc.MustGetTempFile().Name()
	}
	inputFilename = sc.AbsPath(t.defaultCompileFilename(inputFilename))

	f, err := os.Create(sc.AbsPath(outputFilename))
	if err != nil {
		panic(err)
	}
	w := io.Writer(f)
	err = templ.ExecuteTemplate(w, filepath.Base(inputFilename), data)
	if err != nil {
		panic(err)
	}
	f.Close()

	if useTempFile {
		// copy back, remove temp
		err = os.Remove(inputFilename)
		if err != nil {
			panic(err)
		}
		err = sc.CopyFile(outputFilename, inputFilename)
		if err != nil {
			panic(err)
		}
	}
}
Ejemplo n.º 2
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
}
Ejemplo n.º 3
0
func processFile(fc FileConfig, t *template.Template) {
	// in file
	iFile, err := os.Open(fc.Name)
	if err != nil {
		panic("Can't open " + fc.Name)
	}
	defer iFile.Close()

	// out file
	oFile, err := os.Create(fc.Name + "_out.txt")
	if err != nil {
		panic("Can't open/write to " + fc.Name + "_out.txt")
	}
	defer oFile.Close()

	r := csv.NewReader(iFile)
	r.Comma = '\t'
	r.TrailingComma = true
	record, err := r.Read()

	for i := 0; err == nil; record, err = r.Read() {
		if i == 0 {
			t.ExecuteTemplate(oFile, fc.TemplateName+"_H", makeTemplateContext(&record))
		}
		i = i + 1
		if i <= fc.Skip {
			continue
		}
		oFile.Write([]byte("\n"))
		t.ExecuteTemplate(oFile, fc.TemplateName, makeTemplateContext(&record))
	}
	fmt.Println(err)
	oFile.Sync()
}
Ejemplo n.º 4
0
func (r Renderer) RenderPost(pc *PostContext, templates *template.Template) error {
	err := os.MkdirAll(path.Join(r.OutputPath, pc.Slug), 0755)
	if err != nil {
		log.Panicf(err.Error())
	}

	outfile, err := os.Create(path.Join(r.OutputPath, pc.Slug, "index.html"))
	if err != nil {
		log.Panicf(err.Error())
	}

	err = templates.ExecuteTemplate(outfile, "post.html", pc)
	if err != nil {
		log.Panicf(err.Error())
	}

	// copy images
	log.Printf("\"%s\": Using %d %s", pc.Slug, len(pc.Images), pluralize("image", len(pc.Images)))
	for _, image := range pc.Images {
		err = cp(image.SrcAbsPath, path.Join(r.OutputPath, pc.Slug, image.Filename))
		if err != nil {
			log.Panicf(err.Error())
		}
	}

	log.Printf("\"%s\": Done rendering", pc.Slug)
	return nil
}
Ejemplo n.º 5
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()
}
Ejemplo n.º 6
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()
}
Ejemplo n.º 7
0
func (g *Generator) generatePerModelFiles(templateFileNames []string, modelTpls *template.Template, modelsDir string, filter func(modelInfo *modelInfo) bool) error {
	for _, tplFileName := range templateFileNames {
		tplName := filepath.Base(tplFileName)
		// Apply the templates to each model in the API
		for _, modelInfo := range g.modelsInfo {
			if filter(modelInfo) {
				continue
			}
			// TODO: Do this concurrently
			repl := strings.NewReplacer(
				templateExt, "",
				fileNameModelNameInterpolation, modelInfo.Name,
				fileNameAPINameInterpolation, g.config.APIName,
				fileNameAPIPrefixInterpolation, g.config.APIPrefix,
			)
			fileName := repl.Replace(tplName)
			err := generateFile(path.Join(modelsDir, fileName), modelTpls.Lookup(tplName), templateData{
				Config:           g.config,
				API:              g.api,
				CurrentModelInfo: modelInfo,
				AllModelsInfo:    g.modelsInfo,
				AuthInfo:         g.authInfo,
				CurrentTime:      time.Now(),
			})
			if err != nil {
				return errors.Annotatef(err, "when generating model or service %q", modelInfo.Name)
			}
		}
	}
	return nil
}
Ejemplo n.º 8
0
// templateWorker create file from template
// done channel send nil or error back
func templateWorker(tpl *template.Template, ftpl FileTemplates, done chan error) {

	// check file template path
	ok, err := utils.PathExists(ftpl.Path)
	if err != nil {
		done <- err
		return
	}

	// file template path not exists, create new file template path
	if !ok {
		if err := os.MkdirAll(ftpl.Path, 0755); err != nil {
			done <- err
			return
		}
	}

	// create new target file
	f, err := os.OpenFile(filepath.Join(ftpl.Path, ftpl.Target), os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		done <- err
		return
	}

	defer f.Close()

	// generate file content,
	// send return to channel (nil or err)
	done <- tpl.ExecuteTemplate(f, ftpl.Tpl, ftpl.Vars)
}
Ejemplo n.º 9
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
}
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
}
Ejemplo n.º 11
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)
	}
}
Ejemplo n.º 12
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)
		}
	}
}
Ejemplo n.º 13
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)
}
Ejemplo n.º 14
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()

}
Ejemplo n.º 15
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))
}
Ejemplo n.º 16
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)
	}
}
Ejemplo n.º 17
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
}
Ejemplo n.º 18
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)
}
Ejemplo n.º 19
0
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
}
Ejemplo n.º 20
0
func Register(templates *template.Template) {
	// http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	// 	// Load template according to the requested path, excluding the leading "/"
	// 	requestedFile := req.URL.Path[1:]
	// 	template := templates.Lookup(requestedFile + ".html")
	//
	// 	var context interface{} = nil
	// 	context = viewmodels.Get("My Title", requestedFile)
	//
	// 	if template != nil {
	// 		template.Execute(w, context)
	// 	} else {
	// 		w.WriteHeader(404)
	// 		w.Write([]byte("404 - " + http.StatusText(404)))
	// 	}
	// })

	ic := new(indexController)
	ic.template = templates.Lookup("index.html")
	http.HandleFunc("/index", ic.get)

	cc := new(categoriesController)
	cc.template = templates.Lookup("categories.html")
	http.HandleFunc("/categories", cc.get)

	// redirect /img/ and /css/ dir to assets/img/ and assets/css/
	http.HandleFunc("/img/", serveAssets)
	http.HandleFunc("/css/", serveAssets)
}
Ejemplo n.º 21
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()
}
Ejemplo n.º 22
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())
	}
}
Ejemplo n.º 23
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
}
Ejemplo n.º 24
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
}
Ejemplo n.º 25
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
}
Ejemplo n.º 26
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
}
Ejemplo n.º 27
0
func prepTemplate(parent *template.Template, fn, base string) error {
	t := parent.New(base)

	f, err := os.Open(fn)
	if err != nil {
		return err
	}
	defer f.Close()

	msg, err := mail.ReadMessage(f)
	if err != nil {
		return err
	}

	for k, v := range defaultHeaders {
		if msg.Header.Get(k) == "" {
			msg.Header[k] = v
		}
	}

	data := &bytes.Buffer{}

	// This is the only place I could find this method.  :/
	http.Header(msg.Header).Write(data)
	data.Write([]byte{'\r', '\n'})

	_, err = io.Copy(data, msg.Body)
	if err != nil {
		return err
	}

	_, err = t.Parse(data.String())
	return err
}
Ejemplo n.º 28
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
}
Ejemplo n.º 29
0
func makeTemplates(t *[]TemplateConfig) (*template.Template, error) {
	var textTemplates *template.Template
	var err error
	templateFuncs := template.FuncMap{"padBefore": PadBefore}
	for i, templateConfig := range *t {
		t := ""
		h := ""
		for i, l := range templateConfig.Lines {
			if i > 0 {
				t = t + "\t"
				h = h + "\t"
			}
			t = t + l.Value
			h = h + l.Header
		}

		// Template proper
		if i == 0 {
			textTemplates, err = template.New(templateConfig.Name).Funcs(templateFuncs).Parse(t)
		} else {
			textTemplates, err = textTemplates.New(templateConfig.Name).Funcs(templateFuncs).Parse(t)
		}

		// Template header
		textTemplates, err = textTemplates.New(templateConfig.Name + "_H").Funcs(templateFuncs).Parse(h)

		if err != nil {
			break
		}
	}
	return textTemplates, err
}
Ejemplo n.º 30
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
}