Merge branch 'release/0.0.2'
This commit is contained in:
commit
4241333f8c
17
README.md
17
README.md
|
@ -12,7 +12,7 @@ go install forge.cadoles.com/wpetit/scaffold/cmd/scaffold
|
|||
|
||||
### À partir des binaires
|
||||
|
||||
1. [Télécharger la dernière version du binaire correspondant à votre plateforme](https://forge.cadoles.com/wpetit/scaffold/releases)
|
||||
1. [Télécharger la dernière version du binaire correspondant à votre plateforme](https://forge.cadoles.com/wpetit/scaffold/releases) (dernière version stable: 0.0.2)
|
||||
2. Extraire l'archive et place le binaire `bin/scaffold` dans votre `$PATH` (par exemple dans le répertoire `/usr/local/bin`)
|
||||
|
||||
## Usage
|
||||
|
@ -32,15 +32,28 @@ GLOBAL OPTIONS:
|
|||
--help, -h show help (default: false)
|
||||
```
|
||||
|
||||
### `scaffold from [command options] <URL>`
|
||||
### Commandes
|
||||
|
||||
#### `from`
|
||||
|
||||
```
|
||||
NAME:
|
||||
scaffold from - generate a new project from a given template url
|
||||
|
||||
USAGE:
|
||||
scaffold from [command options] <URL>
|
||||
|
||||
OPTIONS:
|
||||
--directory DIR, -d DIR Set destination to DIR (default: "./")
|
||||
--manifest FILE, -m FILE The scaffold manifest FILE (default: "scaffold.yml")
|
||||
--ignore value, -i value Ignore files matching pattern (default: ".git", ".git/**", "./.git/**/*")
|
||||
--help, -h show help (default: false)
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Format du fichier `scaffold.yml`](./doc/scaffold_file_format.md)
|
||||
|
||||
## Licence
|
||||
|
||||
[GPL-3.0](./LICENSE)
|
|
@ -16,7 +16,7 @@ func main() {
|
|||
}
|
||||
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
fmt.Printf("%+v", err)
|
||||
fmt.Printf("%+v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
# Créer un nouveau modèle de projet
|
||||
|
||||
Un modèle de projet `scaffold` est un simple répertoire (ou dépôt Git) contenant à sa racine un fichier `scaffold.yml`.
|
|
@ -0,0 +1,71 @@
|
|||
## Format du fichier `scaffold.yml`
|
||||
|
||||
Le fichier `scaffold.yml` est au format [YAML](https://yaml.org/). C'est ce fichier qui permet de définir les données à injecter dans les modèles lors de la génération d'un nouveau projet avec la commande `scaffold from ...`.
|
||||
|
||||
**Schéma**
|
||||
|
||||
``` yaml
|
||||
# Version du format de fichier. Actuellement, la seule valeur possible est 1.
|
||||
version: 1
|
||||
|
||||
# Liste des variables à injecter dans les modèles de fichier
|
||||
vars:
|
||||
- <Var>
|
||||
# - <Var>...
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
### `<Var>`
|
||||
|
||||
Définition d'une variable injectable dans les modèles de fichier.
|
||||
|
||||
**Schéma**
|
||||
|
||||
```yaml
|
||||
# Type de la variable. Actuellement, la seul valeur possible est "string"
|
||||
type: "string"
|
||||
|
||||
# Nom de la variable. C'est le nom qui permettra d'accéder à la valeur de la variable dans les modèles de fichiers.
|
||||
name: <string>
|
||||
|
||||
# Description de la variable. C'est le texte qui sera affiché dans l'invite de commande au moment de la génération de l'arborescence de fichiers.
|
||||
description: <string>
|
||||
|
||||
# Liste des contraintes appliquées à la valeur de la variable. La valeur est considérée comme invalide tant que l'ensemble des contraintes ne sont pas remplies.
|
||||
constraints:
|
||||
- <Constraint>
|
||||
# - <Constraint>...
|
||||
```
|
||||
|
||||
### `<Constraint>`
|
||||
|
||||
Définition d'une contrainte appliquée à la valeur d'une variable.
|
||||
|
||||
```yaml
|
||||
# Règle de validation à appliquer à la valeur entrée par l'utilisateur.
|
||||
rule: <Rule>
|
||||
|
||||
# Message à afficher à l'utilisateur si la règle de validation concorde avec la valeur entrée par celui ci.
|
||||
message: <string>
|
||||
```
|
||||
|
||||
**Exemple**
|
||||
|
||||
```yaml
|
||||
# Règle validant que la valeur ne doit pas être vide.
|
||||
rule: Input == ""
|
||||
message: Cette valeur ne peut être vide.
|
||||
```
|
||||
|
||||
### `<Rule>`
|
||||
|
||||
Règle de validation d'une contrainte appliquée à une variable.
|
||||
|
||||
Ce n'est ni plus ni moins qu'une condition booléenne écrite avec la syntaxe proposée par la librairie [github.com/antonmedv/expr](https://github.com/antonmedv/expr/blob/master/docs/Language-Definition.md).
|
||||
|
||||
Voici les variables globales disponibles aux règles:
|
||||
|
||||
|Variable|Description|
|
||||
|--------|-----------|
|
||||
|`Input` |Valeur entrée par l'utilisateur|
|
2
go.mod
2
go.mod
|
@ -7,10 +7,12 @@ require (
|
|||
github.com/Masterminds/semver v1.5.0 // indirect
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible
|
||||
github.com/antonmedv/expr v1.4.5
|
||||
github.com/davecgh/go-spew v1.1.1
|
||||
github.com/google/uuid v1.1.1 // indirect
|
||||
github.com/huandu/xstrings v1.3.0 // indirect
|
||||
github.com/imdario/mergo v0.3.8 // indirect
|
||||
github.com/manifoldco/promptui v0.7.0
|
||||
github.com/mattn/go-zglob v0.0.1
|
||||
github.com/mitchellh/copystructure v1.0.0 // indirect
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/urfave/cli/v2 v2.1.1
|
||||
|
|
2
go.sum
2
go.sum
|
@ -67,6 +67,8 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO
|
|||
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/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-zglob v0.0.1 h1:xsEx/XUoVlI6yXjqBK062zYhRTZltCNmYPx6v+8DNaY=
|
||||
github.com/mattn/go-zglob v0.0.1/go.mod h1:9fxibJccNxU2cnpIKLRRFA7zX7qhkJIQWBb449FYHOo=
|
||||
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/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package command
|
||||
|
||||
import (
|
||||
"log"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
|
@ -32,6 +32,12 @@ func fromCommand() *cli.Command {
|
|||
Usage: "The scaffold manifest `FILE`",
|
||||
Value: "scaffold.yml",
|
||||
},
|
||||
&cli.StringSliceFlag{
|
||||
Name: "ignore",
|
||||
Aliases: []string{"i"},
|
||||
Usage: "Ignore files matching pattern",
|
||||
Value: cli.NewStringSlice(".git", ".git/**", "./.git/**/*"),
|
||||
},
|
||||
},
|
||||
Action: fromAction,
|
||||
}
|
||||
|
@ -78,13 +84,13 @@ func fromAction(c *cli.Context) error {
|
|||
return errors.Wrapf(err, "could not read manifest '%s'", manifestPath)
|
||||
}
|
||||
|
||||
log.Println("Could not find scaffold manifest.")
|
||||
fmt.Println("Could not find scaffold manifest.")
|
||||
}
|
||||
|
||||
if manifestFile != nil {
|
||||
defer manifestFile.Close()
|
||||
|
||||
log.Println("Loading template scaffold manifest...")
|
||||
fmt.Println("Loading scaffold manifest.")
|
||||
|
||||
manifest, err := template.Load(manifestFile)
|
||||
if err != nil {
|
||||
|
@ -95,6 +101,7 @@ func fromAction(c *cli.Context) error {
|
|||
return errors.Wrapf(err, "could not validate manifest '%s'", manifestPath)
|
||||
}
|
||||
|
||||
fmt.Println("Prompting for templates variables.")
|
||||
if err := template.Prompt(manifest, templateData); err != nil {
|
||||
return errors.Wrap(err, "could not prompt for template data")
|
||||
}
|
||||
|
@ -102,9 +109,22 @@ func fromAction(c *cli.Context) error {
|
|||
|
||||
directory := c.String("directory")
|
||||
|
||||
return template.CopyDir(vfs, ".", directory, &template.Option{
|
||||
ignore := c.StringSlice("ignore")
|
||||
ignore = append(ignore, manifestPath)
|
||||
|
||||
fmt.Println("Generating project tree.")
|
||||
|
||||
err = template.CopyDir(vfs, ".", directory, &template.Option{
|
||||
TemplateData: templateData,
|
||||
TemplateExt: ".gotpl",
|
||||
IgnorePatterns: []string{manifestPath},
|
||||
IgnorePatterns: ignore,
|
||||
PreferredStrategy: template.Undefined,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Done.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package project
|
||||
|
||||
import (
|
||||
"log"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
@ -51,7 +51,7 @@ func (f *GitFetcher) Fetch(url *url.URL) (billy.Filesystem, error) {
|
|||
url.Fragment = ""
|
||||
}
|
||||
|
||||
log.Printf("Cloning repository '%s'...", url.String())
|
||||
fmt.Printf("Cloning repository '%s'.\n", url.String())
|
||||
|
||||
repo, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
|
||||
URL: url.String(),
|
||||
|
@ -72,7 +72,7 @@ func (f *GitFetcher) Fetch(url *url.URL) (billy.Filesystem, error) {
|
|||
return nil, errors.Wrap(err, "could not retrieve worktree")
|
||||
}
|
||||
|
||||
log.Printf("Checking out branch '%s'...", branchName)
|
||||
fmt.Printf("Checking out branch '%s'.\n", branchName)
|
||||
|
||||
err = worktree.Checkout(&git.CheckoutOptions{
|
||||
Force: true,
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package template
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
@ -13,6 +13,7 @@ import (
|
|||
"gopkg.in/src-d/go-billy.v4"
|
||||
|
||||
"github.com/Masterminds/sprig"
|
||||
"github.com/mattn/go-zglob"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
|
@ -43,12 +44,12 @@ func CopyDir(vfs billy.Filesystem, baseDir string, dst string, opts *Option) err
|
|||
}
|
||||
|
||||
for _, p := range opts.IgnorePatterns {
|
||||
match, err := filepath.Match(p, srcPath)
|
||||
match, err := zglob.Match(p, strings.TrimPrefix(srcPath, "./"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not match ignored file")
|
||||
}
|
||||
if match {
|
||||
log.Printf("Ignoring %s.", srcPath)
|
||||
fmt.Printf("Ignoring %s.\n", srcPath)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@ -61,7 +62,7 @@ func CopyDir(vfs billy.Filesystem, baseDir string, dst string, opts *Option) err
|
|||
dstPath := filepath.Join(dst, relSrcPath)
|
||||
|
||||
if info.IsDir() {
|
||||
log.Printf("creating dir '%s'", dstPath)
|
||||
fmt.Printf("Creating dir '%s'.\n", dstPath)
|
||||
if err := os.MkdirAll(dstPath, 0755); err != nil {
|
||||
return errors.Wrapf(err, "could not create directory '%s'", dstPath)
|
||||
}
|
||||
|
@ -89,6 +90,44 @@ func CopyFile(vfs billy.Filesystem, src, dst string, opts *Option) (err error) {
|
|||
opts = &Option{}
|
||||
}
|
||||
|
||||
stat, err := os.Stat(dst)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
// If dst exists
|
||||
if stat != nil {
|
||||
strategy := opts.PreferredStrategy
|
||||
|
||||
if opts.Unnattended && opts.PreferredStrategy == -1 {
|
||||
strategy = defaultStrategy
|
||||
}
|
||||
|
||||
if opts.PreferredStrategy == -1 {
|
||||
var useAsPreferredStrategy bool
|
||||
|
||||
strategy, useAsPreferredStrategy, err = askOverwriteStrategy(dst)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not ask for overwrite strategy")
|
||||
}
|
||||
|
||||
if useAsPreferredStrategy {
|
||||
opts.PreferredStrategy = strategy
|
||||
}
|
||||
}
|
||||
|
||||
switch strategy {
|
||||
case CopyAsDist:
|
||||
fmt.Printf("Using '%s.dist' as destination file.\n", dst)
|
||||
dst += ".dist"
|
||||
case DoNotCopy:
|
||||
fmt.Printf("Skipping existing file '%s'.\n", dst)
|
||||
return nil
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(src, opts.TemplateExt) {
|
||||
return copyFile(vfs, src, dst)
|
||||
}
|
||||
|
@ -111,7 +150,7 @@ func CopyFile(vfs billy.Filesystem, src, dst string, opts *Option) (err error) {
|
|||
|
||||
dst = strings.TrimSuffix(dst, opts.TemplateExt)
|
||||
|
||||
log.Printf("templating file from '%s' to '%s'", src, dst)
|
||||
fmt.Printf("Templating file from '%s' to '%s'.\n", src, dst)
|
||||
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
|
@ -135,7 +174,7 @@ func CopyFile(vfs billy.Filesystem, src, dst string, opts *Option) (err error) {
|
|||
}
|
||||
|
||||
func copyFile(vfs billy.Filesystem, src, dst string) (err error) {
|
||||
log.Printf("copying file '%s' to '%s'", src, dst)
|
||||
fmt.Printf("Copying file '%s' to '%s'.\n", src, dst)
|
||||
|
||||
in, err := vfs.Open(src)
|
||||
if err != nil {
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
package template
|
||||
|
||||
import "github.com/pkg/errors"
|
||||
|
||||
var (
|
||||
ErrUnexpectedOverwriteStrategy = errors.New("unexpected overwrite strategy")
|
||||
)
|
|
@ -4,4 +4,6 @@ type Option struct {
|
|||
IgnorePatterns []string
|
||||
TemplateData Data
|
||||
TemplateExt string
|
||||
Unnattended bool
|
||||
PreferredStrategy Strategy
|
||||
}
|
||||
|
|
|
@ -0,0 +1,62 @@
|
|||
package template
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Strategy int
|
||||
|
||||
const (
|
||||
Undefined Strategy = -1
|
||||
Overwrite Strategy = iota
|
||||
CopyAsDist
|
||||
DoNotCopy
|
||||
)
|
||||
|
||||
// nolint: gochecknoglobals
|
||||
var defaultStrategy = CopyAsDist
|
||||
|
||||
func askOverwriteStrategy(dst string) (Strategy, bool, error) {
|
||||
strategyPrompt := promptui.Select{
|
||||
Label: fmt.Sprintf("The file '%s' already exists. What do you want to do ?", dst),
|
||||
Items: []string{
|
||||
"Leave <dest> file as is",
|
||||
"Copy source file as '<dest>.dist'",
|
||||
"Overwrite '<dest>' with source file",
|
||||
},
|
||||
}
|
||||
|
||||
strategySelectedIndex, _, err := strategyPrompt.Run()
|
||||
if err != nil {
|
||||
return -1, false, errors.Wrap(err, "could not prompt for overwrite strategy")
|
||||
}
|
||||
|
||||
asPreferredStrategyPrompt := promptui.Select{
|
||||
Label: "Do you want to apply this strategy to all files ?",
|
||||
Items: []string{
|
||||
"Yes",
|
||||
"No",
|
||||
},
|
||||
}
|
||||
|
||||
preferredSelectedIndex, _, err := asPreferredStrategyPrompt.Run()
|
||||
if err != nil {
|
||||
return -1, false, errors.Wrap(err, "could not prompt for preferred strategy")
|
||||
}
|
||||
|
||||
useAsPreferredStrategy := preferredSelectedIndex == 0
|
||||
|
||||
switch strategySelectedIndex {
|
||||
case 0:
|
||||
return DoNotCopy, useAsPreferredStrategy, nil
|
||||
case 1:
|
||||
return CopyAsDist, useAsPreferredStrategy, nil
|
||||
case 2:
|
||||
return Overwrite, useAsPreferredStrategy, nil
|
||||
default:
|
||||
return -1, false, ErrUnexpectedOverwriteStrategy
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue