Jonathon Vandezande
Jonathon Vandezande

Reputation: 2476

Run custom function to generate choices in cookiecutter.json

I need to generate choices for a cookiecutter at runtime that reflect the programs available on a system. The code to do so is ≈30 lines, and thus too complicated to be placed in cookiecutter.json. Where should it be placed and how should it be invoked?

e.g. cookiecutter.json

{
  "project_name": "",
  "program_version": ["generate_program_choices()"]
}

Note: this is for a data science cookiecutter, that will need to use the same version of the program throughout its life (a few months), the program is installed externally from the project, and the project will not be used in multiple locations, thus hardcoding this variable is acceptable.

Upvotes: 0

Views: 92

Answers (1)

Hai Vu
Hai Vu

Reputation: 40773

The cookiecutter.json file is static, that means you cannot place a function there and expect to see the function's output. A work around is to create a short script to edit the JSON file:

# import generate_program_choices

with open("cookiecutter.json") as stream:
    config = json.load(stream)

config["program_version"] = generate_program_choices()
with open("cookiecutter.json", "w") as stream:
    json.dump(config, stream, indent=4)

Then, we run this script before running cookiecutter.

Upvotes: 0

Related Questions