Browse Source

Add basic scaffolding tool to generate new projects

extension
wpetit 2 years ago
parent
commit
7a88321a69
  1. 4
      .gitignore
  2. 12
      Makefile
  3. 4
      cmd/scaffold/.project-layout/web/.gitignore.gotpl
  4. 28
      cmd/scaffold/.project-layout/web/Makefile.gotpl
  5. 15
      cmd/scaffold/.project-layout/web/README.md.gotpl
  6. 78
      cmd/scaffold/.project-layout/web/cmd/server/container.go.gotpl
  7. 111
      cmd/scaffold/.project-layout/web/cmd/server/main.go.gotpl
  8. 18
      cmd/scaffold/.project-layout/web/cmd/server/template/blocks/base.html.tmpl
  9. 23
      cmd/scaffold/.project-layout/web/cmd/server/template/blocks/flash.html.tmpl
  10. 7
      cmd/scaffold/.project-layout/web/cmd/server/template/blocks/footer.html.tmpl
  11. 11
      cmd/scaffold/.project-layout/web/cmd/server/template/blocks/header.html.tmpl
  12. 11
      cmd/scaffold/.project-layout/web/cmd/server/template/layouts/home.html.tmpl
  13. 1
      cmd/scaffold/.project-layout/web/go.mod.gotpl
  14. 71
      cmd/scaffold/.project-layout/web/internal/config/config.go
  15. 9
      cmd/scaffold/.project-layout/web/internal/config/provider.go
  16. 33
      cmd/scaffold/.project-layout/web/internal/config/service.go
  17. 24
      cmd/scaffold/.project-layout/web/internal/route/helper.go
  18. 20
      cmd/scaffold/.project-layout/web/internal/route/home.go
  19. 34
      cmd/scaffold/.project-layout/web/internal/route/mount.go.gotpl
  20. 123
      cmd/scaffold/.project-layout/web/misc/script/release.sh.gotpl
  21. 11
      cmd/scaffold/.project-layout/web/misc/systemd/server.service.gotpl
  22. 13
      cmd/scaffold/.project-layout/web/modd.conf
  23. 11
      cmd/scaffold/command/all.go
  24. 276
      cmd/scaffold/command/new_project.go
  25. 22
      cmd/scaffold/main.go
  26. 11
      go.mod
  27. 72
      go.sum
  28. 13
      modd.conf

4
.gitignore vendored

@ -1 +1,3 @@
/coverage
/coverage
/bin
rice-box.go

12
Makefile

@ -1,6 +1,16 @@
build: embed
CGO_ENABLED=0 go build -o ./bin/scaffold ./cmd/scaffold
embed:
find ./ -name rice-box.go | xargs rm -f
rice embed-go -i ./cmd/scaffold/command
test:
go clean -testcache
go test -v ./...
go test -v -race ./...
watch:
modd
deps:
go get -u golang.org/x/tools/cmd/godoc

4
cmd/scaffold/.project-layout/web/.gitignore.gotpl

@ -0,0 +1,4 @@
/release
/data
/vendor
/bin

28
cmd/scaffold/.project-layout/web/Makefile.gotpl

@ -0,0 +1,28 @@
build: vendor
CGO_ENABLED=0 go build -mod=vendor -v -o bin/server ./cmd/server
test:
go test -v -race ./...
release:
@$(SHELL) ./misc/script/release.sh
vendor:
go mod vendor
tidy:
go mod tidy
watch:
modd
lint:
golangci-lint run --enable-all
clean:
rm -rf release
rm -rf data
rm -rf vendor
rm -rf bin
.PHONY: lint watch build vendor tidy release

15
cmd/scaffold/.project-layout/web/README.md.gotpl

@ -0,0 +1,15 @@
# {{ .ProjectName }}
## Démarrer avec les sources
```
make build
```
## FAQ
### Générer une version de distribution
```
make release
```

78
cmd/scaffold/.project-layout/web/cmd/server/container.go.gotpl

