Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(config): allows user to read the cookiecutterrc file from various locations #1483

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 29 additions & 9 deletions cookiecutter/config.py
Expand Up @@ -14,7 +14,34 @@

logger = logging.getLogger(__name__)

USER_CONFIG_PATH = os.path.expanduser('~/.cookiecutterrc')

def _expand_path(path):
"""Expand both environment variables and user home in the given path."""
path = os.path.expandvars(path)
path = os.path.expanduser(path)
return path


def _find_first_path(paths):
"""Find the first existing path from a list."""
logger.debug("_find_first_path: %s", paths)
for path in paths:
if path:
path = _expand_path(path)
logger.debug("Trying to load: %s", path)
if os.path.exists(path):
return path
return None


USER_CONFIG_PATH = _find_first_path(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally, I do not like execution of slightly more complex code on initialization time. This function should be called in merge_configs below.

[
os.environ.get("COOKIECUTTER_USER_CONFIG_PATH"),
"$XDG_CONFIG_HOME/cookiecutter/cookiecutterrc",
"$XDG_CONFIG_HOME/cookiecutterrc",
os.path.expanduser('~/.cookiecutterrc'),
]
)

BUILTIN_ABBREVIATIONS = {
'gh': 'https://github.com/{0}.git',
Expand All @@ -30,13 +57,6 @@
}


def _expand_path(path: str) -> str:
"""Expand both environment variables and user home in the given path."""
path = os.path.expandvars(path)
path = os.path.expanduser(path)
return path


def merge_configs(default, overwrite):
"""Recursively update a dict with the key/value pair of another.

Expand Down Expand Up @@ -127,7 +147,7 @@ def get_user_config(
except KeyError:
# Load an optional user config if it exists
# otherwise return the defaults
if os.path.exists(USER_CONFIG_PATH):
if USER_CONFIG_PATH and os.path.exists(USER_CONFIG_PATH):
logger.debug("Loading config from %s.", USER_CONFIG_PATH)
return get_config(USER_CONFIG_PATH)
else:
Expand Down