hassle.hassle_config API documentation

# hassle.hassle_config

View Source

      1import argparse
      2from pathlib import Path
      3
      4import tomlkit
      5
      6root = Path(__file__).parent
      7
      8
      9def get_args() -> argparse.Namespace:
     10    parser = argparse.ArgumentParser()
     11
     12    parser.add_argument(
     13        "-n",
     14        "--name",
     15        type=str,
     16        default=None,
     17        help=""" Your name. This will be used to populate the 'authors' field of a packages 'pyproject.toml'. """,
     18    )
     19
     20    parser.add_argument(
     21        "-e",
     22        "--email",
     23        type=str,
     24        default=None,
     25        help=""" Your email. This will be used to populate the 'authors' field of a packages 'pyproject.toml'. """,
     26    )
     27
     28    parser.add_argument(
     29        "-g",
     30        "--github_username",
     31        type=str,
     32        default=None,
     33        help=""" Your github account name. When creating a new package,
     34        say with the name 'mypackage', the pyproject.toml 'Homepage' field
     35        will be set to 'https://github.com/{github_username}/mypackage'
     36        and the 'Source code' field will be set to
     37        'https://github.com/{github_username}/mypackage/tree/main/src/mypackage'.""",
     38    )
     39
     40    parser.add_argument(
     41        "-d",
     42        "--docs_url",
     43        type=str,
     44        default=None,
     45        help=""" The template url to be used in your pyproject.toml file
     46        indicating where your project docs will be hosted.
     47        Pass the url such that the spot the actual package name will go is
     48        held by '$name', e.g. 'https://somedocswebsite/user/projects/$name'.
     49        If 'hassle_config.toml' didn't exist prior to running this tool and nothing
     50        is given for this arg, it will default to using the package's github
     51        url. e.g. for package 'mypackage' the url will be
     52        'https://github.com/{your_github_name}/mypackage/tree/main/docs' """,
     53    )
     54
     55    parser.add_argument(
     56        "-t",
     57        "--tag_prefix",
     58        type=str,
     59        default=None,
     60        help=""" The tag prefix to use with git when tagging source code versions.
     61        e.g. hassle will use the current version in your pyproject.toml file to when
     62        adding a git tag. If you've passed 'v' to this arg and the version of your
     63        hypothetical package is '1.0.1', it will be tagged as 'v1.0.1'.
     64        If 'hassle_config.toml' didn't exist prior to running this tool and you
     65        don't pass anything for this arg, it will default to ''.""",
     66    )
     67
     68    args = parser.parse_args()
     69
     70    return args
     71
     72
     73def config_exists() -> bool:
     74    """Check if hassle_config.toml exists."""
     75    return (root / "hassle_config.toml").exists()
     76
     77
     78def load_config() -> dict:
     79    "Load and return hassle_config contents if it exists."
     80    if config_exists():
     81        return tomlkit.loads((root / "hassle_config.toml").read_text())
     82    else:
     83        raise FileNotFoundError(
     84            f"load_config() could not find {root/'hassle_config.toml'}.\nRun hassle_config to set it."
     85        )
     86
     87
     88def write_config(config: dict):
     89    """Dump config to "hassle_config.toml."""
     90    (root / "hassle_config.toml").write_text(tomlkit.dumps(config))
     91
     92
     93def warn():
     94    print("hassle_config.toml has not been set.")
     95    print("Run hassle_config to set it.")
     96    print("Run 'hassle_config -h' for help.")
     97
     98
     99def create_config(
    100    name: str = None,
    101    email: str = None,
    102    github_username: str = None,
    103    docs_url: str = None,
    104    tag_prefix: str = None,
    105):
    106    """Create hassle_config.toml from given args."""
    107    print(f"Manual edits can be made at {root/'hassle_config.toml'}")
    108    if not config_exists():
    109        config = {}
    110        if name and email:
    111            config["authors"] = [{"name": name, "email": email}]
    112        elif name:
    113            config["authors"] = [{"name": name}]
    114        elif email:
    115            config["authors"] = [{"email": email}]
    116        else:
    117            # In case anything upstream would fail if nothing is present for 'authors'
    118            config["authors"] = [{"name": "", "email": ""}]
    119        config["project_urls"] = {
    120            "Homepage": "",
    121            "Documentation": "",
    122            "Source code": "",
    123        }
    124        config["git"] = {}
    125    else:
    126        config = load_config()
    127        if name and email:
    128            config["authors"].append({"name": name, "email": email})
    129        elif name:
    130            config["authors"].append({"name": name})
    131        elif email:
    132            config["authors"].append({"email": email})
    133
    134    if github_username:
    135        config["project_urls"][
    136            "Homepage"
    137        ] = f"https://github.com/{github_username}/$name"
    138        config["project_urls"][
    139            "Source code"
    140        ] = f"{config['project_urls']['Homepage']}/tree/main/src/$name"
    141
    142    if docs_url:
    143        config["project_urls"]["Documentation"] = docs_url
    144    elif github_username and config["project_urls"]["Documentation"] == "":
    145        config["project_urls"][
    146            "Documentation"
    147        ] = f"https://github.com/{github_username}/$name/tree/main/docs"
    148
    149    if tag_prefix:
    150        config["git"]["tag_prefix"] = tag_prefix
    151    elif not config_exists() and not tag_prefix:
    152        config["git"]["tag_prefix"] = ""
    153
    154    if config:
    155        write_config(config)
    156
    157
    158def main(args: argparse.Namespace = None):
    159    if not args:
    160        args = get_args()
    161    create_config(
    162        args.name, args.email, args.github_username, args.docs_url, args.tag_prefix
    163    )
    164
    165
    166if __name__ == "__main__":
    167    main(get_args())

