Add basic scaffolding tool to generate new projects
This commit is contained in:
4
cmd/scaffold/.project-layout/web/.gitignore.gotpl
Normal file
4
cmd/scaffold/.project-layout/web/.gitignore.gotpl
Normal file
@ -0,0 +1,4 @@
|
||||
/release
|
||||
/data
|
||||
/vendor
|
||||
/bin
|
28
cmd/scaffold/.project-layout/web/Makefile.gotpl
Normal file
28
cmd/scaffold/.project-layout/web/Makefile.gotpl
Normal file
@ -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
Normal file
15
cmd/scaffold/.project-layout/web/README.md.gotpl
Normal file
@ -0,0 +1,15 @@
|
||||
# {{ .ProjectName }}
|
||||
|
||||
## Démarrer avec les sources
|
||||
|
||||
```
|
||||
make build
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
### Générer une version de distribution
|
||||
|
||||
```
|
||||
make release
|
||||
```
|
@ -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
Normal file
111
cmd/scaffold/.project-layout/web/cmd/server/main.go.gotpl
Normal file
@ -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))
|
||||
}
|
||||
}
|
@ -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}}
|
@ -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}}
|
@ -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}}
|
@ -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}}
|
@ -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
Normal file
1
cmd/scaffold/.project-layout/web/go.mod.gotpl
Normal file
@ -0,0 +1 @@
|
||||
module {{ .ProjectNamespace }}
|
71
cmd/scaffold/.project-layout/web/internal/config/config.go
Normal file
71
cmd/scaffold/.project-layout/web/internal/config/config.go
Normal file
@ -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
|
||||
}
|
@ -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
Normal file
33
cmd/scaffold/.project-layout/web/internal/config/service.go
Normal file
@ -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
Normal file
24
cmd/scaffold/.project-layout/web/internal/route/helper.go
Normal file
@ -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
Normal file
20
cmd/scaffold/.project-layout/web/internal/route/home.go
Normal file
@ -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))
|
||||
}
|
||||
}
|
@ -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
Normal file
123
cmd/scaffold/.project-layout/web/misc/script/release.sh.gotpl
Normal file
@ -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
|
@ -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
Normal file
13
cmd/scaffold/.project-layout/web/modd.conf
Normal file
@ -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
Normal file
11
cmd/scaffold/command/all.go
Normal file
@ -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
Normal file
276
cmd/scaffold/command/new_project.go
Normal file
@ -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
Normal file
22
cmd/scaffold/main.go
Normal file
@ -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)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user