Hygen

The simple, fast, and scalable code generator that lives in your project.

README

hygen logo

build status npm version

hygen is the simple, fast, and scalable code generator that lives _in_ your project.



Features


- ✅ Build ad-hoc generators quickly and full on project scaffolds.
- ✅ Local generators per project (and global, if you must)
- ✅ Built-in scaffolds to quickly create generators
- ✅ Full logic templates and rendering
- ✅ Prompts and flows for taking in arguments
- ✅ Automatic CLI arguments
- ✅ Adding new files
- ✅ Injecting into existing files
- ✅ Running shell commands
- ✅ Super fast, constantly optimized for speed


New in hygen v4.0.0: a positional NAME parameter.

Now you can use $ hygen component new MyComponent instead of $ hygen component new --name MyComponent.


Used By


Wix     Airbnb     Mercedes Benz AG     Open Data Institute     Ableneo  City of Amsterdam     Accenture   Birdie    Kind     Ackee   Aerian Studios  Food and Agriculture Organization of the UN Cape Cod Commision   Tweak Things     Crema     Cureon     Astrocoders     Vega/IDL   Sporty Spots    Thrashplay   8base    Instamotionh Biotope Frontend LabsSwydo Gridsome Rosem LaboratorySheffield Hallam UniversityHackoregon Chilly DesignScale LeapChat LogsStelaceEchobind.

Quick Start


Hygen can be used to supercharge your workflow with Redux, React Native, Express and more, by allowing you avoid manual work and generate, add, inject and perform custom operations on your codebase.

If you're on macOS and have Homebrew:

  1. ```
  2. $ brew tap jondot/tap
  3. $ brew install hygen
  4. ```

If you have node.js installed, you can install globally with npm (or Yarn):

  1. ```
  2. $ npm i -g hygen
  3. ```

If you like a no-strings-attached approach, you can use npx without installing globally:

  1. ```
  2. $ npx hygen ...
  3. ```

For other platforms, see releases.

Initialize hygen in your project (do this once per project):

  1. ```
  2. $ cd your-project
  3. $ hygen init self
  4. ```

Build your first generator, called mygen:

  1. ```
  2. $ hygen generator new mygen

  3. Loaded templates: _templates
  4.        added: _templates/mygen/new/hello.ejs.t
  5. ```

Now you can use it:

  1. ```
  2. $ hygen mygen new

  3. Loaded templates: _templates
  4.        added: app/hello.js
  5. ```

You've generated content into the current working directory in app/. To see how the generator is built, look at _templates (which you should check-in to your project from now on, by the way).

You can build a generator that uses an interactive prompt to fill in a variable:

  1. ```
  2. $ hygen generator with-prompt mygen

  3. Loaded templates: _templates
  4.        added: _templates/mygen/with-prompt/hello.ejs.t
  5.        added: _templates/mygen/with-prompt/prompt.js
  6. ```

Done! Now let's use mygen:

  1. ```
  2. $ hygen mygen with-prompt
  3. ? What's your message? hello

  4. Loaded templates: _templates
  5.        added: app/hello.js
  6. ```

Use a template repo


Want to start from a repo?

  1. ```
  2. $ hygen init repo antfu/vitesse --to my-folder
  3. ```

Want to start from an existing repo on an existing project?

  1. ```
  2. $ mkdir your-project && cd your-project
  3. $ hygen init repo antfu/vitesse
  4. ```


What's Next?


Go to the documentation to get to know the rest of Hygen and generators.

If you're in a hurry:

To learn how to edit generator templates, look here
To see how to use generators look here
Take a look at the ecosystem and tooling built around Hygen.

A Different Kind of a Generator


hygen is a scalable generator. It has developer and team ergonomics as first priority.

It avoids "blessed" or dedicated projects that codifies code generation, which before you know it, become a product you build, needs testing, CI, separate pull request reviews, and ultimately sucks up your time and becomes this super hated thing no one likes to touch anymore.

Plus, since they are not the product you are building they become notoriously hard to reason about.

Scratch Your Own Itch


Because hygen templates live _in_ your project, it cuts the time from having an itch for generating code (Redux, anyone?) in your current
project to code generated with it and others benefiting from it.

Template Locality


hygen picks up a local _templates folder
at any folder level of your project you're working from.

This is important because:

Templates are project-local. A git clone of the project fetches all generators as well.
Different generators can be tucked in different parts of the project, making it contextual.
Template locality is scalable; different teams can maintain different generators.
When you change your code, you can make changes in the template and pack in the same commit, to be reviewed and merged in the same PR (as opposed to installing different "plugins" or different templates from out-of-repo places).

And yet, if you don't like project-local templates:

You can have a global _templates folder (maybe a central git repo you maintain?) by populating an environment variable HYGEN_TMPLS
You can build a custom generator of your own withhygen at its core, and pack your own templates with it.

Folder Structure is Command Structure


The templates folder structure _maps directly_ to the command structure:

  1. ```
  2. $ hygen worker new jobrunner
  3. ```

For this command, hygen worker new maps to _templates/worker/new and all files within worker/new are rendered.

Template parameters are given with --flag VALUE, as many as you'd like. In this example we've set a parameter named name to the value jobrunner.

Subcommands