def get_args() -> argparse.Namespace: View Source

    10def get_args() -> argparse.Namespace:
    11    parser = argparse.ArgumentParser()
    12
    13    parser.add_argument(
    14        "-n",
    15        "--name",
    16        type=str,
    17        default=None,
    18        help=""" Your name. This will be used to populate the 'authors' field of a packages 'pyproject.toml'. """,
    19    )
    20
    21    parser.add_argument(
    22        "-e",
    23        "--email",
    24        type=str,
    25        default=None,
    26        help=""" Your email. This will be used to populate the 'authors' field of a packages 'pyproject.toml'. """,
    27    )
    28
    29    parser.add_argument(
    30        "-g",
    31        "--github_username",
    32        type=str,
    33        default=None,
    34        help=""" Your github account name. When creating a new package,
    35        say with the name 'mypackage', the pyproject.toml 'Homepage' field
    36        will be set to 'https://github.com/{github_username}/mypackage'
    37        and the 'Source code' field will be set to
    38        'https://github.com/{github_username}/mypackage/tree/main/src/mypackage'.""",
    39    )
    40
    41    parser.add_argument(
    42        "-d",
    43        "--docs_url",
    44        type=str,
    45        default=None,
    46        help=""" The template url to be used in your pyproject.toml file
    47        indicating where your project docs will be hosted.
    48        Pass the url such that the spot the actual package name will go is
    49        held by '$name', e.g. 'https://somedocswebsite/user/projects/$name'.
    50        If 'hassle_config.toml' didn't exist prior to running this tool and nothing
    51        is given for this arg, it will default to using the package's github
    52        url. e.g. for package 'mypackage' the url will be
    53        'https://github.com/{your_github_name}/mypackage/tree/main/docs' """,
    54    )
    55
    56    parser.add_argument(
    57        "-t",
    58        "--tag_prefix",
    59        type=str,
    60        default=None,
    61        help=""" The tag prefix to use with git when tagging source code versions.
    62        e.g. hassle will use the current version in your pyproject.toml file to when
    63        adding a git tag. If you've passed 'v' to this arg and the version of your
    64        hypothetical package is '1.0.1', it will be tagged as 'v1.0.1'.
    65        If 'hassle_config.toml' didn't exist prior to running this tool and you
    66        don't pass anything for this arg, it will default to ''.""",
    67    )
    68
    69    args = parser.parse_args()
    70
    71    return args

