filter.c 14.8 KB
Newer Older
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3 4 5 6 7 8 9 10 11
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "common.h"
#include "fileops.h"
#include "hash.h"
#include "filter.h"
12
#include "repository.h"
13
#include "global.h"
14
#include "git2/sys/filter.h"
15
#include "git2/config.h"
16
#include "blob.h"
17
#include "attr_file.h"
18
#include "array.h"
19

20 21 22 23 24
struct git_filter_source {
	git_repository *repo;
	const char     *path;
	git_oid         oid;  /* zero if unknown (which is likely) */
	uint16_t        filemode; /* zero if unknown */
25
	git_filter_mode_t mode;
26
	uint32_t        options;
27 28
};

29 30 31 32 33 34 35 36 37 38 39 40 41 42
typedef struct {
	git_filter *filter;
	void *payload;
} git_filter_entry;

struct git_filter_list {
	git_array_t(git_filter_entry) filters;
	git_filter_source source;
	char path[GIT_FLEX_ARRAY];
};

typedef struct {
	const char *filter_name;
	git_filter *filter;
43
	int priority;
44
	int initialized;
45 46 47
	size_t nattrs, nmatches;
	char *attrdata;
	const char *attrs[GIT_FLEX_ARRAY];
48 49
} git_filter_def;

50 51 52 53 54 55 56
static int filter_def_priority_cmp(const void *a, const void *b)
{
	int pa = ((const git_filter_def *)a)->priority;
	int pb = ((const git_filter_def *)b)->priority;
	return (pa < pb) ? -1 : (pa > pb) ? 1 : 0;
}

57 58
struct filter_registry {
	git_vector filters;
59 60
};

61 62 63 64 65 66 67 68 69 70 71 72
static struct filter_registry *git__filter_registry = NULL;

static void filter_registry_shutdown(void)
{
	struct filter_registry *reg = NULL;
	size_t pos;
	git_filter_def *fdef;

	if ((reg = git__swap(git__filter_registry, NULL)) == NULL)
		return;

	git_vector_foreach(&reg->filters, pos, fdef) {
73
		if (fdef->filter && fdef->filter->shutdown) {
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 104 105 106
			fdef->filter->shutdown(fdef->filter);
			fdef->initialized = false;
		}

		git__free(fdef->attrdata);
		git__free(fdef);
	}

	git_vector_free(&reg->filters);
	git__free(reg);
}

static int filter_registry_initialize(void)
{
	int error = 0;
	struct filter_registry *reg;

	if (git__filter_registry)
		return 0;

	reg = git__calloc(1, sizeof(struct filter_registry));
	GITERR_CHECK_ALLOC(reg);

	if ((error = git_vector_init(
			&reg->filters, 2, filter_def_priority_cmp)) < 0)
		goto cleanup;

	reg = git__compare_and_swap(&git__filter_registry, NULL, reg);
	if (reg != NULL)
		goto cleanup;

	git__on_shutdown(filter_registry_shutdown);

Russell Belfer committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	/* try to register both default filters */
	{
		git_filter *crlf = git_crlf_filter_new();
		git_filter *ident = git_ident_filter_new();

		if (crlf && git_filter_register(
				GIT_FILTER_CRLF, crlf, GIT_FILTER_CRLF_PRIORITY) < 0)
			crlf = NULL;
		if (ident && git_filter_register(
				GIT_FILTER_IDENT, ident, GIT_FILTER_IDENT_PRIORITY) < 0)
			ident = NULL;

		if (!crlf || !ident)
			return -1;
	}

	return 0;
124 125 126 127 128 129 130

cleanup:
	git_vector_free(&reg->filters);
	git__free(reg);
	return error;
}

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
static int filter_def_scan_attrs(
	git_buf *attrs, size_t *nattr, size_t *nmatch, const char *attr_str)
{
	const char *start, *scan = attr_str;
	int has_eq;

	*nattr = *nmatch = 0;

	if (!scan)
		return 0;

	while (*scan) {
		while (git__isspace(*scan)) scan++;

		for (start = scan, has_eq = 0; *scan && !git__isspace(*scan); ++scan) {
			if (*scan == '=')
				has_eq = 1;
		}

		if (scan > start) {
			(*nattr)++;
Russell Belfer committed
152
			if (has_eq || *start == '-' || *start == '+' || *start == '!')
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
				(*nmatch)++;

			if (has_eq)
				git_buf_putc(attrs, '=');
			git_buf_put(attrs, start, scan - start);
			git_buf_putc(attrs, '\0');
		}
	}

	return 0;
}

