trace2: handle NULL values in tr2_sysenv config callback
[alt-git.git] / attr.c
blobe62876dfd3e9beae50d18da63f15285d5974b8ec
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 "git-compat-util.h"
10 #include "config.h"
11 #include "environment.h"
12 #include "exec-cmd.h"
13 #include "attr.h"
14 #include "dir.h"
15 #include "gettext.h"
16 #include "path.h"
17 #include "utf8.h"
18 #include "quote.h"
19 #include "read-cache-ll.h"
20 #include "revision.h"
21 #include "object-store-ll.h"
22 #include "setup.h"
23 #include "thread-utils.h"
24 #include "tree-walk.h"
25 #include "object-name.h"
27 const char *git_attr_tree;
29 const char git_attr__true[] = "(builtin)true";
30 const char git_attr__false[] = "\0(builtin)false";
31 static const char git_attr__unknown[] = "(builtin)unknown";
32 #define ATTR__TRUE git_attr__true
33 #define ATTR__FALSE git_attr__false
34 #define ATTR__UNSET NULL
35 #define ATTR__UNKNOWN git_attr__unknown
37 struct git_attr {
38 unsigned int attr_nr; /* unique attribute number */
39 char name[FLEX_ARRAY]; /* attribute name */
42 const char *git_attr_name(const struct git_attr *attr)
44 return attr->name;
47 struct attr_hashmap {
48 struct hashmap map;
49 pthread_mutex_t mutex;
52 static inline void hashmap_lock(struct attr_hashmap *map)
54 pthread_mutex_lock(&map->mutex);
57 static inline void hashmap_unlock(struct attr_hashmap *map)
59 pthread_mutex_unlock(&map->mutex);
62 /* The container for objects stored in "struct attr_hashmap" */
63 struct attr_hash_entry {
64 struct hashmap_entry ent;
65 const char *key; /* the key; memory should be owned by value */
66 size_t keylen; /* length of the key */
67 void *value; /* the stored value */
70 /* attr_hashmap comparison function */
71 static int attr_hash_entry_cmp(const void *cmp_data UNUSED,
72 const struct hashmap_entry *eptr,
73 const struct hashmap_entry *entry_or_key,
74 const void *keydata UNUSED)
76 const struct attr_hash_entry *a, *b;
78 a = container_of(eptr, const struct attr_hash_entry, ent);
79 b = container_of(entry_or_key, const struct attr_hash_entry, ent);
80 return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
84 * The global dictionary of all interned attributes. This
85 * is a singleton object which is shared between threads.
86 * Access to this dictionary must be surrounded with a mutex.
88 static struct attr_hashmap g_attr_hashmap = {
89 .map = HASHMAP_INIT(attr_hash_entry_cmp, NULL),
93 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
94 * If there is no matching entry, return NULL.
96 static void *attr_hashmap_get(struct attr_hashmap *map,
97 const char *key, size_t keylen)
99 struct attr_hash_entry k;
100 struct attr_hash_entry *e;
102 hashmap_entry_init(&k.ent, memhash(key, keylen));
103 k.key = key;
104 k.keylen = keylen;
105 e = hashmap_get_entry(&map->map, &k, ent, NULL);
107 return e ? e->value : NULL;
110 /* Add 'value' to a hashmap based on the provided 'key'. */
111 static void attr_hashmap_add(struct attr_hashmap *map,
112 const char *key, size_t keylen,
113 void *value)
115 struct attr_hash_entry *e;
117 e = xmalloc(sizeof(struct attr_hash_entry));
118 hashmap_entry_init(&e->ent, memhash(key, keylen));
119 e->key = key;
120 e->keylen = keylen;
121 e->value = value;
123 hashmap_add(&map->map, &e->ent);
126 struct all_attrs_item {
127 const struct git_attr *attr;
128 const char *value;
130 * If 'macro' is non-NULL, indicates that 'attr' is a macro based on
131 * the current attribute stack and contains a pointer to the match_attr
132 * definition of the macro
134 const struct match_attr *macro;
138 * Reallocate and reinitialize the array of all attributes (which is used in
139 * the attribute collection process) in 'check' based on the global dictionary
140 * of attributes.
142 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
144 int i;
145 unsigned int size;
147 hashmap_lock(map);
149 size = hashmap_get_size(&map->map);
150 if (size < check->all_attrs_nr)
151 BUG("interned attributes shouldn't be deleted");
154 * If the number of attributes in the global dictionary has increased
155 * (or this attr_check instance doesn't have an initialized all_attrs
156 * field), reallocate the provided attr_check instance's all_attrs
157 * field and fill each entry with its corresponding git_attr.
159 if (size != check->all_attrs_nr) {
160 struct attr_hash_entry *e;
161 struct hashmap_iter iter;
163 REALLOC_ARRAY(check->all_attrs, size);
164 check->all_attrs_nr = size;
166 hashmap_for_each_entry(&map->map, &iter, e,
167 ent /* member name */) {
168 const struct git_attr *a = e->value;
169 check->all_attrs[a->attr_nr].attr = a;
173 hashmap_unlock(map);
176 * Re-initialize every entry in check->all_attrs.
177 * This re-initialization can live outside of the locked region since
178 * the attribute dictionary is no longer being accessed.
180 for (i = 0; i < check->all_attrs_nr; i++) {
181 check->all_attrs[i].value = ATTR__UNKNOWN;
182 check->all_attrs[i].macro = NULL;
186 static int attr_name_valid(const char *name, size_t namelen)
189 * Attribute name cannot begin with '-' and must consist of
190 * characters from [-A-Za-z0-9_.].
192 if (namelen <= 0 || *name == '-')
193 return 0;
194 while (namelen--) {
195 char ch = *name++;
196 if (! (ch == '-' || ch == '.' || ch == '_' ||
197 ('0' <= ch && ch <= '9') ||
198 ('a' <= ch && ch <= 'z') ||
199 ('A' <= ch && ch <= 'Z')) )
200 return 0;
202 return 1;
205 static void report_invalid_attr(const char *name, size_t len,
206 const char *src, int lineno)
208 struct strbuf err = STRBUF_INIT;
209 strbuf_addf(&err, _("%.*s is not a valid attribute name"),
210 (int) len, name);
211 fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
212 strbuf_release(&err);
216 * Given a 'name', lookup and return the corresponding attribute in the global
217 * dictionary. If no entry is found, create a new attribute and store it in
218 * the dictionary.
220 static const struct git_attr *git_attr_internal(const char *name, size_t namelen)
222 struct git_attr *a;
224 if (!attr_name_valid(name, namelen))
225 return NULL;
227 hashmap_lock(&g_attr_hashmap);
229 a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
231 if (!a) {
232 FLEX_ALLOC_MEM(a, name, name, namelen);
233 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
235 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
236 if (a->attr_nr != hashmap_get_size(&g_attr_hashmap.map) - 1)
237 die(_("unable to add additional attribute"));
240 hashmap_unlock(&g_attr_hashmap);
242 return a;
245 const struct git_attr *git_attr(const char *name)
247 return git_attr_internal(name, strlen(name));
250 /* What does a matched pattern decide? */
251 struct attr_state {
252 const struct git_attr *attr;
253 const char *setto;
256 struct pattern {
257 const char *pattern;
258 int patternlen;
259 int nowildcardlen;
260 unsigned flags; /* PATTERN_FLAG_* */
264 * One rule, as from a .gitattributes file.
266 * If is_macro is true, then u.attr is a pointer to the git_attr being
267 * defined.
269 * If is_macro is false, then u.pat is the filename pattern to which the
270 * rule applies.
272 * In either case, num_attr is the number of attributes affected by
273 * this rule, and state is an array listing them. The attributes are
274 * listed as they appear in the file (macros unexpanded).
276 struct match_attr {
277 union {
278 struct pattern pat;
279 const struct git_attr *attr;
280 } u;
281 char is_macro;
282 size_t num_attr;
283 struct attr_state state[FLEX_ARRAY];
286 static const char blank[] = " \t\r\n";
288 /* Flags usable in read_attr() and parse_attr_line() family of functions. */
289 #define READ_ATTR_MACRO_OK (1<<0)
290 #define READ_ATTR_NOFOLLOW (1<<1)
293 * Parse a whitespace-delimited attribute state (i.e., "attr",
294 * "-attr", "!attr", or "attr=value") from the string starting at src.
295 * If e is not NULL, write the results to *e. Return a pointer to the
296 * remainder of the string (with leading whitespace removed), or NULL
297 * if there was an error.
299 static const char *parse_attr(const char *src, int lineno, const char *cp,
300 struct attr_state *e)
302 const char *ep, *equals;
303 size_t len;
305 ep = cp + strcspn(cp, blank);
306 equals = strchr(cp, '=');
307 if (equals && ep < equals)
308 equals = NULL;
309 if (equals)
310 len = equals - cp;
311 else
312 len = ep - cp;
313 if (!e) {
314 if (*cp == '-' || *cp == '!') {
315 cp++;
316 len--;
318 if (!attr_name_valid(cp, len)) {
319 report_invalid_attr(cp, len, src, lineno);
320 return NULL;
322 } else {
324 * As this function is always called twice, once with
325 * e == NULL in the first pass and then e != NULL in
326 * the second pass, no need for attr_name_valid()
327 * check here.
329 if (*cp == '-' || *cp == '!') {
330 e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
331 cp++;
332 len--;
334 else if (!equals)
335 e->setto = ATTR__TRUE;
336 else {
337 e->setto = xmemdupz(equals + 1, ep - equals - 1);
339 e->attr = git_attr_internal(cp, len);
341 return ep + strspn(ep, blank);
344 static struct match_attr *parse_attr_line(const char *line, const char *src,
345 int lineno, unsigned flags)
347 size_t namelen, num_attr, i;
348 const char *cp, *name, *states;
349 struct match_attr *res = NULL;
350 int is_macro;
351 struct strbuf pattern = STRBUF_INIT;
353 cp = line + strspn(line, blank);
354 if (!*cp || *cp == '#')
355 return NULL;
356 name = cp;
358 if (strlen(line) >= ATTR_MAX_LINE_LENGTH) {
359 warning(_("ignoring overly long attributes line %d"), lineno);
360 return NULL;
363 if (*cp == '"' && !unquote_c_style(&pattern, name, &states)) {
364 name = pattern.buf;
365 namelen = pattern.len;
366 } else {
367 namelen = strcspn(name, blank);
368 states = name + namelen;
371 if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
372 starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
373 if (!(flags & READ_ATTR_MACRO_OK)) {
374 fprintf_ln(stderr, _("%s not allowed: %s:%d"),
375 name, src, lineno);
376 goto fail_return;
378 is_macro = 1;
379 name += strlen(ATTRIBUTE_MACRO_PREFIX);
380 name += strspn(name, blank);
381 namelen = strcspn(name, blank);
382 if (!attr_name_valid(name, namelen)) {
383 report_invalid_attr(name, namelen, src, lineno);
384 goto fail_return;
387 else
388 is_macro = 0;
390 states += strspn(states, blank);
392 /* First pass to count the attr_states */
393 for (cp = states, num_attr = 0; *cp; num_attr++) {
394 cp = parse_attr(src, lineno, cp, NULL);
395 if (!cp)
396 goto fail_return;
399 res = xcalloc(1, st_add3(sizeof(*res),
400 st_mult(sizeof(struct attr_state), num_attr),
401 is_macro ? 0 : namelen + 1));
402 if (is_macro) {
403 res->u.attr = git_attr_internal(name, namelen);
404 } else {
405 char *p = (char *)&(res->state[num_attr]);
406 memcpy(p, name, namelen);
407 res->u.pat.pattern = p;
408 parse_path_pattern(&res->u.pat.pattern,
409 &res->u.pat.patternlen,
410 &res->u.pat.flags,
411 &res->u.pat.nowildcardlen);
412 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
413 warning(_("Negative patterns are ignored in git attributes\n"
414 "Use '\\!' for literal leading exclamation."));
415 goto fail_return;
418 res->is_macro = is_macro;
419 res->num_attr = num_attr;
421 /* Second pass to fill the attr_states */
422 for (cp = states, i = 0; *cp; i++) {
423 cp = parse_attr(src, lineno, cp, &(res->state[i]));
426 strbuf_release(&pattern);
427 return res;
429 fail_return:
430 strbuf_release(&pattern);
431 free(res);
432 return NULL;
436 * Like info/exclude and .gitignore, the attribute information can
437 * come from many places.
439 * (1) .gitattributes file of the same directory;
440 * (2) .gitattributes file of the parent directory if (1) does not have
441 * any match; this goes recursively upwards, just like .gitignore.
442 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
444 * In the same file, later entries override the earlier match, so in the
445 * global list, we would have entries from info/attributes the earliest
446 * (reading the file from top to bottom), .gitattributes of the root
447 * directory (again, reading the file from top to bottom) down to the
448 * current directory, and then scan the list backwards to find the first match.
449 * This is exactly the same as what is_excluded() does in dir.c to deal with
450 * .gitignore file and info/excludes file as a fallback.
453 struct attr_stack {
454 struct attr_stack *prev;
455 char *origin;
456 size_t originlen;
457 unsigned num_matches;
458 unsigned alloc;
459 struct match_attr **attrs;
462 static void attr_stack_free(struct attr_stack *e)
464 unsigned i;
465 free(e->origin);
466 for (i = 0; i < e->num_matches; i++) {
467 struct match_attr *a = e->attrs[i];
468 size_t j;
470 for (j = 0; j < a->num_attr; j++) {
471 const char *setto = a->state[j].setto;
472 if (setto == ATTR__TRUE ||
473 setto == ATTR__FALSE ||
474 setto == ATTR__UNSET ||
475 setto == ATTR__UNKNOWN)
477 else
478 free((char *) setto);
480 free(a);
482 free(e->attrs);
483 free(e);
486 static void drop_attr_stack(struct attr_stack **stack)
488 while (*stack) {
489 struct attr_stack *elem = *stack;
490 *stack = elem->prev;
491 attr_stack_free(elem);
495 /* List of all attr_check structs; access should be surrounded by mutex */
496 static struct check_vector {
497 size_t nr;
498 size_t alloc;
499 struct attr_check **checks;
500 pthread_mutex_t mutex;
501 } check_vector;
503 static inline void vector_lock(void)
505 pthread_mutex_lock(&check_vector.mutex);
508 static inline void vector_unlock(void)
510 pthread_mutex_unlock(&check_vector.mutex);
513 static void check_vector_add(struct attr_check *c)
515 vector_lock();
517 ALLOC_GROW(check_vector.checks,
518 check_vector.nr + 1,
519 check_vector.alloc);
520 check_vector.checks[check_vector.nr++] = c;
522 vector_unlock();
525 static void check_vector_remove(struct attr_check *check)
527 int i;
529 vector_lock();
531 /* Find entry */
532 for (i = 0; i < check_vector.nr; i++)
533 if (check_vector.checks[i] == check)
534 break;
536 if (i >= check_vector.nr)
537 BUG("no entry found");
539 /* shift entries over */
540 for (; i < check_vector.nr - 1; i++)
541 check_vector.checks[i] = check_vector.checks[i + 1];
543 check_vector.nr--;
545 vector_unlock();
548 /* Iterate through all attr_check instances and drop their stacks */
549 static void drop_all_attr_stacks(void)
551 int i;
553 vector_lock();
555 for (i = 0; i < check_vector.nr; i++) {
556 drop_attr_stack(&check_vector.checks[i]->stack);
559 vector_unlock();
562 struct attr_check *attr_check_alloc(void)
564 struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
566 /* save pointer to the check struct */
567 check_vector_add(c);
569 return c;
572 struct attr_check *attr_check_initl(const char *one, ...)
574 struct attr_check *check;
575 int cnt;
576 va_list params;
577 const char *param;
579 va_start(params, one);
580 for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
582 va_end(params);
584 check = attr_check_alloc();
585 check->nr = cnt;
586 check->alloc = cnt;
587 CALLOC_ARRAY(check->items, cnt);
589 check->items[0].attr = git_attr(one);
590 va_start(params, one);
591 for (cnt = 1; cnt < check->nr; cnt++) {
592 const struct git_attr *attr;
593 param = va_arg(params, const char *);
594 if (!param)
595 BUG("counted %d != ended at %d",
596 check->nr, cnt);
597 attr = git_attr(param);
598 if (!attr)
599 BUG("%s: not a valid attribute name", param);
600 check->items[cnt].attr = attr;
602 va_end(params);
603 return check;
606 struct attr_check *attr_check_dup(const struct attr_check *check)
608 struct attr_check *ret;
610 if (!check)
611 return NULL;
613 ret = attr_check_alloc();
615 ret->nr = check->nr;
616 ret->alloc = check->alloc;
617 DUP_ARRAY(ret->items, check->items, ret->nr);
619 return ret;
622 struct attr_check_item *attr_check_append(struct attr_check *check,
623 const struct git_attr *attr)
625 struct attr_check_item *item;
627 ALLOC_GROW(check->items, check->nr + 1, check->alloc);
628 item = &check->items[check->nr++];
629 item->attr = attr;
630 return item;
633 void attr_check_reset(struct attr_check *check)
635 check->nr = 0;
638 void attr_check_clear(struct attr_check *check)
640 FREE_AND_NULL(check->items);
641 check->alloc = 0;
642 check->nr = 0;
644 FREE_AND_NULL(check->all_attrs);
645 check->all_attrs_nr = 0;
647 drop_attr_stack(&check->stack);
650 void attr_check_free(struct attr_check *check)
652 if (check) {
653 /* Remove check from the check vector */
654 check_vector_remove(check);
656 attr_check_clear(check);
657 free(check);
661 static const char *builtin_attr[] = {
662 "[attr]binary -diff -merge -text",
663 NULL,
666 static void handle_attr_line(struct attr_stack *res,
667 const char *line,
668 const char *src,
669 int lineno,
670 unsigned flags)
672 struct match_attr *a;
674 a = parse_attr_line(line, src, lineno, flags);
675 if (!a)
676 return;
677 ALLOC_GROW_BY(res->attrs, res->num_matches, 1, res->alloc);
678 res->attrs[res->num_matches - 1] = a;
681 static struct attr_stack *read_attr_from_array(const char **list)
683 struct attr_stack *res;
684 const char *line;
685 int lineno = 0;
687 CALLOC_ARRAY(res, 1);
688 while ((line = *(list++)) != NULL)
689 handle_attr_line(res, line, "[builtin]", ++lineno,
690 READ_ATTR_MACRO_OK);
691 return res;
695 * Callers into the attribute system assume there is a single, system-wide
696 * global state where attributes are read from and when the state is flipped by
697 * calling git_attr_set_direction(), the stack frames that have been
698 * constructed need to be discarded so that subsequent calls into the
699 * attribute system will lazily read from the right place. Since changing
700 * direction causes a global paradigm shift, it should not ever be called while
701 * another thread could potentially be calling into the attribute system.
703 static enum git_attr_direction direction;
705 void git_attr_set_direction(enum git_attr_direction new_direction)
707 if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
708 BUG("non-INDEX attr direction in a bare repo");
710 if (new_direction != direction)
711 drop_all_attr_stacks();
713 direction = new_direction;
716 static struct attr_stack *read_attr_from_file(const char *path, unsigned flags)
718 struct strbuf buf = STRBUF_INIT;
719 int fd;
720 FILE *fp;
721 struct attr_stack *res;
722 int lineno = 0;
723 struct stat st;
725 if (flags & READ_ATTR_NOFOLLOW)
726 fd = open_nofollow(path, O_RDONLY);
727 else
728 fd = open(path, O_RDONLY);
730 if (fd < 0) {
731 warn_on_fopen_errors(path);
732 return NULL;
734 fp = xfdopen(fd, "r");
735 if (fstat(fd, &st)) {
736 warning_errno(_("cannot fstat gitattributes file '%s'"), path);
737 fclose(fp);
738 return NULL;
740 if (st.st_size >= ATTR_MAX_FILE_SIZE) {
741 warning(_("ignoring overly large gitattributes file '%s'"), path);
742 fclose(fp);
743 return NULL;
746 CALLOC_ARRAY(res, 1);
747 while (strbuf_getline(&buf, fp) != EOF) {
748 if (!lineno && starts_with(buf.buf, utf8_bom))
749 strbuf_remove(&buf, 0, strlen(utf8_bom));
750 handle_attr_line(res, buf.buf, path, ++lineno, flags);
753 fclose(fp);
754 strbuf_release(&buf);
755 return res;
758 static struct attr_stack *read_attr_from_buf(char *buf, const char *path,
759 unsigned flags)
761 struct attr_stack *res;
762 char *sp;
763 int lineno = 0;
765 if (!buf)
766 return NULL;
768 CALLOC_ARRAY(res, 1);
769 for (sp = buf; *sp;) {
770 char *ep;
771 int more;
773 ep = strchrnul(sp, '\n');
774 more = (*ep == '\n');
775 *ep = '\0';
776 handle_attr_line(res, sp, path, ++lineno, flags);
777 sp = ep + more;
779 free(buf);
781 return res;
784 static struct attr_stack *read_attr_from_blob(struct index_state *istate,
785 const struct object_id *tree_oid,
786 const char *path, unsigned flags)
788 struct object_id oid;
789 unsigned long sz;
790 enum object_type type;
791 void *buf;
792 unsigned short mode;
794 if (!tree_oid)
795 return NULL;
797 if (get_tree_entry(istate->repo, tree_oid, path, &oid, &mode))
798 return NULL;
800 buf = repo_read_object_file(istate->repo, &oid, &type, &sz);
801 if (!buf || type != OBJ_BLOB) {
802 free(buf);
803 return NULL;
806 return read_attr_from_buf(buf, path, flags);
809 static struct attr_stack *read_attr_from_index(struct index_state *istate,
810 const char *path, unsigned flags)
812 struct attr_stack *stack = NULL;
813 char *buf;
814 unsigned long size;
815 int sparse_dir_pos = -1;
817 if (!istate)
818 return NULL;
821 * When handling sparse-checkouts, .gitattributes files
822 * may reside within a sparse directory. We distinguish
823 * whether a path exists directly in the index or not by
824 * evaluating if 'pos' is negative.
825 * If 'pos' is negative, the path is not directly present
826 * in the index and is likely within a sparse directory.
827 * For paths not in the index, The absolute value of 'pos'
828 * minus 1 gives us the position where the path would be
829 * inserted in lexicographic order within the index.
830 * We then subtract another 1 from this value
831 * (sparse_dir_pos = -pos - 2) to find the position of the
832 * last index entry which is lexicographically smaller than
833 * the path. This would be the sparse directory containing
834 * the path. By identifying the sparse directory containing
835 * the path, we can correctly read the attributes specified
836 * in the .gitattributes file from the tree object of the
837 * sparse directory.
839 if (!path_in_cone_mode_sparse_checkout(path, istate)) {
840 int pos = index_name_pos_sparse(istate, path, strlen(path));
842 if (pos < 0)
843 sparse_dir_pos = -pos - 2;
846 if (sparse_dir_pos >= 0 &&
847 S_ISSPARSEDIR(istate->cache[sparse_dir_pos]->ce_mode) &&
848 !strncmp(istate->cache[sparse_dir_pos]->name, path, ce_namelen(istate->cache[sparse_dir_pos]))) {
849 const char *relative_path = path + ce_namelen(istate->cache[sparse_dir_pos]);
850 stack = read_attr_from_blob(istate, &istate->cache[sparse_dir_pos]->oid, relative_path, flags);
851 } else {
852 buf = read_blob_data_from_index(istate, path, &size);
853 if (!buf)
854 return NULL;
855 if (size >= ATTR_MAX_FILE_SIZE) {
856 warning(_("ignoring overly large gitattributes blob '%s'"), path);
857 return NULL;
859 stack = read_attr_from_buf(buf, path, flags);
861 return stack;
864 static struct attr_stack *read_attr(struct index_state *istate,
865 const struct object_id *tree_oid,
866 const char *path, unsigned flags)
868 struct attr_stack *res = NULL;
870 if (direction == GIT_ATTR_INDEX) {
871 res = read_attr_from_index(istate, path, flags);
872 } else if (tree_oid) {
873 res = read_attr_from_blob(istate, tree_oid, path, flags);
874 } else if (!is_bare_repository()) {
875 if (direction == GIT_ATTR_CHECKOUT) {
876 res = read_attr_from_index(istate, path, flags);
877 if (!res)
878 res = read_attr_from_file(path, flags);
879 } else if (direction == GIT_ATTR_CHECKIN) {
880 res = read_attr_from_file(path, flags);
881 if (!res)
883 * There is no checked out .gitattributes file
884 * there, but we might have it in the index.
885 * We allow operation in a sparsely checked out
886 * work tree, so read from it.
888 res = read_attr_from_index(istate, path, flags);
892 if (!res)
893 CALLOC_ARRAY(res, 1);
894 return res;
897 const char *git_attr_system_file(void)
899 static const char *system_wide;
900 if (!system_wide)
901 system_wide = system_path(ETC_GITATTRIBUTES);
902 return system_wide;
905 const char *git_attr_global_file(void)
907 if (!git_attributes_file)
908 git_attributes_file = xdg_config_home("attributes");
910 return git_attributes_file;
913 int git_attr_system_is_enabled(void)
915 return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
918 static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
920 static void push_stack(struct attr_stack **attr_stack_p,
921 struct attr_stack *elem, char *origin, size_t originlen)
923 if (elem) {
924 elem->origin = origin;
925 if (origin)
926 elem->originlen = originlen;
927 elem->prev = *attr_stack_p;
928 *attr_stack_p = elem;
932 static void bootstrap_attr_stack(struct index_state *istate,
933 const struct object_id *tree_oid,
934 struct attr_stack **stack)
936 struct attr_stack *e;
937 unsigned flags = READ_ATTR_MACRO_OK;
939 if (*stack)
940 return;
942 /* builtin frame */
943 e = read_attr_from_array(builtin_attr);
944 push_stack(stack, e, NULL, 0);
946 /* system-wide frame */
947 if (git_attr_system_is_enabled()) {
948 e = read_attr_from_file(git_attr_system_file(), flags);
949 push_stack(stack, e, NULL, 0);
952 /* home directory */
953 if (git_attr_global_file()) {
954 e = read_attr_from_file(git_attr_global_file(), flags);
955 push_stack(stack, e, NULL, 0);
958 /* root directory */
959 e = read_attr(istate, tree_oid, GITATTRIBUTES_FILE, flags | READ_ATTR_NOFOLLOW);
960 push_stack(stack, e, xstrdup(""), 0);
962 /* info frame */
963 if (startup_info->have_repository)
964 e = read_attr_from_file(git_path_info_attributes(), flags);
965 else
966 e = NULL;
967 if (!e)
968 CALLOC_ARRAY(e, 1);
969 push_stack(stack, e, NULL, 0);
972 static void prepare_attr_stack(struct index_state *istate,
973 const struct object_id *tree_oid,
974 const char *path, int dirlen,
975 struct attr_stack **stack)
977 struct attr_stack *info;
978 struct strbuf pathbuf = STRBUF_INIT;
981 * At the bottom of the attribute stack is the built-in
982 * set of attribute definitions, followed by the contents
983 * of $(prefix)/etc/gitattributes and a file specified by
984 * core.attributesfile. Then, contents from
985 * .gitattributes files from directories closer to the
986 * root to the ones in deeper directories are pushed
987 * to the stack. Finally, at the very top of the stack
988 * we always keep the contents of $GIT_DIR/info/attributes.
990 * When checking, we use entries from near the top of the
991 * stack, preferring $GIT_DIR/info/attributes, then
992 * .gitattributes in deeper directories to shallower ones,
993 * and finally use the built-in set as the default.
995 bootstrap_attr_stack(istate, tree_oid, stack);
998 * Pop the "info" one that is always at the top of the stack.
1000 info = *stack;
1001 *stack = info->prev;
1004 * Pop the ones from directories that are not the prefix of
1005 * the path we are checking. Break out of the loop when we see
1006 * the root one (whose origin is an empty string "") or the builtin
1007 * one (whose origin is NULL) without popping it.
1009 while ((*stack)->origin) {
1010 int namelen = (*stack)->originlen;
1011 struct attr_stack *elem;
1013 elem = *stack;
1014 if (namelen <= dirlen &&
1015 !strncmp(elem->origin, path, namelen) &&
1016 (!namelen || path[namelen] == '/'))
1017 break;
1019 *stack = elem->prev;
1020 attr_stack_free(elem);
1024 * bootstrap_attr_stack() should have added, and the
1025 * above loop should have stopped before popping, the
1026 * root element whose attr_stack->origin is set to an
1027 * empty string.
1029 assert((*stack)->origin);
1031 strbuf_addstr(&pathbuf, (*stack)->origin);
1032 /* Build up to the directory 'path' is in */
1033 while (pathbuf.len < dirlen) {
1034 size_t len = pathbuf.len;
1035 struct attr_stack *next;
1036 char *origin;
1038 /* Skip path-separator */
1039 if (len < dirlen && is_dir_sep(path[len]))
1040 len++;
1041 /* Find the end of the next component */
1042 while (len < dirlen && !is_dir_sep(path[len]))
1043 len++;
1045 if (pathbuf.len > 0)
1046 strbuf_addch(&pathbuf, '/');
1047 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
1048 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
1050 next = read_attr(istate, tree_oid, pathbuf.buf, READ_ATTR_NOFOLLOW);
1052 /* reset the pathbuf to not include "/.gitattributes" */
1053 strbuf_setlen(&pathbuf, len);
1055 origin = xstrdup(pathbuf.buf);
1056 push_stack(stack, next, origin, len);
1060 * Finally push the "info" one at the top of the stack.
1062 push_stack(stack, info, NULL, 0);
1064 strbuf_release(&pathbuf);
1067 static int path_matches(const char *pathname, int pathlen,
1068 int basename_offset,
1069 const struct pattern *pat,
1070 const char *base, int baselen)
1072 const char *pattern = pat->pattern;
1073 int prefix = pat->nowildcardlen;
1074 int isdir = (pathlen && pathname[pathlen - 1] == '/');
1076 if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
1077 return 0;
1079 if (pat->flags & PATTERN_FLAG_NODIR) {
1080 return match_basename(pathname + basename_offset,
1081 pathlen - basename_offset - isdir,
1082 pattern, prefix,
1083 pat->patternlen, pat->flags);
1085 return match_pathname(pathname, pathlen - isdir,
1086 base, baselen,
1087 pattern, prefix, pat->patternlen);
1090 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
1092 static int fill_one(struct all_attrs_item *all_attrs,
1093 const struct match_attr *a, int rem)
1095 size_t i;
1097 for (i = a->num_attr; rem > 0 && i > 0; i--) {
1098 const struct git_attr *attr = a->state[i - 1].attr;
1099 const char **n = &(all_attrs[attr->attr_nr].value);
1100 const char *v = a->state[i - 1].setto;
1102 if (*n == ATTR__UNKNOWN) {
1103 *n = v;
1104 rem--;
1105 rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
1108 return rem;
1111 static int fill(const char *path, int pathlen, int basename_offset,
1112 const struct attr_stack *stack,
1113 struct all_attrs_item *all_attrs, int rem)
1115 for (; rem > 0 && stack; stack = stack->prev) {
1116 unsigned i;
1117 const char *base = stack->origin ? stack->origin : "";
1119 for (i = stack->num_matches; 0 < rem && 0 < i; i--) {
1120 const struct match_attr *a = stack->attrs[i - 1];
1121 if (a->is_macro)
1122 continue;
1123 if (path_matches(path, pathlen, basename_offset,
1124 &a->u.pat, base, stack->originlen))
1125 rem = fill_one(all_attrs, a, rem);
1129 return rem;
1132 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
1134 const struct all_attrs_item *item = &all_attrs[nr];
1136 if (item->macro && item->value == ATTR__TRUE)
1137 return fill_one(all_attrs, item->macro, rem);
1138 else
1139 return rem;
1143 * Marks the attributes which are macros based on the attribute stack.
1144 * This prevents having to search through the attribute stack each time
1145 * a macro needs to be expanded during the fill stage.
1147 static void determine_macros(struct all_attrs_item *all_attrs,
1148 const struct attr_stack *stack)
1150 for (; stack; stack = stack->prev) {
1151 unsigned i;
1152 for (i = stack->num_matches; i > 0; i--) {
1153 const struct match_attr *ma = stack->attrs[i - 1];
1154 if (ma->is_macro) {
1155 unsigned int n = ma->u.attr->attr_nr;
1156 if (!all_attrs[n].macro) {
1157 all_attrs[n].macro = ma;
1165 * Collect attributes for path into the array pointed to by check->all_attrs.
1166 * If check->check_nr is non-zero, only attributes in check[] are collected.
1167 * Otherwise all attributes are collected.
1169 static void collect_some_attrs(struct index_state *istate,
1170 const struct object_id *tree_oid,
1171 const char *path, struct attr_check *check)
1173 int pathlen, rem, dirlen;
1174 const char *cp, *last_slash = NULL;
1175 int basename_offset;
1177 for (cp = path; *cp; cp++) {
1178 if (*cp == '/' && cp[1])
1179 last_slash = cp;
1181 pathlen = cp - path;
1182 if (last_slash) {
1183 basename_offset = last_slash + 1 - path;
1184 dirlen = last_slash - path;
1185 } else {
1186 basename_offset = 0;
1187 dirlen = 0;
1190 prepare_attr_stack(istate, tree_oid, path, dirlen, &check->stack);
1191 all_attrs_init(&g_attr_hashmap, check);
1192 determine_macros(check->all_attrs, check->stack);
1194 rem = check->all_attrs_nr;
1195 fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
1198 static const char *default_attr_source_tree_object_name;
1199 static int ignore_bad_attr_tree;
1201 void set_git_attr_source(const char *tree_object_name)
1203 default_attr_source_tree_object_name = xstrdup(tree_object_name);
1206 static void compute_default_attr_source(struct object_id *attr_source)
1208 if (!default_attr_source_tree_object_name)
1209 default_attr_source_tree_object_name = getenv(GIT_ATTR_SOURCE_ENVIRONMENT);
1211 if (!default_attr_source_tree_object_name && git_attr_tree) {
1212 default_attr_source_tree_object_name = git_attr_tree;
1213 ignore_bad_attr_tree = 1;
1216 if (!default_attr_source_tree_object_name &&
1217 startup_info->have_repository &&
1218 is_bare_repository()) {
1219 default_attr_source_tree_object_name = "HEAD";
1220 ignore_bad_attr_tree = 1;
1223 if (!default_attr_source_tree_object_name || !is_null_oid(attr_source))
1224 return;
1226 if (repo_get_oid_treeish(the_repository,
1227 default_attr_source_tree_object_name,
1228 attr_source) && !ignore_bad_attr_tree)
1229 die(_("bad --attr-source or GIT_ATTR_SOURCE"));
1232 static struct object_id *default_attr_source(void)
1234 static struct object_id attr_source;
1236 if (is_null_oid(&attr_source))
1237 compute_default_attr_source(&attr_source);
1238 if (is_null_oid(&attr_source))
1239 return NULL;
1240 return &attr_source;
1243 void git_check_attr(struct index_state *istate,
1244 const char *path,
1245 struct attr_check *check)
1247 int i;
1248 const struct object_id *tree_oid = default_attr_source();
1250 collect_some_attrs(istate, tree_oid, path, check);
1252 for (i = 0; i < check->nr; i++) {
1253 unsigned int n = check->items[i].attr->attr_nr;
1254 const char *value = check->all_attrs[n].value;
1255 if (value == ATTR__UNKNOWN)
1256 value = ATTR__UNSET;
1257 check->items[i].value = value;
1261 void git_all_attrs(struct index_state *istate,
1262 const char *path, struct attr_check *check)
1264 int i;
1265 const struct object_id *tree_oid = default_attr_source();
1267 attr_check_reset(check);
1268 collect_some_attrs(istate, tree_oid, path, check);
1270 for (i = 0; i < check->all_attrs_nr; i++) {
1271 const char *name = check->all_attrs[i].attr->name;
1272 const char *value = check->all_attrs[i].value;
1273 struct attr_check_item *item;
1274 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1275 continue;
1276 item = attr_check_append(check, git_attr(name));
1277 item->value = value;
1281 void attr_start(void)
1283 pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1284 pthread_mutex_init(&check_vector.mutex, NULL);