def config_exists() -> bool: View Source

    74def config_exists() -> bool:
    75    """Check if hassle_config.toml exists."""
    76    return (root / "hassle_config.toml").exists()

Check if hassle_config.toml exists.

def load_config() -> dict: View Source

    79def load_config() -> dict:
    80    "Load and return hassle_config contents if it exists."
    81    if config_exists():
    82        return tomlkit.loads((root / "hassle_config.toml").read_text())
    83    else:
    84        raise FileNotFoundError(
    85            f"load_config() could not find {root/'hassle_config.toml'}.\nRun hassle_config to set it."
    86        )

Load and return hassle_config contents if it exists.

def write_config(config: dict): View Source

    89def write_config(config: dict):
    90    """Dump config to "hassle_config.toml."""
    91    (root / "hassle_config.toml").write_text(tomlkit.dumps(config))

Dump config to "hassle_config.toml.

def warn(): View Source

    94def warn():
    95    print("hassle_config.toml has not been set.")
    96    print("Run hassle_config to set it.")
    97    print("Run 'hassle_config -h' for help.")

def create_config( name: str = None, email: str = None, github_username: str = None, docs_url: str = None, tag_prefix: str = None): View Source

    100def create_config(
    101    name: str = None,
    102    email: str = None,
    103    github_username: str = None,
    104    docs_url: str = None,
    105    tag_prefix: str = None,
    106):
    107    """Create hassle_config.toml from given args."""
    108    print(f"Manual edits can be made at {root/'hassle_config.toml'}")
    109    if not config_exists():
    110        config = {}
    111        if name and email:
    112            config["authors"] = [{"name": name, "email": email}]
    113        elif name:
    114            config["authors"] = [{"name": name}]
    115        elif email:
    116            config["authors"] = [{"email": email}]
    117        else:
    118            # In case anything upstream would fail if nothing is present for 'authors'
    119            config["authors"] = [{"name": "", "email": ""}]
    120        config["project_urls"] = {
    121            "Homepage": "",
    122            "Documentation": "",
    123            "Source code": "",
    124        }
    125        config["git"] = {}
    126    else:
    127        config = load_config()
    128        if name and email:
    129            config["authors"].append({"name": name, "email": email})
    130        elif name:
    131            config["authors"].append({"name": name})
    132        elif email:
    133            config["authors"].append({"email": email})
    134
    135    if github_username:
    136        config["project_urls"][
    137            "Homepage"
    138        ] = f"https://github.com/{github_username}/$name"
    139        config["project_urls"][
    140            "Source code"
    141        ] = f"{config['project_urls']['Homepage']}/tree/main/src/$name"
    142
    143    if docs_url:
    144        config["project_urls"]["Documentation"] = docs_url
    145    elif github_username and config["project_urls"]["Documentation"] == "":
    146        config["project_urls"][
    147            "Documentation"
    148        ] = f"https://github.com/{github_username}/$name/tree/main/docs"
    149
    150    if tag_prefix:
    151        config["git"]["tag_prefix"] = tag_prefix
    152    elif not config_exists() and not tag_prefix:
    153        config["git"]["tag_prefix"] = ""
    154
    155    if config:
    156        write_config(config)

Create hassle_config.toml from given args.

def main(args: argparse.Namespace = None): View Source

    159def main(args: argparse.Namespace = None):
    160    if not args:
    161        args = get_args()
    162    create_config(
    163        args.name, args.email, args.github_username, args.docs_url, args.tag_prefix
    164    )