Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a file optional based on a variable's value in cookiecutter.json

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).

like image 697
nichochar Avatar asked Jan 26 '16 00:01

nichochar


2 Answers

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)

like image 169
nichochar Avatar answered Nov 21 '22 00:11

nichochar


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)
like image 43
partmor Avatar answered Nov 20 '22 23:11

partmor