generator

package
v0.0.0-...-0d5c51c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2019 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package generator deals with creating projects from template files.

A generator is a directory containing a definition file, template files, and partials.

In addition to metadata, the definition file, which must be a JSON document named `generator.json` at the root of the generator, can define variables and user inputs that will be made available to the templates and partials. An input is read from the user only when its value is needed for the first time.

The templates are files that should be placed in a `files` directory, and use the Go template syntax to produce project files. Every template will result in a file of the same name being created in the generated project directory. The path of the generated file within the generated project wil be the path of the template relative to the `files` directory.

Templates can include partials via the `partial` function. The partials should be placed in a `partials` directory. As opposed to templates, partials will not result in files being generated. The `partial` function expects the path of a partial relative to the `partials` directory, and optionally a variadic list of variable maps for the partial. The partials have access to the same functions and variables as the templates.

By default templates are evaluated in alphabetical order. You can have more control over the order by adding a `priorities` array to the definition file. This array should contain a list of files relative to the `files` directory that will be evaluated first. That way it is possible to control the order which inputs will be read from the user.

A basic definition file may look something like this:

{
  "name": "basic",
  "version": "x.x.x",
  "description": "A basic generator",
  "author": "Stratumn",
  "license": "MIT",
  "inputs": {
    "name": {
      "type": "string",
      "prompt": "Project name:",
      "default": "{{.dir}}",
      "format": ".+"
    }
  }
}

In this case, one input called `name` of type `string` is defined. Its default value is `{{.dir}}`, which should be a variable given to the definition file parser.

A template file in the `template` directory can access the user input for `name` using the template function `input`. For instance it could be a Markdown file containing the following:

# {{input "name"}}
A basic project

A project can be generated from the generator this way:

// Directory where the project will be generated.
dst := "path/to/generated/project"

// Add a `dir` variable for the definition file set to the name
// of the project directory.
opts := generator.Options{
        DefVars: map[string]interface{}{
                "dir": filepath.Dir(dst),
        },
}

// Load the generator.
gen, err := generator.NewFromDir("path/to/generator", &opts)
if err != nil {
        panic(err)
}

// Generate the project.
if err := gen.Exec(dst); err != nil {
        panic(err)
}

Index

Constants

View Source
const (
	// DefinitionFile is the file containing the generator definition within
	// a generator.
	DefinitionFile = "generator.json"

	// PartialsDir is the directory containing partials within a generator.
	PartialsDir = "partials"

	// FilesDir is the directory containing files within a generator.
	FilesDir = "files"

	// DirPerm is the files permissions for the generated directory.
	DirPerm = 0700
)
View Source
const (
	// IntInputID is the string identifying an int input.
	IntInputID = "int"

	// StringInputID is the string identifying a string input.
	StringInputID = "string"

	// StringSelectID is the string identifying a string select.
	StringSelectID = "select:string"

	// StringSelectMultiID is the string identifying a string select with multiple choices.
	StringSelectMultiID = "selectmulti:string"

	// StringSliceID is a slice of string for mutiple entries.
	StringSliceID = "slice:string"
)

Variables

This section is empty.

Functions

func StdDefinitionFuncs

func StdDefinitionFuncs() template.FuncMap

StdDefinitionFuncs returns the standard function map used when parsing a generator definition. It adds the following functions:

  • getenv(name string) string: returns the value of an environment variable
  • now(format string) string: returns a formatted representation of the current date
  • nowUTC(format string) string: returns a formatted representation of the current UTC date
  • secret(length int) (string, error): returns a random secret string

Types

type Definition

type Definition struct {
	// Name is the name of the generator.
	// It should be short, lowercase, and contain only letters, numbers, and
	// dashes.
	Name string `json:"name"`

	// Version is the version string of the generator.
	Version string `json:"version"`

	// Description is a short description of the generator.
	Description string `json:"description"`

	// Author is the name of the author of the generator.
	Author string `json:"author"`

	// License is the license of the generator (not of the generated code).
	// If the generated project has a license, it should be defined within
	// the templates.
	License string `json:"license"`

	// Variables is a map of variables for the templates and partials.
	Variables map[string]interface{} `json:"variables"`

	// Inputs is a map of user inputs.
	Inputs InputMap `json:"inputs"`

	// Priorities is an array of files which should be parsed first.
	// The paths are relative to the `files` directory.
	Priorities []string `json:"priorities"`

	// FilenameSubsts is a map to replace a string in a filename by an input content.
	FilenameSubsts map[string]string `json:"filename-substitutions"`
}

Definition contains properties for a template generator definition.

func NewDefinitionFromFile

func NewDefinitionFromFile(path string, vars map[string]interface{}, funcs template.FuncMap) (*Definition, error)

NewDefinitionFromFile loads a generator definition from a file. The file is treated as a template and is fed the given variables and functions. Extra variables and functions given will be added to the template context.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator deals with parsing templates, handling user input, and outputting processed templates.

func NewFromDir

func NewFromDir(src string, opts *Options) (*Generator, error)

NewFromDir create a new generator from a directory.

func (*Generator) Exec

func (gen *Generator) Exec(dst string) error

