Giter Club home page Giter Club logo

cookiecutter's Introduction

cookiecutter πŸͺ βœ‚οΈ

CircleCI Greenkeeper badge npm version

A CLI for creating boilerplate files/folders based on templates you provide. Like Yeoman or Python's Cookiecutter but much, much simpler.

Show me:

Example with Error

It is designed for existing projects where you want an easy way to create boilerplate files - instead of having to copy paste an existing file & then remember to make the necessary changes.

A good use-case for cookiecutter is, for example, creating a new Redux connected React component within a project. Not hard... but also not fun.

βœ… Cookiecutter supports:

  • Multiple templates with the ability to pick which template to use via the CLI.
  • Multiple fields per template with the ability to specify them from the CLI.
  • Custom validation & error messages for fields.
  • Any type of file or folder structure.

❌ Cookiecutter doesn't support:

  • Conditionals or any other logic in templates. You can however achieve similar things by having multiple templates).
  • Bootstrapping a project from scratch (i.e I have no code but need to set a project up)
  • Adding code to existing files
  • Lots of other things Yeoman does support. If your use-case is complex, cookiecutter might not cut it.

Quick Setup

First npm install --save-dev cookiecutter. You can also install this globally if you prefer.

The add the following to your package.json (no need to do this if you are using yarn):

"scripts": {
    "cookiecutter": "cookiecutter"
}

You can now start creating your template. For example if you create a 'templates' folder in your root and add the following template:

// templates/COMPONENT_NAME.js
import React from "react";

class COMPONENT_NAME extends React.Component {
  render() {
    return <div>Hello World</div>;
  }
}

export default COMPONENT_NAME;

You can now configure Cookiecutter to replace the string COMPONENT_NAME like so by creating a file in the root of your project called cookiecutter.config.js. Cookiecutter will always look in your root for a file called cookiecutter.config.js.

// cookiecutter.config.js
module.exports = [
  {
    name: "Normal React Component",
    templatePath: "templates/COMPONENT_NAME.js",
    outputPath: "src/components/",
    fields: [
      {
        templateVariable: "COMPONENT_NAME",
        question: "What is the component's name?"
      }
    ]
  }
];

If you now run npm run cookiecutter you will be prompted to pick which template you'd like to use. After which you will be asked to answer each field's question. It should look something like this:

Example from Tutorial

That's it. Cookiecutter now created the following file:

    - src
      - components
+       - ExampleComponent.js
        - OtherComponent.js
        - Etc.js

Cookiecutter will never overwrite any existing files.

Validating fields / custom validation

To do this you can add isValid and a custom errorMessage to a fields configuration. Using the example above you could, for example, ensure component names follow a naming convention.

// in cookiecutter.config.js
module.exports = [
    {
       name: "Normal React Component",
        templatePath: "templates/COMPONENT_NAME/index.js",
        outputPath: "src/components/",
        fields: [
            {
                templateVariable: 'COMPONENT_NAME',
                question: "What is the component's name?",
+               errorMessage: 'A component must be in PascalCase and can only include letters.',
+               isValid(value) {
+                   return !!value.match(/^[A-Z][a-z]+(?:[A-Z][a-z]+)*$/g);
+               }
            }
        ]
    }
];

Select style options at the field level

Set the options key in the fields object to enable user-selectable responses to the template variables.

// in cookiecutter.config.js
module.exports = [
    {
       name: "Normal React Component",
        templatePath: "templates/COMPONENT_NAME/index.js",
        outputPath: "src/components/",
        fields: [
            {
                templateVariable: 'COMPONENT_NAME',
                question: "What is the component's name?",
+               choices: ["CoolComponent", "BigComponent", "TestComponent"],
            }
        ]
    }
];

Multiple templates

You can configure multiple templates and Cookiecutter will let you pick which template to use. The template's 'name' is what will be used in the CLI when asking which template to use.

You can specify multiple templates like so:

// in cookiecutter.config.js
module.exports = [
  {
    // Configuration for the 1st template
  },
  {
    // Configuration for the 2nd template
  }
];

Templates with folders

If you specify a folder as a template, then the folder will be created in the output directory as well. This is useful if you have a folder structure such as:

- ComponentName
    - index.js
    - styles.css

Cookiecutter will recursively copy all files within your templates folder and replace any occurrences of your specified fields.

If you don't want this behavior, specify a file as your template's templatePath.

Custom config location

If you would like your config to be somewhere else you can use the -c=path/to/your/config.js flag when you call cookiecutter.

Contributing

After cloning the repo yarn install.

You can play with the cli in the 'playground' folder. To do this, cd into it and run . run.sh. This is like running the cli once it's published and on npm but allows you to work on it locally.

To run tests run yarn test. To lint files (this will also happen in CircleCI when you open a PR): yarn lint

Roadmap/Plans

  • Offer a set of helpers for validation user input. Esp. for common 'cases' such as snake_case, PascalCase etc.
  • Allow users to specify a custom path for their config.
  • Offer the ability for people to show a message that is only shown AFTER a template is successfully rendered. This could be helpful for things such as help-text such as: 'You can import this component like so: ...'

cookiecutter's People

Contributors

greenkeeper[bot] avatar mattvagni avatar tejovanthwork avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cookiecutter's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Exit code is incorrect on failure

When I run cookiecutter without a config file, it prints an error message to indicate the failure. But the exit code is still zero which causes issues in automation. E.g invocation and output:

ashoknn@PF0ZBVNJ:~/temp$ ./node_modules/.bin/cookiecutter
! Cannot find module '/home/ashoknn/temp/cookiecutter.config.js'
  at Function.Module._resolveFilename (module.js:543:15)
  at Function.Module._load (module.js:470:25)
  at Module.require (module.js:593:17)
  at require (internal/module.js:11:18)
  at getConfig (/home/ashoknn/bbgithub/temp/node_modules/cookiecutter/src/lib/config.js:103:20)
  at Promise.resolve.then (/home/ashoknn/temp/node_modules/cookiecutter/src/index.js:15:24)
  at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:118:7)
  at Function.Module.runMain (module.js:692:11)
  at startup (bootstrap_node.js:194:16)

ashoknn@PF0ZBVNJ:~/temp$ echo $?
0

Improvement suggestion: templatePath should be resolved relative to config location

We have a shared NPM package that we distribute to our teams for creating infrastructure. Im hoping to use this to generate base structures and components, but it would be good to have the cookiecutter templates distributed as part of that project.

I can achieve having the config in the node module by having the shred library list cookie cutter as a dependency and that puts the CLI in node_modules/.bin. I can call it providing the config with the command be: cookiecutter -c=node_modules/my-shared-library/cookiecutter.config.js, but then templatePath resolves to the location im caling the CLI from. The error i get is:

❯ cookiecutter -c=node_modules/@deepcrawl/base-cdk-app/cookiecutter.config.js
? What is the component's name? test
! ENOENT: no such file or directory, stat '/home/matt/source/playground/generator-test/examples/base-app'
  at Object.statSync (node:fs:1596:3)
  at Object.statSync (/home/matt/source/playground/generator-test/node_modules/graceful-fs/polyfills.js:319:16)
  at isDirectory (/home/matt/source/playground/generator-test/node_modules/cookiecutter/src/lib/renderer.js:27:19)
  at renderFiles (/home/matt/source/playground/generator-test/node_modules/cookiecutter/src/lib/renderer.js:21:30)
  at /home/matt/source/playground/generator-test/node_modules/cookiecutter/src/index.js:36:16

Set outputPath as a variable

Hey,
A project I'm working on requires different components nested inside each other.
A feature request would be to allow me to set the outputPath as an input, so that I can decide where to have the files dumped finally.
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.