コード例 #1
0
ファイル: publicizer.go プロジェクト: konstantin-dzreev/goa
func init() {
	var err error
	fm := template.FuncMap{
		"tabs":                Tabs,
		"goify":               Goify,
		"gotyperef":           GoTypeRef,
		"gotypedef":           GoTypeDef,
		"add":                 Add,
		"publicizer":          Publicizer,
		"recursivePublicizer": RecursivePublicizer,
	}
	if simplePublicizeT, err = template.New("simplePublicize").Funcs(fm).Parse(simplePublicizeTmpl); err != nil {
		panic(err)
	}
	if recursivePublicizeT, err = template.New("recursivePublicize").Funcs(fm).Parse(recursivePublicizeTmpl); err != nil {
		panic(err)
	}
	if objectPublicizeT, err = template.New("objectPublicize").Funcs(fm).Parse(objectPublicizeTmpl); err != nil {
		panic(err)
	}
	if arrayPublicizeT, err = template.New("arrPublicize").Funcs(fm).Parse(arrayPublicizeTmpl); err != nil {
		panic(err)
	}
	if hashPublicizeT, err = template.New("hashPublicize").Funcs(fm).Parse(hashPublicizeTmpl); err != nil {
		panic(err)
	}
}
コード例 #2
0
ファイル: smoke_test.go プロジェクト: huslage/deis
// Runs a test case and logs the results.
func runTest(t *testing.T, tt *deisTest, cfg *deisTestConfig) {
	// Fill in the command string template from our test configuration.
	var cmdBuf bytes.Buffer
	tmpl := template.Must(template.New("cmd").Parse(tt.cmd))
	if err := tmpl.Execute(&cmdBuf, cfg); err != nil {
		t.Fatal(err)
	}
	cmdString := cmdBuf.String()
	// Change to the target directory if needed.
	if tt.dir != "" {
		// Fill in the directory template from our test configuration.
		var dirBuf bytes.Buffer
		tmpl := template.Must(template.New("dir").Parse(tt.dir))
		if err := tmpl.Execute(&dirBuf, cfg); err != nil {
			t.Fatal(err)
		}
		dir, _ := filepath.Abs(filepath.Join(wd, dirBuf.String()))
		if err := os.Chdir(dir); err != nil {
			t.Fatal(err)
		}
	}
	// TODO: Go's testing package doesn't seem to allow for reporting interim
	// progress--we have to wait until everything completes (or fails) to see
	// anything that was written with t.Log or t.Fatal. Interim output would
	// be extremely helpful here, as this takes a while.
	// Execute the command and log the input and output on error.
	fmt.Printf("%v ... ", strings.TrimSpace(cmdString))
	cmd := exec.Command("sh", "-c", cmdString)
	if out, err := cmd.Output(); err != nil {
		t.Fatalf("%v\nOutput:\n%v", err, string(out))
	} else {
		fmt.Println("ok")
	}
}
コード例 #3
0
func render(templName string, templ1Data interface{}, pipelineName string) (io.Reader, error) {
	templateSrc, err := Asset(templName)
	if err != nil {
		return nil, err
	}

	// 1st pass
	templ, err := template.New(templName + "/1").Parse(string(templateSrc))
	if err != nil {
		return nil, err
	}

	var firstRender bytes.Buffer
	err = templ.Execute(&firstRender, templ1Data)
	if err != nil {
		return nil, err
	}

	// 2nd pass: some properties contain {{ .PipelineName }}
	templ, err = template.New(templName + "/2").Parse(firstRender.String())
	if err != nil {
		return nil, fmt.Errorf("error rendering template: %s\n\ntemplate content: %s", err, firstRender.String())
	}

	var secondRender bytes.Buffer
	err = templ.Execute(&secondRender, struct{ PipelineName string }{pipelineName})

	return &secondRender, err

}
コード例 #4
0
ファイル: writers.go プロジェクト: yonglehou/goa
// NewControllersWriter returns a handlers code writer.
// Handlers provide the glue between the underlying request data and the user controller.
func NewControllersWriter(filename string) (*ControllersWriter, error) {
	cw := codegen.NewGoGenerator(filename)
	funcMap := cw.FuncMap
	funcMap["add"] = func(a, b int) int { return a + b }
	funcMap["gotypename"] = codegen.GoTypeName
	ctrlTmpl, err := template.New("controller").Funcs(funcMap).Parse(ctrlT)
	if err != nil {
		return nil, err
	}
	mountTmpl, err := template.New("mount").Funcs(funcMap).Parse(mountT)
	if err != nil {
		return nil, err
	}
	unmarshalTmpl, err := template.New("unmarshal").Funcs(funcMap).Parse(unmarshalT)
	if err != nil {
		return nil, err
	}
	w := ControllersWriter{
		GoGenerator:   cw,
		CtrlTmpl:      ctrlTmpl,
		MountTmpl:     mountTmpl,
		UnmarshalTmpl: unmarshalTmpl,
	}
	return &w, nil
}
コード例 #5
0
ファイル: main.go プロジェクト: client9/gospell
func init() {
	// we see it so it doesn't use a prefix or include a time stamp.
	stdout = log.New(os.Stdout, "", 0)
	defaultLog = template.Must(template.New("defaultLog").Parse(defaultLogTmpl))
	defaultWord = template.Must(template.New("defaultWord").Parse(defaultWordTmpl))
	defaultLine = template.Must(template.New("defaultLine").Parse(defaultLineTmpl))
}
コード例 #6
0
ファイル: downloads-page.go プロジェクト: yl10/goxc
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
}
コード例 #7
0
ファイル: help.go プロジェクト: kinvolk/appc-spec
func init() {
	globalUsageTemplate = template.Must(template.New("global_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Executable .Description}}

USAGE:
{{printf "\t%s" .Executable}} [global options] <command> [command options] [arguments...]

VERSION:
{{printf "\t%s" .Version}}

COMMANDS:{{range .Commands}}
{{printf "\t%s\t%s" .Name .Summary}}{{end}}

GLOBAL OPTIONS:{{range .Flags}}
{{printOption .Name .DefValue .Usage}}{{end}}

Run "{{.Executable}} help <command>" for more details on a specific command.
`[1:]))
	commandUsageTemplate = template.Must(template.New("command_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Cmd.Name .Cmd.Summary}}

USAGE:
{{printf "\t%s %s %s" .Executable .Cmd.Name .Cmd.Usage}}

DESCRIPTION:
{{range $line := descToLines .Cmd.Description}}{{printf "\t%s" $line}}
{{end}}
{{if .CmdFlags}}OPTIONS:{{range .CmdFlags}}
{{printOption .Name .DefValue .Usage}}{{end}}

{{end}}For help on global options run "{{.Executable}} help"
`[1:]))
}
コード例 #8
0
ファイル: mgoExample.go プロジェクト: dbmlabs/hellothere
func admin(w http.ResponseWriter, r *http.Request) {
	/* import template
	t, _ := template.ParseFiles("../template/shotchart.html")
	t.Execute(wr io.Writer, p)
	*/

	temp := new(Page)

	values := readDB()
	buf := new(bytes.Buffer)
	for _, value := range values {
		if value.Content == "" {
			continue
		}
		fmt.Println("this is reading from the database the different lines", value)
		t := template.Must(template.New("form").Parse(form))
		t.Execute(buf, value)
	}
	fmt.Println("this is the string of template", buf.String())
	temp.Form = buf.String()
	t := template.Must(template.New("page").Parse(adminPage))
	t.Execute(w, temp)

	//t := template.Must(template.New("form").Parse(form))
	//t.Execute(w, Tom)
	//fmt.Println("this is admin page")
}
コード例 #9
0
ファイル: templates.go プロジェクト: elliott-stroud/modelq
func init() {
	tmHeader = template.Must(template.New("header").Parse(header))
	tmStruct = template.Must(template.New("modelStruct").Parse(modelStruct))
	tmObjApi = template.Must(template.New("objApi").Parse(objApi))
	tmQueryApi = template.Must(template.New("queryApi").Parse(queryApi))
	tmManagedObjApi = template.Must(template.New("managedApi").Parse(managedApi))
}
コード例 #10
0
ファイル: tmpl_test.go プロジェクト: hiromaily/golibs
//-----------------------------------------------------------------------------
// Check
//-----------------------------------------------------------------------------
func TestTextTemplate(t *testing.T) {
	//t.Skip("skipping TestTextTemplate")

	teachers := getTeathers()

	//normal
	for i, td := range tmpleTests {
		fmt.Printf("[%d] name:%s\n", i+1, td.tmplName)

		tmpl, err := tt.New(td.tmplName).Parse(td.tmplString)
		if err != nil {
			t.Fatalf("[%d] template.New(%s) error: %s", i+1, td.tmplName, err)
		}
		err = tmpl.Execute(os.Stdout, teachers)
		if err != nil {
			t.Fatalf("[%d] template.Execute(%s) error: %s", i+1, td.tmplName, err)
		}
	}

	//with func
	for i, td := range tmpleTests2 {
		tmpl, err := tt.New("td.tmplName").Funcs(tt.FuncMap{"plus10": plus10}).Parse(td.tmplString)
		if err != nil {
			t.Fatalf("[%d] template.New(%s) error: %s", i+1, td.tmplName, err)
		}
		err = tmpl.Execute(os.Stdout, teachers)
		if err != nil {
			t.Fatalf("[%d] template.Execute(%s) error: %s", i+1, td.tmplName, err)
		}
	}
}
コード例 #11
0
func (n *NatsClient) PrepareJob(jobName string) {
	templateID, sha1, err := n.uploadJob(jobName)
	Expect(err).NotTo(HaveOccurred())

	prepareTemplateConfig := PrepareTemplateConfig{
		JobName:                             jobName,
		TemplateBlobstoreID:                 templateID,
		RenderedTemplatesArchiveBlobstoreID: templateID,
		RenderedTemplatesArchiveSHA1:        sha1,
		ReplyTo: senderID,
	}

	buffer := bytes.NewBuffer([]byte{})
	t := template.Must(template.New("prepare").Parse(prepareTemplate))
	err = t.Execute(buffer, prepareTemplateConfig)
	Expect(err).NotTo(HaveOccurred())
	prepareResponse, err := n.SendMessage(buffer.String())
	Expect(err).NotTo(HaveOccurred())

	_, err = n.WaitForTask(prepareResponse["value"]["agent_task_id"], -1)
	Expect(err).ToNot(HaveOccurred())

	buffer.Reset()
	t = template.Must(template.New("apply").Parse(applyTemplate))
	err = t.Execute(buffer, prepareTemplateConfig)
	Expect(err).NotTo(HaveOccurred())
	applyResponse, err := n.SendMessage(buffer.String())
	Expect(err).NotTo(HaveOccurred())

	_, err = n.WaitForTask(applyResponse["value"]["agent_task_id"], -1)
	Expect(err).ToNot(HaveOccurred())
}
コード例 #12
0
// NewHipchatHandler creates a new by reading the environment
func NewHipchatHandler() *HipchatHandler {
	alertTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_TEMPLATE")
	if alertTemplate == "" {
		alertTemplate = `Severity {{.Severity}} alert triggered by {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
	}

	recoveryTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_TEMPLATE")
	if recoveryTemplate == "" {
		recoveryTemplate = `Recovery of {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
	}

	hh := &HipchatHandler{
		HipchatClient:    &hipchat.Client{AuthToken: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_API_TOKEN")},
		AlertTemplate:    template.Must(template.New("alert").Parse(alertTemplate)),
		RecoveryTemplate: template.Must(template.New("recovery").Parse(recoveryTemplate)),
		AlertColor:       os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_COLOR"),
		RecoveryColor:    os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_COLOR"),
		From:             os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_FROM"),
	}

	if hh.AlertColor == "" {
		hh.AlertColor = hipchat.ColorRed
	}

	if hh.RecoveryColor == "" {
		hh.RecoveryColor = hipchat.ColorGreen
	}

	if hh.From == "" {
		hh.From = "Circonus"
	}

	return hh
}
コード例 #13
0
ファイル: template.go プロジェクト: vichetuc/boxed
func loadTemplates() {
	templateBox := rice.MustFindBox("templates")
	layout, err := templateBox.String("layout.html")
	if err != nil {
		log.Fatal(err)
	}

	t := []string{
		"index",
		"article",
		"archive",
	}

	for _, tplName := range t {
		tplContent, err := templateBox.String(tplName + ".html")
		if err != nil {
			log.Fatal(err)
		}
		templates[tplName] = template.Must(template.New("layout").Parse(layout + tplContent))
	}

	feed, err := templateBox.String("feed.atom")
	if err != nil {
		log.Fatal(err)
	}

	templates["feed.atom"] = template.Must(template.New("feed.atom").Parse(feed))

	sitemap, err := templateBox.String("sitemap.xml")
	if err != nil {
		log.Fatal(err)
	}

	templates["sitemap.xml"] = template.Must(template.New("sitemap.xml").Parse(sitemap))
}
コード例 #14
0
ファイル: tvrenamer.go プロジェクト: swietrc/go-tvrenamer
// New allocates a new TvRenamer with the given language, formatting, path and regexp
func New(language string, nameFormatting string, newPath string, regex string, move bool) *TvRenamer {

	var err error

	tvr := TvRenamer{
		Language: language,
		Move:     move,
	}

	tvr.NameFormatting, err = template.New("Filename formatting").Parse(nameFormatting)
	if err != nil {
		log.Fatal(err)
	}

	tvr.NewPath, err = template.New("Path formatting").Parse(newPath)
	if err != nil {
		log.Fatal(err)
	}

	tvr.Regex, err = regexp.Compile(regex)
	if err != nil {
		log.Fatal(err)
	}

	return &tvr
}
コード例 #15
0
ファイル: main.go プロジェクト: bboalimoe/pachyderm
func printRegistryService(name string, port int) error {
	sTemplate, err := template.New("registry").Parse(registryTemplateString)
	if err != nil {
		return err
	}

	aTemplate, err := template.New("announce").Parse(announceTemplateString)
	if err != nil {
		return err
	}

	config := new(service)
	config.Name = name
	config.Port = port

	server, err := os.Create(fmt.Sprintf("%s/%s.service", outPath, config.Name))
	if err != nil {
		return err
	}

	announce, err := os.Create(fmt.Sprintf("%s/announce-%s.service", outPath, config.Name))
	if err != nil {
		return err
	}

	err = sTemplate.Execute(server, config)
	if err != nil {
		return err
	}

	return aTemplate.Execute(announce, config)
}
コード例 #16
0
ファイル: generator.go プロジェクト: drborges/appx-cli
func GenerateApi(model *ModelDescriptor) error {
	t := template.Must(template.New("model").Parse(templates.AppxModel))
	output := model.Pkg + "/appx_model_" + model.Name + ".go"
	f, err := os.Create(output)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := t.Execute(f, model); err != nil {
		return err
	}

	t = template.Must(template.New("repo").Funcs(templates.FuncMap).Parse(templates.AppxRepository))
	output = model.Pkg + "/appx_model_" + model.Name + "_repository.go"
	f, err = os.Create(output)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := t.Execute(f, model); err != nil {
		return err
	}

	log.Println("[API] generated for model", model.Name)
	return nil
}
コード例 #17
0
ファイル: tmplWithEnd.go プロジェクト: EmperorEarth/learnGo
func main() {
	t, _ := template.New("test").Parse("{{with `hello`}}{{.}}{{end}}!\n")
	t.Execute(os.Stdout, nil)

	t1, _ := template.New("test").Parse("{{with `hello`}}{{.}} {{with `Mary`}}{{.}}{{end}}{{end}}!\n") //when nested, the dot takes the value according to closest scope
	t1.Execute(os.Stdout, nil)
}
コード例 #18
0
func (g *renderer) Render(input bftinput.Input, manifestPath string, cloudConfigPath string) error {
	deploymentTemplate := template.Must(template.New("deployment").Parse(DeploymentTemplate))

	buffer := bytes.NewBuffer([]byte{})
	err := deploymentTemplate.Execute(buffer, input)
	if err != nil {
		return bosherr.WrapErrorf(err, "Generating deployment manifest")
	}

	err = g.fs.WriteFile(manifestPath, buffer.Bytes())
	if err != nil {
		return bosherr.WrapErrorf(err, "Saving generated manifest")
	}

	cloudTemplate := template.Must(template.New("cloud-config").Parse(CloudTemplate))

	buffer = bytes.NewBuffer([]byte{})

	err = cloudTemplate.Execute(buffer, input)
	if err != nil {
		return bosherr.WrapErrorf(err, "Generating cloud config")
	}

	err = g.fs.WriteFile(cloudConfigPath, buffer.Bytes())
	if err != nil {
		return bosherr.WrapErrorf(err, "Saving generated cloud config")
	}

	return nil
}
コード例 #19
0
func (net centosNetManager) writeNetworkInterfaces(dhcpInterfaceConfigurations []DHCPInterfaceConfiguration, staticInterfaceConfigurations []StaticInterfaceConfiguration, dnsServers []string) (bool, error) {
	anyInterfaceChanged := false

	staticConfig := centosStaticIfcfg{}
	staticConfig.DNSServers = newDNSConfigs(dnsServers)
	staticTemplate := template.Must(template.New("ifcfg").Parse(centosStaticIfcfgTemplate))

	for i := range staticInterfaceConfigurations {
		staticConfig.StaticInterfaceConfiguration = &staticInterfaceConfigurations[i]

		changed, err := net.writeIfcfgFile(staticConfig.StaticInterfaceConfiguration.Name, staticTemplate, staticConfig)
		if err != nil {
			return false, bosherr.WrapError(err, "Writing static config")
		}

		anyInterfaceChanged = anyInterfaceChanged || changed
	}

	dhcpTemplate := template.Must(template.New("ifcfg").Parse(centosDHCPIfcfgTemplate))

	for i := range dhcpInterfaceConfigurations {
		config := &dhcpInterfaceConfigurations[i]

		changed, err := net.writeIfcfgFile(config.Name, dhcpTemplate, config)
		if err != nil {
			return false, bosherr.WrapError(err, "Writing dhcp config")
		}

		anyInterfaceChanged = anyInterfaceChanged || changed
	}

	return anyInterfaceChanged, nil
}
コード例 #20
0
ファイル: main.go プロジェクト: nolenroyalty/bangarang
func main() {
	if len(os.Args) > 1 {
		if os.Args[1] == "test" {
			top := template.Must(template.New("top").Parse(NewTestTopTemplate()))
			out(top, nil)
			types := NewTypes()
			t := template.Must(template.New("types").Parse(NewTestTypeTemplate()))
			for _, typ := range types {
				out(t, typ)
			}
			return
		}
	}
	top := template.Must(template.New("top").Parse(NewTopTemplate()))
	out(top, nil)
	types := NewTypes()
	t := template.Must(template.New("types").Parse(NewTypeTemplate()))
	for _, typ := range types {
		if typ.packed {
			out(t, typ)
		}
		typ.packed = false
		out(t, typ)
	}
}
コード例 #21
0
ファイル: operation.go プロジェクト: berngp/go-swagger
func init() {
	bv, _ := Asset("templates/server/parameter.gotmpl")
	parameterTemplate = template.Must(template.New("parameter").Parse(string(bv)))

	bm, _ := Asset("templates/server/operation.gotmpl")
	operationTemplate = template.Must(template.New("operation").Parse(string(bm)))
}
コード例 #22
0
ファイル: html_main.go プロジェクト: dongwq/go-demo
func main() {

	type Inventory struct {
		Material string
		Count    uint
	}

	sweaters := Inventory{"wool", 17}
	tmpl, err := template.New("test").Parse("1.{{.Count}} items are made of {{.Material}}\n")
	if err != nil {
		panic(err)
	}
	err = tmpl.Execute(os.Stdout, sweaters)
	if err != nil {
		panic(err)
	}

	t, err := template.New("foo").Parse(`2. {{define "T"}}Hello, {{.}}!{{end}}\n`)
	if err != nil {
		log.Fatalf("parse err", err)
		return
	}
	out := os.Stdout
	err = t.ExecuteTemplate(out, "T", "3. <script>alert('you have been pwned')</script>\n")
	if err != nil {
		log.Fatalf("parse err", err)
		return
	}

}
コード例 #23
0
ファイル: smoke_test.go プロジェクト: bdemers/deis
// Runs a test case and logs the results.
func runTest(t *testing.T, tt *deisTest, cfg *utils.DeisTestConfig) {
	// Fill in the command string template from our test configuration.
	var cmdBuf bytes.Buffer
	tmpl := template.Must(template.New("cmd").Parse(tt.cmd))
	if err := tmpl.Execute(&cmdBuf, cfg); err != nil {
		t.Fatal(err)
	}
	cmdString := cmdBuf.String()
	// Change to the target directory if needed.
	if tt.dir != "" {
		// Fill in the directory template from our test configuration.
		var dirBuf bytes.Buffer
		tmpl := template.Must(template.New("dir").Parse(tt.dir))
		if err := tmpl.Execute(&dirBuf, cfg); err != nil {
			t.Fatal(err)
		}
		dir, _ := filepath.Abs(filepath.Join(wd, dirBuf.String()))
		if err := os.Chdir(dir); err != nil {
			t.Fatal(err)
		}
	}
	// Execute the command and log the input and output on error.
	fmt.Printf("%v ... ", strings.TrimSpace(cmdString))
	cmd := exec.Command("sh", "-c", cmdString)
	if out, err := cmd.Output(); err != nil {
		t.Fatalf("%v\nOutput:\n%v", err, string(out))
	} else {
		fmt.Println("ok")
	}
}
コード例 #24
0
ファイル: importer.go プロジェクト: pzduniak/importer
func Render(w http.ResponseWriter, settings *RenderSettings) {
	root_tpl := tt.Must(tt.New("rtt").Parse(settings.RootTemplate))
	repo_tpl := tt.Must(tt.New("rpt").Parse(settings.RepositoryTemplate))

	root_buf := new(bytes.Buffer)
	err := root_tpl.Execute(root_buf, settings.Path)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	repo_buf := new(bytes.Buffer)
	err = repo_tpl.Execute(repo_buf, settings.Path)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = PageTemplate.Execute(w, templateInput{
		Root: root_buf.String(),
		Repo: repo_buf.String(),
	})

	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
}
コード例 #25
0
ファイル: main.go プロジェクト: balrajb/goberry
// Generate handler functions based on an API definition.
func generate(api *raml.APIDefinition, genFile string) {

	f, err := os.Create(genFile)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	// Write the header - import statements and root handler.
	f.WriteString(handlerHead)
	// Start the route map (string to handler).
	f.WriteString(mapStart)
	// Add the route map entries.
	e := template.Must(template.New("mapEntry").Parse(mapEntry))
	for name, resource := range api.Resources {
		generateMap("", name, &resource, e, f)
	}
	// Close the route map.
	f.WriteString(mapEnd)
	// Now add the HTTP handlers.
	t := template.Must(template.New("handlerText").Parse(handlerText))
	for name, resource := range api.Resources {
		generateResource("", name, &resource, t, f)
	}
	format(f)
}
コード例 #26
0
ファイル: bundle.go プロジェクト: kod3r/plumber
// Bundle stuff...
// BUG(echu): need to figure out how to handle conflicts in bundle names
func (ctx *Context) Bundle(bundlePath string) error {
	log.Printf("==> Creating bundle from '%s'", bundlePath)
	defer log.Printf("<== Bundling complete.")

	log.Printf(" |  Parsing bundle config.")
	bundleConfig, err := ParseBundleFromDir(bundlePath)
	if err != nil {
		return err
	}
	log.Printf("    %v", bundleConfig)

	log.Printf(" |  Making temp file for python wrapper")
	wrapper, err := ioutil.TempFile(bundlePath, "plumber")
	defer removeTempFile(wrapper)
	if err != nil {
		return err
	}
	log.Printf("    Created '%s'", wrapper.Name())

	templateCtx := templateContext{
		Wrapper: path.Base(wrapper.Name()),
		Plumber: bundleConfig,
	}

	log.Printf(" |  Writing wrapper.")
	tmpl, err := template.New("wrapper").Parse(wrapperTemplate)
	if err != nil {
		return err
	}
	if err := tmpl.Execute(wrapper, templateCtx); err != nil {
		return err
	}
	log.Printf("    Done.")

	log.Printf(" |  Making temp file for Dockerfile")
	dockerfile, err := ioutil.TempFile(bundlePath, "plumber")
	defer removeTempFile(dockerfile)
	if err != nil {
		return err
	}
	log.Printf("    Created '%s'", dockerfile.Name())

	log.Printf(" |  Writing Dockerfile.")
	tmpl, err = template.New("dockerfile").Parse(dockerfileTemplate)
	if err != nil {
		return err
	}
	if err := tmpl.Execute(dockerfile, templateCtx); err != nil {
		return err
	}
	log.Printf("    Done.")

	log.Printf(" |  Building container.")
	err = shell.RunAndLog(ctx.DockerCmd, "build", "--pull", "-t", ctx.GetImage(bundleConfig.Name), "-f", dockerfile.Name(), bundlePath)
	if err != nil {
		return err
	}
	log.Printf("    Container '%s' built.", ctx.GetImage(bundleConfig.Name))
	return nil
}
コード例 #27
0
ファイル: types.go プロジェクト: RouGang/goa
// Initialize all templates
func init() {
	var err error
	fn := template.FuncMap{
		"tabs":               Tabs,
		"add":                func(a, b int) int { return a + b },
		"goify":              Goify,
		"gotyperef":          GoTypeRef,
		"gotypename":         GoTypeName,
		"transformAttribute": transformAttribute,
		"transformArray":     transformArray,
		"transformHash":      transformHash,
		"transformObject":    transformObject,
		"typeName":           typeName,
	}
	if transformT, err = template.New("transform").Funcs(fn).Parse(transformTmpl); err != nil {
		panic(err) // bug
	}
	if transformArrayT, err = template.New("transformArray").Funcs(fn).Parse(transformArrayTmpl); err != nil {
		panic(err) // bug
	}
	if transformHashT, err = template.New("transformHash").Funcs(fn).Parse(transformHashTmpl); err != nil {
		panic(err) // bug
	}
	if transformObjectT, err = template.New("transformObject").Funcs(fn).Parse(transformObjectTmpl); err != nil {
		panic(err) // bug
	}
}
コード例 #28
0
ファイル: client.go プロジェクト: gitter-badger/gohan
//Output sub command helps
func (gohanClientCLI *GohanClientCLI) outputSubCommands(command string) (string, error) {
	schemas, err := gohanClientCLI.getSchemas()
	command = strings.TrimSpace(command)
	buf := new(bytes.Buffer)
	if err != nil {
		return "", err
	}
	//Output schema specific help
	for _, schema := range schemas {
		if command == schema.ID {
			tmpl, _ := template.New("schema").Parse(schemaTemplate)
			tmpl.Execute(buf, schema)
			return buf.String(), nil
		}
	}

	tmpl, _ := template.New("schema").Parse(schemaListTemplate)
	if command != "" {
		buf.WriteString("Command not found")
		return buf.String(), nil
	}
	for _, schema := range schemas {
		tmpl.Execute(buf, schema)
	}
	return buf.String(), nil
}
コード例 #29
0
ファイル: generator.go プロジェクト: gophergala2016/gogen
// Generate will call the generator to generate
// results
func (g *generator) Generate() error {
	err := g.Prepare()
	if err != nil {
		return err
	}

	// compile package template
	packTmpl, err := template.New("package").Parse(packageTemplate)
	if err != nil {
		return err
	}

	// compile model template
	tmpl, err := template.New("model").Parse(modelTemplate)
	if err != nil {
		return err
	}

	for _, resource := range *g.Resources {
		if model, ok := resource.(*Model); ok {
			genlog.Info("Generating model for %s", model.Name)
			content := bytes.Buffer{}
			packTmpl.Execute(&content, g)
			tmpl.Execute(&content, model)
			g.SaveFile(model.Name, content)

			// set other meta to model
			model.Package = g.PackageName()
		}
	}

	return nil
}
コード例 #30
0
ファイル: template.go プロジェクト: bubble-bot/weavebox
// Init parses all the given singel and layout templates. And stores them in the
// template cache.
func (t *TemplateEngine) Init() {
	for layout, templates := range t.templWithLayout {
		layout, err := ioutil.ReadFile(path.Join(t.root, layout))
		handleErr(err)

		for _, page := range templates {
			parsedLayout, err := template.New("_").Parse(string(layout))
			handleErr(err)

			templ, err := ioutil.ReadFile(path.Join(t.root, page))
			handleErr(err)

			parsedTempl, err := parsedLayout.Parse(string(templ))
			handleErr(err)

			t.cache[page] = parsedTempl
		}
	}

	for _, file := range t.templates {
		templ, err := ioutil.ReadFile(path.Join(t.root, file))
		handleErr(err)

		parsedTempl, err := template.New("_").Parse(string(templ))
		handleErr(err)

		t.cache[file] = parsedTempl
	}
}