Exec parses templates, handles user input, and outputs processed templates to given dir.

func (*Generator) StdTmplFuncs

func (gen *Generator) StdTmplFuncs() template.FuncMap

StdTmplFuncs returns the standard function map used when parsing a template. It adds the following functions:

  • ask(json string) (interface{}, error): creates an input on-the-fly and returns its value
  • getenv(name string) string: returns the value of an environment variable
  • gid() int: returns the system group id (GID)
  • input(id string) (interface{}, error): returns the value of an input
  • now(format string) string: returns a formatted representation of the current date
  • nowUTC(format string) string: returns a formatted representation of the current UTC date
  • partial(path, vars ...interface{}) (string, error): executes the partial with given name and variables (path relative to `partials` directory)
  • secret(length int) (string, error): returns a random secret string
  • uid() int: returns the system user id (UID)
  • add(i, j int) int: returns i + j
  • loop(start, end int) []int: implements a basic for start <= i < end loop

type GenericSelect

type GenericSelect struct {
	InputShared

	// Options is a map of possible values.
	Options GenericSelectOptions `json:"options"`
}

GenericSelect contains properties for generic select input.

func (*GenericSelect) Run

func (in *GenericSelect) Run() (interface{}, error)

Run implements generator.Input.

type GenericSelectOptions

type GenericSelectOptions map[interface{}]string

GenericSelectOptions is a map of options that can have any type

func (GenericSelectOptions) FindText

func (options GenericSelectOptions) FindText(value string) string

FindText have to be replaced when []StringSelectOption will be a map[string]string

func (GenericSelectOptions) FindValue

func (options GenericSelectOptions) FindValue(text string) interface{}

FindValue have to be replaced when []StringSelectOption will be a map[string]string

type Input

type Input interface {
	Run() (interface{}, error)
}

Input must be implemented by all input types.

func UnmarshalJSONInput

func UnmarshalJSONInput(data []byte) (Input, error)

UnmarshalJSONInput creates an input from JSON.

type InputMap

type InputMap map[string]Input

InputMap is a maps input names to inputs.

func (*InputMap) UnmarshalJSON

func (im *InputMap) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type InputShared

type InputShared struct {
	// Type is the type of the input.
	Type string `json:"type"`

	// Prompt is the string that will be displayed to the user when asking
	// the value.
	Prompt string `json:"prompt"`
}

InputShared contains properties shared by all input types.

type IntInput

type IntInput struct {
	InputShared

	Default int `json:"default"`
}

IntInput contains properties for int inputs.

func (*IntInput) Run

func (in *IntInput) Run() (interface{}, error)

Run implements generator.Input.

type Options

type Options struct {
	// Variables for the definition file.
	DefVars map[string]interface{}

	// Functions for the definition file.
	DefFuncs template.FuncMap

	// Variables for the templates.
	TmplVars map[string]interface{}

	// Functions for the templates.
	TmplFuncs template.FuncMap

	// A reader for user input, default to stdin.
	Reader io.Reader
}

Options contains options for a generator.

type StringInput

type StringInput struct {
	InputShared

	// Default is the default value.
	Default string `json:"default"`

	// Format is a string containing a regexp the value must have.
	Format string `json:"format"`
}

StringInput contains properties for string inputs.

func (*StringInput) Run

func (in *StringInput) Run() (interface{}, error)

Run implements generator.Input.

type StringSelect

type StringSelect struct {
	InputShared

	// Default is the default value.
	Default string `json:"default"`

	// Options is a map of possible values.
	Options StringSelectOptions `json:"options"`
}

StringSelect contains properties for string select inputs.

func (*StringSelect) Run

func (in *StringSelect) Run() (interface{}, error)

Run implements generator.Input.

type StringSelectMulti

type StringSelectMulti struct {
	InputShared

	// Default is the default value.
	Default string `json:"default"`

	// Options is an array of possible values.
	Options StringSelectOptions `json:"options"`

	// IsRequired is a bool indicating wether an input is needed.
	IsRequired bool `json:"isRequired"`
}

StringSelectMulti contains properties for multiple select inputs.

func (*StringSelectMulti) Run

func (in *StringSelectMulti) Run() (interface{}, error)

Run implements generator.Input.

type StringSelectOptions

type StringSelectOptions map[string]string

StringSelectOptions is a map of options (key/value strings)

func (StringSelectOptions) FindText

func (options StringSelectOptions) FindText(value string) string

FindText have to be replaced when []StringSelectOption will be a map[string]string

func (StringSelectOptions) FindValue

func (options StringSelectOptions) FindValue(text string) string

FindValue have to be replaced when []StringSelectOption will be a map[string]string

type StringSlice

type StringSlice struct {
	InputShared

	// Default is the default value.
	Default string `json:"default"`

	// Format is a string containing a regexp the value must have.
	Format string `json:"format"`
}

StringSlice contains properties for string inputs.

func (*StringSlice) Run

func (in *StringSlice) Run() (interface{}, error)

Run implements generator.Input.

Directories

Path Synopsis
Package repo deals with a Github repository of generators.
Package repo deals with a Github repository of generators.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL