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

8 9
#include "attr_file.h"

10
#include "repository.h"
11
#include "filebuf.h"
12
#include "attrcache.h"
13 14
#include "git2/blob.h"
#include "git2/tree.h"
15
#include "index.h"
16 17
#include <ctype.h>

18 19
static void attr_file_free(git_attr_file *file)
{
20 21
	bool unlock = !git_mutex_lock(&file->lock);
	git_attr_file__clear_rules(file, false);
22
	git_pool_clear(&file->pool);
23 24 25 26
	if (unlock)
		git_mutex_unlock(&file->lock);
	git_mutex_free(&file->lock);

27 28 29
	git__memzero(file, sizeof(*file));
	git__free(file);
}
30

31
int git_attr_file__new(
32
	git_attr_file **out,
33 34
	git_attr_file_entry *entry,
	git_attr_file_source source)
35
{
36
	git_attr_file *attrs = git__calloc(1, sizeof(git_attr_file));
37
	GITERR_CHECK_ALLOC(attrs);
38

39
	if (git_mutex_init(&attrs->lock) < 0) {
40
		giterr_set(GITERR_OS, "failed to initialize lock");
41 42 43 44
		git__free(attrs);
		return -1;
	}

45
	git_pool_init(&attrs->pool, 1);
46
	GIT_REFCOUNT_INC(attrs);
47
	attrs->entry  = entry;
48 49 50 51
	attrs->source = source;
	*out = attrs;
	return 0;
}
52

53
int git_attr_file__clear_rules(git_attr_file *file, bool need_lock)
54 55 56
{
	unsigned int i;
	git_attr_rule *rule;
57

58
	if (need_lock && git_mutex_lock(&file->lock) < 0) {
59
		giterr_set(GITERR_OS, "failed to lock attribute file");
60 61 62
		return -1;
	}

63 64 65
	git_vector_foreach(&file->rules, i, rule)
		git_attr_rule__free(rule);
	git_vector_free(&file->rules);
66 67 68 69 70

	if (need_lock)
		git_mutex_unlock(&file->lock);

	return 0;
71
}
72

73 74 75 76 77 78
void git_attr_file__free(git_attr_file *file)
{
	if (!file)
		return;
	GIT_REFCOUNT_DEC(file, attr_file_free);
}
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
static int attr_file_oid_from_index(
	git_oid *oid, git_repository *repo, const char *path)
{
	int error;
	git_index *idx;
	size_t pos;
	const git_index_entry *entry;

	if ((error = git_repository_index__weakptr(&idx, repo)) < 0 ||
		(error = git_index__find_pos(&pos, idx, path, 0, 0)) < 0)
		return error;

	if (!(entry = git_index_get_byindex(idx, pos)))
		return GIT_ENOTFOUND;

	*oid = entry->id;
96
	return 0;
97 98 99 100 101
}

int git_attr_file__load(
	git_attr_file **out,
	git_repository *repo,
102
	git_attr_session *attr_session,
103 104 105
	git_attr_file_entry *entry,
	git_attr_file_source source,
	git_attr_file_parser parser)
106 107 108 109 110
{
	int error = 0;
	git_blob *blob = NULL;
	git_buf content = GIT_BUF_INIT;
	git_attr_file *file;
111
	struct stat st;
112
	bool nonexistent = false;
113 114 115

	*out = NULL;

116 117 118 119 120
	switch (source) {
	case GIT_ATTR_FILE__IN_MEMORY:
		/* in-memory attribute file doesn't need data */
		break;
	case GIT_ATTR_FILE__FROM_INDEX: {
121
		git_oid id;
122

123
		if ((error = attr_file_oid_from_index(&id, repo, entry->path)) < 0 ||
124 125 126
			(error = git_blob_lookup(&blob, repo, &id)) < 0)
			return error;

127 128 129
		/* Do not assume that data straight from the ODB is NULL-terminated;
		 * copy the contents of a file to a buffer to work on */
		git_buf_put(&content, git_blob_rawcontent(blob), git_blob_rawsize(blob));
130 131 132
		break;
	}
	case GIT_ATTR_FILE__FROM_FILE: {
133
		int fd = -1;
134

135
		/* For open or read errors, pretend that we got ENOTFOUND. */
136 137
		/* TODO: issue warning when warning API is available */

138 139 140 141 142
		if (p_stat(entry->fullpath, &st) < 0 ||
			S_ISDIR(st.st_mode) ||
			(fd = git_futils_open_ro(entry->fullpath)) < 0 ||
			(error = git_futils_readbuffer_fd(&content, fd, (size_t)st.st_size)) < 0)
			nonexistent = true;
143 144

		if (fd >= 0)
145
			p_close(fd);
146 147 148 149

		break;
	}
	default:
150
		giterr_set(GITERR_INVALID, "unknown file source %d", source);
151
		return -1;
152 153
	}

154
	if ((error = git_attr_file__new(&file, entry, source)) < 0)
155 156
		goto cleanup;

157 158 159 160 161 162
	/* store the key of the attr_reader; don't bother with cache
	 * invalidation during the same attr reader session.
	 */
	if (attr_session)
		file->session_key = attr_session->key;

163
	if (parser && (error = parser(repo, file, git_buf_cstr(&content))) < 0) {
164
		git_attr_file__free(file);
165 166 167
		goto cleanup;
	}

168 169 170 171
	/* write cache breakers */
	if (nonexistent)
		file->nonexistent = 1;
	else if (source == GIT_ATTR_FILE__FROM_INDEX)
172 173 174 175 176 177
		git_oid_cpy(&file->cache_data.oid, git_blob_id(blob));
	else if (source == GIT_ATTR_FILE__FROM_FILE)
		git_futils_filestamp_set_from_stat(&file->cache_data.stamp, &st);
	/* else always cacheable */

	*out = file;
178 179 180 181 182 183

cleanup:
	git_blob_free(blob);
	git_buf_free(&content);

	return error;
184 185
}

186 187 188 189
int git_attr_file__out_of_date(
	git_repository *repo,
	git_attr_session *attr_session,
	git_attr_file *file)
190 191 192 193
{
	if (!file)
		return 1;

194 195 196 197 198 199 200 201
	/* we are never out of date if we just created this data in the same
	 * attr_session; otherwise, nonexistent files must be invalidated
	 */
	if (attr_session && attr_session->key == file->session_key)
		return 0;
	else if (file->nonexistent)
		return 1;

202 203 204 205 206 207 208 209 210
	switch (file->source) {
	case GIT_ATTR_FILE__IN_MEMORY:
		return 0;

	case GIT_ATTR_FILE__FROM_FILE:
		return git_futils_filestamp_check(
			&file->cache_data.stamp, file->entry->fullpath);

	case GIT_ATTR_FILE__FROM_INDEX: {
211 212 213
		int error;
		git_oid id;

214 215
		if ((error = attr_file_oid_from_index(
				&id, repo, file->entry->path)) < 0)
216 217 218 219 220
			return error;

		return (git_oid__cmp(&file->cache_data.oid, &id) != 0);
	}

221
	default:
222
		giterr_set(GITERR_INVALID, "invalid file type %d", file->source);
223 224
		return -1;
	}
225 226 227 228 229 230 231 232 233
}

static int sort_by_hash_and_name(const void *a_raw, const void *b_raw);
static void git_attr_rule__clear(git_attr_rule *rule);
static bool parse_optimized_patterns(
	git_attr_fnmatch *spec,
	git_pool *pool,
	const char *pattern);

234
int git_attr_file__parse_buffer(
235
	git_repository *repo, git_attr_file *attrs, const char *data)
