#!/usr/bin/env python
"""
Report of commits from configured repo names.

Generate a repo commit report using configured values including the owner name
and one or more repos. This script cannot pickup repos dynamically.

A second CSV of summarized commit data by repo is written out as well.
"""
import argparse
import datetime
from collections import defaultdict

import lib
import lib.text
import repo_commits
from config import COMMIT_REPORT_CONF

CSV_OUT_NAME = "repos-commits--configured--end-{end_date}--start-{start_date}.csv"
CSV_OUT_NAME_SUMMARY = (
    "repos-commits--configured-summary--end-{end_date}--start-{start_date}.csv"
)


def report_config():
    """
    Get commit report values from config.

    Returns a tuple of strings.
    """
    owner = COMMIT_REPORT_CONF["owner"]
    repo_names = COMMIT_REPORT_CONF["repo_names"]

    input_start_date = COMMIT_REPORT_CONF["start_date"]
    if input_start_date is None:
        start_date = None
    elif isinstance(input_start_date, int):
        start_date = lib.time.days_ago(input_start_date)
    else:
        # Stringify a datetime object generated by PyYAML.
        start_date = str(input_start_date)

    return owner, repo_names, start_date


def commits_to_csv(owner, repo_names, start_date=None):
    """
    Fetch commits for given repos and append to a CSV after each repo is done.
    """
    filename = CSV_OUT_NAME.format(
        end_date=datetime.date.today(),
        start_date=start_date if start_date else "INIT",
    )
    path = lib.VAR_DIR / filename

    summary_filename = CSV_OUT_NAME_SUMMARY.format(
        end_date=datetime.date.today(),
        start_date=start_date if start_date else "INIT",
    )
    summary_path = lib.VAR_DIR / summary_filename

    print(f"Start: {start_date if start_date else 'first commit'}")
    print()

    repos_summary = []

    for repo_name in repo_names:
        commits = repo_commits.get_commits(owner, repo_name, start_date)
        # TODO delete if it is first round. Or wait until the end and write out
        # everything with overwriting but that just means an incomplete report
        # is not generated of the script aborts which might be okay

        lib.write_csv(path, commits, append=True)

        # TODO Move this to a separate function, possibly using commits returned
        # from the function.
        repo_summary = defaultdict(int)
        repo_summary["name"] = repo_name
        repo_summary["commits"] = len(commits)
        # Note that lines changed or files changed would not be accurate when
        # adding commits so that is left out.
        for commit in commits:
            repo_summary["additions"] += commit["additions"]
            repo_summary["deletions"] += commit["deletions"]
        repos_summary.append(repo_summary)

    lib.write_csv(summary_path, repos_summary)


def main() -> None:
    """
    Main command-line entrypoint.
    """
    parser = argparse.ArgumentParser(description="Repo commits report")

    parser.add_argument(
        "-d",
        "--dry-run",
        action="store_true",
        help="If supplied, list configured repos and date range",
    )

    args = parser.parse_args()

    owner, repo_names, start_date = report_config()

    if args.dry_run:
        pretty_text = lib.text.prettify(
            dict(owner=owner, repo_names=repo_names, start_date=start_date)
        )
        print(pretty_text)
    else:
        commits_to_csv(owner, repo_names, start_date)


if __name__ == "__main__":
    main()

#!/usr/bin/env python
"""
Report of commits from configured repo names.

Generate a repo commit report using configured values including the owner name
and one or more repos. This script cannot pickup repos dynamically.

A second CSV of summarized commit data by repo is written out as well.
"""
import argparse
import datetime
from collections import defaultdict

import lib
import lib.text
import repo_commits
from config import COMMIT_REPORT_CONF

CSV_OUT_NAME = "repos-commits--configured--end-{end_date}--start-{start_date}.csv"
CSV_OUT_NAME_SUMMARY = (
    "repos-commits--configured-summary--end-{end_date}--start-{start_date}.csv"
)


def report_config():
    """
    Get commit report values from config.

    Returns a tuple of strings.
    """
    owner = COMMIT_REPORT_CONF["owner"]
    repo_names = COMMIT_REPORT_CONF["repo_names"]

    input_start_date = COMMIT_REPORT_CONF["start_date"]
    if input_start_date is None:
        start_date = None
    elif isinstance(input_start_date, int):
        start_date = lib.time.days_ago(input_start_date)
    else:
        # Stringify a datetime object generated by PyYAML.
        start_date = str(input_start_date)

    return owner, repo_names, start_date


def commits_to_csv(owner, repo_names, start_date=None):
    """
    Fetch commits for given repos and append to a CSV after each repo is done.
    """
    filename = CSV_OUT_NAME.format(
        end_date=datetime.date.today(),
        start_date=start_date if start_date else "INIT",
    )
    path = lib.VAR_DIR / filename

    summary_filename = CSV_OUT_NAME_SUMMARY.format(
        end_date=datetime.date.today(),
        start_date=start_date if start_date else "INIT",
    )
    summary_path = lib.VAR_DIR / summary_filename

    print(f"Start: {start_date if start_date else 'first commit'}")
    print()

    repos_summary = []

    for repo_name in repo_names:
        commits = repo_commits.get_commits(owner, repo_name, start_date)
        # TODO delete if it is first round. Or wait until the end and write out
        # everything with overwriting but that just means an incomplete report
        # is not generated of the script aborts which might be okay

        lib.write_csv(path, commits, append=True)

        # TODO Move this to a separate function, possibly using commits returned
        # from the function.
        repo_summary = defaultdict(int)
        repo_summary["name"] = repo_name
        repo_summary["commits"] = len(commits)
        # Note that lines changed or files changed would not be accurate when
        # adding commits so that is left out.
        for commit in commits:
            repo_summary["additions"] += commit["additions"]
            repo_summary["deletions"] += commit["deletions"]
        repos_summary.append(repo_summary)

    lib.write_csv(summary_path, repos_summary)


def main() -> None:
    """
    Main command-line entrypoint.
    """
    parser = argparse.ArgumentParser(description="Repo commits report")

    parser.add_argument(
        "-d",
        "--dry-run",
        action="store_true",
        help="If supplied, list configured repos and date range",
    )

    args = parser.parse_args()

    owner, repo_names, start_date = report_config()

    if args.dry_run:
        pretty_text = lib.text.prettify(
            dict(owner=owner, repo_names=repo_names, start_date=start_date)
        )
        print(pretty_text)
    else:
        commits_to_csv(owner, repo_names, start_date)


if __name__ == "__main__":
    main()

#!/usr/bin/env python Report of commits from configured repo names.  Generate a repo commit report using configured values including the owner name and one or more repos. This script cannot pickup repos dynamically.  A second CSV of summarized commit data by repo is written out as well. Get commit report values from config.      Returns a tuple of strings. # Stringify a datetime object generated by PyYAML. Fetch commits for given repos and append to a CSV after each repo is done. # TODO delete if it is first round. Or wait until the end and write out # everything with overwriting but that just means an incomplete report # is not generated of the script aborts which might be okay # TODO Move this to a separate function, possibly using commits returned # from the function. # Note that lines changed or files changed would not be accurate when # adding commits so that is left out. Main command-line entrypoint.