easygen

package module
v1.0.0-...-87d805d Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2017 License: MIT Imports: 14 Imported by: 0

README

easygen

MIT License GoDoc Go Report Card travis Status Codeship Status for go-easygen/easygen

TOC

easygen - Easy to use universal code/text generator

Command easygen is an easy to use universal code/text generator.

It can be used as a text or html generator for arbitrary purposes with arbitrary data and templates.

It can be used as a code generator, or anything that is structurally repetitive. Some command line parameter handling code generator are provided as examples, including the Go's built-in flag package, and the viper & cobra package.

You can even use easygen as a generic Go template testing tool using the -ts commandline option, and much much more.

Usage

$ easygen
Usage:
 easygen [flags] YamlFileName [YamlFileName...]

Flags:

  -debug level
    	debugging level
  -et extension
    	extension of template file (default ".tmpl")
  -ey extension
    	extension of yaml file (default ".yaml")
  -html
    	treat the template file as html instead of text
  -rf string
    	replace from, the from string used for the replace function
  -rt string
    	replace to, the to string used for the replace function
  -tf name(s)
    	.tmpl (comma-separated) template file name(s) (default: same as .yaml file)
  -ts string
    	template string (in text)

YamlFileName: The name for the .yaml data and .tmpl template file
	Only the name part, without extension. Can include the path as well.

Install

go get github.com/go-easygen/easygen/...
ls -l $GOPATH/bin

You should find an easygen executable newly created in there.

Test

export PATH=$PATH:$GOPATH/bin

$ easygen $GOPATH/src/github.com/go-easygen/easygen/test/list0
The colors are: red, blue, white, .

cd $GOPATH/src/github.com/go-easygen/easygen

$ easygen test/list1 
The quoted colors are: "red", "blue", "white", .

$ easygen -tf test/listfunc1 test/list0
red, blue, white.

And also check out the provided more examples in the Go Doc document.

Details

Command line flag handling code auto-generation

As explained above, one practical use of easygen is to auto-generating Go code for command line parameter handling, for both viper and cobra, and Go's built-in flag package.

Currently, easygen's command line parameter handling is built on top of Go's built-in flag package, and the handling code is entirely generated by easygen itself. Thus, showing how easygen is handling the command line parameters itself also means showing what functionality the auto-generated command line parameter handling code can do for you.

Currently, there are three tiers program parameters can be given:

  1. Default values defined within the program, so that program parameters can have meaningful defaults to start with
  2. Values defined in environment variables
  3. Values passed from command line

The latter will have higher priority and will override values defined formerly. I.e., the values from command line will override that in environment variables, which in turn override program defaults.

We will use the -ts, template string, as an example to illustrate. The program defaults is empty, which means using the .tmpl template file the same as the .yaml data file. We will override that first by environment variable, then from command line, illustrated in next section.

Testing the templates on the fly

echo 'Name: some-init-method' > /tmp/var.yaml

$ EASYGEN_TS='{{.Name}}' easygen /tmp/var
some-init-method

I.e., with the environment variable EASYGEN_TS, the .tmpl template file is not used.

$ EASYGEN_TS='{{.Name}}' easygen -ts '{{ck2uc .Name}}' /tmp/var
SomeInitMethod

I.e., command line value takes the highest priority, even overriding the environment variable EASYGEN_TS's value.

As such, if you have a different naming convention than using .tmpl for template file and .yaml for data file, you can override them in environment variables, EASYGEN_ET and EASYGEN_EY, so that you don't need to use -et and/or -ey to override them from command line each time.

echo 'Name: myConstantVariable' > /tmp/var.yml

$ EASYGEN_EY=.yml easygen -ts '{{clc2ss .Name}}' /tmp/var
MY_CONSTANT_VARIABLE

Tips

You can use easygen as an generic Go template testing tool with the -ts commandline option. For example,

echo "Age: 16" > /tmp/age.yaml

$ easygen -ts "{{.Age}}" /tmp/age
16

$ easygen -ts '{{printf "%x" .Age}}' /tmp/age
10

echo '{FirstName: John, LastName: Doe}' > /tmp/name.yaml