236
{
237
	int error = 0;
238
	const char *scan = data, *context = NULL;
239 240
	git_attr_rule *rule = NULL;

241
	/* if subdir file path, convert context for file paths */
242 243 244 245
	if (attrs->entry &&
		git_path_root(attrs->entry->path) < 0 &&
		!git__suffixcmp(attrs->entry->path, "/" GIT_ATTR_FILE))
		context = attrs->entry->path;
246

247
	if (git_mutex_lock(&attrs->lock) < 0) {
248
		giterr_set(GITERR_OS, "failed to lock attribute file");
249 250 251
		return -1;
	}

252
	while (!error && *scan) {
253
		/* allocate rule if needed */
254 255 256
		if (!rule && !(rule = git__calloc(1, sizeof(*rule)))) {
			error = -1;
			break;
257 258
		}

259 260 261
		rule->match.flags =
			GIT_ATTR_FNMATCH_ALLOWNEG | GIT_ATTR_FNMATCH_ALLOWMACRO;

262
		/* parse the next "pattern attr attr attr" line */
263
		if (!(error = git_attr_fnmatch__parse(
264
				&rule->match, &attrs->pool, context, &scan)) &&
265
			!(error = git_attr_assignment__parse(
266
				repo, &attrs->pool, &rule->assigns, &scan)))
267 268
		{
			if (rule->match.flags & GIT_ATTR_FNMATCH_MACRO)
269
				/* TODO: warning if macro found in file below repo root */
270 271 272 273
				error = git_attr_cache__insert_macro(repo, rule);
			else
				error = git_vector_insert(&attrs->rules, rule);
		}
274 275

		/* if the rule wasn't a pattern, on to the next */
276
		if (error < 0) {
Russell Belfer committed
277
			git_attr_rule__clear(rule); /* reset rule contents */
278
			if (error == GIT_ENOTFOUND)
279
				error = 0;
280 281 282 283 284
		} else {
			rule = NULL; /* vector now "owns" the rule */
		}
	}

285
	git_mutex_unlock(&attrs->lock);
286
	git_attr_rule__free(rule);
287

288 289 290
	return error;
}

291
uint32_t git_attr_file__name_hash(const char *name)
292
{
293
	uint32_t h = 5381;
294 295 296 297 298 299 300 301 302
	int c;
	assert(name);
	while ((c = (int)*name++) != 0)
		h = ((h << 5) + h) + c;
	return h;
}

int git_attr_file__lookup_one(
	git_attr_file *file,
303
	git_attr_path *path,
304 305 306
	const char *attr,
	const char **value)
{
307
	size_t i;
308 309 310 311 312 313 314 315 316
	git_attr_name name;
	git_attr_rule *rule;

	*value = NULL;

	name.name = attr;
	name.name_hash = git_attr_file__name_hash(attr);

	git_attr_file__foreach_matching_rule(file, path, i, rule) {
317
		size_t pos;
318

319
		if (!git_vector_bsearch(&pos, &rule->assigns, &name)) {
320 321 322 323 324 325
			*value = ((git_attr_assignment *)
					  git_vector_get(&rule->assigns, pos))->value;
			break;
		}
	}

326
	return 0;
327 328
}

329
int git_attr_file__load_standalone(git_attr_file **out, const char *path)
330 331 332 333 334
{
	int error;
	git_attr_file *file;
	git_buf content = GIT_BUF_INIT;

335
	error = git_attr_file__new(&file, NULL, GIT_ATTR_FILE__FROM_FILE);
336 337 338
	if (error < 0)
		return error;

339 340
	error = git_attr_cache__alloc_file_entry(
		&file->entry, NULL, path, &file->pool);
341 342 343 344 345 346 347 348 349
	if (error < 0) {
		git_attr_file__free(file);
		return error;
	}
	/* because the cache entry is allocated from the file's own pool, we
	 * don't have to free it - freeing file+pool will free cache entry, too.
	 */

	if (!(error = git_futils_readbuffer(&content, path))) {
350
		error = git_attr_file__parse_buffer(NULL, file, content.ptr);
351 352 353 354 355 356 357 358 359 360
		git_buf_free(&content);
	}

	if (error < 0)
		git_attr_file__free(file);
	else
		*out = file;

	return error;
}
361

362
bool git_attr_fnmatch__match(
363
	git_attr_fnmatch *match,
364
	git_attr_path *path)
