Merge branch 'ds/fsck-bitmap'
[git/gitster.git] / attr.c
blobddf2b0cbc2ec8e0deac3b03cbfffae84af0a075a
1 /*
2 * Handle git attributes. See gitattributes(5) for a description of
3 * the file syntax, and attr.h for a description of the API.
5 * One basic design decision here is that we are not going to support
6 * an insanely large number of attributes.
7 */
9 #include "cache.h"
10 #include "alloc.h"
11 #include "config.h"
12 #include "environment.h"
13 #include "exec-cmd.h"
14 #include "attr.h"
15 #include "dir.h"
16 #include "gettext.h"
17 #include "utf8.h"
18 #include "quote.h"
19 #include "revision.h"
20 #include "object-store.h"
21 #include "setup.h"
22 #include "thread-utils.h"
23 #include "tree-walk.h"
25 const char git_attr__true[] = "(builtin)true";
26 const char git_attr__false[] = "\0(builtin)false";
27 static const char git_attr__unknown[] = "(builtin)unknown";
28 #define ATTR__TRUE git_attr__true
29 #define ATTR__FALSE git_attr__false
30 #define ATTR__UNSET NULL
31 #define ATTR__UNKNOWN git_attr__unknown
33 struct git_attr {
34 unsigned int attr_nr; /* unique attribute number */
35 char name[FLEX_ARRAY]; /* attribute name */
38 const char *git_attr_name(const struct git_attr *attr)
40 return attr->name;
43 struct attr_hashmap {
44 struct hashmap map;
45 pthread_mutex_t mutex;
48 static inline void hashmap_lock(struct attr_hashmap *map)
50 pthread_mutex_lock(&map->mutex);
53 static inline void hashmap_unlock(struct attr_hashmap *map)
55 pthread_mutex_unlock(&map->mutex);
58 /* The container for objects stored in "struct attr_hashmap" */
59 struct attr_hash_entry {
60 struct hashmap_entry ent;
61 const char *key; /* the key; memory should be owned by value */
62 size_t keylen; /* length of the key */
63 void *value; /* the stored value */
66 /* attr_hashmap comparison function */
67 static int attr_hash_entry_cmp(const void *cmp_data UNUSED,
68 const struct hashmap_entry *eptr,
69 const struct hashmap_entry *entry_or_key,
70 const void *keydata UNUSED)
72 const struct attr_hash_entry *a, *b;
74 a = container_of(eptr, const struct attr_hash_entry, ent);
75 b = container_of(entry_or_key, const struct attr_hash_entry, ent);
76 return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
80 * The global dictionary of all interned attributes. This
81 * is a singleton object which is shared between threads.
82 * Access to this dictionary must be surrounded with a mutex.
84 static struct attr_hashmap g_attr_hashmap = {
85 .map = HASHMAP_INIT(attr_hash_entry_cmp, NULL),
89 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
90 * If there is no matching entry, return NULL.
92 static void *attr_hashmap_get(struct attr_hashmap *map,
93 const char *key, size_t keylen)
95 struct attr_hash_entry k;
96 struct attr_hash_entry *e;
98 hashmap_entry_init(&k.ent, memhash(key, keylen));
99 k.key = key;
100 k.keylen = keylen;
101 e = hashmap_get_entry(&map->map, &k, ent, NULL);
103 return e ? e->value : NULL;
106 /* Add 'value' to a hashmap based on the provided 'key'. */
107 static void attr_hashmap_add(struct attr_hashmap *map,
108 const char *key, size_t keylen,
109 void *value)
111 struct attr_hash_entry *e;
113 e = xmalloc(sizeof(struct attr_hash_entry));
114 hashmap_entry_init(&e->ent, memhash(key, keylen));
115 e->key = key;
116 e->keylen = keylen;
117 e->value = value;
119 hashmap_add(&map->map, &e->ent);
122 struct all_attrs_item {
123 const struct git_attr *attr;
124 const char *value;
126 * If 'macro' is non-NULL, indicates that 'attr' is a macro based on
127 * the current attribute stack and contains a pointer to the match_attr
128 * definition of the macro
130 const struct match_attr *macro;
134 * Reallocate and reinitialize the array of all attributes (which is used in
135 * the attribute collection process) in 'check' based on the global dictionary
136 * of attributes.
138 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
140 int i;
141 unsigned int size;
143 hashmap_lock(map);
145 size = hashmap_get_size(&map->map);
146 if (size < check->all_attrs_nr)
147 BUG("interned attributes shouldn't be deleted");
150 * If the number of attributes in the global dictionary has increased
151 * (or this attr_check instance doesn't have an initialized all_attrs
152 * field), reallocate the provided attr_check instance's all_attrs
153 * field and fill each entry with its corresponding git_attr.
155 if (size != check->all_attrs_nr) {
156 struct attr_hash_entry *e;
157 struct hashmap_iter iter;
159 REALLOC_ARRAY(check->all_attrs, size);
160 check->all_attrs_nr = size;
162 hashmap_for_each_entry(&map->map, &iter, e,
163 ent /* member name */) {
164 const struct git_attr *a = e->value;
165 check->all_attrs[a->attr_nr].attr = a;
169 hashmap_unlock(map);
172 * Re-initialize every entry in check->all_attrs.
173 * This re-initialization can live outside of the locked region since
174 * the attribute dictionary is no longer being accessed.
176 for (i = 0; i < check->all_attrs_nr; i++) {
177 check->all_attrs[i].value = ATTR__UNKNOWN;
178 check->all_attrs[i].macro = NULL;
182 static int attr_name_valid(const char *name, size_t namelen)
185 * Attribute name cannot begin with '-' and must consist of
186 * characters from [-A-Za-z0-9_.].
188 if (namelen <= 0 || *name == '-')
189 return 0;
190 while (namelen--) {
191 char ch = *name++;
192 if (! (ch == '-' || ch == '.' || ch == '_' ||
193 ('0' <= ch && ch <= '9') ||
194 ('a' <= ch && ch <= 'z') ||
195 ('A' <= ch && ch <= 'Z')) )
196 return 0;
198 return 1;
201 static void report_invalid_attr(const char *name, size_t len,
202 const char *src, int lineno)
204 struct strbuf err = STRBUF_INIT;
205 strbuf_addf(&err, _("%.*s is not a valid attribute name"),
206 (int) len, name);
207 fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
208 strbuf_release(&err);
212 * Given a 'name', lookup and return the corresponding attribute in the global
213 * dictionary. If no entry is found, create a new attribute and store it in
214 * the dictionary.
216 static const struct git_attr *git_attr_internal(const char *name, size_t namelen)
218 struct git_attr *a;
220 if (!attr_name_valid(name, namelen))
221 return NULL;
223 hashmap_lock(&g_attr_hashmap);
225 a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
227 if (!a) {
228 FLEX_ALLOC_MEM(a, name, name, namelen);
229 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
231 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
232 if (a->attr_nr != hashmap_get_size(&g_attr_hashmap.map) - 1)
233 die(_("unable to add additional attribute"));
236 hashmap_unlock(&g_attr_hashmap);
238 return a;
241 const struct git_attr *git_attr(const char *name)
243 return git_attr_internal(name, strlen(name));
246 /* What does a matched pattern decide? */
247 struct attr_state {
248 const struct git_attr *attr;
249 const char *setto;
252 struct pattern {
253 const char *pattern;
254 int patternlen;
255 int nowildcardlen;
256 unsigned flags; /* PATTERN_FLAG_* */
260 * One rule, as from a .gitattributes file.
262 * If is_macro is true, then u.attr is a pointer to the git_attr being
263 * defined.
265 * If is_macro is false, then u.pat is the filename pattern to which the
266 * rule applies.
268 * In either case, num_attr is the number of attributes affected by
269 * this rule, and state is an array listing them. The attributes are
270 * listed as they appear in the file (macros unexpanded).
272 struct match_attr {
273 union {
274 struct pattern pat;
275 const struct git_attr *attr;
276 } u;
277 char is_macro;
278 size_t num_attr;
279 struct attr_state state[FLEX_ARRAY];
282 static const char blank[] = " \t\r\n";
284 /* Flags usable in read_attr() and parse_attr_line() family of functions. */
285 #define READ_ATTR_MACRO_OK (1<<0)
286 #define READ_ATTR_NOFOLLOW (1<<1)
289 * Parse a whitespace-delimited attribute state (i.e., "attr",
290 * "-attr", "!attr", or "attr=value") from the string starting at src.
291 * If e is not NULL, write the results to *e. Return a pointer to the
292 * remainder of the string (with leading whitespace removed), or NULL
293 * if there was an error.
295 static const char *parse_attr(const char *src, int lineno, const char *cp,
296 struct attr_state *e)
298 const char *ep, *equals;
299 size_t len;
301 ep = cp + strcspn(cp, blank);
302 equals = strchr(cp, '=');
303 if (equals && ep < equals)
304 equals = NULL;
305 if (equals)
306 len = equals - cp;
307 else
308 len = ep - cp;
309 if (!e) {
310 if (*cp == '-' || *cp == '!') {
311 cp++;
312 len--;
314 if (!attr_name_valid(cp, len)) {
315 report_invalid_attr(cp, len, src, lineno);
316 return NULL;
318 } else {
320 * As this function is always called twice, once with
321 * e == NULL in the first pass and then e != NULL in
322 * the second pass, no need for attr_name_valid()
323 * check here.
325 if (*cp == '-' || *cp == '!') {
326 e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
327 cp++;
328 len--;
330 else if (!equals)
331 e->setto = ATTR__TRUE;
332 else {
333 e->setto = xmemdupz(equals + 1, ep - equals - 1);
335 e->attr = git_attr_internal(cp, len);
337 return ep + strspn(ep, blank);
340 static struct match_attr *parse_attr_line(const char *line, const char *src,
341 int lineno, unsigned flags)
343 size_t namelen, num_attr, i;
344 const char *cp, *name, *states;
345 struct match_attr *res = NULL;
346 int is_macro;
347 struct strbuf pattern = STRBUF_INIT;
349 cp = line + strspn(line, blank);
350 if (!*cp || *cp == '#')
351 return NULL;
352 name = cp;
354 if (strlen(line) >= ATTR_MAX_LINE_LENGTH) {
355 warning(_("ignoring overly long attributes line %d"), lineno);
356 return NULL;
359 if (*cp == '"' && !unquote_c_style(&pattern, name, &states)) {
360 name = pattern.buf;
361 namelen = pattern.len;
362 } else {
363 namelen = strcspn(name, blank);
364 states = name + namelen;
367 if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
368 starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
369 if (!(flags & READ_ATTR_MACRO_OK)) {
370 fprintf_ln(stderr, _("%s not allowed: %s:%d"),
371 name, src, lineno);
372 goto fail_return;
374 is_macro = 1;
375 name += strlen(ATTRIBUTE_MACRO_PREFIX);
376 name += strspn(name, blank);
377 namelen = strcspn(name, blank);
378 if (!attr_name_valid(name, namelen)) {
379 report_invalid_attr(name, namelen, src, lineno);
380 goto fail_return;
383 else
384 is_macro = 0;
386 states += strspn(states, blank);
388 /* First pass to count the attr_states */
389 for (cp = states, num_attr = 0; *cp; num_attr++) {
390 cp = parse_attr(src, lineno, cp, NULL);
391 if (!cp)
392 goto fail_return;
395 res = xcalloc(1, st_add3(sizeof(*res),
396 st_mult(sizeof(struct attr_state), num_attr),
397 is_macro ? 0 : namelen + 1));
398 if (is_macro) {
399 res->u.attr = git_attr_internal(name, namelen);
400 } else {
401 char *p = (char *)&(res->state[num_attr]);
402 memcpy(p, name, namelen);
403 res->u.pat.pattern = p;
404 parse_path_pattern(&res->u.pat.pattern,
405 &res->u.pat.patternlen,
406 &res->u.pat.flags,
407 &res->u.pat.nowildcardlen);
408 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
409 warning(_("Negative patterns are ignored in git attributes\n"
410 "Use '\\!' for literal leading exclamation."));
411 goto fail_return;
414 res->is_macro = is_macro;
415 res->num_attr = num_attr;
417 /* Second pass to fill the attr_states */
418 for (cp = states, i = 0; *cp; i++) {
419 cp = parse_attr(src, lineno, cp, &(res->state[i]));
422 strbuf_release(&pattern);
423 return res;
425 fail_return:
426 strbuf_release(&pattern);
427 free(res);
428 return NULL;
432 * Like info/exclude and .gitignore, the attribute information can
433 * come from many places.
435 * (1) .gitattributes file of the same directory;
436 * (2) .gitattributes file of the parent directory if (1) does not have
437 * any match; this goes recursively upwards, just like .gitignore.
438 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
440 * In the same file, later entries override the earlier match, so in the
441 * global list, we would have entries from info/attributes the earliest
442 * (reading the file from top to bottom), .gitattributes of the root
443 * directory (again, reading the file from top to bottom) down to the
444 * current directory, and then scan the list backwards to find the first match.
445 * This is exactly the same as what is_excluded() does in dir.c to deal with
446 * .gitignore file and info/excludes file as a fallback.
449 struct attr_stack {
450 struct attr_stack *prev;
451 char *origin;
452 size_t originlen;
453 unsigned num_matches;
454 unsigned alloc;
455 struct match_attr **attrs;
458 static void attr_stack_free(struct attr_stack *e)
460 unsigned i;
461 free(e->origin);
462 for (i = 0; i < e->num_matches; i++) {
463 struct match_attr *a = e->attrs[i];
464 size_t j;
466 for (j = 0; j < a->num_attr; j++) {
467 const char *setto = a->state[j].setto;
468 if (setto == ATTR__TRUE ||
469 setto == ATTR__FALSE ||
470 setto == ATTR__UNSET ||
471 setto == ATTR__UNKNOWN)
473 else
474 free((char *) setto);
476 free(a);
478 free(e->attrs);
479 free(e);
482 static void drop_attr_stack(struct attr_stack **stack)
484 while (*stack) {
485 struct attr_stack *elem = *stack;
486 *stack = elem->prev;
487 attr_stack_free(elem);
491 /* List of all attr_check structs; access should be surrounded by mutex */
492 static struct check_vector {
493 size_t nr;
494 size_t alloc;
495 struct attr_check **checks;
496 pthread_mutex_t mutex;
497 } check_vector;
499 static inline void vector_lock(void)
501 pthread_mutex_lock(&check_vector.mutex);
504 static inline void vector_unlock(void)
506 pthread_mutex_unlock(&check_vector.mutex);
509 static void check_vector_add(struct attr_check *c)
511 vector_lock();
513 ALLOC_GROW(check_vector.checks,
514 check_vector.nr + 1,
515 check_vector.alloc);
516 check_vector.checks[check_vector.nr++] = c;
518 vector_unlock();
521 static void check_vector_remove(struct attr_check *check)
523 int i;
525 vector_lock();
527 /* Find entry */
528 for (i = 0; i < check_vector.nr; i++)
529 if (check_vector.checks[i] == check)
530 break;
532 if (i >= check_vector.nr)
533 BUG("no entry found");
535 /* shift entries over */
536 for (; i < check_vector.nr - 1; i++)
537 check_vector.checks[i] = check_vector.checks[i + 1];
539 check_vector.nr--;
541 vector_unlock();
544 /* Iterate through all attr_check instances and drop their stacks */
545 static void drop_all_attr_stacks(void)
547 int i;
549 vector_lock();
551 for (i = 0; i < check_vector.nr; i++) {
552 drop_attr_stack(&check_vector.checks[i]->stack);
555 vector_unlock();
558 struct attr_check *attr_check_alloc(void)
560 struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
562 /* save pointer to the check struct */
563 check_vector_add(c);
565 return c;
568 struct attr_check *attr_check_initl(const char *one, ...)
570 struct attr_check *check;
571 int cnt;
572 va_list params;
573 const char *param;
575 va_start(params, one);
576 for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
578 va_end(params);
580 check = attr_check_alloc();
581 check->nr = cnt;
582 check->alloc = cnt;
583 CALLOC_ARRAY(check->items, cnt);
585 check->items[0].attr = git_attr(one);
586 va_start(params, one);
587 for (cnt = 1; cnt < check->nr; cnt++) {
588 const struct git_attr *attr;
589 param = va_arg(params, const char *);
590 if (!param)
591 BUG("counted %d != ended at %d",
592 check->nr, cnt);
593 attr = git_attr(param);
594 if (!attr)
595 BUG("%s: not a valid attribute name", param);
596 check->items[cnt].attr = attr;
598 va_end(params);
599 return check;
602 struct attr_check *attr_check_dup(const struct attr_check *check)
604 struct attr_check *ret;
606 if (!check)
607 return NULL;
609 ret = attr_check_alloc();
611 ret->nr = check->nr;
612 ret->alloc = check->alloc;
613 DUP_ARRAY(ret->items, check->items, ret->nr);
615 return ret;
618 struct attr_check_item *attr_check_append(struct attr_check *check,
619 const struct git_attr *attr)
621 struct attr_check_item *item;
623 ALLOC_GROW(check->items, check->nr + 1, check->alloc);
624 item = &check->items[check->nr++];
625 item->attr = attr;
626 return item;
629 void attr_check_reset(struct attr_check *check)
631 check->nr = 0;
634 void attr_check_clear(struct attr_check *check)
636 FREE_AND_NULL(check->items);
637 check->alloc = 0;
638 check->nr = 0;
640 FREE_AND_NULL(check->all_attrs);
641 check->all_attrs_nr = 0;
643 drop_attr_stack(&check->stack);
646 void attr_check_free(struct attr_check *check)
648 if (check) {
649 /* Remove check from the check vector */
650 check_vector_remove(check);
652 attr_check_clear(check);
653 free(check);
657 static const char *builtin_attr[] = {
658 "[attr]binary -diff -merge -text",
659 NULL,
662 static void handle_attr_line(struct attr_stack *res,
663 const char *line,
664 const char *src,
665 int lineno,
666 unsigned flags)
668 struct match_attr *a;
670 a = parse_attr_line(line, src, lineno, flags);
671 if (!a)
672 return;
673 ALLOC_GROW_BY(res->attrs, res->num_matches, 1, res->alloc);
674 res->attrs[res->num_matches - 1] = a;
677 static struct attr_stack *read_attr_from_array(const char **list)
679 struct attr_stack *res;
680 const char *line;
681 int lineno = 0;
683 CALLOC_ARRAY(res, 1);
684 while ((line = *(list++)) != NULL)
685 handle_attr_line(res, line, "[builtin]", ++lineno,
686 READ_ATTR_MACRO_OK);
687 return res;
691 * Callers into the attribute system assume there is a single, system-wide
692 * global state where attributes are read from and when the state is flipped by
693 * calling git_attr_set_direction(), the stack frames that have been
694 * constructed need to be discarded so that subsequent calls into the
695 * attribute system will lazily read from the right place. Since changing
696 * direction causes a global paradigm shift, it should not ever be called while
697 * another thread could potentially be calling into the attribute system.
699 static enum git_attr_direction direction;
701 void git_attr_set_direction(enum git_attr_direction new_direction)
703 if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
704 BUG("non-INDEX attr direction in a bare repo");
706 if (new_direction != direction)
707 drop_all_attr_stacks();
709 direction = new_direction;
712 static struct attr_stack *read_attr_from_file(const char *path, unsigned flags)
714 struct strbuf buf = STRBUF_INIT;
715 int fd;
716 FILE *fp;
717 struct attr_stack *res;
718 int lineno = 0;
719 struct stat st;
721 if (flags & READ_ATTR_NOFOLLOW)
722 fd = open_nofollow(path, O_RDONLY);
723 else
724 fd = open(path, O_RDONLY);
726 if (fd < 0) {
727 warn_on_fopen_errors(path);
728 return NULL;
730 fp = xfdopen(fd, "r");
731 if (fstat(fd, &st)) {
732 warning_errno(_("cannot fstat gitattributes file '%s'"), path);
733 fclose(fp);
734 return NULL;
736 if (st.st_size >= ATTR_MAX_FILE_SIZE) {
737 warning(_("ignoring overly large gitattributes file '%s'"), path);
738 fclose(fp);
739 return NULL;
742 CALLOC_ARRAY(res, 1);
743 while (strbuf_getline(&buf, fp) != EOF) {
744 if (!lineno && starts_with(buf.buf, utf8_bom))
745 strbuf_remove(&buf, 0, strlen(utf8_bom));
746 handle_attr_line(res, buf.buf, path, ++lineno, flags);
749 fclose(fp);
750 strbuf_release(&buf);
751 return res;
754 static struct attr_stack *read_attr_from_buf(char *buf, const char *path,
755 unsigned flags)
757 struct attr_stack *res;
758 char *sp;
759 int lineno = 0;
761 if (!buf)
762 return NULL;
764 CALLOC_ARRAY(res, 1);
765 for (sp = buf; *sp;) {
766 char *ep;
767 int more;
769 ep = strchrnul(sp, '\n');
770 more = (*ep == '\n');
771 *ep = '\0';
772 handle_attr_line(res, sp, path, ++lineno, flags);
773 sp = ep + more;
775 free(buf);
777 return res;
780 static struct attr_stack *read_attr_from_blob(struct index_state *istate,
781 const struct object_id *tree_oid,
782 const char *path, unsigned flags)
784 struct object_id oid;
785 unsigned long sz;
786 enum object_type type;
787 void *buf;
788 unsigned short mode;
790 if (!tree_oid)
791 return NULL;
793 if (get_tree_entry(istate->repo, tree_oid, path, &oid, &mode))
794 return NULL;
796 buf = repo_read_object_file(istate->repo, &oid, &type, &sz);
797 if (!buf || type != OBJ_BLOB) {
798 free(buf);
799 return NULL;
802 return read_attr_from_buf(buf, path, flags);
805 static struct attr_stack *read_attr_from_index(struct index_state *istate,
806 const char *path, unsigned flags)
808 char *buf;
809 unsigned long size;
811 if (!istate)
812 return NULL;
815 * The .gitattributes file only applies to files within its
816 * parent directory. In the case of cone-mode sparse-checkout,
817 * the .gitattributes file is sparse if and only if all paths
818 * within that directory are also sparse. Thus, don't load the
819 * .gitattributes file since it will not matter.
821 * In the case of a sparse index, it is critical that we don't go
822 * looking for a .gitattributes file, as doing so would cause the
823 * index to expand.
825 if (!path_in_cone_mode_sparse_checkout(path, istate))
826 return NULL;
828 buf = read_blob_data_from_index(istate, path, &size);
829 if (!buf)
830 return NULL;
831 if (size >= ATTR_MAX_FILE_SIZE) {
832 warning(_("ignoring overly large gitattributes blob '%s'"), path);
833 return NULL;
836 return read_attr_from_buf(buf, path, flags);
839 static struct attr_stack *read_attr(struct index_state *istate,
840 const struct object_id *tree_oid,
841 const char *path, unsigned flags)
843 struct attr_stack *res = NULL;
845 if (direction == GIT_ATTR_INDEX) {
846 res = read_attr_from_index(istate, path, flags);
847 } else if (tree_oid) {
848 res = read_attr_from_blob(istate, tree_oid, path, flags);
849 } else if (!is_bare_repository()) {
850 if (direction == GIT_ATTR_CHECKOUT) {
851 res = read_attr_from_index(istate, path, flags);
852 if (!res)
853 res = read_attr_from_file(path, flags);
854 } else if (direction == GIT_ATTR_CHECKIN) {
855 res = read_attr_from_file(path, flags);
856 if (!res)
858 * There is no checked out .gitattributes file
859 * there, but we might have it in the index.
860 * We allow operation in a sparsely checked out
861 * work tree, so read from it.
863 res = read_attr_from_index(istate, path, flags);
867 if (!res)
868 CALLOC_ARRAY(res, 1);
869 return res;
872 static const char *git_etc_gitattributes(void)
874 static const char *system_wide;
875 if (!system_wide)
876 system_wide = system_path(ETC_GITATTRIBUTES);
877 return system_wide;
880 static const char *get_home_gitattributes(void)
882 if (!git_attributes_file)
883 git_attributes_file = xdg_config_home("attributes");
885 return git_attributes_file;
888 static int git_attr_system(void)
890 return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
893 static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
895 static void push_stack(struct attr_stack **attr_stack_p,
896 struct attr_stack *elem, char *origin, size_t originlen)
898 if (elem) {
899 elem->origin = origin;
900 if (origin)
901 elem->originlen = originlen;
902 elem->prev = *attr_stack_p;
903 *attr_stack_p = elem;
907 static void bootstrap_attr_stack(struct index_state *istate,
908 const struct object_id *tree_oid,
909 struct attr_stack **stack)
911 struct attr_stack *e;
912 unsigned flags = READ_ATTR_MACRO_OK;
914 if (*stack)
915 return;
917 /* builtin frame */
918 e = read_attr_from_array(builtin_attr);
919 push_stack(stack, e, NULL, 0);
921 /* system-wide frame */
922 if (git_attr_system()) {
923 e = read_attr_from_file(git_etc_gitattributes(), flags);
924 push_stack(stack, e, NULL, 0);
927 /* home directory */
928 if (get_home_gitattributes()) {
929 e = read_attr_from_file(get_home_gitattributes(), flags);
930 push_stack(stack, e, NULL, 0);
933 /* root directory */
934 e = read_attr(istate, tree_oid, GITATTRIBUTES_FILE, flags | READ_ATTR_NOFOLLOW);
935 push_stack(stack, e, xstrdup(""), 0);
937 /* info frame */
938 if (startup_info->have_repository)
939 e = read_attr_from_file(git_path_info_attributes(), flags);
940 else
941 e = NULL;
942 if (!e)
943 CALLOC_ARRAY(e, 1);
944 push_stack(stack, e, NULL, 0);
947 static void prepare_attr_stack(struct index_state *istate,
948 const struct object_id *tree_oid,
949 const char *path, int dirlen,
950 struct attr_stack **stack)
952 struct attr_stack *info;
953 struct strbuf pathbuf = STRBUF_INIT;
956 * At the bottom of the attribute stack is the built-in
957 * set of attribute definitions, followed by the contents
958 * of $(prefix)/etc/gitattributes and a file specified by
959 * core.attributesfile. Then, contents from
960 * .gitattributes files from directories closer to the
961 * root to the ones in deeper directories are pushed
962 * to the stack. Finally, at the very top of the stack
963 * we always keep the contents of $GIT_DIR/info/attributes.
965 * When checking, we use entries from near the top of the
966 * stack, preferring $GIT_DIR/info/attributes, then
967 * .gitattributes in deeper directories to shallower ones,
968 * and finally use the built-in set as the default.
970 bootstrap_attr_stack(istate, tree_oid, stack);
973 * Pop the "info" one that is always at the top of the stack.
975 info = *stack;
976 *stack = info->prev;
979 * Pop the ones from directories that are not the prefix of
980 * the path we are checking. Break out of the loop when we see
981 * the root one (whose origin is an empty string "") or the builtin
982 * one (whose origin is NULL) without popping it.
984 while ((*stack)->origin) {
985 int namelen = (*stack)->originlen;
986 struct attr_stack *elem;
988 elem = *stack;
989 if (namelen <= dirlen &&
990 !strncmp(elem->origin, path, namelen) &&
991 (!namelen || path[namelen] == '/'))
992 break;
994 *stack = elem->prev;
995 attr_stack_free(elem);
999 * bootstrap_attr_stack() should have added, and the
1000 * above loop should have stopped before popping, the
1001 * root element whose attr_stack->origin is set to an
1002 * empty string.
1004 assert((*stack)->origin);
1006 strbuf_addstr(&pathbuf, (*stack)->origin);
1007 /* Build up to the directory 'path' is in */
1008 while (pathbuf.len < dirlen) {
1009 size_t len = pathbuf.len;
1010 struct attr_stack *next;
1011 char *origin;
1013 /* Skip path-separator */
1014 if (len < dirlen && is_dir_sep(path[len]))
1015 len++;
1016 /* Find the end of the next component */
1017 while (len < dirlen && !is_dir_sep(path[len]))
1018 len++;
1020 if (pathbuf.len > 0)
1021 strbuf_addch(&pathbuf, '/');
1022 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
1023 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
1025 next = read_attr(istate, tree_oid, pathbuf.buf, READ_ATTR_NOFOLLOW);
1027 /* reset the pathbuf to not include "/.gitattributes" */
1028 strbuf_setlen(&pathbuf, len);
1030 origin = xstrdup(pathbuf.buf);
1031 push_stack(stack, next, origin, len);
1035 * Finally push the "info" one at the top of the stack.
1037 push_stack(stack, info, NULL, 0);
1039 strbuf_release(&pathbuf);
1042 static int path_matches(const char *pathname, int pathlen,
1043 int basename_offset,
1044 const struct pattern *pat,
1045 const char *base, int baselen)
1047 const char *pattern = pat->pattern;
1048 int prefix = pat->nowildcardlen;
1049 int isdir = (pathlen && pathname[pathlen - 1] == '/');
1051 if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
1052 return 0;
1054 if (pat->flags & PATTERN_FLAG_NODIR) {
1055 return match_basename(pathname + basename_offset,
1056 pathlen - basename_offset - isdir,
1057 pattern, prefix,
1058 pat->patternlen, pat->flags);
1060 return match_pathname(pathname, pathlen - isdir,
1061 base, baselen,
1062 pattern, prefix, pat->patternlen);
1065 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
1067 static int fill_one(struct all_attrs_item *all_attrs,
1068 const struct match_attr *a, int rem)
1070 size_t i;
1072 for (i = a->num_attr; rem > 0 && i > 0; i--) {
1073 const struct git_attr *attr = a->state[i - 1].attr;
1074 const char **n = &(all_attrs[attr->attr_nr].value);
1075 const char *v = a->state[i - 1].setto;
1077 if (*n == ATTR__UNKNOWN) {
1078 *n = v;
1079 rem--;
1080 rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
1083 return rem;
1086 static int fill(const char *path, int pathlen, int basename_offset,
1087 const struct attr_stack *stack,
1088 struct all_attrs_item *all_attrs, int rem)
1090 for (; rem > 0 && stack; stack = stack->prev) {
1091 unsigned i;
1092 const char *base = stack->origin ? stack->origin : "";
1094 for (i = stack->num_matches; 0 < rem && 0 < i; i--) {
1095 const struct match_attr *a = stack->attrs[i - 1];
1096 if (a->is_macro)
1097 continue;
1098 if (path_matches(path, pathlen, basename_offset,
1099 &a->u.pat, base, stack->originlen))
1100 rem = fill_one(all_attrs, a, rem);
1104 return rem;
1107 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
1109 const struct all_attrs_item *item = &all_attrs[nr];
1111 if (item->macro && item->value == ATTR__TRUE)
1112 return fill_one(all_attrs, item->macro, rem);
1113 else
1114 return rem;
1118 * Marks the attributes which are macros based on the attribute stack.
1119 * This prevents having to search through the attribute stack each time
1120 * a macro needs to be expanded during the fill stage.
1122 static void determine_macros(struct all_attrs_item *all_attrs,
1123 const struct attr_stack *stack)
1125 for (; stack; stack = stack->prev) {
1126 unsigned i;
1127 for (i = stack->num_matches; i > 0; i--) {
1128 const struct match_attr *ma = stack->attrs[i - 1];
1129 if (ma->is_macro) {
1130 unsigned int n = ma->u.attr->attr_nr;
1131 if (!all_attrs[n].macro) {
1132 all_attrs[n].macro = ma;
1140 * Collect attributes for path into the array pointed to by check->all_attrs.
1141 * If check->check_nr is non-zero, only attributes in check[] are collected.
1142 * Otherwise all attributes are collected.
1144 static void collect_some_attrs(struct index_state *istate,
1145 const struct object_id *tree_oid,
1146 const char *path, struct attr_check *check)
1148 int pathlen, rem, dirlen;
1149 const char *cp, *last_slash = NULL;
1150 int basename_offset;
1152 for (cp = path; *cp; cp++) {
1153 if (*cp == '/' && cp[1])
1154 last_slash = cp;
1156 pathlen = cp - path;
1157 if (last_slash) {
1158 basename_offset = last_slash + 1 - path;
1159 dirlen = last_slash - path;
1160 } else {
1161 basename_offset = 0;
1162 dirlen = 0;
1165 prepare_attr_stack(istate, tree_oid, path, dirlen, &check->stack);
1166 all_attrs_init(&g_attr_hashmap, check);
1167 determine_macros(check->all_attrs, check->stack);
1169 rem = check->all_attrs_nr;
1170 fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
1173 void git_check_attr(struct index_state *istate,
1174 const struct object_id *tree_oid, const char *path,
1175 struct attr_check *check)
1177 int i;
1179 collect_some_attrs(istate, tree_oid, path, check);
1181 for (i = 0; i < check->nr; i++) {
1182 unsigned int n = check->items[i].attr->attr_nr;
1183 const char *value = check->all_attrs[n].value;
1184 if (value == ATTR__UNKNOWN)
1185 value = ATTR__UNSET;
1186 check->items[i].value = value;
1190 void git_all_attrs(struct index_state *istate, const struct object_id *tree_oid,
1191 const char *path, struct attr_check *check)
1193 int i;
1195 attr_check_reset(check);
1196 collect_some_attrs(istate, tree_oid, path, check);
1198 for (i = 0; i < check->all_attrs_nr; i++) {
1199 const char *name = check->all_attrs[i].attr->name;
1200 const char *value = check->all_attrs[i].value;
1201 struct attr_check_item *item;
1202 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1203 continue;
1204 item = attr_check_append(check, git_attr(name));
1205 item->value = value;
1209 void attr_start(void)
1211 pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1212 pthread_mutex_init(&check_vector.mutex, NULL);