Source code for labelord.helpers

"""Helpers module

This module contains helper functions for use by other modules.
"""

import click
import configparser
import os
import sys

from .constants import DEFAULT_CONFIG_FILE, DEFAULT_ERROR_RETURN
from .constants import GH_ERROR_RETURN, NO_GH_TOKEN_RETURN
from .constants import NO_REPOS_SPEC_RETURN, NO_LABELS_SPEC_RETURN
from .printers import Printer, QuietPrinter, VerbosePrinter
from .processors import RunProcessor, DryRunProcessor

[docs]def create_config(config_filename=None, token=None): """Creates configuration object This function parses configuration file and GitHub API token into configuration object. Example: .. testcode:: import configparser import labelord cfg = labelord.helpers.create_config('../config.example.cfg', '123456') .. doctest:: >>> cfg['github']['token'] '123456' >>> cfg['github']['webhook_secret'] 'MY_WEBHOOK_SECRET' >>> cfg['labels']['Bug'] 'FF0000' >>> cfg['others']['template-repo'] 'MarekSuchanek/myLabels' >>> cfg['repos']['MarekSuchanek/repo1'] 'on' >>> cfg['repos']['CVUT/MI-PYT'] 'off' Args: config_filename (Optional[str]): Path to configuration file, default: None. token (Optional[str]): GitHub API token, default: None. Returns: configparser.ConfigParser: Parsed configuration object. """ cfg = configparser.ConfigParser() cfg.optionxform = str cfg_filename = config_filename or DEFAULT_CONFIG_FILE if os.access(cfg_filename, os.R_OK): with open(cfg_filename) as f: cfg.read_file(f) if token is not None: cfg.read_dict({'github': {'token': token}}) return cfg
[docs]def extract_labels(gh, template_opt, cfg): """Extracts GitHub labels from various locations This function lists labels from specified GitHub repository, from template repository specified in configuration file, or from 'labels' section in the configuration file. Example: .. testcode:: import labelord gh = labelord.github.GitHub('123456') cfg = labelord.helpers.create_config('../config.example.cfg', '123456') cfg.pop('others', None) labels = labelord.helpers.extract_labels(gh, None, cfg) .. doctest:: >>> labels['Idea'] '23FB89' Args: gh (GitHub): GitHub class instance. template_opt (str): Template repository to get list of labels from. cfg (configparser.ConfigParser): Parsed configuration object. Returns: dict: Color for each extracted label. """ if template_opt is not None: return gh.list_labels(template_opt) if cfg.has_section('others') and 'template-repo' in cfg['others']: return gh.list_labels(cfg['others']['template-repo']) if cfg.has_section('labels'): return {name: str(color) for name, color in cfg['labels'].items()} click.echo('No labels specification has been found', err=True) sys.exit(NO_LABELS_SPEC_RETURN)
[docs]def extract_repos(cfg): """Extracts GitHub repositories from configuration This function extracts list of GitHub repositories from parsed configuration object. Example: .. testcode:: import labelord cfg = labelord.helpers.create_config('../config.example.cfg', '123456') repos = labelord.helpers.extract_repos(cfg) .. doctest:: >>> 'MarekSuchanek/repo1' in repos True >>> 'CVUT/MI-PYT' in repos False >>> 'MarekSuchanek/repo3' in repos False Args: cfg (configparser.ConfigParser): Parsed configuration object. Returns: list: List of repositories. """ if cfg.has_section('repos'): repos = cfg['repos'].keys() return [r for r in repos if cfg['repos'].getboolean(r, False)] click.echo('No repositories specification has been found', err=True) sys.exit(NO_REPOS_SPEC_RETURN)
[docs]def pick_printer(verbose, quiet): """Returns specified printer This function returns a Printer based on specified parameters. Args: verbose (bool): Whether to return a VerbosePrinter. quiet (bool): Whether to return a QuietPrinter. Returns: Printer: Instance of a Printer (Printer, QuietPrinter or VerbosePrinter). """ if verbose and not quiet: return VerbosePrinter if quiet and not verbose: return QuietPrinter return Printer
[docs]def pick_runner(dry_run): """Returns specified processor This function returns a Processor based on specified parameters. Args: dry_run (bool): Whether to return a DryRunProcessor. Returns: Printer: Instance of a Processor (RunProcessor or DryRunProcessor). """ return DryRunProcessor if dry_run else RunProcessor
[docs]def gh_error_return(github_error): """Gets return code based on a GitHub error This function returns appropriate return code for a status code returned by GitHub API. Example: .. testcode:: import requests import labelord res = requests.Response() res.status_code = 401 res.json = lambda: {} gh_error = labelord.github.GitHubError(res) .. doctest:: >>> labelord.helpers.gh_error_return(gh_error) 4 .. testcode:: gh_error.status_code = 404 .. doctest:: >>> labelord.helpers.gh_error_return(gh_error) 5 Args: github_error (GitHubError): Error returned by GitHub API. Returns: int: Return code. """ return GH_ERROR_RETURN.get(github_error.status_code, DEFAULT_ERROR_RETURN)
[docs]def retrieve_github_client(ctx): """Retrieves GitHub class instance This function gets GitHub class instance from configuration for communitation with GitHub API. Args: ctx (click.Context): Click context object. Returns: GitHub: GitHub class instance """ if 'GitHub' not in ctx.obj: click.echo('No GitHub token has been provided', err=True) sys.exit(NO_GH_TOKEN_RETURN) return ctx.obj['GitHub']