$ easygen -ts '{{.FirstName}}'\''s full name is {{printf "%s%s" .FirstName .LastName | len}} letters long.' /tmp/name
John's full name is 7 letters long.

$ easygen -ts "{{.FirstName}} {{ck2ss .LastName}}'s full name is "'{{len (printf "%s%s" .FirstName .LastName)}} letters long.' /tmp/name
John DOE's full name is 7 letters long.

echo 'Name: some-init-method' > /tmp/var.yaml

$ easygen -ts '{{.Name}} {{6 | minus1}} {{minus1 6}} {{ck2lc .Name}} {{ck2uc .Name}}' /tmp/var
some-init-method 5 5 someInitMethod SomeInitMethod

Author(s) & Contributor(s)

Tong SUN
suntong from cpan.org

Gerrit Renker
https://github.com/grrtrr

All patches welcome.

Documentation

Overview

Package easygen is an easy to use universal code/text generator library.

It can be used as a text or html generator for arbitrary purposes with arbitrary data and templates.

It can be used as a code generator, or anything that is structurally repetitive. Some command line parameter handling code generator are provided as examples, including the Go's built-in flag package, and the viper & cobra package.

Many examples have been provided to showcase its functionality, and different ways to use it.

Index

Examples

Constants

This section is empty.

Variables

View Source
var Opts = Options{ExtYaml: ".yaml", ExtTmpl: ".tmpl"}

Opts holds the actual values from the command line parameters

Functions

func Generate

func Generate(HTML bool, fileName string) string

Generate will produce output from the template according to the corresponding driving data, fileName is for both template and data file name

Example (CommandLineCobraViper)

Test the provided Cobra/Viper command line flag auto generation

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen test/commandlineCV
	fmt.Print(easygen.Generate(false, "test/commandlineCV"))
}
Output:


	flags.Bool("debug", false, "Turn on debugging.")
	viper.BindPFlag("debug", flags.Lookup("debug"))

	flags.String("addr", "localhost:5002", "Address of the service.")
	viper.BindPFlag("addr", flags.Lookup("addr"))

	flags.String("smtp-addr", "localhost:25", "Address of the SMTP server.")
	viper.BindPFlag("smtp-addr", flags.Lookup("smtp-addr"))

	flags.String("smtp-user", "", "User for the SMTP server.")
	viper.BindPFlag("smtp-user", flags.Lookup("smtp-user"))

	flags.String("smtp-password", "", "Password for the SMTP server.")
	viper.BindPFlag("smtp-password", flags.Lookup("smtp-password"))

	flags.String("email-from", "noreply@abc.com", "The from email address.")
	viper.BindPFlag("email-from", flags.Lookup("email-from"))
Example (CommandLineCobraViperInit)

Test the provided Cobra/Viper command line flag init() function auto generation

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen test/commandlineCVFull
	fmt.Print(easygen.Generate(false, "test/commandlineCVFull"))
}
Output:

func init() {

  viper.SetEnvPrefix("DISPATCH")
  viper.AutomaticEnv()

  /*

    When AutomaticEnv called, Viper will check for an environment variable any
    time a viper.Get request is made. It will apply the following rules. It
    will check for a environment variable with a name matching the key
    uppercased and prefixed with the EnvPrefix if set.

  */

  flags := mainCmd.Flags()

  flags.Bool("Debug", false, "Turn on debugging.")
  viper.BindPFlag("Debug", flags.Lookup("Debug"))

  flags.String("addr", "localhost:5002", "Address of the service.")
  viper.BindPFlag("addr", flags.Lookup("addr"))

  flags.String("smtp-addr", "localhost:25", "Address of the SMTP server.")
  viper.BindPFlag("smtp-addr", flags.Lookup("smtp-addr"))

  flags.String("smtp-user", "", "User for the SMTP server.")
  viper.BindPFlag("smtp-user", flags.Lookup("smtp-user"))

  flags.String("smtp-password", "", "Password for the SMTP server.")
  viper.BindPFlag("smtp-password", flags.Lookup("smtp-password"))

  flags.String("email-from", "noreply@abc.com", "The from email address.")
  viper.BindPFlag("email-from", flags.Lookup("email-from"))

  // Viper supports reading from yaml, toml and/or json files. Viper can
  // search multiple paths. Paths will be searched in the order they are
  // provided. Searches stopped once Config File found.

  viper.SetConfigName("CommandLineCV") // name of config file (without extension)

  viper.AddConfigPath("/tmp")
  viper.AddConfigPath(".")

  err := viper.ReadInConfig()
  if err != nil {
    println("No config file found. Using built-in defaults.")
  }

}
Example (Listfunc1)

