src/main.cpp

Tue, 25 Feb 2025 18:46:17 +0100

author
Mike Becker <universe@uap-core.de>
date
Tue, 25 Feb 2025 18:46:17 +0100
changeset 44
de22ded6d50a
parent 41
19cc90878968
permissions
-rw-r--r--

add total commits counters

fixes #605

/* Copyright 2025 Mike Becker. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "settings.h"
#include "repositories.h"
#include "process.h"
#include "heatmap.h"
#include "html.h"

#include <chrono>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>

#include <numeric>

using namespace std::chrono;

static constexpr auto program_version = "1.1.0 (dev)";

static void print_help() {
    fputs(
        "Usage: repoheat [OPTION]... [PATH]...\n\n"
        "Options:\n"
        "   -a, --author <name>       Only report this author\n"
        "                             (repeat option to report multiple authors)\n"
        "   -A, --authormap <file>    Apply an author mapping file\n"
        "   -d, --depth <num>         The search depth (default: 1, max: 255)\n"
        "   -f, --fragment            Output as fragment\n"
        "   -h, --help                Print this help message\n"
        "   -p, --pull                Try to pull the repositories\n"
        "   -s, --separate            Output a separate heat map for each repository\n"
        "   -V, --version             Output the version of this program and exit\n"
        "   -y, --year <year>         The year for which to create the heat map\n"
        "       --hg <path>           Path to hg binary (default: /usr/bin/hg)\n"
        "       --git <path>          Path to git binary (default: /usr/bin/git)\n\n"
        "Scans all specified paths recursively for Mercurial and Git repositories and\n"
        "creates a commit heat map for the specified \033[1myear\033[22m or the current year.\n"
        "By default, the recursion \033[1mdepth\033[22m is one, meaning that this tool assumes that\n"
        "each \033[1mpath\033[22m is either a repository or contains repositories as subdirectories.\n"
        "You can change the \033[1mdepth\033[22m to support other directory structures.\n\n"
        "When you specify the \033[1m--pull\033[22m option, this tool will execute the pull command\n"
        "(and for hg the update command) before retrieving the commit log, assuming\n"
        "to be on the default branch with \033[4mno uncommitted changes\033[24m. If pulling leads to\n"
        "an error, an error message is written to stderr and the process continues\n"
        "with the repository in its current state. This is also the case when pulling\n"
        "would require authorization.\n\n"
        "By default, this tool reports commits from all authors. If you want to include\n"
        "only specific authors in the report, you can use the \033[1m--author\033[22m option with as\n"
        "many authors as you like. You can specify either the full author strings with\n"
        "name and mail address, just the mail address, or even just the local-part of\n"
        "the mail address. In case your repository contains commits from an author who\n"
        "used different names or mail addresses, you can use the \033[1m--authormap\033[22m option\n"
        "to specify a file that contains pairs of author strings, like in the following\n"
        "example:\n\n"
        "   Full Name <full.name@example.org> = New Name <new.name@example.org>\n"
        "   just.mail@example.org = Jus Mail <just.mail@example.org>\n"
        "   jane = Jane Doe <jane.doe@example.org>\n\n"
        "The different variants of full string, only mail address, and only local-part\n"
        "should \033[4monly\033[24m be used on the left-hand side. When you use the \033[1m--author\033[22m option at\n"
        "the same time, you only need to specify the new author names.\n\n"
        "Finally, this tool prints an HTML page to stdout. A separate heap map is\n"
        "generated for each author showing commits across all repositories, unless the\n"
        "\033[1m--separate\033[22m option is specified in which case each repository is displayed with\n"
        "its own heat map. By using the \033[1m--fragment\033[22m option, the tool only outputs a\n"
        "single HTML div container without any header or footer that can be embedded in\n"
        "your custom web page.\n"
        , stderr);
}

static bool chk_arg(const char *arg, const char *opt1, const char *opt2) {
    return strcmp(arg, opt1) == 0 || (opt2 != nullptr && strcmp(arg, opt2) == 0);
}

template<typename T>
static bool parse_unsigned(const char *str, T *result, unsigned long max) {
    char *endptr;
    errno = 0;
    unsigned long d = strtoul(str, &endptr, 10);
    if (*endptr != '\0' || errno == ERANGE) return true;
    if (d < max) {
        *result = d;
        return false;
    } else {
        return true;
    }
}

static int parse_args(fm::settings &settings, int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (chk_arg(argv[i], "-h", "--help")) {
            print_help();
            return 1;
        } else if (chk_arg(argv[i], "-d", "--depth")) {
            if (i + 1 >= argc || parse_unsigned(argv[++i], &settings.depth, 256)) {
                fputs("missing or invalid depth\n", stderr);
                return -1;
            }
        } else if (chk_arg(argv[i], "-y", "--year")) {
            if (i + 1 >= argc || parse_unsigned(argv[++i], &settings.year, 9999)) {
                fputs("missing or invalid year\n", stderr);
                return -1;
            }
        } else if (chk_arg(argv[i], "-a", "--author")) {
            if (i + 1 < argc) {
                settings.authors.emplace_back(argv[++i]);
            } else {
                fputs("missing author name\n", stderr);
                return -1;
            }
        } else if (chk_arg(argv[i], "-p", "--pull")) {
            settings.update_repos = true;
        } else if (chk_arg(argv[i], "-f", "--fragment")) {
            settings.fragment = true;
        } else if (chk_arg(argv[i], "-s", "--separate")) {
            settings.separate = true;
        } else if (chk_arg(argv[i], "-A", "--authormap")) {
            if (i + 1 < argc) {
                if (settings.parse_authormap(argv[++i])) {
                    fputs("parsing authormap failed\n", stderr);
                    return -1;
                }
            } else {
                fputs("missing filename for authormap\n", stderr);
                return -1;
            }
        } else if (chk_arg(argv[i], "-V", "--version")) {
            printf("repoheat version %s\n", program_version);
            return 1;
        } else if (chk_arg(argv[i], "--hg", nullptr)) {
            if (i + 1 < argc) {
                settings.hg.assign(argv[++i]);
            } else {
                fputs("--hg is expecting a path\n", stderr);
                return -1;
            }
        } else if (chk_arg(argv[i], "--git", nullptr)) {
            if (i + 1 < argc) {
                settings.git.assign(argv[++i]);
            } else {
                fputs("--git is expecting a path\n", stderr);
                return -1;
            }
        } else if (argv[i][0] == '-') {
            fprintf(stderr, "Unknown option: %s\n", argv[i]);
            return -1;
        } else {
            settings.paths.emplace_back(argv[i]);
        }
    }

    if (settings.paths.empty()) {
        settings.paths.emplace_back("./");
    }

    return 0;
}

int main(int argc, char *argv[]) {
    // parse settings
    fm::settings settings;
    if (int result = parse_args(settings, argc, argv); result != 0) {
        return result < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
    }

    // check hg and git
    fm::process proc;
    proc.setbin(settings.hg);
    if (proc.exec({"--version"})) {
        fprintf(stderr, "Testing hg binary '%s' failed!\n", settings.hg.c_str());
        return EXIT_FAILURE;
    }
    proc.setbin(settings.git);
    if (proc.exec({"--version"})) {
        fprintf(stderr, "Testing git binary '%s' failed!\n", settings.git.c_str());
        return EXIT_FAILURE;
    }

    // scan for repos
    fm::repositories repos;
    for (auto &&path: settings.paths) {
        repos.scan(path, settings.depth);
    }

    // update repos, if not disabled
    if (settings.update_repos) {
        for (auto &&repo : repos.list()) {
            proc.chdir(repo.path);
            if (repo.type == fm::HG) {
                proc.setbin(settings.hg);
                if (proc.exec({"pull", "-y"})) {
                    fprintf(stderr, "Pulling repo '%s' failed - continue without pull.\n", repo.path.c_str());
                } else if (proc.exec({"update"})) {
                    fprintf(stderr, "Updating repo '%s' failed!\nMaybe there are local changes?\n", repo.path.c_str());
                }
            } else {
                proc.setbin(settings.git);
                if (proc.exec({"pull", "-q"})) {
                    fprintf(stderr, "Pulling repo '%s' failed - continue without pull.\n", repo.path.c_str());
                }
            }
        }
    }

    // determine our reporting range
    year report_year{
        settings.year == fm::settings_current_year
            ? year_month_day{floor<days>(system_clock::now())}.year()
            : year{settings.year}
    };
    year_month_day report_begin{report_year, January, 1d};
    year_month_day report_end{report_year, December, 31d};

    // read the commit logs
    fm::heatmap heatmap;
    for (auto &&repo : repos.list()) {
        if (settings.separate) {
            heatmap.set_repo(repo.name);
        }
        proc.chdir(repo.path);
        if (repo.type == fm::HG) {
            proc.setbin(settings.hg);
            if (proc.exec_log({"log",
                "--date", std::format("{0}-01-01 00:00:00 to {0}-12-31 23:59:59", report_year),
                "--template", "{author}#{date|shortdate}\n"})) {
                fprintf(stderr, "Reading commit log for repo '%s' failed!\n", repo.path.c_str());
                return EXIT_FAILURE;
            }
            heatmap.add(settings, proc.output());
        } else {
            proc.setbin(settings.git);
            if (proc.exec_log({"log",
                "--since", std::format("{0}-01-01 00:00:00", report_year),
                "--until", std::format("{0}-12-31 23:59:59", report_year),
                "--format=tformat:%an <%ae>#%cs"})) {
                fprintf(stderr, "Reading commit log for repo '%s' failed!\n", repo.path.c_str());
                return EXIT_FAILURE;
            }
            heatmap.add(settings, proc.output());
        }
    }

    html::open(settings.fragment);
    for (const auto &[repo, authors] : heatmap.data()) {
        bool h1_rendered = false;
        for (const auto &[author, entries] : authors) {
            if (settings.exclude_author(author)) continue;
            if (!h1_rendered) {
                html::heading_repo(repo);
                h1_rendered = true;
            }

            const auto commits_per_month = heatmap.commits_per_month(repo, author, report_year);
            const auto total_commits = std::accumulate(commits_per_month.begin(), commits_per_month.end(), 0u);
            html::heading_author(author, total_commits);
            html::table_begin(report_year, commits_per_month);

            // initialize counters
            unsigned column = 0, row = 0;

            // initialize first day (which must be a Monday, possibly the year before)
            sys_days day_to_check = January / Monday[1] / report_year;
            if (year_month_day{day_to_check}.day() != 1d) {
                day_to_check -= days{7};
            }

            // remember the starting point
            auto start = day_to_check;

            // now add all entries for Monday, Tuesdays, etc. always starting back in january
            while (true) {
                html::row_begin(row);

                // check if we need to add blank cells
                while (day_to_check < report_begin) {
                    html::cell_out_of_range();
                    day_to_check += days{7};
                    column++;
                }

                while (day_to_check <= report_end) {
                    // get the entry from the heatmap
                    auto find_result = entries.find(day_to_check);
                    if (find_result == entries.end()) {
                        html::cell(day_to_check, 0);
                    } else {
                        html::cell(day_to_check, find_result->second);
                    }
                    // advance seven days and one column
                    day_to_check += days{7};
                    column++;
                }
                // fill remaining columns with blank cells
                for (unsigned i = column ; i < html::columns ; i++) {
                    html::cell_out_of_range();
                }

                // terminate the row
                html::row_end();

                // if we have seen all seven weekdays, that's it
                if (++row == 7) break;

                // otherwise, advance the starting point by one day, reset, and begin a new row
                start += days{1};
                day_to_check = start;
                column =0;
            }

            html::table_end();
        }
    }
    html::close(settings.fragment);

    return EXIT_SUCCESS;
}

mercurial