clar_libgit2.c 14.9 KB
Newer Older
1
#include "clar_libgit2.h"
2
#include "posix.h"
3
#include "path.h"
4
#include "git2/sys/repository.h"
Vicent Marti committed
5

6
void cl_git_report_failure(
7
	int error, int expected, const char *file, int line, const char *fncall)
8 9 10
{
	char msg[4096];
	const git_error *last = giterr_last();
11 12 13 14 15 16 17 18 19 20

	if (expected)
		p_snprintf(msg, 4096, "error %d (expected %d) - %s",
			error, expected, last ? last->message : "<no message>");
	else if (error || last)
		p_snprintf(msg, 4096, "error %d - %s",
			error, last ? last->message : "<no message>");
	else
		p_snprintf(msg, 4096, "no error, expected non-zero return");

21 22 23
	clar__assert(0, file, line, fncall, msg, 1);
}

24 25 26 27 28
void cl_git_mkfile(const char *filename, const char *content)
{
	int fd;

	fd = p_creat(filename, 0666);
29
	cl_assert(fd != -1);
30 31 32 33 34 35 36 37 38 39

	if (content) {
		cl_must_pass(p_write(fd, content, strlen(content)));
	} else {
		cl_must_pass(p_write(fd, filename, strlen(filename)));
		cl_must_pass(p_write(fd, "\n", 1));
	}

	cl_must_pass(p_close(fd));
}
40

41
void cl_git_write2file(
42 43
	const char *path, const char *content, size_t content_len,
	int flags, unsigned int mode)
44
{
45 46 47 48 49 50
	int fd;
	cl_assert(path && content);
	cl_assert((fd = p_open(path, flags, mode)) >= 0);
	if (!content_len)
		content_len = strlen(content);
	cl_must_pass(p_write(fd, content, content_len));
51 52 53
	cl_must_pass(p_close(fd));
}

54
void cl_git_append2file(const char *path, const char *content)
55
{
56
	cl_git_write2file(path, content, 0, O_WRONLY | O_CREAT | O_APPEND, 0644);
57 58
}

59
void cl_git_rewritefile(const char *path, const char *content)
60
{
61
	cl_git_write2file(path, content, 0, O_WRONLY | O_CREAT | O_TRUNC, 0644);
62 63
}

64 65 66 67 68
void cl_git_rmfile(const char *filename)
{
	cl_must_pass(p_unlink(filename));
}

69 70
char *cl_getenv(const char *name)
{
71 72
	git_buf out = GIT_BUF_INIT;
	int error = git__getenv(&out, name);
73

74
	cl_assert(error >= 0 || error == GIT_ENOTFOUND);
75

76 77
	if (error == GIT_ENOTFOUND)
		return NULL;
78

79 80 81 82 83
	if (out.size == 0) {
		char *dup = git__strdup("");
		cl_assert(dup);

		return dup;
84
	}
85

86
	return git_buf_detach(&out);
87 88
}

89 90 91 92 93 94 95 96 97 98 99 100
bool cl_is_env_set(const char *name)
{
	char *env = cl_getenv(name);
	bool result = (env != NULL);
	git__free(env);
	return result;
}

#ifdef GIT_WIN32

#include "win32/utf-conv.h"

101 102
int cl_setenv(const char *name, const char *value)
{
103
	wchar_t *wide_name, *wide_value = NULL;
104

105
	cl_assert(git__utf8_to_16_alloc(&wide_name, name) >= 0);
106

107
	if (value) {
108 109
		cl_assert(git__utf8_to_16_alloc(&wide_value, value) >= 0);
		cl_assert(SetEnvironmentVariableW(wide_name, wide_value));
110 111
	} else {
		/* Windows XP returns 0 (failed) when passing NULL for lpValue when
112 113 114 115
		* lpName does not exist in the environment block. This behavior
		* seems to have changed in later versions. Don't check the return value
		* of SetEnvironmentVariable when passing NULL for lpValue. */
		SetEnvironmentVariableW(wide_name, NULL);
116
	}
117

118 119
	git__free(wide_name);
	git__free(wide_value);
120 121
	return 0;
}
122 123 124 125 126 127 128