365
{
366
	const char *relpath = path->path;
367 368
	const char *filename;
	int flags = 0;
369

370 371 372 373 374 375 376 377 378 379 380 381 382
	/*
	 * If the rule was generated in a subdirectory, we must only
	 * use it for paths inside that directory. We can thus return
	 * a non-match if the prefixes don't match.
	 */
	if (match->containing_dir) {
		if (match->flags & GIT_ATTR_FNMATCH_ICASE) {
			if (git__strncasecmp(path->path, match->containing_dir, match->containing_dir_length))
				return 0;
		} else {
			if (git__prefixcmp(path->path, match->containing_dir))
				return 0;
		}
383 384

		relpath += match->containing_dir_length;
385 386
	}

387 388
	if (match->flags & GIT_ATTR_FNMATCH_ICASE)
		flags |= FNM_CASEFOLD;
389 390
	if (match->flags & GIT_ATTR_FNMATCH_LEADINGDIR)
		flags |= FNM_LEADING_DIR;
391 392

	if (match->flags & GIT_ATTR_FNMATCH_FULLPATH) {
393
		filename = relpath;
394 395 396 397 398 399 400
		flags |= FNM_PATHNAME;
	} else {
		filename = path->basename;

		if (path->is_dir)
			flags |= FNM_LEADING_DIR;
	}
401

402
	if ((match->flags & GIT_ATTR_FNMATCH_DIRECTORY) && !path->is_dir) {
403 404
		bool samename;

405 406 407 408 409
		/*
		 * for attribute checks or checks at the root of this match's
		 * containing_dir (or root of the repository if no containing_dir),
		 * do not match.
		 */
410
		if (!(match->flags & GIT_ATTR_FNMATCH_IGNORE) ||
411
			path->basename == relpath)
412 413 414
			return false;

		flags |= FNM_LEADING_DIR;
415

416
		/* fail match if this is a file with same name as ignored folder */
417
		samename = (match->flags & GIT_ATTR_FNMATCH_ICASE) ?
418 419
			!strcasecmp(match->pattern, relpath) :
			!strcmp(match->pattern, relpath);
420 421 422 423

		if (samename)
			return false;

424
		return (p_fnmatch(match->pattern, relpath, flags) != FNM_NOMATCH);
425 426
	}

427 428
	/* if path is a directory prefix of a negated pattern, then match */
	if ((match->flags & GIT_ATTR_FNMATCH_NEGATIVE) && path->is_dir) {
429
		size_t pathlen = strlen(relpath);
430 431
		bool prefixed = (pathlen <= match->length) &&
			((match->flags & GIT_ATTR_FNMATCH_ICASE) ?
432 433
			!strncasecmp(match->pattern, relpath, pathlen) :
			!strncmp(match->pattern, relpath, pathlen));
434 435 436 437 438

		if (prefixed && git_path_at_end_of_segment(&match->pattern[pathlen]))
			return true;
	}

439
	return (p_fnmatch(match->pattern, filename, flags) != FNM_NOMATCH);
440 441
}

442
bool git_attr_rule__match(
443
	git_attr_rule *rule,
444
	git_attr_path *path)
445
{
446
	bool matched = git_attr_fnmatch__match(&rule->match, path);
447

448
	if (rule->match.flags & GIT_ATTR_FNMATCH_NEGATIVE)
449
		matched = !matched;
450 451 452 453 454 455 456

	return matched;
}

git_attr_assignment *git_attr_rule__lookup_assignment(
	git_attr_rule *rule, const char *name)
{
457
	size_t pos;
458 459 460 461
	git_attr_name key;
	key.name = name;
	key.name_hash = git_attr_file__name_hash(name);

462 463
	if (git_vector_bsearch(&pos, &rule->assigns, &key))
		return NULL;
464

465
	return git_vector_get(&rule->assigns, pos);
466 467 468
}

int git_attr_path__init(
469
	git_attr_path *info, const char *path, const char *base, git_dir_flag dir_flag)
470
{
471 472
	ssize_t root;

473 474
	/* build full path as best we can */
	git_buf_init(&info->full, 0);
475

476 477 478 479
	if (git_path_join_unrooted(&info->full, path, base, &root) < 0)
		return -1;

	info->path = info->full.ptr + root;
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

	/* remove trailing slashes */
	while (info->full.size > 0) {
		if (info->full.ptr[info->full.size - 1] != '/')
			break;
		info->full.size--;
	}
	info->full.ptr[info->full.size] = '\0';

	/* skip leading slashes in path */
	while (*info->path == '/')
		info->path++;

	/* find trailing basename component */
	info->basename = strrchr(info->path, '/');
	if (info->basename)
		info->basename++;
	if (!info->basename || !*info->basename)
		info->basename = info->path;

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	switch (dir_flag)
	{
	case GIT_DIR_FLAG_FALSE:
		info->is_dir = 0;
		break;

	case GIT_DIR_FLAG_TRUE:
		info->is_dir = 1;
		break;

	case GIT_DIR_FLAG_UNKNOWN:
	default:
		info->is_dir = (int)git_path_isdir(info->full.ptr);
		break;
	}
515

516
	return 0;
517 518
}

519 520 521 522 523 524 525
void git_attr_path__free(git_attr_path *info)
{
	git_buf_free(&info->full);
	info->path = NULL;
	info->basename = NULL;
}