Test the provided listfunc1, template and data

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen test/listfunc1
	fmt.Print(easygen.Generate(false, "test/listfunc1"))
}
Output:

red, blue, white.
Example (Listfunc2)

Test the provided listfunc2, template and data

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen test/listfunc2
	fmt.Print(easygen.Generate(false, "test/listfunc2"))
}
Output:

some-init-method 5 5 someInitMethod SomeInitMethod

func Generate0

func Generate0(HTML bool, strTempl string, fileName string) string

Generate0 will produce output according from driving data without a template file, using the string from strTempl as the template

Example (List0StrTemplate)

Test string template with list0 data

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen -ts '{{range .Colors}}{{.}}, {{end}}' test/list0
	fmt.Print(easygen.Generate0(false, "{{range .Colors}}{{.}}, {{end}}", "test/list0"))
}
Output:

red, blue, white,
Example (Split0)

Test the string split function in template

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen -ts '{{split .Colorlist}}' test/list0
	fmt.Print(easygen.Generate0(false, `{{split .Colorlist}}`, "test/list0"))
}
Output:

[red blue white]
Example (Split1)

Test the string split function in template again

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen -ts '{{range ... {{end}}' test/list0
	fmt.Print(easygen.Generate0(false, `{{range (split .Colorlist)}}{{.}} {{end}}`, "test/list0"))
}
Output:

red blue white
Example (StringsCmp)

Test string comparison in template

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen -ts '{{The {{if ... {{end}}.' test/strings0
	fmt.Print(easygen.Generate0(false, `The {{if eq .StrTest "-AB-axxb- HTML Html html"}}eq says Yea{{else}}eq says Nay{{end}} but {{if eqf .StrTest "-AB-axxb- HTML Html html"}}eqf says Yea{{else}}eqf says Nay{{end}}.`, "test/strings0"))
}
Output:

The eq says Nay but eqf says Yea.

func Generate2

func Generate2(HTML bool, fileNameTempl string, fileNames ...string) (ret string)

Generate2 will produce output according to the given template and driving data files, specified via fileNameTempl and fileNames (for data) respectively.

Example (Listfunc1List0)

Test the provided listfunc1 template with list0 data

package main

import (
	"fmt"

	"github.com/go-easygen/easygen"
)

func main() {
	// Equivalent testing on commandline:
	//   easygen -tf test/listfunc1 test/list0
	fmt.Print(easygen.Generate2(false, "test/listfunc1", "test/list0"))
}
Output:

red, blue, white.

func ParseFiles

func ParseFiles(HTML bool, filenames ...string) (template, error)

ParseFiles wraps parsing text or HTML template files into a single function, dictated by the first parameter "HTML". By Matt Harden @gmail.com

func TFStringsInit

func TFStringsInit()

TFStringsInit does initialization for strings related template functions

func Usage

func Usage()

Usage function shows help on commandline usage

Types

type Options

type Options struct {
	HTML         bool   // treat the template file as html instead of text
	TemplateStr  string // template string (in text)
	TemplateFile string // .tmpl template file `name` (default: same as .yaml file)
	ExtYaml      string // `extension` of yaml file
	ExtTmpl      string // `extension` of template file
	StrFrom      string // replace from, the from string used for the replace function
	StrTo        string // replace to, the to string used for the replace function
	Debug        int    // debugging `level`
}

The Options struct defines the structure to hold the commandline values

Directories

Path Synopsis
cmd
easygen
Command easygen is an easy to use universal code/text generator.
Command easygen is an easy to use universal code/text generator.

Jump to

Keyboard shortcuts

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