/* This function performs retries on calls to MoveFile in order
 * to provide enhanced reliability in the face of antivirus
 * agents that may be scanning the source (or in the case that
 * the source is a directory, a child of the source). */
int cl_rename(const char *source, const char *dest)
{
129 130
	git_win32_path source_utf16;
	git_win32_path dest_utf16;
131 132
	unsigned retries = 1;

133 134
	cl_assert(git_win32_path_from_utf8(source_utf16, source) >= 0);
	cl_assert(git_win32_path_from_utf8(dest_utf16, dest) >= 0);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

	while (!MoveFileW(source_utf16, dest_utf16)) {
		/* Only retry if the error is ERROR_ACCESS_DENIED;
		 * this may indicate that an antivirus agent is
		 * preventing the rename from source to target */
		if (retries > 5 ||
			ERROR_ACCESS_DENIED != GetLastError())
			return -1;

		/* With 5 retries and a coefficient of 10ms, the maximum
		 * delay here is 550 ms */
		Sleep(10 * retries * retries);
		retries++;
	}

	return 0;
}

153 154 155 156 157 158 159 160
#else

#include <stdlib.h>

int cl_setenv(const char *name, const char *value)
{
	return (value == NULL) ? unsetenv(name) : setenv(name, value, 1);
}
161 162 163 164 165 166

int cl_rename(const char *source, const char *dest)
{
	return p_rename(source, dest);
}

167 168
#endif

169 170 171 172 173
static const char *_cl_sandbox = NULL;
static git_repository *_cl_repo = NULL;

git_repository *cl_git_sandbox_init(const char *sandbox)
{
174
	/* Get the name of the sandbox folder which will be created */
175 176
	const char *basename = cl_fixture_basename(sandbox);

177 178 179 180 181 182
	/* Copy the whole sandbox folder from our fixtures to our test sandbox
	 * area.  After this it can be accessed with `./sandbox`
	 */
	cl_fixture_sandbox(sandbox);
	_cl_sandbox = sandbox;

183
	cl_git_pass(p_chdir(basename));
184

185 186 187
	/* If this is not a bare repo, then rename `sandbox/.gitted` to
	 * `sandbox/.git` which must be done since we cannot store a folder
	 * named `.git` inside the fixtures folder of our libgit2 repo.
188
	 */
189
	if (p_access(".gitted", F_OK) == 0)
190
		cl_git_pass(cl_rename(".gitted", ".git"));
191 192 193 194 195 196

	/* If we have `gitattributes`, rename to `.gitattributes`.  This may
	 * be necessary if we don't want the attributes to be applied in the
	 * libgit2 repo, but just during testing.
	 */
	if (p_access("gitattributes", F_OK) == 0)
197
		cl_git_pass(cl_rename("gitattributes", ".gitattributes"));
198 199 200

	/* As with `gitattributes`, we may need `gitignore` just for testing. */
	if (p_access("gitignore", F_OK) == 0)
201
		cl_git_pass(cl_rename("gitignore", ".gitignore"));
202

203
	cl_git_pass(p_chdir(".."));
204 205

	/* Now open the sandbox repository and make it available for tests */
206
	cl_git_pass(git_repository_open(&_cl_repo, basename));
207

208
	/* Adjust configs after copying to new filesystem */
209
	cl_git_pass(git_repository_reinit_filesystem(_cl_repo, 0));
210

211 212 213
	return _cl_repo;
}

214 215 216 217 218 219 220 221
git_repository *cl_git_sandbox_init_new(const char *sandbox)
{
	cl_git_pass(git_repository_init(&_cl_repo, sandbox, false));
	_cl_sandbox = sandbox;

	return _cl_repo;
}

222 223 224 225 226 227
git_repository *cl_git_sandbox_reopen(void)
{
	if (_cl_repo) {
		git_repository_free(_cl_repo);
		_cl_repo = NULL;

228
		cl_git_pass(git_repository_open(
229
			&_cl_repo, cl_fixture_basename(_cl_sandbox)));
230 231 232 233 234
	}

	return _cl_repo;
}