526 527 528 529 530 531 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
/*
 * From gitattributes(5):
 *
 * Patterns have the following format:
 *
 * - A blank line matches no files, so it can serve as a separator for
 *   readability.
 *
 * - A line starting with # serves as a comment.
 *
 * - An optional prefix ! which negates the pattern; any matching file
 *   excluded by a previous pattern will become included again. If a negated
 *   pattern matches, this will override lower precedence patterns sources.
 *
 * - If the pattern ends with a slash, it is removed for the purpose of the
 *   following description, but it would only find a match with a directory. In
 *   other words, foo/ will match a directory foo and paths underneath it, but
 *   will not match a regular file or a symbolic link foo (this is consistent
 *   with the way how pathspec works in general in git).
 *
 * - If the pattern does not contain a slash /, git treats it as a shell glob
 *   pattern and checks for a match against the pathname without leading
 *   directories.
 *
 * - Otherwise, git treats the pattern as a shell glob suitable for consumption
 *   by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will
 *   not match a / in the pathname. For example, "Documentation/\*.html" matches
 *   "Documentation/git.html" but not "Documentation/ppc/ppc.html". A leading
 *   slash matches the beginning of the pathname; for example, "/\*.c" matches
 *   "cat-file.c" but not "mozilla-sha1/sha1.c".
 */

/*
559
 * This will return 0 if the spec was filled out,
560 561 562
 * GIT_ENOTFOUND if the fnmatch does not require matching, or
 * another error code there was an actual problem.
 */
563
int git_attr_fnmatch__parse(
564
	git_attr_fnmatch *spec,
565
	git_pool *pool,
566
	const char *context,
567 568
	const char **base)
{
569 570
	const char *pattern, *scan;
	int slash_count, allow_space;
571

572
	assert(spec && base && *base);
573

574 575 576 577 578 579
	if (parse_optimized_patterns(spec, pool, *base))
		return 0;

	spec->flags = (spec->flags & GIT_ATTR_FNMATCH__INCOMING);
	allow_space = ((spec->flags & GIT_ATTR_FNMATCH_ALLOWSPACE) != 0);

580 581
	pattern = *base;

582
	while (git__isspace(*pattern)) pattern++;
583
	if (!*pattern || *pattern == '#') {
584 585
		*base = git__next_line(pattern);
		return GIT_ENOTFOUND;
586 587
	}

588
	if (*pattern == '[' && (spec->flags & GIT_ATTR_FNMATCH_ALLOWMACRO) != 0) {
589 590 591 592
		if (strncmp(pattern, "[attr]", 6) == 0) {
			spec->flags = spec->flags | GIT_ATTR_FNMATCH_MACRO;
			pattern += 6;
		}
593
		/* else a character range like [a-e]* which is accepted */
594 595
	}

596
	if (*pattern == '!' && (spec->flags & GIT_ATTR_FNMATCH_ALLOWNEG) != 0) {
597 598
		spec->flags = spec->flags |
			GIT_ATTR_FNMATCH_NEGATIVE | GIT_ATTR_FNMATCH_LEADINGDIR;
599 600 601 602 603
		pattern++;
	}

	slash_count = 0;
	for (scan = pattern; *scan != '\0'; ++scan) {
604
		/* scan until (non-escaped) white space */
605
		if (git__isspace(*scan) && *(scan - 1) != '\\') {
606
			if (!allow_space || (*scan != ' ' && *scan != '\t' && *scan != '\r'))
607 608
				break;
		}
609 610

		if (*scan == '/') {
611
			spec->flags = spec->flags | GIT_ATTR_FNMATCH_FULLPATH;
612
			slash_count++;
613 614
			if (pattern == scan)
				pattern++;
615
		}
616
		/* remember if we see an unescaped wildcard in pattern */
617
		else if (git__iswildcard(*scan) &&
618 619
			(scan == pattern || (*(scan - 1) != '\\')))
			spec->flags = spec->flags | GIT_ATTR_FNMATCH_HASWILD;
620 621 622
	}

	*base = scan;
623

624 625
	if ((spec->length = scan - pattern) == 0)
		return GIT_ENOTFOUND;
626

627 628 629 630 631 632 633 634 635
	/*
	 * Remove one trailing \r in case this is a CRLF delimited
	 * file, in the case of Icon\r\r\n, we still leave the first
	 * \r there to match against.
	 */
	if (pattern[spec->length - 1] == '\r')
		if (--spec->length == 0)
			return GIT_ENOTFOUND;

636 637 638 639 640
	/* Remove trailing spaces. */
	while (pattern[spec->length - 1] == ' ' || pattern[spec->length - 1] == '\t')
		if (--spec->length == 0)
			return GIT_ENOTFOUND;

641 642
	if (pattern[spec->length - 1] == '/') {
		spec->length--;
643
		spec->flags = spec->flags | GIT_ATTR_FNMATCH_DIRECTORY;
644
		if (--slash_count <= 0)
645
			spec->flags = spec->flags & ~GIT_ATTR_FNMATCH_FULLPATH;
646
	}
Russell Belfer committed
647 648
	if ((spec->flags & GIT_ATTR_FNMATCH_NOLEADINGDIR) == 0 &&
		spec->length >= 2 &&
649 650 651 652 653 654
		pattern[spec->length - 1] == '*' &&
		pattern[spec->length - 2] == '/') {
		spec->length -= 2;
		spec->flags = spec->flags | GIT_ATTR_FNMATCH_LEADINGDIR;
		/* leave FULLPATH match on, however */
	}
655

656
	if (context) {
657
		char *slash = strrchr(context, '/');
658 659 660 661 662 663 664 665 666
		size_t len;
		if (slash) {
			/* include the slash for easier matching */
			len = slash - context + 1;
			spec->containing_dir = git_pool_strndup(pool, context, len);
			spec->containing_dir_length = len;
		}
	}

667
	spec->pattern = git_pool_strndup(pool, pattern, spec->length);
668 669 670

	if (!spec->pattern) {
		*base = git__next_line(pattern);
671
		return -1;
672
	} else {
673
		/* strip '\' that might have be used for internal whitespace */
674
		spec->length = git__unescape(spec->pattern);
675
		/* TODO: convert remaining '\' into '/' for POSIX ??? */
676 677
	}

678
	return 0;
679 680
}

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
static bool parse_optimized_patterns(
	git_attr_fnmatch *spec,
	git_pool *pool,
	const char *pattern)
{
	if (!pattern[1] && (pattern[0] == '*' || pattern[0] == '.')) {
		spec->flags = GIT_ATTR_FNMATCH_MATCH_ALL;
		spec->pattern = git_pool_strndup(pool, pattern, 1);
		spec->length = 1;

		return true;
	}

	return false;
}

