Skip to content

Commit

Permalink
Improve user docs for writing hooks (cookiecutter#1057)
Browse files Browse the repository at this point in the history
This PR adds documentation based on my experience writing a hook for
the first time.

This adds a new section to hooks.rst called "Writing hooks" that
includes topics related to writing pre/post-generate hooks:

- exit status (restructured from a note)
- current working directory of a script when its run
- highlight that Cookiecutter evaluates jinja syntax in the scripts
  • Loading branch information
jonathansick authored and pydanny committed Mar 26, 2018
1 parent 83c3d6b commit 75d67a5
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions docs/advanced/hooks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,40 @@ hooks, as these can be run on any platform. However, if you intend for your
template to only be run on a single platform, a shell script (or `.bat` file
on Windows) can be a quicker alternative.

.. note::
Make sure your hook scripts work in a robust manner. If a hook script fails
(that is, `if it finishes with a nonzero exit status
<https://docs.python.org/3/library/sys.html#sys.exit>`_), the project
generation will stop and the generated directory will be cleaned up.
Writing hooks
-------------

Here are some details on how to write pre/post-generate hook scripts.

Exit with an appropriate status
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Make sure your hook scripts work in a robust manner. If a hook script fails
(that is, `if it finishes with a nonzero exit status
<https://docs.python.org/3/library/sys.html#sys.exit>`_), the project
generation will stop and the generated directory will be cleaned up.

Current working directory
^^^^^^^^^^^^^^^^^^^^^^^^^

When the hook scripts script are run, their current working directory is the
root of the generated project. This makes it easy for a post-generate hook to
find generated files using relative paths.

Template variables are rendered in the script
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Just like your project template, Cookiecutter also renders Jinja template
syntax in your scripts. This lets you incorporate Jinja template variables in
your scripts. For example, this line of Python sets ``module_name`` to the
value of the ``cookiecutter.module_name`` template variable:

.. code-block:: python
module_name = '{{ cookiecutter.module_name }}'
Example: Validating template variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--------------------------------------

Here is an example of script that validates a template variable
before generating the project, to be used as ``hooks/pre_gen_project.py``:
Expand Down

0 comments on commit 75d67a5

Please sign in to comment.