static void filter_def_set_attrs(git_filter_def *fdef)
{
	char *scan = fdef->attrdata;
	size_t i;

	for (i = 0; i < fdef->nattrs; ++i) {
		const char *name, *value;

		switch (*scan) {
		case '=':
			name = scan + 1;
			for (scan++; *scan != '='; scan++) /* find '=' */;
			*scan++ = '\0';
			value = scan;
			break;
		case '-':
			name = scan + 1; value = git_attr__false; break;
		case '+':
			name = scan + 1; value = git_attr__true;  break;
		case '!':
			name = scan + 1; value = git_attr__unset; break;
		default:
			name = scan;     value = NULL; break;
		}

		fdef->attrs[i] = name;
		fdef->attrs[i + fdef->nattrs] = value;

		scan += strlen(scan) + 1;
	}
}

197 198 199 200
static int filter_def_name_key_check(const void *key, const void *fdef)
{
	const char *name =
		fdef ? ((const git_filter_def *)fdef)->filter_name : NULL;
201 202 203 204 205 206 207
	return name ? git__strcmp(key, name) : -1;
}

static int filter_def_filter_key_check(const void *key, const void *fdef)
{
	const void *filter = fdef ? ((const git_filter_def *)fdef)->filter : NULL;
	return (key == filter) ? 0 : -1;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
}

static int filter_registry_find(size_t *pos, const char *name)
{
	return git_vector_search2(
		pos, &git__filter_registry->filters, filter_def_name_key_check, name);
}

static git_filter_def *filter_registry_lookup(size_t *pos, const char *name)
{
	git_filter_def *fdef = NULL;

	if (!filter_registry_find(pos, name))
		fdef = git_vector_get(&git__filter_registry->filters, *pos);

	return fdef;
}

226 227 228 229 230 231 232
int git_filter_register(
	const char *name, git_filter *filter, int priority)
{
	git_filter_def *fdef;
	size_t nattr = 0, nmatch = 0;
	git_buf attrs = GIT_BUF_INIT;

233 234 235 236
	if (filter_registry_initialize() < 0)
		return -1;

	if (!filter_registry_find(NULL, name)) {
237 238
		giterr_set(
			GITERR_FILTER, "Attempt to reregister existing filter '%s'", name);
Russell Belfer committed
239
		return GIT_EEXISTS;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
	}

	if (filter_def_scan_attrs(&attrs, &nattr, &nmatch, filter->attributes) < 0)
		return -1;

	fdef = git__calloc(
		sizeof(git_filter_def) + 2 * nattr * sizeof(char *), 1);
	GITERR_CHECK_ALLOC(fdef);

	fdef->filter_name = name;
	fdef->filter      = filter;
	fdef->priority    = priority;
	fdef->nattrs      = nattr;
	fdef->nmatches    = nmatch;
	fdef->attrdata    = git_buf_detach(&attrs);

	filter_def_set_attrs(fdef);

258
	if (git_vector_insert(&git__filter_registry->filters, fdef) < 0) {
259 260 261 262 263
		git__free(fdef->attrdata);
		git__free(fdef);
		return -1;
	}

264
	git_vector_sort(&git__filter_registry->filters);
265 266 267
	return 0;
}