697 698 699 700 701 702 703 704 705 706 707 708 709
static int sort_by_hash_and_name(const void *a_raw, const void *b_raw)
{
	const git_attr_name *a = a_raw;
	const git_attr_name *b = b_raw;

	if (b->name_hash < a->name_hash)
		return 1;
	else if (b->name_hash > a->name_hash)
		return -1;
	else
		return strcmp(b->name, a->name);
}

710
static void git_attr_assignment__free(git_attr_assignment *assign)
711
{
712 713 714
	/* name and value are stored in a git_pool associated with the
	 * git_attr_file, so they do not need to be freed here
	 */
715
	assign->name = NULL;
716
	assign->value = NULL;
717 718 719
	git__free(assign);
}

720 721 722 723 724 725 726 727 728 729
static int merge_assignments(void **old_raw, void *new_raw)
{
	git_attr_assignment **old = (git_attr_assignment **)old_raw;
	git_attr_assignment *new = (git_attr_assignment *)new_raw;

	GIT_REFCOUNT_DEC(*old, git_attr_assignment__free);
	*old = new;
	return GIT_EEXISTS;
}

730 731
int git_attr_assignment__parse(
	git_repository *repo,
732
	git_pool *pool,
733 734 735
	git_vector *assigns,
	const char **base)
{
736
	int error;
737 738 739 740 741
	const char *scan = *base;
	git_attr_assignment *assign = NULL;

	assert(assigns && !assigns->length);

742
	git_vector_set_cmp(assigns, sort_by_hash_and_name);
743

744
	while (*scan && *scan != '\n') {
745 746 747
		const char *name_start, *value_start;

		/* skip leading blanks */
748
		while (git__isspace(*scan) && *scan != '\n') scan++;
749 750 751 752

		/* allocate assign if needed */
		if (!assign) {
			assign = git__calloc(1, sizeof(git_attr_assignment));
753
			GITERR_CHECK_ALLOC(assign);
754
			GIT_REFCOUNT_INC(assign);
755 756 757
		}

		assign->name_hash = 5381;
758
		assign->value = git_attr__true;
759 760 761

		/* look for magic name prefixes */
		if (*scan == '-') {
762
			assign->value = git_attr__false;
763 764
			scan++;
		} else if (*scan == '!') {
765
			assign->value = git_attr__unset; /* explicit unspecified state */
766 767 768 769 770 771
			scan++;
		} else if (*scan == '#') /* comment rest of line */
			break;

		/* find the name */
		name_start = scan;
772
		while (*scan && !git__isspace(*scan) && *scan != '=') {
773 774 775 776
			assign->name_hash =
				((assign->name_hash << 5) + assign->name_hash) + *scan;
			scan++;
		}
777
		if (scan == name_start) {
778 779 780
			/* must have found lone prefix (" - ") or leading = ("=foo")
			 * or end of buffer -- advance until whitespace and continue
			 */
781
			while (*scan && !git__isspace(*scan)) scan++;
782 783 784
			continue;
		}

785
		/* allocate permanent storage for name */
786
		assign->name = git_pool_strndup(pool, name_start, scan - name_start);
787
		GITERR_CHECK_ALLOC(assign->name);
788

789 790
		/* if there is an equals sign, find the value */
		if (*scan == '=') {
791
			for (value_start = ++scan; *scan && !git__isspace(*scan); ++scan);
792 793 794

			/* if we found a value, allocate permanent storage for it */
			if (scan > value_start) {
795
				assign->value = git_pool_strndup(pool, value_start, scan - value_start);
796
				GITERR_CHECK_ALLOC(assign->value);
797 798 799
			}
		}

800
		/* expand macros (if given a repo with a macro cache) */
801
		if (repo != NULL && assign->value == git_attr__true) {
802 803
			git_attr_rule *macro =
				git_attr_cache__lookup_macro(repo, assign->name);
804 805 806 807 808

			if (macro != NULL) {
				unsigned int i;
				git_attr_assignment *massign;

809 810
				git_vector_foreach(&macro->assigns, i, massign) {
					GIT_REFCOUNT_INC(massign);
811

812 813
					error = git_vector_insert_sorted(
						assigns, massign, &merge_assignments);
Jacques Germishuys committed
814 815
					if (error < 0 && error != GIT_EEXISTS) {
						git_attr_assignment__free(assign);
816
						return error;
Jacques Germishuys committed
817
					}
818 819
				}
			}
820 821 822
		}

		/* insert allocated assign into vector */
823
		error = git_vector_insert_sorted(assigns, assign, &merge_assignments);
824 825
		if (error < 0 && error != GIT_EEXISTS)
			return error;
826 827 828 829 830

		/* clear assign since it is now "owned" by the vector */
		assign = NULL;
	}

831
	if (assign != NULL)
832
		git_attr_assignment__free(assign);
833

834
	*base = git__next_line(scan);
835

836
	return (assigns->length == 0) ? GIT_ENOTFOUND : 0;
837 838
}

