diff --git a/README.md b/README.md index 95060fc..2c3a67b 100644 --- a/README.md +++ b/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] ` +### Commandes + +#### `from` ``` +NAME: + scaffold from - generate a new project from a given template url + +USAGE: + scaffold from [command options] + 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) \ No newline at end of file diff --git a/cmd/scaffold/main.go b/cmd/scaffold/main.go index b1ca64d..137f251 100644 --- a/cmd/scaffold/main.go +++ b/cmd/scaffold/main.go @@ -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) } } diff --git a/doc/create_projet_template.md b/doc/create_projet_template.md new file mode 100644 index 0000000..41b216a --- /dev/null +++ b/doc/create_projet_template.md @@ -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`. diff --git a/doc/generate_project_from_template.md b/doc/generate_project_from_template.md new file mode 100644 index 0000000..e69de29 diff --git a/doc/scaffold_file_format.md b/doc/scaffold_file_format.md new file mode 100644 index 0000000..c126fc9 --- /dev/null +++ b/doc/scaffold_file_format.md @@ -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: + - +# - ... +``` + +## Types + +### `` + +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: + +# 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: + +# 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: + - +# - ... +``` + +### `` + +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: + +# Message à afficher à l'utilisateur si la règle de validation concorde avec la valeur entrée par celui ci. +message: +``` + +**Exemple** + +```yaml +# Règle validant que la valeur ne doit pas être vide. +rule: Input == "" +message: Cette valeur ne peut être vide. +``` + +### `` + +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| \ No newline at end of file diff --git a/go.mod b/go.mod index 4b36cce..5d7ad94 100644 --- a/go.mod +++ b/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 diff --git a/go.sum b/go.sum index c683454..8cd87c4 100644 --- a/go.sum +++ b/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= diff --git a/internal/command/from_project.go b/internal/command/from_project.go index a53d500..bc8d2c0 100644 --- a/internal/command/from_project.go +++ b/internal/command/from_project.go @@ -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{ - TemplateData: templateData, - TemplateExt: ".gotpl", - IgnorePatterns: []string{manifestPath}, + 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: ignore, + PreferredStrategy: template.Undefined, }) + if err != nil { + return err + } + + fmt.Println("Done.") + + return nil } diff --git a/internal/project/git.go b/internal/project/git.go index cfc942d..77f59ac 100644 --- a/internal/project/git.go +++ b/internal/project/git.go @@ -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, diff --git a/internal/template/copy.go b/internal/template/copy.go index dae09bf..1ac769e 100644 --- a/internal/template/copy.go +++ b/internal/template/copy.go @@ -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 { diff --git a/internal/template/error.go b/internal/template/error.go new file mode 100644 index 0000000..4af2d91 --- /dev/null +++ b/internal/template/error.go @@ -0,0 +1,7 @@ +package template + +import "github.com/pkg/errors" + +var ( + ErrUnexpectedOverwriteStrategy = errors.New("unexpected overwrite strategy") +) diff --git a/internal/template/option.go b/internal/template/option.go index 5e02013..fa20d75 100644 --- a/internal/template/option.go +++ b/internal/template/option.go @@ -1,7 +1,9 @@ package template type Option struct { - IgnorePatterns []string - TemplateData Data - TemplateExt string + IgnorePatterns []string + TemplateData Data + TemplateExt string + Unnattended bool + PreferredStrategy Strategy } diff --git a/internal/template/strategy.go b/internal/template/strategy.go new file mode 100644 index 0000000..74bb84c --- /dev/null +++ b/internal/template/strategy.go @@ -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 file as is", + "Copy source file as '.dist'", + "Overwrite '' 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 + } +}