A subcommand is a file inside a your folder structure. So if the structure is this:

  1. ```
  2. _templates/
  3.     worker/
  4.       new/
  5.         index.html.ejs
  6.         setup.html.ejs
  7. ```

And you only want setup, you can run:

  1. ```
  2. $ hygen worker new:setup
  3. ```

You can also use the subcommand as a regular expression so, these will do the same:

  1. ```
  2. $ hygen worker new:se
  3. ```

  1. ```
  2. $ hygen worker new:se.*
  3. ```

Frontmatter for Decluttering


Here's how a template looks like (in our example, index.ejs.t). Templates bodies are ejs:

  1. ``` js
  2. ---
  3. to: app/workers/<%=name%>.js
  4. ---

  5. class <%= h.capitalize(name) %> {
  6.     work(){
  7.         // your code here!
  8.     }
  9. }
  10. ```

The first part of the template is a front matter, idea borrowed from Markdown, this is the metadata part of ahygen template and is part of the reason of why your templates will feel more lightweight and flexible.

All frontmatter metadata _are also run through the template engine_ so feel free to use variables in the frontmatter as you wish.

There's one required metadata variable: to.
to points to where this file will be placed (folders are created as needed).

Case changing


hygen provides ability to semantic case changing with change-case library, it's simple to use and very easy to understand.

There is a usecase for react based components generation:

  1. ```yaml
  2. ---
  3. to: components/<%= name %>/index.jsx
  4. ---
  5. import React from 'react'

  6. export const <%= name %> = ({ children }) => (
  7.   <div className="<%= h.changeCase.paramCase(name) %>">{children}</div>"
  8. )
  9. ```

With name HelloWorld will be compiled to:

  1. ``` js
  2. import React from 'react'

  3. export const HelloWorld = ({ children }) => (
  4.   <div className="hello-world">{children}</div>"
  5. )
  6. ```

You can see the full list here.

Addition, Injection, and More


By default templates are 'added' to your project as a new target file, but you can also choose to inject a template _into_ an existing target file.

For this to work, you need to use inject: true with the accompanied inject-specific props.

  1. ```yaml
  2. ---
  3. to: package.json
  4. inject: true
  5. after: dependencies
  6. skip_if: react-native-fs
  7. ---
  8. "react-native-fs":"*",
  9. ```

This template will add the react-native-fs dependency into a package.json file, but it will not add it twice (see skip_if).

Here are the available mutually-exclusive options for where to inject at:

before | after - a regular expression / text to locate. The inject line will appear before or after the located line.
prepend | append - add a line to start or end of file respectively.
line_at - add a line at this exact line number.

You can guard against double injection:

skip_if - a regular expression / text. If exists injection is skipped.

Also you can insert or remove empty line to injection body. That feature very useful if your editor or formatter automatically insert blank line at the end of file on save:

eof_last - if falsy - trim blank line from the end of injection body, if truthy - insert it.

Build Your Own


hygen is highly embeddable. You should be able to use it by simply listing it
as a dependency and having this kind of workflow in your binary.

  1. ``` js
  2. const { runner } = require('hygen')
  3. const Logger = require('hygen/dist/logger')
  4. const path = require('path')
  5. const defaultTemplates = path.join(__dirname, 'templates')

  6. runner(process.argv.slice(2), {
  7.   templates: defaultTemplates,
  8.   cwd: process.cwd(),
  9.   logger: new Logger.default(console.log.bind(console)),
  10.   createPrompter: () => require('enquirer'),
  11.   exec: (action, body) => {
  12.     const opts = body && body.length > 0 ? { input: body } : {}
  13.     return require('execa').shell(action, opts)
  14.   },
  15.   debug: !!process.env.DEBUG
  16. })
  17. ```

Development


The Hygen codebase has a functional style where possible. This is because naturally, it
feeds parameters and spits out files. Try to keep it that way.

Running hygen locally, rigged to your current codebase (note the additional -- to allow passing flags)

  1. ```
  2. $ yarn hygen -- mailer new foobar
  3. ```

Running tests in watch mode:

  1. ```
  2. $ yarn watch
  3. ```

Metaverse Testing


The easiest way to make an impact is to use the built-in [metaverse](src/__tests__/metaverse) tests suite, and then add the tests here.

The idea here is to copy templates from any project that use hygen and to test that it works at all times. This keeps tabs on the hygen universe / ecosystem (nicknamed metaverse) and makes sure this test suite breaks before hygen clients break.

Internal Testing


Start Up Speed Testing


Many generators become painfully slow to use as the thing you want to generate grow (because, real life),

This is why hygen takes speed as a first class citizen, and sports a dedicated start-up timing suite:

  1. ```
  2. $ yarn test:require
  3. ```

In addition, thought is given to which dependencies to take in, how their file structure fan out and what kind of disk access (due to require) would hygen ultimately have when we run it. This is recorded with every test run.

Bundling a single file was evaluated (and the infrastructure is still there, using webpack) and wasn't faster than what we have right now.

Contributing


Fork, implement, add tests, pull request, get my everlasting thanks and a respectable place here :).

Thanks:


To all Contributors - you make this happen, thanks!

Copyright


Copyright (c) 2018 Dotan Nahum @jondot. See LICENSE for further details.