aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/ci.c
blob: 5f3dad4e41effb935fae913beb4e183e7d6d24b2 (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
#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",
};
/* clang-format on */

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

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

	print_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 proc_output *output)
{
	char *oldpwd;
	git_repository *repo;
	int ret = 0;

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

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

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

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

free_repo:
	ci_cleanup_git_repo(repo);

exit:
	return ret;
}