235 236 237 238 239 240 241 242 243 244 245
void cl_git_sandbox_cleanup(void)
{
	if (_cl_repo) {
		git_repository_free(_cl_repo);
		_cl_repo = NULL;
	}
	if (_cl_sandbox) {
		cl_fixture_cleanup(_cl_sandbox);
		_cl_sandbox = NULL;
	}
}
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
bool cl_toggle_filemode(const char *filename)
{
	struct stat st1, st2;

	cl_must_pass(p_stat(filename, &st1));
	cl_must_pass(p_chmod(filename, st1.st_mode ^ 0100));
	cl_must_pass(p_stat(filename, &st2));

	return (st1.st_mode != st2.st_mode);
}

bool cl_is_chmod_supported(void)
{
	static int _is_supported = -1;

	if (_is_supported < 0) {
		cl_git_mkfile("filemode.t", "Test if filemode can be modified");
		_is_supported = cl_toggle_filemode("filemode.t");
		cl_must_pass(p_unlink("filemode.t"));
	}

	return _is_supported;
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
const char* cl_git_fixture_url(const char *fixturename)
{
	return cl_git_path_url(cl_fixture(fixturename));
}

const char* cl_git_path_url(const char *path)
{
	static char url[4096];

	const char *in_buf;
	git_buf path_buf = GIT_BUF_INIT;
	git_buf url_buf = GIT_BUF_INIT;

	cl_git_pass(git_path_prettify_dir(&path_buf, path, NULL));
	cl_git_pass(git_buf_puts(&url_buf, "file://"));

287
#ifdef GIT_WIN32
288 289 290 291 292 293 294 295 296
	/*
	 * A FILE uri matches the following format: file://[host]/path
	 * where "host" can be empty and "path" is an absolute path to the resource.
	 *
	 * In this test, no hostname is used, but we have to ensure the leading triple slashes:
	 *
	 * *nix: file:///usr/home/...
	 * Windows: file:///C:/Users/...
	 */
297
	cl_git_pass(git_buf_putc(&url_buf, '/'));
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
#endif

	in_buf = git_buf_cstr(&path_buf);

	/*
	 * A very hacky Url encoding that only takes care of escaping the spaces
	 */
	while (*in_buf) {
		if (*in_buf == ' ')
			cl_git_pass(git_buf_puts(&url_buf, "%20"));
		else
			cl_git_pass(git_buf_putc(&url_buf, *in_buf));

		in_buf++;
	}

314 315
	cl_assert(url_buf.size < 4096);

316
	strncpy(url, git_buf_cstr(&url_buf), 4096);
317 318
	git_buf_dispose(&url_buf);
	git_buf_dispose(&path_buf);
319 320
	return url;
}
321

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
const char *cl_git_sandbox_path(int is_dir, ...)
{
	const char *path = NULL;
	static char _temp[GIT_PATH_MAX];
	git_buf buf = GIT_BUF_INIT;
	va_list arg;

	cl_git_pass(git_buf_sets(&buf, clar_sandbox_path()));

	va_start(arg, is_dir);

	while ((path = va_arg(arg, const char *)) != NULL) {
		cl_git_pass(git_buf_joinpath(&buf, buf.ptr, path));
	}
	va_end(arg);

	cl_git_pass(git_path_prettify(&buf, buf.ptr, NULL));
	if (is_dir)
		git_path_to_dir(&buf);

	/* make sure we won't truncate */
	cl_assert(git_buf_len(&buf) < sizeof(_temp));
	git_buf_copy_cstr(_temp, sizeof(_temp), &buf);

	git_buf_dispose(&buf);

	return _temp;
}

351 352 353 354 355 356 357 358 359 360 361
typedef struct {
	const char *filename;
	size_t filename_len;
} remove_data;

static int remove_placeholders_recurs(void *_data, git_buf *path)
{
	remove_data *data = (remove_data *)_data;
	size_t pathlen;

	if (git_path_isdir(path->ptr) == true)
362
		return git_path_direach(path, 0, remove_placeholders_recurs, data);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

	pathlen = path->size;

	if (pathlen < data->filename_len)
		return 0;

	/* if path ends in '/'+filename (or equals filename) */
	if (!strcmp(data->filename, path->ptr + pathlen - data->filename_len) &&
		(pathlen == data->filename_len ||
		 path->ptr[pathlen - data->filename_len - 1] == '/'))
		return p_unlink(path->ptr);

	return 0;
}

int cl_git_remove_placeholders(const char *directory_path, const char *filename)
{
	int error;
	remove_data data;
	git_buf buffer = GIT_BUF_INIT;

	if (git_path_isdir(directory_path) == false)
		return -1;

	if (git_buf_sets(&buffer, directory_path) < 0)
		return -1;

	data.filename = filename;
	data.filename_len = strlen(filename);

	error = remove_placeholders_recurs(&data, &buffer);

395
	git_buf_dispose(&buffer);
396 397 398

	return error;
}
399

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
#define CL_COMMIT_NAME "Libgit2 Tester"
#define CL_COMMIT_EMAIL "libgit2-test@github.com"
#define CL_COMMIT_MSG "Test commit of tree "

void cl_repo_commit_from_index(
	git_oid *out,
	git_repository *repo,
	git_signature *sig,
	git_time_t time,
	const char *msg)
{
	git_index *index;
	git_oid commit_id, tree_id;
	git_object *parent = NULL;
	git_reference *ref = NULL;
	git_tree *tree = NULL;
	char buf[128];
	int free_sig = (sig == NULL);

	/* it is fine if looking up HEAD fails - we make this the first commit */
	git_revparse_ext(&parent, &ref, repo, "HEAD");

	/* write the index content as a tree */
	cl_git_pass(git_repository_index(&index, repo));
	cl_git_pass(git_index_write_tree(&tree_id, index));
	cl_git_pass(git_index_write(index));
	git_index_free(index);

	cl_git_pass(git_tree_lookup(&tree, repo, &tree_id));

	if (sig)
		cl_assert(sig->name && sig->email);
	else if (!time)
		cl_git_pass(git_signature_now(&sig, CL_COMMIT_NAME, CL_COMMIT_EMAIL));
	else
		cl_git_pass(git_signature_new(
			&sig, CL_COMMIT_NAME, CL_COMMIT_EMAIL, time, 0));

	if (!msg) {
		strcpy(buf, CL_COMMIT_MSG);
		git_oid_tostr(buf + strlen(CL_COMMIT_MSG),
			sizeof(buf) - strlen(CL_COMMIT_MSG), &tree_id);
		msg = buf;
	}

	cl_git_pass(git_commit_create_v(
		&commit_id, repo, ref ? git_reference_name(ref) : "HEAD",
		sig, sig, NULL, msg, tree, parent ? 1 : 0, parent));

	if (out)
		git_oid_cpy(out, &commit_id);

	git_object_free(parent);
	git_reference_free(ref);
	if (free_sig)
		git_signature_free(sig);
	git_tree_free(tree);
}

459 460 461 462 463 464 465
void cl_repo_set_bool(git_repository *repo, const char *cfg, int value)
{
	git_config *config;
	cl_git_pass(git_repository_config(&config, repo));
	cl_git_pass(git_config_set_bool(config, cfg, value != 0));
	git_config_free(config);
}
466 467 468 469 470 471

int cl_repo_get_bool(git_repository *repo, const char *cfg)
{
	int val = 0;
	git_config *config;
	cl_git_pass(git_repository_config(&config, repo));
472 473
	if (git_config_get_bool(&val, config, cfg) < 0)
		giterr_clear();
474 475 476
	git_config_free(config);
	return val;
}
477

478 479 480 481 482 483 484 485
void cl_repo_set_string(git_repository *repo, const char *cfg, const char *value)
{
	git_config *config;
	cl_git_pass(git_repository_config(&config, repo));
	cl_git_pass(git_config_set_string(config, cfg, value));
	git_config_free(config);
}

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
/* this is essentially the code from git__unescape modified slightly */
static size_t strip_cr_from_buf(char *start, size_t len)
{
	char *scan, *trail, *end = start + len;

	for (scan = trail = start; scan < end; trail++, scan++) {
		while (*scan == '\r')
			scan++; /* skip '\r' */

		if (trail != scan)
			*trail = *scan;
	}

	*trail = '\0';

	return (trail - start);
}

void clar__assert_equal_file(
	const char *expected_data,
	size_t expected_bytes,
	int ignore_cr,
	const char *path,
	const char *file,
nulltoken committed
510
	int line)
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
{
	char buf[4000];
	ssize_t bytes, total_bytes = 0;
	int fd = p_open(path, O_RDONLY | O_BINARY);
	cl_assert(fd >= 0);

	if (expected_data && !expected_bytes)
		expected_bytes = strlen(expected_data);

	while ((bytes = p_read(fd, buf, sizeof(buf))) != 0) {
		clar__assert(
			bytes > 0, file, line, "error reading from file", path, 1);

		if (ignore_cr)
			bytes = strip_cr_from_buf(buf, bytes);

527 528 529 530 531
		if (memcmp(expected_data, buf, bytes) != 0) {
			int pos;
			for (pos = 0; pos < bytes && expected_data[pos] == buf[pos]; ++pos)
				/* find differing byte offset */;
			p_snprintf(
532 533
				buf, sizeof(buf), "file content mismatch at byte %"PRIdZ,
				(ssize_t)(total_bytes + pos));
534
			p_close(fd);
535
			clar__fail(file, line, path, buf, 1);
536
		}
537 538 539 540 541 542 543 544 545 546 547

		expected_data += bytes;
		total_bytes   += bytes;
	}

	p_close(fd);

	clar__assert(!bytes, file, line, "error reading from file", path, 1);
	clar__assert_equal(file, line, "mismatched file length", 1, "%"PRIuZ,
		(size_t)expected_bytes, (size_t)total_bytes);
}
548

549 550 551 552 553 554 555 556 557
static char *_cl_restore_home = NULL;

void cl_fake_home_cleanup(void *payload)
{
	char *restore = _cl_restore_home;
	_cl_restore_home = NULL;

	GIT_UNUSED(payload);

558 559 560 561 562
	if (restore) {
		cl_git_pass(git_libgit2_opts(
			GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, restore));
		git__free(restore);
	}
563 564 565
}

void cl_fake_home(void)
566 567 568 569
{
	git_buf path = GIT_BUF_INIT;

	cl_git_pass(git_libgit2_opts(
570 571 572 573
		GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &path));

	_cl_restore_home = git_buf_detach(&path);
	cl_set_cleanup(cl_fake_home_cleanup, NULL);
574

575 576
	if (!git_path_exists("home"))
		cl_must_pass(p_mkdir("home", 0777));
577 578 579
	cl_git_pass(git_path_prettify(&path, "home", NULL));
	cl_git_pass(git_libgit2_opts(
		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr));
580
	git_buf_dispose(&path);
581
}
582 583 584

void cl_sandbox_set_search_path_defaults(void)
{
585 586 587 588 589 590
	git_buf path = GIT_BUF_INIT;

	git_buf_joinpath(&path, clar_sandbox_path(), "__config");

	if (!git_path_exists(path.ptr))
		cl_must_pass(p_mkdir(path.ptr, 0777));
591 592

	git_libgit2_opts(
593
		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr);
594
	git_libgit2_opts(
595
		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr);
596
	git_libgit2_opts(
597
		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr);
598
	git_libgit2_opts(
599 600
		GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_PROGRAMDATA, path.ptr);

601
	git_buf_dispose(&path);
602 603
}

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
#ifdef GIT_WIN32
bool cl_sandbox_supports_8dot3(void)
{
	git_buf longpath = GIT_BUF_INIT;
	char *shortname;
	bool supported;

	cl_git_pass(
		git_buf_joinpath(&longpath, clar_sandbox_path(), "longer_than_8dot3"));

	cl_git_write2file(longpath.ptr, "", 0, O_RDWR|O_CREAT, 0666);
	shortname = git_win32_path_8dot3_name(longpath.ptr);

	supported = (shortname != NULL);

	git__free(shortname);
620
	git_buf_dispose(&longpath);
621 622 623 624 625

	return supported;
}
#endif