t0410: make test description clearer
[git/gitster.git] / attr.c
blobc605d2c1703808668830947331fd4bc9c2a8fb54
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 #define USE_THE_REPOSITORY_VARIABLE
11 #include "git-compat-util.h"
12 #include "config.h"
13 #include "environment.h"
14 #include "exec-cmd.h"
15 #include "attr.h"
16 #include "dir.h"
17 #include "gettext.h"
18 #include "path.h"
19 #include "utf8.h"
20 #include "quote.h"
21 #include "read-cache-ll.h"
22 #include "refs.h"
23 #include "revision.h"
24 #include "object-store-ll.h"
25 #include "setup.h"
26 #include "thread-utils.h"
27 #include "tree-walk.h"
28 #include "object-name.h"
30 char *git_attr_tree;
32 const char git_attr__true[] = "(builtin)true";
33 const char git_attr__false[] = "\0(builtin)false";
34 static const char git_attr__unknown[] = "(builtin)unknown";
35 #define ATTR__TRUE git_attr__true
36 #define ATTR__FALSE git_attr__false
37 #define ATTR__UNSET NULL
38 #define ATTR__UNKNOWN git_attr__unknown
40 struct git_attr {
41 unsigned int attr_nr; /* unique attribute number */
42 char name[FLEX_ARRAY]; /* attribute name */
45 const char *git_attr_name(const struct git_attr *attr)
47 return attr->name;
50 struct attr_hashmap {
51 struct hashmap map;
52 pthread_mutex_t mutex;
55 static inline void hashmap_lock(struct attr_hashmap *map)
57 pthread_mutex_lock(&map->mutex);
60 static inline void hashmap_unlock(struct attr_hashmap *map)
62 pthread_mutex_unlock(&map->mutex);
65 /* The container for objects stored in "struct attr_hashmap" */
66 struct attr_hash_entry {
67 struct hashmap_entry ent;
68 const char *key; /* the key; memory should be owned by value */
69 size_t keylen; /* length of the key */
70 void *value; /* the stored value */
73 /* attr_hashmap comparison function */
74 static int attr_hash_entry_cmp(const void *cmp_data UNUSED,
75 const struct hashmap_entry *eptr,
76 const struct hashmap_entry *entry_or_key,
77 const void *keydata UNUSED)
79 const struct attr_hash_entry *a, *b;
81 a = container_of(eptr, const struct attr_hash_entry, ent);
82 b = container_of(entry_or_key, const struct attr_hash_entry, ent);
83 return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
87 * The global dictionary of all interned attributes. This
88 * is a singleton object which is shared between threads.
89 * Access to this dictionary must be surrounded with a mutex.
91 static struct attr_hashmap g_attr_hashmap = {
92 .map = HASHMAP_INIT(attr_hash_entry_cmp, NULL),
96 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
97 * If there is no matching entry, return NULL.
99 static void *attr_hashmap_get(struct attr_hashmap *map,
100 const char *key, size_t keylen)
102 struct attr_hash_entry k;
103 struct attr_hash_entry *e;
105 hashmap_entry_init(&k.ent, memhash(key, keylen));
106 k.key = key;
107 k.keylen = keylen;
108 e = hashmap_get_entry(&map->map, &k, ent, NULL);
110 return e ? e->value : NULL;
113 /* Add 'value' to a hashmap based on the provided 'key'. */
114 static void attr_hashmap_add(struct attr_hashmap *map,
115 const char *key, size_t keylen,
116 void *value)
118 struct attr_hash_entry *e;
120 e = xmalloc(sizeof(struct attr_hash_entry));
121 hashmap_entry_init(&e->ent, memhash(key, keylen));
122 e->key = key;
123 e->keylen = keylen;
124 e->value = value;
126 hashmap_add(&map->map, &e->ent);
129 struct all_attrs_item {
130 const struct git_attr *attr;
131 const char *value;
133 * If 'macro' is non-NULL, indicates that 'attr' is a macro based on
134 * the current attribute stack and contains a pointer to the match_attr
135 * definition of the macro
137 const struct match_attr *macro;
141 * Reallocate and reinitialize the array of all attributes (which is used in
142 * the attribute collection process) in 'check' based on the global dictionary
143 * of attributes.
145 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
147 int i;
148 unsigned int size;
150 hashmap_lock(map);
152 size = hashmap_get_size(&map->map);
153 if (size < check->all_attrs_nr)
154 BUG("interned attributes shouldn't be deleted");
157 * If the number of attributes in the global dictionary has increased
158 * (or this attr_check instance doesn't have an initialized all_attrs
159 * field), reallocate the provided attr_check instance's all_attrs
160 * field and fill each entry with its corresponding git_attr.
162 if (size != check->all_attrs_nr) {
163 struct attr_hash_entry *e;
164 struct hashmap_iter iter;
166 REALLOC_ARRAY(check->all_attrs, size);
167 check->all_attrs_nr = size;
169 hashmap_for_each_entry(&map->map, &iter, e,
170 ent /* member name */) {
171 const struct git_attr *a = e->value;
172 check->all_attrs[a->attr_nr].attr = a;
176 hashmap_unlock(map);
179 * Re-initialize every entry in check->all_attrs.
180 * This re-initialization can live outside of the locked region since
181 * the attribute dictionary is no longer being accessed.
183 for (i = 0; i < check->all_attrs_nr; i++) {
184 check->all_attrs[i].value = ATTR__UNKNOWN;
185 check->all_attrs[i].macro = NULL;
190 * Attribute name cannot begin with "builtin_" which
191 * is a reserved namespace for built in attributes values.
193 static int attr_name_reserved(const char *name)
195 return starts_with(name, "builtin_");
198 static int attr_name_valid(const char *name, size_t namelen)
201 * Attribute name cannot begin with '-' and must consist of
202 * characters from [-A-Za-z0-9_.].
204 if (namelen <= 0 || *name == '-')
205 return 0;
206 while (namelen--) {
207 char ch = *name++;
208 if (! (ch == '-' || ch == '.' || ch == '_' ||
209 ('0' <= ch && ch <= '9') ||
210 ('a' <= ch && ch <= 'z') ||
211 ('A' <= ch && ch <= 'Z')) )
212 return 0;
214 return 1;
217 static void report_invalid_attr(const char *name, size_t len,
218 const char *src, int lineno)
220 struct strbuf err = STRBUF_INIT;
221 strbuf_addf(&err, _("%.*s is not a valid attribute name"),
222 (int) len, name);
223 fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
224 strbuf_release(&err);
228 * Given a 'name', lookup and return the corresponding attribute in the global
229 * dictionary. If no entry is found, create a new attribute and store it in
230 * the dictionary.
232 static const struct git_attr *git_attr_internal(const char *name, size_t namelen)
234 struct git_attr *a;
236 if (!attr_name_valid(name, namelen))
237 return NULL;
239 hashmap_lock(&g_attr_hashmap);
241 a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
243 if (!a) {
244 FLEX_ALLOC_MEM(a, name, name, namelen);
245 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
247 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
248 if (a->attr_nr != hashmap_get_size(&g_attr_hashmap.map) - 1)
249 die(_("unable to add additional attribute"));
252 hashmap_unlock(&g_attr_hashmap);
254 return a;
257 const struct git_attr *git_attr(const char *name)
259 return git_attr_internal(name, strlen(name));
262 /* What does a matched pattern decide? */
263 struct attr_state {
264 const struct git_attr *attr;
265 const char *setto;
268 struct pattern {
269 const char *pattern;
270 int patternlen;
271 int nowildcardlen;
272 unsigned flags; /* PATTERN_FLAG_* */
276 * One rule, as from a .gitattributes file.
278 * If is_macro is true, then u.attr is a pointer to the git_attr being
279 * defined.
281 * If is_macro is false, then u.pat is the filename pattern to which the
282 * rule applies.
284 * In either case, num_attr is the number of attributes affected by
285 * this rule, and state is an array listing them. The attributes are
286 * listed as they appear in the file (macros unexpanded).
288 struct match_attr {
289 union {
290 struct pattern pat;
291 const struct git_attr *attr;
292 } u;
293 char is_macro;
294 size_t num_attr;
295 struct attr_state state[FLEX_ARRAY];
298 static const char blank[] = " \t\r\n";
300 /* Flags usable in read_attr() and parse_attr_line() family of functions. */
301 #define READ_ATTR_MACRO_OK (1<<0)
302 #define READ_ATTR_NOFOLLOW (1<<1)
305 * Parse a whitespace-delimited attribute state (i.e., "attr",
306 * "-attr", "!attr", or "attr=value") from the string starting at src.
307 * If e is not NULL, write the results to *e. Return a pointer to the
308 * remainder of the string (with leading whitespace removed), or NULL
309 * if there was an error.
311 static const char *parse_attr(const char *src, int lineno, const char *cp,
312 struct attr_state *e)
314 const char *ep, *equals;
315 size_t len;
317 ep = cp + strcspn(cp, blank);
318 equals = strchr(cp, '=');
319 if (equals && ep < equals)
320 equals = NULL;
321 if (equals)
322 len = equals - cp;
323 else
324 len = ep - cp;
325 if (!e) {
326 if (*cp == '-' || *cp == '!') {
327 cp++;
328 len--;
330 if (!attr_name_valid(cp, len) || attr_name_reserved(cp)) {
331 report_invalid_attr(cp, len, src, lineno);
332 return NULL;
334 } else {
336 * As this function is always called twice, once with
337 * e == NULL in the first pass and then e != NULL in
338 * the second pass, no need for attr_name_valid()
339 * check here.
341 if (*cp == '-' || *cp == '!') {
342 e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
343 cp++;
344 len--;
346 else if (!equals)
347 e->setto = ATTR__TRUE;
348 else {
349 e->setto = xmemdupz(equals + 1, ep - equals - 1);
351 e->attr = git_attr_internal(cp, len);
353 return ep + strspn(ep, blank);
356 static struct match_attr *parse_attr_line(const char *line, const char *src,
357 int lineno, unsigned flags)
359 size_t namelen, num_attr, i;
360 const char *cp, *name, *states;
361 struct match_attr *res = NULL;
362 int is_macro;
363 struct strbuf pattern = STRBUF_INIT;
365 cp = line + strspn(line, blank);
366 if (!*cp || *cp == '#')
367 return NULL;
368 name = cp;
370 if (strlen(line) >= ATTR_MAX_LINE_LENGTH) {
371 warning(_("ignoring overly long attributes line %d"), lineno);
372 return NULL;
375 if (*cp == '"' && !unquote_c_style(&pattern, name, &states)) {
376 name = pattern.buf;
377 namelen = pattern.len;
378 } else {
379 namelen = strcspn(name, blank);
380 states = name + namelen;
383 if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
384 starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
385 if (!(flags & READ_ATTR_MACRO_OK)) {
386 fprintf_ln(stderr, _("%s not allowed: %s:%d"),
387 name, src, lineno);
388 goto fail_return;
390 is_macro = 1;
391 name += strlen(ATTRIBUTE_MACRO_PREFIX);
392 name += strspn(name, blank);
393 namelen = strcspn(name, blank);
394 if (!attr_name_valid(name, namelen) || attr_name_reserved(name)) {
395 report_invalid_attr(name, namelen, src, lineno);
396 goto fail_return;
399 else
400 is_macro = 0;
402 states += strspn(states, blank);
404 /* First pass to count the attr_states */
405 for (cp = states, num_attr = 0; *cp; num_attr++) {
406 cp = parse_attr(src, lineno, cp, NULL);
407 if (!cp)
408 goto fail_return;
411 res = xcalloc(1, st_add3(sizeof(*res),
412 st_mult(sizeof(struct attr_state), num_attr),
413 is_macro ? 0 : namelen + 1));
414 if (is_macro) {
415 res->u.attr = git_attr_internal(name, namelen);
416 } else {
417 char *p = (char *)&(res->state[num_attr]);
418 memcpy(p, name, namelen);
419 res->u.pat.pattern = p;
420 parse_path_pattern(&res->u.pat.pattern,
421 &res->u.pat.patternlen,
422 &res->u.pat.flags,
423 &res->u.pat.nowildcardlen);
424 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
425 warning(_("Negative patterns are ignored in git attributes\n"
426 "Use '\\!' for literal leading exclamation."));
427 goto fail_return;
430 res->is_macro = is_macro;
431 res->num_attr = num_attr;
433 /* Second pass to fill the attr_states */
434 for (cp = states, i = 0; *cp; i++) {
435 cp = parse_attr(src, lineno, cp, &(res->state[i]));
438 strbuf_release(&pattern);
439 return res;
441 fail_return:
442 strbuf_release(&pattern);
443 free(res);
444 return NULL;
448 * Like info/exclude and .gitignore, the attribute information can
449 * come from many places.
451 * (1) .gitattributes file of the same directory;
452 * (2) .gitattributes file of the parent directory if (1) does not have
453 * any match; this goes recursively upwards, just like .gitignore.
454 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
456 * In the same file, later entries override the earlier match, so in the
457 * global list, we would have entries from info/attributes the earliest
458 * (reading the file from top to bottom), .gitattributes of the root
459 * directory (again, reading the file from top to bottom) down to the
460 * current directory, and then scan the list backwards to find the first match.
461 * This is exactly the same as what is_excluded() does in dir.c to deal with
462 * .gitignore file and info/excludes file as a fallback.
465 struct attr_stack {
466 struct attr_stack *prev;
467 char *origin;
468 size_t originlen;
469 unsigned num_matches;
470 unsigned alloc;
471 struct match_attr **attrs;
474 static void attr_stack_free(struct attr_stack *e)
476 unsigned i;
477 free(e->origin);
478 for (i = 0; i < e->num_matches; i++) {
479 struct match_attr *a = e->attrs[i];
480 size_t j;
482 for (j = 0; j < a->num_attr; j++) {
483 const char *setto = a->state[j].setto;
484 if (setto == ATTR__TRUE ||
485 setto == ATTR__FALSE ||
486 setto == ATTR__UNSET ||
487 setto == ATTR__UNKNOWN)
489 else
490 free((char *) setto);
492 free(a);
494 free(e->attrs);
495 free(e);
498 static void drop_attr_stack(struct attr_stack **stack)
500 while (*stack) {
501 struct attr_stack *elem = *stack;
502 *stack = elem->prev;
503 attr_stack_free(elem);
507 /* List of all attr_check structs; access should be surrounded by mutex */
508 static struct check_vector {
509 size_t nr;
510 size_t alloc;
511 struct attr_check **checks;
512 pthread_mutex_t mutex;
513 } check_vector;
515 static inline void vector_lock(void)
517 pthread_mutex_lock(&check_vector.mutex);
520 static inline void vector_unlock(void)
522 pthread_mutex_unlock(&check_vector.mutex);
525 static void check_vector_add(struct attr_check *c)
527 vector_lock();
529 ALLOC_GROW(check_vector.checks,
530 check_vector.nr + 1,
531 check_vector.alloc);
532 check_vector.checks[check_vector.nr++] = c;
534 vector_unlock();
537 static void check_vector_remove(struct attr_check *check)
539 int i;
541 vector_lock();
543 /* Find entry */
544 for (i = 0; i < check_vector.nr; i++)
545 if (check_vector.checks[i] == check)
546 break;
548 if (i >= check_vector.nr)
549 BUG("no entry found");
551 /* shift entries over */
552 for (; i < check_vector.nr - 1; i++)
553 check_vector.checks[i] = check_vector.checks[i + 1];
555 check_vector.nr--;
557 vector_unlock();
560 /* Iterate through all attr_check instances and drop their stacks */
561 static void drop_all_attr_stacks(void)
563 int i;
565 vector_lock();
567 for (i = 0; i < check_vector.nr; i++) {
568 drop_attr_stack(&check_vector.checks[i]->stack);
571 vector_unlock();
574 struct attr_check *attr_check_alloc(void)
576 struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
578 /* save pointer to the check struct */
579 check_vector_add(c);
581 return c;
584 struct attr_check *attr_check_initl(const char *one, ...)
586 struct attr_check *check;
587 int cnt;
588 va_list params;
589 const char *param;
591 va_start(params, one);
592 for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
594 va_end(params);
596 check = attr_check_alloc();
597 check->nr = cnt;
598 check->alloc = cnt;
599 CALLOC_ARRAY(check->items, cnt);
601 check->items[0].attr = git_attr(one);
602 va_start(params, one);
603 for (cnt = 1; cnt < check->nr; cnt++) {
604 const struct git_attr *attr;
605 param = va_arg(params, const char *);
606 if (!param)
607 BUG("counted %d != ended at %d",
608 check->nr, cnt);
609 attr = git_attr(param);
610 if (!attr)
611 BUG("%s: not a valid attribute name", param);
612 check->items[cnt].attr = attr;
614 va_end(params);
615 return check;
618 struct attr_check *attr_check_dup(const struct attr_check *check)
620 struct attr_check *ret;
622 if (!check)
623 return NULL;
625 ret = attr_check_alloc();
627 ret->nr = check->nr;
628 ret->alloc = check->alloc;
629 DUP_ARRAY(ret->items, check->items, ret->nr);
631 return ret;
634 struct attr_check_item *attr_check_append(struct attr_check *check,
635 const struct git_attr *attr)
637 struct attr_check_item *item;
639 ALLOC_GROW(check->items, check->nr + 1, check->alloc);
640 item = &check->items[check->nr++];
641 item->attr = attr;
642 return item;
645 void attr_check_reset(struct attr_check *check)
647 check->nr = 0;
650 void attr_check_clear(struct attr_check *check)
652 FREE_AND_NULL(check->items);
653 check->alloc = 0;
654 check->nr = 0;
656 FREE_AND_NULL(check->all_attrs);
657 check->all_attrs_nr = 0;
659 drop_attr_stack(&check->stack);
662 void attr_check_free(struct attr_check *check)
664 if (check) {
665 /* Remove check from the check vector */
666 check_vector_remove(check);
668 attr_check_clear(check);
669 free(check);
673 static const char *builtin_attr[] = {
674 "[attr]binary -diff -merge -text",
675 NULL,
678 static void handle_attr_line(struct attr_stack *res,
679 const char *line,
680 const char *src,
681 int lineno,
682 unsigned flags)
684 struct match_attr *a;
686 a = parse_attr_line(line, src, lineno, flags);
687 if (!a)
688 return;
689 ALLOC_GROW_BY(res->attrs, res->num_matches, 1, res->alloc);
690 res->attrs[res->num_matches - 1] = a;
693 static struct attr_stack *read_attr_from_array(const char **list)
695 struct attr_stack *res;
696 const char *line;
697 int lineno = 0;
699 CALLOC_ARRAY(res, 1);
700 while ((line = *(list++)) != NULL)
701 handle_attr_line(res, line, "[builtin]", ++lineno,
702 READ_ATTR_MACRO_OK);
703 return res;
707 * Callers into the attribute system assume there is a single, system-wide
708 * global state where attributes are read from and when the state is flipped by
709 * calling git_attr_set_direction(), the stack frames that have been
710 * constructed need to be discarded so that subsequent calls into the
711 * attribute system will lazily read from the right place. Since changing
712 * direction causes a global paradigm shift, it should not ever be called while
713 * another thread could potentially be calling into the attribute system.
715 static enum git_attr_direction direction;
717 void git_attr_set_direction(enum git_attr_direction new_direction)
719 if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
720 BUG("non-INDEX attr direction in a bare repo");
722 if (new_direction != direction)
723 drop_all_attr_stacks();
725 direction = new_direction;
728 static struct attr_stack *read_attr_from_file(const char *path, unsigned flags)
730 struct strbuf buf = STRBUF_INIT;
731 int fd;
732 FILE *fp;
733 struct attr_stack *res;
734 int lineno = 0;
735 struct stat st;
737 if (flags & READ_ATTR_NOFOLLOW)
738 fd = open_nofollow(path, O_RDONLY);
739 else
740 fd = open(path, O_RDONLY);
742 if (fd < 0) {
743 warn_on_fopen_errors(path);
744 return NULL;
746 fp = xfdopen(fd, "r");
747 if (fstat(fd, &st)) {
748 warning_errno(_("cannot fstat gitattributes file '%s'"), path);
749 fclose(fp);
750 return NULL;
752 if (st.st_size >= ATTR_MAX_FILE_SIZE) {
753 warning(_("ignoring overly large gitattributes file '%s'"), path);
754 fclose(fp);
755 return NULL;
758 CALLOC_ARRAY(res, 1);
759 while (strbuf_getline(&buf, fp) != EOF) {
760 if (!lineno && starts_with(buf.buf, utf8_bom))
761 strbuf_remove(&buf, 0, strlen(utf8_bom));
762 handle_attr_line(res, buf.buf, path, ++lineno, flags);
765 fclose(fp);
766 strbuf_release(&buf);
767 return res;
770 static struct attr_stack *read_attr_from_buf(char *buf, size_t length,
771 const char *path, unsigned flags)
773 struct attr_stack *res;
774 char *sp;
775 int lineno = 0;
777 if (!buf)
778 return NULL;
779 if (length >= ATTR_MAX_FILE_SIZE) {
780 warning(_("ignoring overly large gitattributes blob '%s'"), path);
781 free(buf);
782 return NULL;
785 CALLOC_ARRAY(res, 1);
786 for (sp = buf; *sp;) {
787 char *ep;
788 int more;
790 ep = strchrnul(sp, '\n');
791 more = (*ep == '\n');
792 *ep = '\0';
793 handle_attr_line(res, sp, path, ++lineno, flags);
794 sp = ep + more;
796 free(buf);
798 return res;
801 static struct attr_stack *read_attr_from_blob(struct index_state *istate,
802 const struct object_id *tree_oid,
803 const char *path, unsigned flags)
805 struct object_id oid;
806 unsigned long sz;
807 enum object_type type;
808 void *buf;
809 unsigned short mode;
811 if (!tree_oid)
812 return NULL;
814 if (get_tree_entry(istate->repo, tree_oid, path, &oid, &mode))
815 return NULL;
817 buf = repo_read_object_file(istate->repo, &oid, &type, &sz);
818 if (!buf || type != OBJ_BLOB) {
819 free(buf);
820 return NULL;
823 return read_attr_from_buf(buf, sz, path, flags);
826 static struct attr_stack *read_attr_from_index(struct index_state *istate,
827 const char *path, unsigned flags)
829 struct attr_stack *stack = NULL;
830 char *buf;
831 unsigned long size;
832 int sparse_dir_pos = -1;
834 if (!istate)
835 return NULL;
838 * When handling sparse-checkouts, .gitattributes files
839 * may reside within a sparse directory. We distinguish
840 * whether a path exists directly in the index or not by
841 * evaluating if 'pos' is negative.
842 * If 'pos' is negative, the path is not directly present
843 * in the index and is likely within a sparse directory.
844 * For paths not in the index, The absolute value of 'pos'
845 * minus 1 gives us the position where the path would be
846 * inserted in lexicographic order within the index.
847 * We then subtract another 1 from this value
848 * (sparse_dir_pos = -pos - 2) to find the position of the
849 * last index entry which is lexicographically smaller than
850 * the path. This would be the sparse directory containing
851 * the path. By identifying the sparse directory containing
852 * the path, we can correctly read the attributes specified
853 * in the .gitattributes file from the tree object of the
854 * sparse directory.
856 if (!path_in_cone_mode_sparse_checkout(path, istate)) {
857 int pos = index_name_pos_sparse(istate, path, strlen(path));
859 if (pos < 0)
860 sparse_dir_pos = -pos - 2;
863 if (sparse_dir_pos >= 0 &&
864 S_ISSPARSEDIR(istate->cache[sparse_dir_pos]->ce_mode) &&
865 !strncmp(istate->cache[sparse_dir_pos]->name, path, ce_namelen(istate->cache[sparse_dir_pos]))) {
866 const char *relative_path = path + ce_namelen(istate->cache[sparse_dir_pos]);
867 stack = read_attr_from_blob(istate, &istate->cache[sparse_dir_pos]->oid, relative_path, flags);
868 } else {
869 buf = read_blob_data_from_index(istate, path, &size);
870 if (buf)
871 stack = read_attr_from_buf(buf, size, path, flags);
873 return stack;
876 static struct attr_stack *read_attr(struct index_state *istate,
877 const struct object_id *tree_oid,
878 const char *path, unsigned flags)
880 struct attr_stack *res = NULL;
882 if (direction == GIT_ATTR_INDEX) {
883 res = read_attr_from_index(istate, path, flags);
884 } else if (tree_oid) {
885 res = read_attr_from_blob(istate, tree_oid, path, flags);
886 } else if (!is_bare_repository()) {
887 if (direction == GIT_ATTR_CHECKOUT) {
888 res = read_attr_from_index(istate, path, flags);
889 if (!res)
890 res = read_attr_from_file(path, flags);
891 } else if (direction == GIT_ATTR_CHECKIN) {
892 res = read_attr_from_file(path, flags);
893 if (!res)
895 * There is no checked out .gitattributes file
896 * there, but we might have it in the index.
897 * We allow operation in a sparsely checked out
898 * work tree, so read from it.
900 res = read_attr_from_index(istate, path, flags);
904 if (!res)
905 CALLOC_ARRAY(res, 1);
906 return res;
909 const char *git_attr_system_file(void)
911 static const char *system_wide;
912 if (!system_wide)
913 system_wide = system_path(ETC_GITATTRIBUTES);
914 return system_wide;
917 const char *git_attr_global_file(void)
919 if (!git_attributes_file)
920 git_attributes_file = xdg_config_home("attributes");
922 return git_attributes_file;
925 int git_attr_system_is_enabled(void)
927 return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
930 static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
932 static void push_stack(struct attr_stack **attr_stack_p,
933 struct attr_stack *elem, char *origin, size_t originlen)
935 if (elem) {
936 elem->origin = origin;
937 if (origin)
938 elem->originlen = originlen;
939 elem->prev = *attr_stack_p;
940 *attr_stack_p = elem;
944 static void bootstrap_attr_stack(struct index_state *istate,
945 const struct object_id *tree_oid,
946 struct attr_stack **stack)
948 struct attr_stack *e;
949 unsigned flags = READ_ATTR_MACRO_OK;
951 if (*stack)
952 return;
954 /* builtin frame */
955 e = read_attr_from_array(builtin_attr);
956 push_stack(stack, e, NULL, 0);
958 /* system-wide frame */
959 if (git_attr_system_is_enabled()) {
960 e = read_attr_from_file(git_attr_system_file(), flags);
961 push_stack(stack, e, NULL, 0);
964 /* home directory */
965 if (git_attr_global_file()) {
966 e = read_attr_from_file(git_attr_global_file(), flags);
967 push_stack(stack, e, NULL, 0);
970 /* root directory */
971 e = read_attr(istate, tree_oid, GITATTRIBUTES_FILE, flags | READ_ATTR_NOFOLLOW);
972 push_stack(stack, e, xstrdup(""), 0);
974 /* info frame */
975 if (startup_info->have_repository)
976 e = read_attr_from_file(git_path_info_attributes(), flags);
977 else
978 e = NULL;
979 if (!e)
980 CALLOC_ARRAY(e, 1);
981 push_stack(stack, e, NULL, 0);
984 static void prepare_attr_stack(struct index_state *istate,
985 const struct object_id *tree_oid,
986 const char *path, int dirlen,
987 struct attr_stack **stack)
989 struct attr_stack *info;
990 struct strbuf pathbuf = STRBUF_INIT;
993 * At the bottom of the attribute stack is the built-in
994 * set of attribute definitions, followed by the contents
995 * of $(prefix)/etc/gitattributes and a file specified by
996 * core.attributesfile. Then, contents from
997 * .gitattributes files from directories closer to the
998 * root to the ones in deeper directories are pushed
999 * to the stack. Finally, at the very top of the stack
1000 * we always keep the contents of $GIT_DIR/info/attributes.
1002 * When checking, we use entries from near the top of the
1003 * stack, preferring $GIT_DIR/info/attributes, then
1004 * .gitattributes in deeper directories to shallower ones,
1005 * and finally use the built-in set as the default.
1007 bootstrap_attr_stack(istate, tree_oid, stack);
1010 * Pop the "info" one that is always at the top of the stack.
1012 info = *stack;
1013 *stack = info->prev;
1016 * Pop the ones from directories that are not the prefix of
1017 * the path we are checking. Break out of the loop when we see
1018 * the root one (whose origin is an empty string "") or the builtin
1019 * one (whose origin is NULL) without popping it.
1021 while ((*stack)->origin) {
1022 int namelen = (*stack)->originlen;
1023 struct attr_stack *elem;
1025 elem = *stack;
1026 if (namelen <= dirlen &&
1027 !strncmp(elem->origin, path, namelen) &&
1028 (!namelen || path[namelen] == '/'))
1029 break;
1031 *stack = elem->prev;
1032 attr_stack_free(elem);
1036 * bootstrap_attr_stack() should have added, and the
1037 * above loop should have stopped before popping, the
1038 * root element whose attr_stack->origin is set to an
1039 * empty string.
1041 assert((*stack)->origin);
1043 strbuf_addstr(&pathbuf, (*stack)->origin);
1044 /* Build up to the directory 'path' is in */
1045 while (pathbuf.len < dirlen) {
1046 size_t len = pathbuf.len;
1047 struct attr_stack *next;
1048 char *origin;
1050 /* Skip path-separator */
1051 if (len < dirlen && is_dir_sep(path[len]))
1052 len++;
1053 /* Find the end of the next component */
1054 while (len < dirlen && !is_dir_sep(path[len]))
1055 len++;
1057 if (pathbuf.len > 0)
1058 strbuf_addch(&pathbuf, '/');
1059 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
1060 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
1062 next = read_attr(istate, tree_oid, pathbuf.buf, READ_ATTR_NOFOLLOW);
1064 /* reset the pathbuf to not include "/.gitattributes" */
1065 strbuf_setlen(&pathbuf, len);
1067 origin = xstrdup(pathbuf.buf);
1068 push_stack(stack, next, origin, len);
1072 * Finally push the "info" one at the top of the stack.
1074 push_stack(stack, info, NULL, 0);
1076 strbuf_release(&pathbuf);
1079 static int path_matches(const char *pathname, int pathlen,
1080 int basename_offset,
1081 const struct pattern *pat,
1082 const char *base, int baselen)
1084 const char *pattern = pat->pattern;
1085 int prefix = pat->nowildcardlen;
1086 int isdir = (pathlen && pathname[pathlen - 1] == '/');
1088 if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
1089 return 0;
1091 if (pat->flags & PATTERN_FLAG_NODIR) {
1092 return match_basename(pathname + basename_offset,
1093 pathlen - basename_offset - isdir,
1094 pattern, prefix,
1095 pat->patternlen, pat->flags);
1097 return match_pathname(pathname, pathlen - isdir,
1098 base, baselen,
1099 pattern, prefix, pat->patternlen);
1102 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
1104 static int fill_one(struct all_attrs_item *all_attrs,
1105 const struct match_attr *a, int rem)
1107 size_t i;
1109 for (i = a->num_attr; rem > 0 && i > 0; i--) {
1110 const struct git_attr *attr = a->state[i - 1].attr;
1111 const char **n = &(all_attrs[attr->attr_nr].value);
1112 const char *v = a->state[i - 1].setto;
1114 if (*n == ATTR__UNKNOWN) {
1115 *n = v;
1116 rem--;
1117 rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
1120 return rem;
1123 static int fill(const char *path, int pathlen, int basename_offset,
1124 const struct attr_stack *stack,
1125 struct all_attrs_item *all_attrs, int rem)
1127 for (; rem > 0 && stack; stack = stack->prev) {
1128 unsigned i;
1129 const char *base = stack->origin ? stack->origin : "";
1131 for (i = stack->num_matches; 0 < rem && 0 < i; i--) {
1132 const struct match_attr *a = stack->attrs[i - 1];
1133 if (a->is_macro)
1134 continue;
1135 if (path_matches(path, pathlen, basename_offset,
1136 &a->u.pat, base, stack->originlen))
1137 rem = fill_one(all_attrs, a, rem);
1141 return rem;
1144 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
1146 const struct all_attrs_item *item = &all_attrs[nr];
1148 if (item->macro && item->value == ATTR__TRUE)
1149 return fill_one(all_attrs, item->macro, rem);
1150 else
1151 return rem;
1155 * Marks the attributes which are macros based on the attribute stack.
1156 * This prevents having to search through the attribute stack each time
1157 * a macro needs to be expanded during the fill stage.
1159 static void determine_macros(struct all_attrs_item *all_attrs,
1160 const struct attr_stack *stack)
1162 for (; stack; stack = stack->prev) {
1163 unsigned i;
1164 for (i = stack->num_matches; i > 0; i--) {
1165 const struct match_attr *ma = stack->attrs[i - 1];
1166 if (ma->is_macro) {
1167 unsigned int n = ma->u.attr->attr_nr;
1168 if (!all_attrs[n].macro) {
1169 all_attrs[n].macro = ma;
1177 * Collect attributes for path into the array pointed to by check->all_attrs.
1178 * If check->check_nr is non-zero, only attributes in check[] are collected.
1179 * Otherwise all attributes are collected.
1181 static void collect_some_attrs(struct index_state *istate,
1182 const struct object_id *tree_oid,
1183 const char *path, struct attr_check *check)
1185 int pathlen, rem, dirlen;
1186 const char *cp, *last_slash = NULL;
1187 int basename_offset;
1189 for (cp = path; *cp; cp++) {
1190 if (*cp == '/' && cp[1])
1191 last_slash = cp;
1193 pathlen = cp - path;
1194 if (last_slash) {
1195 basename_offset = last_slash + 1 - path;
1196 dirlen = last_slash - path;
1197 } else {
1198 basename_offset = 0;
1199 dirlen = 0;
1202 prepare_attr_stack(istate, tree_oid, path, dirlen, &check->stack);
1203 all_attrs_init(&g_attr_hashmap, check);
1204 determine_macros(check->all_attrs, check->stack);
1206 rem = check->all_attrs_nr;
1207 fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
1210 static const char *default_attr_source_tree_object_name;
1212 void set_git_attr_source(const char *tree_object_name)
1214 default_attr_source_tree_object_name = xstrdup(tree_object_name);
1217 static int compute_default_attr_source(struct object_id *attr_source)
1219 int ignore_bad_attr_tree = 0;
1221 if (!default_attr_source_tree_object_name)
1222 default_attr_source_tree_object_name = getenv(GIT_ATTR_SOURCE_ENVIRONMENT);
1224 if (!default_attr_source_tree_object_name && git_attr_tree) {
1225 default_attr_source_tree_object_name = git_attr_tree;
1226 ignore_bad_attr_tree = 1;
1229 if (!default_attr_source_tree_object_name)
1230 return 0;
1232 if (!startup_info->have_repository) {
1233 if (!ignore_bad_attr_tree)
1234 die(_("cannot use --attr-source or GIT_ATTR_SOURCE without repo"));
1235 return 0;
1238 if (repo_get_oid_treeish(the_repository,
1239 default_attr_source_tree_object_name,
1240 attr_source)) {
1241 if (!ignore_bad_attr_tree)
1242 die(_("bad --attr-source or GIT_ATTR_SOURCE"));
1243 return 0;
1246 return 1;
1249 static struct object_id *default_attr_source(void)
1251 static struct object_id attr_source;
1252 static int has_attr_source = -1;
1254 if (has_attr_source < 0)
1255 has_attr_source = compute_default_attr_source(&attr_source);
1256 if (!has_attr_source)
1257 return NULL;
1258 return &attr_source;
1261 static const char *interned_mode_string(unsigned int mode)
1263 static struct {
1264 unsigned int val;
1265 char str[7];
1266 } mode_string[] = {
1267 { .val = 0040000 },
1268 { .val = 0100644 },
1269 { .val = 0100755 },
1270 { .val = 0120000 },
1271 { .val = 0160000 },
1273 int i;
1275 for (i = 0; i < ARRAY_SIZE(mode_string); i++) {
1276 if (mode_string[i].val != mode)
1277 continue;
1278 if (!*mode_string[i].str)
1279 snprintf(mode_string[i].str, sizeof(mode_string[i].str),
1280 "%06o", mode);
1281 return mode_string[i].str;
1283 BUG("Unsupported mode 0%o", mode);
1286 static const char *builtin_object_mode_attr(struct index_state *istate, const char *path)
1288 unsigned int mode;
1290 if (direction == GIT_ATTR_CHECKIN) {
1291 struct object_id oid;
1292 struct stat st;
1293 if (lstat(path, &st))
1294 die_errno(_("unable to stat '%s'"), path);
1295 mode = canon_mode(st.st_mode);
1296 if (S_ISDIR(mode)) {
1298 *`path` is either a directory or it is a submodule,
1299 * in which case it is already indexed as submodule
1300 * or it does not exist in the index yet and we need to
1301 * check if we can resolve to a ref.
1303 int pos = index_name_pos(istate, path, strlen(path));
1304 if (pos >= 0) {
1305 if (S_ISGITLINK(istate->cache[pos]->ce_mode))
1306 mode = istate->cache[pos]->ce_mode;
1307 } else if (repo_resolve_gitlink_ref(the_repository, path,
1308 "HEAD", &oid) == 0) {
1309 mode = S_IFGITLINK;
1312 } else {
1314 * For GIT_ATTR_CHECKOUT and GIT_ATTR_INDEX we only check
1315 * for mode in the index.
1317 int pos = index_name_pos(istate, path, strlen(path));
1318 if (pos >= 0)
1319 mode = istate->cache[pos]->ce_mode;
1320 else
1321 return ATTR__UNSET;
1324 return interned_mode_string(mode);
1328 static const char *compute_builtin_attr(struct index_state *istate,
1329 const char *path,
1330 const struct git_attr *attr) {
1331 static const struct git_attr *object_mode_attr;
1333 if (!object_mode_attr)
1334 object_mode_attr = git_attr("builtin_objectmode");
1336 if (attr == object_mode_attr)
1337 return builtin_object_mode_attr(istate, path);
1338 return ATTR__UNSET;
1341 void git_check_attr(struct index_state *istate,
1342 const char *path,
1343 struct attr_check *check)
1345 int i;
1346 const struct object_id *tree_oid = default_attr_source();
1348 collect_some_attrs(istate, tree_oid, path, check);
1350 for (i = 0; i < check->nr; i++) {
1351 unsigned int n = check->items[i].attr->attr_nr;
1352 const char *value = check->all_attrs[n].value;
1353 if (value == ATTR__UNKNOWN)
1354 value = compute_builtin_attr(istate, path, check->all_attrs[n].attr);
1355 check->items[i].value = value;
1359 void git_all_attrs(struct index_state *istate,
1360 const char *path, struct attr_check *check)
1362 int i;
1363 const struct object_id *tree_oid = default_attr_source();
1365 attr_check_reset(check);
1366 collect_some_attrs(istate, tree_oid, path, check);
1368 for (i = 0; i < check->all_attrs_nr; i++) {
1369 const char *name = check->all_attrs[i].attr->name;
1370 const char *value = check->all_attrs[i].value;
1371 struct attr_check_item *item;
1372 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1373 continue;
1374 item = attr_check_append(check, git_attr(name));
1375 item->value = value;
1379 void attr_start(void)
1381 pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1382 pthread_mutex_init(&check_vector.mutex, NULL);