Skip to content

git repository name

Loic Coyle edited this page May 16, 2020 · 3 revisions

Say you want to use the name of the git repository in your template and have clinja automatically find it's value.

To achieve this you will have to make use of clinja's dynamic source.

Add the following to your dynamic.py file (use clinja --help to find it):

# This is clinja's dynamic source.
# Use this file to dynamically compute jinja variables form the variables
# provided at run time:

# TEMPLATE (Path): Path to the template, is None when using stdin.
# DESTINATION (Path): Path to the destination, is None when using stdout.
# RUN_CWD (Path): Directory were the clinja command was run.
# STATIC_VARS (dict): Dictionary of static variables.

# This file should populate the DYNAMIC_VARS dictionary:

# DYNAMIC_VARS (dict): Dictionary of dynamic variables.

from pathlib import Path
from configparser import ConfigParser


def prep_folders(folders: list) -> list:
    '''Takes a list of pathlib Paths, and return a list of parent directories.
    '''
    folders = [folder for folder in folders if folder is not None]
    folders = [folder.parent if not folder.is_dir() else folder for folder in folders]
    return folders


def get_git_repo_name(check_folders: list) -> str:
    for folder in check_folders:
        maybe_git_config = folder / '.git/config'
        if maybe_git_config.is_file():
            conf = ConfigParser()
            conf.read(maybe_git_config)
            git_url = conf.get('remote "origin"', 'url', fallback=None)
            if git_url is not None:
                if git_url.startswith('git@'):
                    return Path(git_url).stem
                else:
                    return Path(git_url).name


# DESTINATION and TEMPLATE can be None when clinja is run using stdin or stdout
# the prep_folders function, drops the Nones and gets the parent folders of the
# paths
check_folders = prep_folders([DESTINATION, RUN_CWD, TEMPLATE])

# Try to get the git repository name from the .git/config file and add it to the
# dynamic variables dict.
DYNAMIC_VARS['git_repo_name'] = get_git_repo_name(check_folders)

See it in action

asciicast

Clone this wiki locally