I would like to have a file that is optionally added in my python cookiecutter project.
An example would be in cookiecutter.json have the variable
{"settings_file": true}
which would create a file settings.py
at the root of my directory (with maybe some contents).
Does cookiecutter offer an option to do this? Or should I be using the post processing hook to write a script which creates the files (which I feel like is not the most elegant solution).
I'm going to answer my own question, in case someone runs into it: it is not yet implemented as a feature of the project, see ticket for enhancement here: https://github.com/audreyr/cookiecutter/issues/127
The "least ugly" solution I have come up with is to create the files every time, and clean them up during the post hook (you could also create them during the post hook, but would lose cookiecutter templating advantages)
According to the official docs, you can use a post-generate hook script (hooks/post_gen_project.py
)
(Copying the snippet here for those skimming through)
import os
import sys
REMOVE_PATHS = [
'{% if cookiecutter.packaging != "pip" %} requirements.txt {% endif %}',
'{% if cookiecutter.packaging != "poetry" %} poetry.lock {% endif %}',
]
for path in REMOVE_PATHS:
path = path.strip()
if path and os.path.exists(path):
if os.path.isdir(path):
os.rmdir(path)
else:
os.unlink(path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With