jondot / hygen

The simple, fast, and scalable code generator that lives in your project.
http://www.hygen.io
MIT License
5.68k stars 256 forks source link

Skip some or all prompts according to variables defined in template file? #426

Open Toshinaki opened 1 year ago

Toshinaki commented 1 year ago

I have some template files under a folder doc/new.

One template (file.ejs.t) looks like:

---
to: doc/<%= name %>.md
---

And one (random.ejs.t) looks like:

---
to: doc/<%= h.customRandomGen() %>.md
---

The second one used a custom util function to generate a random file name. But a filename name is required to be input for the first one.

I created a prompt.js under doc/new:

module.exports = [
  {
    type: "input",
    name: "name",
    message: "File name:",
    validate: function (value) {
      if (value.trim().length === 0) {
        return "File name can't be empty!";
      }
      return true;
    },
  }
];

And I can generate files by doc new:file or doc new:random.

For doc new:file, it's ok to ask for a name input, but for doc new:random, no input is needed, but the prompt shows and since the validation I defined, I can't input empty.

Is there any way to filter the prompts array, based on the variables appeared in template file?

So for template A, which uses a required name and optional desc, template B which uses only a required name, template C which uses optional desc, and template D which uses no input, I can define a single array of prompts:

module.exports = [
  { ... name: "name", ...}, 
  { ... name: "desc", ...}, 
];

And the prompts are filtered: template A: name,desc template B: name template C: desc template D: nothing

Is there any way to do this?