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

3

14

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

Phenomenon answered 26/1, 2016 at 0:34 Comment(0)
P
15

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)

Phenomenon answered 26/1, 2016 at 17:58 Comment(0)
U
6

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

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)
Unction answered 11/8, 2021 at 13:15 Comment(1)
sys is not usedQuintuplicate
G
0

It is possible to use Jinja templating and conditionals in file names.

As such you can have a file named {% if cookiecutter.settings_file == "true" -%} __main__.py {%- endif %} which will only be created if settings_file is true.

Note that boolean variables are not yet supported in Cookiecutter, although there is a merged PR to add this functionality. One way to solve it now is to use e.g., ["true", "false"] as values.

Glogau answered 16/8, 2022 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.