268 269 270 271 272 273
int git_filter_unregister(const char *name)
{
	size_t pos;
	git_filter_def *fdef;

	/* cannot unregister default filters */
Russell Belfer committed
274
	if (!strcmp(GIT_FILTER_CRLF, name) || !strcmp(GIT_FILTER_IDENT, name)) {
275 276 277 278
		giterr_set(GITERR_FILTER, "Cannot unregister filter '%s'", name);
		return -1;
	}

279
	if ((fdef = filter_registry_lookup(&pos, name)) == NULL) {
280 281 282 283
		giterr_set(GITERR_FILTER, "Cannot find filter '%s' to unregister", name);
		return GIT_ENOTFOUND;
	}

284
	(void)git_vector_remove(&git__filter_registry->filters, pos);
285

286
	if (fdef->initialized && fdef->filter && fdef->filter->shutdown) {
287
		fdef->filter->shutdown(fdef->filter);
288 289
		fdef->initialized = false;
	}
290 291 292 293 294 295 296

	git__free(fdef->attrdata);
	git__free(fdef);

	return 0;
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
static int filter_initialize(git_filter_def *fdef)
{
	int error = 0;

	if (!fdef->initialized &&
		fdef->filter &&
		fdef->filter->initialize &&
		(error = fdef->filter->initialize(fdef->filter)) < 0)
	{
		/* auto-unregister if initialize fails */
		git_filter_unregister(fdef->filter_name);
		return error;
	}

	fdef->initialized = true;
	return 0;
}

315 316 317
git_filter *git_filter_lookup(const char *name)
{
	size_t pos;
318 319 320 321
	git_filter_def *fdef;

	if (filter_registry_initialize() < 0)
		return NULL;
322

323
	if ((fdef = filter_registry_lookup(&pos, name)) == NULL)
324 325 326 327 328 329
		return NULL;

	if (!fdef->initialized && filter_initialize(fdef) < 0)
		return NULL;

	return fdef->filter;
330 331
}

Russell Belfer committed
332 333 334 335 336
void git_filter_free(git_filter *filter)
{
	git__free(filter);
}

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
git_repository *git_filter_source_repo(const git_filter_source *src)
{
	return src->repo;
}

const char *git_filter_source_path(const git_filter_source *src)
{
	return src->path;
}

uint16_t git_filter_source_filemode(const git_filter_source *src)
{
	return src->filemode;
}

const git_oid *git_filter_source_id(const git_filter_source *src)
{
	return git_oid_iszero(&src->oid) ? NULL : &src->oid;
}

357 358 359 360 361
git_filter_mode_t git_filter_source_mode(const git_filter_source *src)
{
	return src->mode;
}

362
uint32_t git_filter_source_options(const git_filter_source *src)
363 364 365 366
{
	return src->options;
}

367
static int filter_list_new(
368
	git_filter_list **out, const git_filter_source *src)
369
{
370 371 372 373 374 375 376 377 378 379
	git_filter_list *fl = NULL;
	size_t pathlen = src->path ? strlen(src->path) : 0;

	fl = git__calloc(1, sizeof(git_filter_list) + pathlen + 1);
	GITERR_CHECK_ALLOC(fl);

	if (src->path)
		memcpy(fl->path, src->path, pathlen);
	fl->source.repo = src->repo;
	fl->source.path = fl->path;
380
	fl->source.mode = src->mode;
381
	fl->source.options = src->options;
382 383 384 385 386

	*out = fl;
	return 0;
}

387 388 389 390 391 392 393 394 395 396 397 398 399 400
static int filter_list_check_attributes(
	const char ***out, git_filter_def *fdef, const git_filter_source *src)
{
	int error;
	size_t i;
	const char **strs = git__calloc(fdef->nattrs, sizeof(const char *));
	GITERR_CHECK_ALLOC(strs);

	error = git_attr_get_many(
		strs, src->repo, 0, src->path, fdef->nattrs, fdef->attrs);

	/* if no values were found but no matches are needed, it's okay! */
	if (error == GIT_ENOTFOUND && !fdef->nmatches) {
		giterr_clear();
Russell Belfer committed
401
		git__free((void *)strs);
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		return 0;
	}

	for (i = 0; !error && i < fdef->nattrs; ++i) {
		const char *want = fdef->attrs[fdef->nattrs + i];
		git_attr_t want_type, found_type;

		if (!want)
			continue;

		want_type  = git_attr_value(want);
		found_type = git_attr_value(strs[i]);

		if (want_type != found_type ||
			(want_type == GIT_ATTR_VALUE_T && strcmp(want, strs[i])))
			error = GIT_ENOTFOUND;
	}

	if (error)
Russell Belfer committed
421
		git__free((void *)strs);
422 423 424 425 426 427
	else
		*out = strs;

	return error;
}

428
int git_filter_list_new(
429 430 431
	git_filter_list **out,
	git_repository *repo,
	git_filter_mode_t mode,
432
	uint32_t options)
433 434 435 436 437
{
	git_filter_source src = { 0 };
	src.repo = repo;
	src.path = NULL;
	src.mode = mode;
438
	src.options = options;
439 440 441
	return filter_list_new(out, &src);
}

442 443 444
int git_filter_list_load(
	git_filter_list **filters,
	git_repository *repo,
Russell Belfer committed
445
	git_blob *blob, /* can be NULL */
446
	const char *path,
447
	git_filter_mode_t mode,
448
	uint32_t options)
449 450 451 452 453
{
	int error = 0;
	git_filter_list *fl = NULL;
	git_filter_source src = { 0 };
	git_filter_entry *fe;
454 455
	size_t idx;
	git_filter_def *fdef;
456

457
	if (filter_registry_initialize() < 0)
458 459 460 461
		return -1;

	src.repo = repo;
	src.path = path;
462
	src.mode = mode;
463
	src.options = options;
Russell Belfer committed
464 465
	if (blob)
		git_oid_cpy(&src.oid, git_blob_id(blob));
466

467
	git_vector_foreach(&git__filter_registry->filters, idx, fdef) {
468
		const char **values = NULL;
469 470 471 472
		void *payload = NULL;

		if (!fdef || !fdef->filter)
			continue;
473

474 475 476 477 478 479 480 481 482
		if (fdef->nattrs > 0) {
			error = filter_list_check_attributes(&values, fdef, &src);
			if (error == GIT_ENOTFOUND) {
				error = 0;
				continue;
			} else if (error < 0)
				break;
		}

483 484 485
		if (!fdef->initialized && (error = filter_initialize(fdef)) < 0)
			break;

486
		if (fdef->filter->check)
487
			error = fdef->filter->check(
488
				fdef->filter, &payload, &src, values);
489

Russell Belfer committed
490
		git__free((void *)values);
491

Russell Belfer committed
492
		if (error == GIT_PASSTHROUGH)
493 494 495 496
			error = 0;
		else if (error < 0)
			break;
		else {
497
			if (!fl && (error = filter_list_new(&fl, &src)) < 0)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
				return error;

			fe = git_array_alloc(fl->filters);
			GITERR_CHECK_ALLOC(fe);
			fe->filter  = fdef->filter;
			fe->payload = payload;
		}
	}

	if (error && fl != NULL) {
		git_array_clear(fl->filters);
		git__free(fl);
		fl = NULL;
	}

	*filters = fl;
	return error;
}

void git_filter_list_free(git_filter_list *fl)
{
	uint32_t i;

	if (!fl)
		return;

	for (i = 0; i < git_array_size(fl->filters); ++i) {
		git_filter_entry *fe = git_array_get(fl->filters, i);
		if (fe->filter->cleanup)
			fe->filter->cleanup(fe->filter, fe->payload);
528 529
	}

530 531
	git_array_clear(fl->filters);
	git__free(fl);
532 533
}

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
int git_filter_list_push(
	git_filter_list *fl, git_filter *filter, void *payload)
{
	int error = 0;
	size_t pos;
	git_filter_def *fdef;
	git_filter_entry *fe;

	assert(fl && filter);

	if (git_vector_search2(
			&pos, &git__filter_registry->filters,
			filter_def_filter_key_check, filter) < 0) {
		giterr_set(GITERR_FILTER, "Cannot use an unregistered filter");
		return -1;
	}

	fdef = git_vector_get(&git__filter_registry->filters, pos);

	if (!fdef->initialized && (error = filter_initialize(fdef)) < 0)
		return error;

	fe = git_array_alloc(fl->filters);
	GITERR_CHECK_ALLOC(fe);
	fe->filter  = filter;
	fe->payload = payload;

	return 0;
}

Russell Belfer committed
564 565 566 567 568
size_t git_filter_list_length(const git_filter_list *fl)
{
	return fl ? git_array_size(fl->filters) : 0;
}

569
static int filter_list_out_buffer_from_raw(
570
	git_buf *out, const void *ptr, size_t size)
571
{
572 573 574 575 576 577 578 579 580 581
	if (git_buf_is_allocated(out))
		git_buf_free(out);

	if (!size) {
		git_buf_init(out, 0);
	} else {
		out->ptr   = (char *)ptr;
		out->asize = 0;
		out->size  = size;
	}
582 583 584 585 586

	return 0;
}

int git_filter_list_apply_to_data(
587
	git_buf *tgt, git_filter_list *fl, git_buf *src)
588
{
589 590
	int error = 0;
	uint32_t i;
591
	git_buf *dbuffer[2], local = GIT_BUF_INIT;
592
	unsigned int si = 0;
593

594 595 596
	git_buf_sanitize(tgt);
	git_buf_sanitize(src);

597 598
	if (!fl)
		return filter_list_out_buffer_from_raw(tgt, src->ptr, src->size);
599

600 601
	dbuffer[0] = src;
	dbuffer[1] = tgt;
602

603
	/* if `src` buffer is reallocable, then use it, otherwise copy it */
604 605
	if (!git_buf_is_allocated(src)) {
		if (git_buf_set(&local, src->ptr, src->size) < 0)
606 607 608
			return -1;
		dbuffer[0] = &local;
	}
609

610
	for (i = 0; i < git_array_size(fl->filters); ++i) {
611
		unsigned int di = 1 - si;
612
		uint32_t fidx = (fl->source.mode == GIT_FILTER_TO_WORKTREE) ?
613 614
			i : git_array_size(fl->filters) - 1 - i;
		git_filter_entry *fe = git_array_get(fl->filters, fidx);
615

616
		dbuffer[di]->size = 0;
617

618
		/* Apply the filter from dbuffer[src] to the other buffer;
619 620 621 622 623
		 * if the filtering is canceled by the user mid-filter,
		 * we skip to the next filter without changing the source
		 * of the double buffering (so that the text goes through
		 * cleanly).
		 */
624

625 626
		error = fe->filter->apply(
			fe->filter, &fe->payload, dbuffer[di], dbuffer[si], &fl->source);
627

Russell Belfer committed
628 629
		if (error == GIT_PASSTHROUGH) {
			/* PASSTHROUGH means filter decided not to process the buffer */
630
			error = 0;
Russell Belfer committed
631
		} else if (!error) {
632
			git_buf_sanitize(dbuffer[di]); /* force NUL termination */
633
			si = di; /* swap buffers */
Russell Belfer committed
634
		} else {
635
			tgt->size = 0;
636
			goto cleanup;
637
		}
638 639 640
	}

	/* Ensure that the output ends up in dbuffer[1] (i.e. the dest) */
641 642
	if (si != 1)
		git_buf_swap(dbuffer[0], dbuffer[1]);
643

644
cleanup:
645
	git_buf_free(&local); /* don't leak if we allocated locally */
646

647
	return error;
648
}
649 650

int git_filter_list_apply_to_file(
651
	git_buf *out,
652 653 654 655 656 657 658 659 660 661 662
	git_filter_list *filters,
	git_repository *repo,
	const char *path)
{
	int error;
	const char *base = repo ? git_repository_workdir(repo) : NULL;
	git_buf abspath = GIT_BUF_INIT, raw = GIT_BUF_INIT;

	if (!(error = git_path_join_unrooted(&abspath, path, base, NULL)) &&
		!(error = git_futils_readbuffer(&raw, abspath.ptr)))
	{
663
		error = git_filter_list_apply_to_data(out, filters, &raw);
664

665
		git_buf_free(&raw);
666 667 668 669 670 671 672
	}

	git_buf_free(&abspath);
	return error;
}

int git_filter_list_apply_to_blob(
673
	git_buf *out,
674 675 676
	git_filter_list *filters,
	git_blob *blob)
{
677 678 679 680 681 682 683 684 685 686 687
	git_buf in = GIT_BUF_INIT;
	git_off_t rawsize = git_blob_rawsize(blob);

	if (!git__is_sizet(rawsize)) {
		giterr_set(GITERR_OS, "Blob is too large to filter");
		return -1;
	}

	in.ptr   = (char *)git_blob_rawcontent(blob);
	in.asize = 0;
	in.size  = (size_t)rawsize;
688

Russell Belfer committed
689 690 691
	if (filters)
		git_oid_cpy(&filters->source.oid, git_blob_id(blob));

692 693
	return git_filter_list_apply_to_data(out, filters, &in);
}