radeklat / delfino

A toolbox of command line helper script, wrapping tools used during Python development.
MIT License
12 stars 3 forks source link

[idea] Add API to configure environment variable for context #27

Closed shimpeko closed 1 year ago

shimpeko commented 2 years ago

What

I'd like to propose adding API to configure environment variable for AppContext; and adding AppContext.run() which respect the configured context.

It means we should always use AppContext.run() over execution.run() when possible.

Example of new API:

update_path = {"PYTHONPATH", delfino.sources_directory}
with app_context.set_env(env_update_path: update_path) as ctx:
    click_context.forward(test_unit)
    ctx.run(...)

Why

With existing design, it is hard to pass environment variable to child commands. We need to write custom code to set/unset environment variable when we want to pass it to child command.

Example:

org_pythonpath = os.environ.get("PYTHONPATH", "")
os.environ["PYTHONPATH"] = org_pythonpath + os.pathsep + str(delfino.sources_directory)
click_context.forward(test_unit)
os.environ["PYTHONPATH"] = org_pythonpath
shimpeko commented 2 years ago

Another options is providing a helper function to set/unset env var. But my solution is more explicit and it will not provide multiple ways to configure environment variables (always set the env parameter of subprocess.run()).