Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
72 lines (62 sloc) 1.77 KB
// Copyright 2014 Brett Slatkin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"io"
"path/filepath"
"strings"
"text/template"
)
var (
generatedTemplate = template.Must(template.New("render").Parse(`// generated by joiner -- DO NOT EDIT
package {{.Package}}
import (
"fmt"
"strings"
)
{{range .Types}}{{if not .IsStringer}}
func (t {{.Name}}) String() string {
return fmt.Sprintf("%#v", t)
}
{{end}}
type Join{{.Name}} []{{.Name}}
func (j Join{{.Name}}) With(sep string) string {
all := make([]string, 0, len(j))
for _, s := range j {
all = append(all, s.String())
}
return strings.Join(all, sep)
}
{{end}}`))
)
type GeneratedType struct {
Name string
IsStringer bool
}
func getRenderedPath(inputPath string) (string, error) {
if !strings.HasSuffix(inputPath, ".go") {
return "", fmt.Errorf("Input path %s doesn't have .go extension", inputPath)
}
trimmed := strings.TrimSuffix(inputPath, ".go")
dir, file := filepath.Split(trimmed)
return filepath.Join(dir, fmt.Sprintf("%s_joiner.go", file)), nil
}
type generateTemplateData struct {
Package string
Types []GeneratedType
}
func render(w io.Writer, packageName string, types []GeneratedType) error {
return generatedTemplate.Execute(w, generateTemplateData{packageName, types})
}