aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/ci.c
blob: 4692b19a594294b396f72388993331b9878d0954 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
 * Copyright (c) 2022 Egor Tensin <egor@tensin.name>
 * This file is part of the "cimple" project.
 * For details, see https://github.com/egor-tensin/cimple.
 * Distributed under the MIT License.
 */

#include "ci.h"

#include "file.h"
#include "git.h"
#include "log.h"
#include "process.h"

#include <git2.h>

#include <stddef.h>
#include <stdlib.h>

/* clang-format off */
static const char *ci_scripts[] = {
    "./.ci.sh",
    "./.ci",
    "./ci.sh",
    "./ci",
    NULL,
};

static const char *ci_env[] = {
    "CI=y",
    "CIMPLE=y",
    NULL,
};
/* clang-format on */

static int ci_run_script(const char* script, struct process_output* result) {
    const char* args[] = {script, NULL};
    return process_execute_and_capture(args, ci_env, result);
}

int ci_run(struct process_output* result) {
    for (const char** script = ci_scripts; *script; ++script) {
        if (!file_exists(*script))
            continue;
        log("Going to run: %s\n", *script);
        return ci_run_script(*script, result);
    }

    log("Couldn't find any CI scripts to run\n");
    return -1;
}

static void ci_cleanup_git_repo(git_repository* repo) {
    rm_rf(git_repository_workdir(repo));
    libgit_repository_free(repo);
}

static int ci_prepare_git_repo(git_repository** repo, const char* url, const char* rev) {
    int ret = 0;

    ret = libgit_clone_to_tmp(repo, url);
    if (ret < 0)
        return ret;

    ret = libgit_checkout(*repo, rev);
    if (ret < 0)
        goto cleanup_repo;

    return ret;

cleanup_repo:
    ci_cleanup_git_repo(*repo);

    return ret;
}

int ci_run_git_repo(const char* url, const char* rev, struct process_output* output) {
    char* oldpwd = NULL;
    git_repository* repo = NULL;
    int ret = 0;

    ret = ci_prepare_git_repo(&repo, url, rev);
    if (ret < 0)
        goto exit;

    ret = chdir_wrapper(git_repository_workdir(repo), &oldpwd);
    if (ret < 0)
        goto free_repo;

    ret = ci_run(output);
    if (ret < 0)
        goto oldpwd;

oldpwd:
    chdir_wrapper(oldpwd, NULL);
    free(oldpwd);

free_repo:
    ci_cleanup_git_repo(repo);

exit:
    return ret;
}