Russell Belfer committed
839
static void git_attr_rule__clear(git_attr_rule *rule)
840 841 842 843 844
{
	unsigned int i;
	git_attr_assignment *assign;

	if (!rule)
845
		return;
846

847 848 849 850 851 852
	if (!(rule->match.flags & GIT_ATTR_FNMATCH_IGNORE)) {
		git_vector_foreach(&rule->assigns, i, assign)
			GIT_REFCOUNT_DEC(assign, git_attr_assignment__free);
		git_vector_free(&rule->assigns);
	}

853
	/* match.pattern is stored in a git_pool, so no need to free */
854 855 856
	rule->match.pattern = NULL;
	rule->match.length = 0;
}
Russell Belfer committed
857 858 859 860 861 862 863

void git_attr_rule__free(git_attr_rule *rule)
{
	git_attr_rule__clear(rule);
	git__free(rule);
}

864 865 866 867 868 869 870 871
int git_attr_session__init(git_attr_session *session, git_repository *repo)
{
	assert(repo);

	session->key = git_atomic_inc(&repo->attr_session_key);

	return 0;
}
872 873 874 875 876 877 878

void git_attr_session__free(git_attr_session *session)
{
	if (!session)
		return;

	git_buf_free(&session->sysdir);
879
	git_buf_free(&session->tmp);
880 881 882

	memset(session, 0, sizeof(git_attr_session));
}