@ -0,0 +1,78 @@
package main
import (
"log"
"net/http"
"gitlab.com/wpetit/goweb/template/html"
"{{ .ProjectNamespace }}/internal/config"
"github.com/gorilla/sessions"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
"gitlab.com/wpetit/goweb/service/build"
"gitlab.com/wpetit/goweb/service/session"
"gitlab.com/wpetit/goweb/service/template"
"gitlab.com/wpetit/goweb/session/gorilla"
)
func getServiceContainer(conf *config.Config) (*service.Container, error) {
// Initialize and configure service container
ctn := service.NewContainer()
ctn.Provide(build.ServiceName, build.ServiceProvider(ProjectVersion, GitRef, BuildDate))
// Generate random cookie authentication key if none is set
if conf.HTTP.CookieAuthenticationKey == "" {
log.Println("could not find cookie authentication key. generating one...")
cookieAuthenticationKey, err := gorilla.GenerateRandomBytes(64)
if err != nil {
return nil, errors.Wrap(err, "could not generate cookie authentication key")
}
conf.HTTP.CookieAuthenticationKey = string(cookieAuthenticationKey)
}
// Generate random cookie encryption key if none is set
if conf.HTTP.CookieEncryptionKey == "" {
log.Println("could not find cookie encryption key. generating one...")
cookieEncryptionKey, err := gorilla.GenerateRandomBytes(32)
if err != nil {
return nil, errors.Wrap(err, "could not generate cookie encryption key")
}
conf.HTTP.CookieEncryptionKey = string(cookieEncryptionKey)
}
// Create and initialize HTTP session service provider
cookieStore := sessions.NewCookieStore(
[]byte(conf.HTTP.CookieAuthenticationKey),
[]byte(conf.HTTP.CookieEncryptionKey),
)
// Define default cookie options
cookieStore.Options = &sessions.Options{
Path: "/",
HttpOnly: true,
MaxAge: conf.HTTP.CookieMaxAge,
SameSite: http.SameSiteStrictMode,
}
ctn.Provide(
session.ServiceName,
gorilla.ServiceProvider("scaffold-test", cookieStore),
)
// Create and expose template service provider
// Create and expose template service provider
ctn.Provide(template.ServiceName, html.ServiceProvider(
conf.HTTP.TemplateDir,
))
// Create and expose config service provider
ctn.Provide(config.ServiceName, config.ServiceProvider(conf))
return ctn, nil
}

111
cmd/scaffold/.project-layout/web/cmd/server/main.go.gotpl

@ -0,0 +1,111 @@
package main
import (
"net/http"
"{{ .ProjectNamespace }}/internal/route"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"gitlab.com/wpetit/goweb/middleware/container"
"flag"
"fmt"
"log"
"os"
"{{ .ProjectNamespace }}/internal/config"
"github.com/pkg/errors"
)
//nolint: gochecknoglobals
var (
configFile = ""
workdir = ""
dumpConfig = false
version = false
)
// nolint: gochecknoglobals
var (
GitRef = "unknown"
ProjectVersion = "unknown"
BuildDate = "unknown"
)
//nolint: gochecknoinits
func init() {
flag.StringVar(&configFile, "config", configFile, "configuration file")
flag.StringVar(&workdir, "workdir", workdir, "working directory")
flag.BoolVar(&dumpConfig, "dump-config", dumpConfig, "dump configuration and exit")
flag.BoolVar(&version, "version", version, "show version and exit")
}
func main() {
flag.Parse()
if version {
fmt.Printf("%s (%s) - %s\n", ProjectVersion, GitRef, BuildDate)
os.Exit(0)
}
// Switch to new working directory if defined
if workdir != "" {
if err := os.Chdir(workdir); err != nil {
log.Fatalf("%+v", errors.Wrapf(err, "could not change working directory to '%s'", workdir))
}
}
// Load configuration file if defined, use default configuration otherwise
var conf *config.Config
var err error
if configFile != "" {
conf, err = config.NewFromFile(configFile)
if err != nil {
log.Fatalf("%+v", errors.Wrapf(err, "could not load config file '%s'", configFile))
}
} else {
if dumpConfig {
conf = config.NewDumpDefault()
} else {
conf = config.NewDefault()
}
}
// Dump configuration if asked
if dumpConfig {
if err := config.Dump(conf, os.Stdout); err != nil {
log.Fatalf("%+v", errors.Wrap(err, "could not dump config"))
}
os.Exit(0)
}
// Create service container
ctn, err := getServiceContainer(conf)
if err != nil {
log.Fatalf("%+v", errors.Wrap(err, "could not create service container"))
}
r := chi.NewRouter()
// Define base middlewares
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Expose service container on router
r.Use(container.ServiceContainer(ctn))
// Define routes
if err := route.Mount(r, conf); err != nil {
log.Fatalf("%+v", errors.Wrap(err, "could not mount http routes"))
}
if err := http.ListenAndServe(conf.HTTP.Address, r); err != nil {
log.Fatalf("%+v", errors.Wrapf(err, "could not listen on '%s'", conf.HTTP.Address))
}
}

