def generate_context( context_file='cookiecutter.json', default_context=None, context_key=None, extra_context=None, ): """Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value pairs for populating the cookiecutter's variables. :param default_context: Dictionary containing config to take into account. :param extra_context: Dictionary containing configuration overrides """ context = OrderedDict([]) try: obj = read_config_file(context_file) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more # friendly for the developer or user. full_fpath = os.path.abspath(context_file) json_exc_message = str(e) our_exc_message = ('JSON decoding error while loading "{0}". Decoding' ' error details: "{1}"'.format( full_fpath, json_exc_message)) raise ContextDecodingException(our_exc_message) # Add the Python object to the context dictionary if not context_key: file_name = os.path.split(context_file)[1] file_stem = file_name.split('.')[0] context[file_stem] = obj else: context[context_key] = obj # Overwrite context variable defaults with the default context from the # user's global config, if available if default_context: apply_overwrites_to_context(obj, default_context) if extra_context: apply_overwrites_to_context(obj, extra_context) logger.debug('Context generated is %s', context) return context
def generate_context( context_file='rubric.json', default_context=None, extra_context=None ): """Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value pairs for populating the cookiecutter's variables. :param default_context: Dictionary containing config to take into account. :param extra_context: Dictionary containing configuration overrides """ context = OrderedDict([]) if context_file.endswith('.json'): try: with open(context_file) as file_handle: context = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more # friendly for the developer or user. full_fpath = os.path.abspath(context_file) json_exc_message = str(e) our_exc_message = ( 'JSON decoding error while loading "{0}". Decoding' ' error details: "{1}"'.format(full_fpath, json_exc_message)) raise ContextDecodingException(our_exc_message) else: # FIXME handle potential errors with open(context_file, encoding='utf-8') as file_handle: context = ordered_load(file_handle, yaml.SafeLoader) # Overwrite context variable defaults with the default context from the # user's global config, if available if default_context: apply_overwrites_to_context(context, default_context) if extra_context: apply_overwrites_to_context(context, extra_context) logger.debug('Context generated is %s', context) return context