18
cmd/scaffold/.project-layout/web/cmd/server/template/blocks/base.html.tmpl

@ -0,0 +1,18 @@
{{define "base"}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{block "title" . -}}{{- end}}</title>
{{- block "head_style" . -}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css" />
{{end}}
{{- block "head_script" . -}}{{end}}
</head>
<body>
{{- block "body" . -}}{{- end -}}
{{- block "body_script" . -}}{{end}}
</body>
</html>
{{end}}

23
cmd/scaffold/.project-layout/web/cmd/server/template/blocks/flash.html.tmpl

@ -0,0 +1,23 @@
{{define "flash"}}
<div class="flash has-margin-top-small has-margin-bottom-small">
{{- range .Flashes -}}
{{- if eq .Type "error" -}}
{{template "flash_message" map "Title" "Erreur" "MessageClass" "is-danger" "Message" .Message }}
{{- else if eq .Type "warn" -}}
{{template "flash_message" map "Title" "Attention" "MessageClass" "is-warning" "Message" .Message }}
{{- else if eq .Type "success" -}}
{{template "flash_message" map "Title" "Succès" "MessageClass" "is-success" "Message" .Message }}
{{- else -}}
{{template "flash_message" map "Title" "Information" "MessageClass" "is-info" "Message" .Message }}
{{- end -}}
{{- end -}}
</div>
{{end}}
{{define "flash_message" -}}
<div class="message {{.MessageClass}}">
<div class="message-body">
<span class="has-text-weight-bold">{{.Title}}</span> {{.Message}}
</div>
</div>
{{- end}}

7
cmd/scaffold/.project-layout/web/cmd/server/template/blocks/footer.html.tmpl

@ -0,0 +1,7 @@
{{define "footer"}}
<p class="has-margin-top-small has-text-right is-size-7 has-text-grey">
Version: {{ .BuildInfo.ProjectVersion }} -
Réf.: {{ .BuildInfo.GitRef }} -
Date de construction: {{ .BuildInfo.BuildDate }}
</p>
{{end}}

11
cmd/scaffold/.project-layout/web/cmd/server/template/blocks/header.html.tmpl

@ -0,0 +1,11 @@
{{define "header"}}
<div class="columns is-mobile">
<div class="column is-4-tablet is-8-mobile">
<div class="columns is-mobile is-gapless">
<div class="column is-narrow">
<h1 class="is-size-3 title"><a href="/" rel="Homepage" class="has-text-black">Your project</a></h1>
</div>
</div>
</div>
</div>
{{end}}

11
cmd/scaffold/.project-layout/web/cmd/server/template/layouts/home.html.tmpl

@ -0,0 +1,11 @@
{{define "title"}}Accueil{{end}}
{{define "body"}}
<section class="home is-fullheight section">
<div class="container">
{{template "header" .}}
<h1>Bienvenue !</h1>
{{template "footer" .}}
</div>
</section>
{{end}}
{{template "base" .}}

1
cmd/scaffold/.project-layout/web/go.mod.gotpl

@ -0,0 +1 @@
module {{ .ProjectNamespace }}

71
cmd/scaffold/.project-layout/web/internal/config/config.go

@ -0,0 +1,71 @@
package config
import (
"io"
"io/ioutil"
"time"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type Config struct {
HTTP HTTPConfig `yaml:"http"`
}
// NewFromFile retrieves the configuration from the given file
func NewFromFile(filepath string) (*Config, error) {
config := NewDefault()
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.Wrapf(err, "could not read file '%s'", filepath)
}
if err := yaml.Unmarshal(data, config); err != nil {
return nil, errors.Wrapf(err, "could not unmarshal configuration")
}
return config, nil
}
type HTTPConfig struct {
Address string `yaml:"address"`
CookieAuthenticationKey string `yaml:"cookieAuthenticationKey"`
CookieEncryptionKey string `yaml:"cookieEncryptionKey"`
CookieMaxAge int `yaml:"cookieMaxAge"`
TemplateDir string `yaml:"templateDir"`
PublicDir string `yaml:"publicDir"`
}
func NewDumpDefault() *Config {
config := NewDefault()
return config
}
func NewDefault() *Config {
return &Config{
HTTP: HTTPConfig{
Address: ":3000",
CookieAuthenticationKey: "",
CookieEncryptionKey: "",
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
TemplateDir: "template",
PublicDir: "public",
},
}
}
func Dump(config *Config, w io.Writer) error {
data, err := yaml.Marshal(config)
if err != nil {
return errors.Wrap(err, "could not dump config")
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}

9
cmd/scaffold/.project-layout/web/internal/config/provider.go

@ -0,0 +1,9 @@
package config
import "gitlab.com/wpetit/goweb/service"
func ServiceProvider(config *Config) service.Provider {
return func(ctn *service.Container) (interface{}, error) {
return config, nil
}
}

33
cmd/scaffold/.project-layout/web/internal/config/service.go

@ -0,0 +1,33 @@
package config
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "config"
// From retrieves the config service in the given container
func From(container *service.Container) (*Config, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Config)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the config service in the given container or panic otherwise
func Must(container *service.Container) *Config {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}

24
cmd/scaffold/.project-layout/web/internal/route/helper.go

@ -0,0 +1,24 @@
package route
import (
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
"gitlab.com/wpetit/goweb/template/html"
)
func extendTemplateData(w http.ResponseWriter, r *http.Request, data template.Data) template.Data {
ctn := container.Must(r.Context())
data, err := template.Extend(data,
html.WithFlashes(w, r, ctn),
template.WithBuildInfo(w, r, ctn),
)
if err != nil {
panic(errors.Wrap(err, "could not extend template data"))
}
return data
}

20
cmd/scaffold/.project-layout/web/internal/route/home.go

@ -0,0 +1,20 @@
package route
import (
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveHomePage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{})
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}

34
cmd/scaffold/.project-layout/web/internal/route/mount.go.gotpl

@ -0,0 +1,34 @@
package route
import (
"{{ .ProjectNamespace }}/internal/config"
"github.com/go-chi/chi"
"github.com/gorilla/csrf"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/static"
"gitlab.com/wpetit/goweb/session/gorilla"
)
func Mount(r *chi.Mux, config *config.Config) error {
csrfSecret, err := gorilla.GenerateRandomBytes(32)
if err != nil {
return errors.Wrap(err, "could not generate CSRF secret")
}
csrfMiddleware := csrf.Protect(
csrfSecret,
csrf.Secure(false),
)
r.Group(func(r chi.Router) {
r.Use(csrfMiddleware)
r.Get("/", serveHomePage)
})
notFoundHandler := r.NotFoundHandler()
r.Get("/*", static.Dir(config.HTTP.PublicDir, "", notFoundHandler))
return nil
}

123
cmd/scaffold/.project-layout/web/misc/script/release.sh.gotpl

@ -0,0 +1,123 @@
#!/bin/bash
set -eo pipefail
OS_TARGETS=(linux)
ARCH_TARGETS=${ARCH_TARGETS:-amd64 arm 386}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
PROJECT_DIR="$DIR/../.."
function build {
local name=$1
local srcdir=$2
local os=$3
local arch=$4
local dirname="$name-$os-$arch"
local destdir="$PROJECT_DIR/release/$dirname"
rm -rf "$destdir"
mkdir -p "$destdir"
echo "building $dirname..."
CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build \
-mod=vendor \
-ldflags="-s -w -X 'main.GitRef=$(current_commit_ref)' -X 'main.ProjectVersion=$(current_version)' -X 'main.BuildDate=$(current_date)'" \
-gcflags=-trimpath="${PWD}" \
-asmflags=-trimpath="${PWD}" \
-o "$destdir/bin/$name" \
"$srcdir"
if [ ! -z "$(which upx)" ]; then
upx --best "$destdir/bin/$name"
fi
}
function current_date {
date '+%Y-%m-%d %H:%M'
}
function current_commit_ref {
git log -n 1 --pretty="format:%h"
}
function current_version {
local latest_tag=$(git describe --abbrev=0 2>/dev/null)
echo ${latest_tag:-0.0.0}
}
function copy {
local name=$1
local os=$2
local arch=$3
local src=$4
local dest=$5
local dirname="$name-$os-$arch"
local destdir="$PROJECT_DIR/release/$dirname"
echo "copying '$src' to '$destdir/$dest'..."
mkdir -p "$(dirname $destdir/$dest)"
cp -rfL $src "$destdir/$dest"
}
function dump_default_conf {
# Generate and copy configuration file
local command=$1
local os=$2
local arch=$3
local tmp_conf=$(mktemp)
go run "$PROJECT_DIR/cmd/$command" -dump-config > "$tmp_conf"
copy "$command" $os $arch "$tmp_conf" "$command.yml"
rm -f "$tmp_conf"
}
function compress {
local name=$1
local os=$2
local arch=$3
local dirname="$name-$os-$arch"
local destdir="$PROJECT_DIR/release/$dirname"
echo "compressing $dirname..."
tar -czf "$destdir.tar.gz" -C "$destdir/../" "$dirname"
}
function release_server {
local os=$1
local arch=$2
build 'server' "$PROJECT_DIR/cmd/server" $os $arch
dump_default_conf 'server' $os $arch
copy 'server' $os $arch "$PROJECT_DIR/README.md" "README.md"
copy 'server' $os $arch "$PROJECT_DIR/cmd/server/public" "public"
copy 'server' $os $arch "$PROJECT_DIR/cmd/server/template" "template"
compress 'server' $os $arch
}
function main {
for os in ${OS_TARGETS[@]}; do
for arch in ${ARCH_TARGETS[@]}; do
release_server $os $arch
done
done
}
main

11
cmd/scaffold/.project-layout/web/misc/systemd/server.service.gotpl

@ -0,0 +1,11 @@
[Unit]
Description={{ .ProjectName }}
After=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/server -workdir /usr/local/share/server -config /etc/server/config.yml
Restart=on-failure
[Install]
WantedBy=multi-user.target

13
cmd/scaffold/.project-layout/web/modd.conf

@ -0,0 +1,13 @@
**/*.go
!**/*_test.go
data/config.yml
!**/rice-box.go
modd.conf {
prep: make build
prep: [ -e data/config.yml ] || ( mkdir -p data && bin/server -dump-config > data/config.yml )
daemon: bin/server -workdir "./cmd/server" -config ../../data/config.yml
}
**/*.go {
prep: make test
}

11
cmd/scaffold/command/all.go

@ -0,0 +1,11 @@
package command
import (
"github.com/urfave/cli/v2"
)
func All() []*cli.Command {
return []*cli.Command{
newProjectCommand(),
}
}

276
cmd/scaffold/command/new_project.go

@ -0,0 +1,276 @@
package command
import (
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/manifoldco/promptui"
rice "github.com/GeertJohan/go.rice"
"github.com/Masterminds/sprig"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
)
func newProjectCommand() *cli.Command {
return &cli.Command{
Name: "new",
Aliases: []string{"n"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "directory",
Aliases: []string{"d"},
Value: "./",
Usage: "project base directory",
Required: false,
},
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Value: "",
Usage: "project name",
Required: false,
},
&cli.StringFlag{
Name: "namespace",
Aliases: []string{"ns"},
Value: "",
Usage: "project module namespace",
Required: false,
},
&cli.StringFlag{
Name: "type",
Aliases: []string{"t"},
Value: "",
Usage: "project type",
Required: false,
},
},
Usage: "generate a new project",
Action: newProjectAction,
}
}
func newProjectAction(c *cli.Context) error {
projectLayoutBox, err := rice.FindBox("../.project-layout")
if err != nil {
return err
}
destDir := c.String("directory")
projectName := c.String("name")
if projectName == "" {
projectName, err = promptForProjectName()
if err != nil {
return err
}
}
projectNamespace := c.String("namespace")
if projectNamespace == "" {
projectNamespace, err = promptForProjectNamespace()
if err != nil {
return err
}
}
projectType := c.String("type")
if projectType == "" {
projectType, err = promptForProjectType()
if err != nil {
return err
}
}
data := map[string]interface{}{
"ProjectName": projectName,
"ProjectType": projectType,
"ProjectNamespace": projectNamespace,
}
return copyTemplateDir(projectLayoutBox, projectType, destDir, data, ".gotpl")
}
func promptForProjectName() (string, error) {
validate := func(input string) error {
if input == "" {
return errors.New("Project name cannot be empty")
}
return nil
}
prompt := promptui.Prompt{
Label: "Project Name",
Validate: validate,
}
return prompt.Run()
}
func promptForProjectNamespace() (string, error) {
validate := func(input string) error {
if input == "" {
return errors.New("Project namespace cannot be empty")
}
return nil
}
prompt := promptui.Prompt{
Label: "Project namespace",
Validate: validate,
}
return prompt.Run()
}
func promptForProjectType() (string, error) {
prompt := promptui.Select{
Label: "Project Type",
Items: []string{"web"},
}
_, result, err := prompt.Run()
return result, err
}
func copyFile(box *rice.Box, src, dst string) (err error) {
log.Printf("copying file '%s' to '%s'", src, dst)
in, err := box.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer func() {
if e := out.Close(); e != nil {
err = e
}
}()
_, err = io.Copy(out, in)
if err != nil {
return err
}
err = out.Sync()
if err != nil {
return err
}
return nil
}
func copyTemplateFile(box *rice.Box, src, dst string, data map[string]interface{}, templateExt string) (err error) {
if !strings.HasSuffix(src, templateExt) {
return copyFile(box, src, dst)
}
in, err := box.Open(src)
if err != nil {
return err
}
defer in.Close()
templateData, err := ioutil.ReadAll(in)
if err != nil {
return err
}
tmpl, err := template.New(filepath.Base(src)).Funcs(sprig.TxtFuncMap()).Parse(string(templateData))
if err != nil {
return err
}
dst = strings.TrimSuffix(dst, templateExt)
log.Printf("templating file from '%s' to '%s'", src, dst)
out, err := os.Create(dst)
if err != nil {
return err
}
defer func() {
if e := out.Close(); e != nil {
err = e
}
}()
data["SourceFile"] = src
data["DestFile"] = dst
if err := tmpl.Execute(out, data); err != nil {
return err
}
return nil
}
func copyTemplateDir(box *rice.Box, baseDir string, dst string, data map[string]interface{}, templateExt string) error {
baseDir = filepath.Clean(baseDir)
dst = filepath.Clean(dst)
_, err := os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return err
}
if err := os.MkdirAll(dst, 0755); err != nil {
return errors.Wrapf(err, "could not create directory '%s'", dst)
}
err = box.Walk(baseDir, func(srcPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if srcPath == baseDir {
return nil
}
relSrcPath, err := filepath.Rel(baseDir, srcPath)
if err != nil {
return err
}
dstPath := filepath.Join(dst, relSrcPath)
if info.IsDir() {
log.Printf("creating dir '%s'", dstPath)
if err := os.MkdirAll(dstPath, 0755); err != nil {
return errors.Wrapf(err, "could not create directory '%s'", dstPath)
}
return nil
}
err = copyTemplateFile(box, srcPath, dstPath, data, templateExt)
if err != nil {
return errors.Wrapf(err, "could not copy file '%s'", srcPath)
}
return nil
})
if err != nil {
return errors.Wrapf(err, "could not walk source directory '%s'", baseDir)
}
return nil
}

22
cmd/scaffold/main.go

@ -0,0 +1,22 @@
package main
import (
"log"
"os"
"gitlab.com/wpetit/goweb/cmd/scaffold/command"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Usage: "generate source code for goweb based projects",
Commands: command.All(),
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}

11
go.mod

@ -3,15 +3,24 @@ module gitlab.com/wpetit/goweb
go 1.12
require (
github.com/davecgh/go-spew v1.1.0
github.com/GeertJohan/go.rice v1.0.0
github.com/Masterminds/goutils v1.1.0 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Masterminds/sprig v2.22.0+incompatible
github.com/go-chi/chi v4.0.2+incompatible
github.com/go-playground/locales v0.12.1 // indirect
github.com/go-playground/universal-translator v0.16.0 // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/gorilla/securecookie v1.1.1
github.com/gorilla/sessions v1.2.0
github.com/huandu/xstrings v1.3.0 // indirect
github.com/imdario/mergo v0.3.8 // indirect
github.com/leodido/go-urn v1.1.0 // indirect
github.com/manifoldco/promptui v0.7.0
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c
github.com/pkg/errors v0.8.1
github.com/urfave/cli/v2 v2.1.1
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 // indirect
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/go-playground/validator.v9 v9.29.1

72
go.sum

@ -1,33 +1,105 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/GeertJohan/go.incremental v1.0.0 h1:7AH+pY1XUgQE4Y1HcXYaMqAI0m9yrFqo/jt0CW30vsg=
github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0=
github.com/GeertJohan/go.rice v1.0.0 h1:KkI6O9uMaQU3VEKaj01ulavtF7o1fWT7+pk/4voiMLQ=
github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0=
github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg=
github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
github.com/akavel/rsrc v0.8.0 h1:zjWn7ukO9Kc5Q62DOJCcxGpXC18RawVtYAGdz2aLlfw=
github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/daaku/go.zipexe v1.0.0 h1:VSOgZtH418pH9L16hC/JrgSNJbbAL26pj7lmD1+CGdY=
github.com/daaku/go.zipexe v1.0.0/go.mod h1:z8IiR6TsVLEYKwXAoE/I+8ys/sDkgTzSL0CLnGVd57E=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs=
github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
github.com/go-playground/locales v0.12.1 h1:2FITxuFt/xuCNP1Acdhv62OzaCiviiE4kotfhkmOqEc=
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
github.com/go-playground/universal-translator v0.16.0 h1:X++omBR/4cE2MNg91AoC3rmGrCjJ8eAeUP/K/EKx4DM=
github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.0 h1:S7P+1Hm5V/AT9cjEcUD5uDaQSX0OE577aCXgoaKpYbQ=
github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/huandu/xstrings v1.3.0 h1:gvV6jG9dTgFEncxo+AF7PH6MZXi/vZl25owA/8Dg8Wo=
github.com/huandu/xstrings v1.3.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/imdario/mergo v0.3.8 h1:CGgOkSJeqMRmt0D9XLWExdT4m4F1vd3FV3VPt+0VxkQ=
github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a h1:FaWFmfWdAUKbSCtOU2QjDaorUexogfaMgbipgYATUMU=
github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.1.0 h1:Sm1gr51B1kKyfD2BlRcLSiEkffoG96g6TPv6eRoEiB8=
github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw=
github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a h1:weJVJJRzAJBFRlAiJQROKQs8oC9vOxvm4rZmBBk0ONw=
github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/manifoldco/promptui v0.7.0 h1:3l11YT8tm9MnwGFQ4kETwkzpAwY2Jt9lCrumCUW4+z4=
github.com/manifoldco/promptui v0.7.0/go.mod h1:n4zTdgP0vr0S3w7/O/g98U+e0gwLScEXGwov2nIKuGQ=
github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ=
github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229 h1:E2B8qYyeSgv5MXpmzZXRNp8IAQ4vjxIjhpAf5hv/tAg=
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/urfave/cli/v2 v2.1.1 h1:Qt8FeAtxE/vfdrLmR3rxR6JRE0RoVmbXu8+6kZtYU4k=
github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1 h1:tY9CJiPnMXf1ERmG2EyK7gNUd+c6RKGD0IfU8WdUSz8=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 h1:Ao/3l156eZf2AW5wK8a7/smtodRU+gha3+BeqJ69lRk=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/go-playground/validator.v9 v9.29.1 h1:SvGtYmN60a5CVKTOzMSyfzWDeZRxRuGvRQyEAKbw1xc=
gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

13
modd.conf

@ -0,0 +1,13 @@
**/*.go
!**/rice-box.go {
prep: make build
}
cmd/scaffold/.project-layout/** {
prep: make build
}
**/*.go
!**/rice-box.go {
prep: make test
}
Loading…
Cancel
Save