documentation: add missing article
[alt-git.git] / attr.c
blob71c84fbcf865ebeb160b775fe5ca106a89cd4471
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__true[] = "(builtin)true";
28 const char git_attr__false[] = "\0(builtin)false";
29 static const char git_attr__unknown[] = "(builtin)unknown";
30 #define ATTR__TRUE git_attr__true
31 #define ATTR__FALSE git_attr__false
32 #define ATTR__UNSET NULL
33 #define ATTR__UNKNOWN git_attr__unknown
35 struct git_attr {
36 unsigned int attr_nr; /* unique attribute number */
37 char name[FLEX_ARRAY]; /* attribute name */
40 const char *git_attr_name(const struct git_attr *attr)
42 return attr->name;
45 struct attr_hashmap {
46 struct hashmap map;
47 pthread_mutex_t mutex;
50 static inline void hashmap_lock(struct attr_hashmap *map)
52 pthread_mutex_lock(&map->mutex);
55 static inline void hashmap_unlock(struct attr_hashmap *map)
57 pthread_mutex_unlock(&map->mutex);
60 /* The container for objects stored in "struct attr_hashmap" */
61 struct attr_hash_entry {
62 struct hashmap_entry ent;
63 const char *key; /* the key; memory should be owned by value */
64 size_t keylen; /* length of the key */
65 void *value; /* the stored value */
68 /* attr_hashmap comparison function */
69 static int attr_hash_entry_cmp(const void *cmp_data UNUSED,
70 const struct hashmap_entry *eptr,
71 const struct hashmap_entry *entry_or_key,
72 const void *keydata UNUSED)
74 const struct attr_hash_entry *a, *b;
76 a = container_of(eptr, const struct attr_hash_entry, ent);
77 b = container_of(entry_or_key, const struct attr_hash_entry, ent);
78 return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
82 * The global dictionary of all interned attributes. This
83 * is a singleton object which is shared between threads.
84 * Access to this dictionary must be surrounded with a mutex.
86 static struct attr_hashmap g_attr_hashmap = {
87 .map = HASHMAP_INIT(attr_hash_entry_cmp, NULL),
91 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
92 * If there is no matching entry, return NULL.
94 static void *attr_hashmap_get(struct attr_hashmap *map,
95 const char *key, size_t keylen)
97 struct attr_hash_entry k;
98 struct attr_hash_entry *e;
100 hashmap_entry_init(&k.ent, memhash(key, keylen));
101 k.key = key;
102 k.keylen = keylen;
103 e = hashmap_get_entry(&map->map, &k, ent, NULL);
105 return e ? e->value : NULL;
108 /* Add 'value' to a hashmap based on the provided 'key'. */
109 static void attr_hashmap_add(struct attr_hashmap *map,
110 const char *key, size_t keylen,
111 void *value)
113 struct attr_hash_entry *e;
115 e = xmalloc(sizeof(struct attr_hash_entry));
116 hashmap_entry_init(&e->ent, memhash(key, keylen));
117 e->key = key;
118 e->keylen = keylen;
119 e->value = value;
121 hashmap_add(&map->map, &e->ent);
124 struct all_attrs_item {
125 const struct git_attr *attr;
126 const char *value;
128 * If 'macro' is non-NULL, indicates that 'attr' is a macro based on
129 * the current attribute stack and contains a pointer to the match_attr
130 * definition of the macro
132 const struct match_attr *macro;
136 * Reallocate and reinitialize the array of all attributes (which is used in
137 * the attribute collection process) in 'check' based on the global dictionary
138 * of attributes.
140 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
142 int i;
143 unsigned int size;
145 hashmap_lock(map);
147 size = hashmap_get_size(&map->map);
148 if (size < check->all_attrs_nr)
149 BUG("interned attributes shouldn't be deleted");
152 * If the number of attributes in the global dictionary has increased
153 * (or this attr_check instance doesn't have an initialized all_attrs
154 * field), reallocate the provided attr_check instance's all_attrs
155 * field and fill each entry with its corresponding git_attr.
157 if (size != check->all_attrs_nr) {
158 struct attr_hash_entry *e;
159 struct hashmap_iter iter;
161 REALLOC_ARRAY(check->all_attrs, size);
162 check->all_attrs_nr = size;
164 hashmap_for_each_entry(&map->map, &iter, e,
165 ent /* member name */) {
166 const struct git_attr *a = e->value;
167 check->all_attrs[a->attr_nr].attr = a;
171 hashmap_unlock(map);
174 * Re-initialize every entry in check->all_attrs.
175 * This re-initialization can live outside of the locked region since
176 * the attribute dictionary is no longer being accessed.
178 for (i = 0; i < check->all_attrs_nr; i++) {
179 check->all_attrs[i].value = ATTR__UNKNOWN;
180 check->all_attrs[i].macro = NULL;
184 static int attr_name_valid(const char *name, size_t namelen)
187 * Attribute name cannot begin with '-' and must consist of
188 * characters from [-A-Za-z0-9_.].
190 if (namelen <= 0 || *name == '-')
191 return 0;
192 while (namelen--) {
193 char ch = *name++;
194 if (! (ch == '-' || ch == '.' || ch == '_' ||
195 ('0' <= ch && ch <= '9') ||
196 ('a' <= ch && ch <= 'z') ||
197 ('A' <= ch && ch <= 'Z')) )
198 return 0;
200 return 1;
203 static void report_invalid_attr(const char *name, size_t len,
204 const char *src, int lineno)
206 struct strbuf err = STRBUF_INIT;
207 strbuf_addf(&err, _("%.*s is not a valid attribute name"),
208 (int) len, name);
209 fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
210 strbuf_release(&err);
214 * Given a 'name', lookup and return the corresponding attribute in the global
215 * dictionary. If no entry is found, create a new attribute and store it in
216 * the dictionary.
218 static const struct git_attr *git_attr_internal(const char *name, size_t namelen)
220 struct git_attr *a;
222 if (!attr_name_valid(name, namelen))
223 return NULL;
225 hashmap_lock(&g_attr_hashmap);
227 a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
229 if (!a) {
230 FLEX_ALLOC_MEM(a, name, name, namelen);
231 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
233 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
234 if (a->attr_nr != hashmap_get_size(&g_attr_hashmap.map) - 1)
235 die(_("unable to add additional attribute"));
238 hashmap_unlock(&g_attr_hashmap);
240 return a;
243 const struct git_attr *git_attr(const char *name)
245 return git_attr_internal(name, strlen(name));
248 /* What does a matched pattern decide? */
249 struct attr_state {
250 const struct git_attr *attr;
251 const char *setto;
254 struct pattern {
255 const char *pattern;
256 int patternlen;
257 int nowildcardlen;
258 unsigned flags; /* PATTERN_FLAG_* */
262 * One rule, as from a .gitattributes file.
264 * If is_macro is true, then u.attr is a pointer to the git_attr being
265 * defined.
267 * If is_macro is false, then u.pat is the filename pattern to which the
268 * rule applies.
270 * In either case, num_attr is the number of attributes affected by
271 * this rule, and state is an array listing them. The attributes are
272 * listed as they appear in the file (macros unexpanded).
274 struct match_attr {
275 union {
276 struct pattern pat;
277 const struct git_attr *attr;
278 } u;
279 char is_macro;
280 size_t num_attr;
281 struct attr_state state[FLEX_ARRAY];
284 static const char blank[] = " \t\r\n";
286 /* Flags usable in read_attr() and parse_attr_line() family of functions. */
287 #define READ_ATTR_MACRO_OK (1<<0)
288 #define READ_ATTR_NOFOLLOW (1<<1)
291 * Parse a whitespace-delimited attribute state (i.e., "attr",
292 * "-attr", "!attr", or "attr=value") from the string starting at src.
293 * If e is not NULL, write the results to *e. Return a pointer to the
294 * remainder of the string (with leading whitespace removed), or NULL
295 * if there was an error.
297 static const char *parse_attr(const char *src, int lineno, const char *cp,
298 struct attr_state *e)
300 const char *ep, *equals;
301 size_t len;
303 ep = cp + strcspn(cp, blank);
304 equals = strchr(cp, '=');
305 if (equals && ep < equals)
306 equals = NULL;
307 if (equals)
308 len = equals - cp;
309 else
310 len = ep - cp;
311 if (!e) {
312 if (*cp == '-' || *cp == '!') {
313 cp++;
314 len--;
316 if (!attr_name_valid(cp, len)) {
317 report_invalid_attr(cp, len, src, lineno);
318 return NULL;
320 } else {
322 * As this function is always called twice, once with
323 * e == NULL in the first pass and then e != NULL in
324 * the second pass, no need for attr_name_valid()
325 * check here.
327 if (*cp == '-' || *cp == '!') {
328 e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
329 cp++;
330 len--;
332 else if (!equals)
333 e->setto = ATTR__TRUE;
334 else {
335 e->setto = xmemdupz(equals + 1, ep - equals - 1);
337 e->attr = git_attr_internal(cp, len);
339 return ep + strspn(ep, blank);
342 static struct match_attr *parse_attr_line(const char *line, const char *src,
343 int lineno, unsigned flags)
345 size_t namelen, num_attr, i;
346 const char *cp, *name, *states;
347 struct match_attr *res = NULL;
348 int is_macro;
349 struct strbuf pattern = STRBUF_INIT;
351 cp = line + strspn(line, blank);
352 if (!*cp || *cp == '#')
353 return NULL;
354 name = cp;
356 if (strlen(line) >= ATTR_MAX_LINE_LENGTH) {
357 warning(_("ignoring overly long attributes line %d"), lineno);
358 return NULL;
361 if (*cp == '"' && !unquote_c_style(&pattern, name, &states)) {
362 name = pattern.buf;
363 namelen = pattern.len;
364 } else {
365 namelen = strcspn(name, blank);
366 states = name + namelen;
369 if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
370 starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
371 if (!(flags & READ_ATTR_MACRO_OK)) {
372 fprintf_ln(stderr, _("%s not allowed: %s:%d"),
373 name, src, lineno);
374 goto fail_return;
376 is_macro = 1;
377 name += strlen(ATTRIBUTE_MACRO_PREFIX);
378 name += strspn(name, blank);
379 namelen = strcspn(name, blank);
380 if (!attr_name_valid(name, namelen)) {
381 report_invalid_attr(name, namelen, src, lineno);
382 goto fail_return;
385 else
386 is_macro = 0;
388 states += strspn(states, blank);
390 /* First pass to count the attr_states */
391 for (cp = states, num_attr = 0; *cp; num_attr++) {
392 cp = parse_attr(src, lineno, cp, NULL);
393 if (!cp)
394 goto fail_return;
397 res = xcalloc(1, st_add3(sizeof(*res),
398 st_mult(sizeof(struct attr_state), num_attr),
399 is_macro ? 0 : namelen + 1));
400 if (is_macro) {
401 res->u.attr = git_attr_internal(name, namelen);
402 } else {
403 char *p = (char *)&(res->state[num_attr]);
404 memcpy(p, name, namelen);
405 res->u.pat.pattern = p;
406 parse_path_pattern(&res->u.pat.pattern,
407 &res->u.pat.patternlen,
408 &res->u.pat.flags,
409 &res->u.pat.nowildcardlen);
410 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
411 warning(_("Negative patterns are ignored in git attributes\n"
412 "Use '\\!' for literal leading exclamation."));
413 goto fail_return;
416 res->is_macro = is_macro;
417 res->num_attr = num_attr;
419 /* Second pass to fill the attr_states */
420 for (cp = states, i = 0; *cp; i++) {
421 cp = parse_attr(src, lineno, cp, &(res->state[i]));
424 strbuf_release(&pattern);
425 return res;
427 fail_return:
428 strbuf_release(&pattern);
429 free(res);
430 return NULL;
434 * Like info/exclude and .gitignore, the attribute information can
435 * come from many places.
437 * (1) .gitattributes file of the same directory;
438 * (2) .gitattributes file of the parent directory if (1) does not have
439 * any match; this goes recursively upwards, just like .gitignore.
440 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
442 * In the same file, later entries override the earlier match, so in the
443 * global list, we would have entries from info/attributes the earliest
444 * (reading the file from top to bottom), .gitattributes of the root
445 * directory (again, reading the file from top to bottom) down to the
446 * current directory, and then scan the list backwards to find the first match.
447 * This is exactly the same as what is_excluded() does in dir.c to deal with
448 * .gitignore file and info/excludes file as a fallback.
451 struct attr_stack {
452 struct attr_stack *prev;
453 char *origin;
454 size_t originlen;
455 unsigned num_matches;
456 unsigned alloc;
457 struct match_attr **attrs;
460 static void attr_stack_free(struct attr_stack *e)
462 unsigned i;
463 free(e->origin);
464 for (i = 0; i < e->num_matches; i++) {
465 struct match_attr *a = e->attrs[i];
466 size_t j;
468 for (j = 0; j < a->num_attr; j++) {
469 const char *setto = a->state[j].setto;
470 if (setto == ATTR__TRUE ||
471 setto == ATTR__FALSE ||
472 setto == ATTR__UNSET ||
473 setto == ATTR__UNKNOWN)
475 else
476 free((char *) setto);
478 free(a);
480 free(e->attrs);
481 free(e);
484 static void drop_attr_stack(struct attr_stack **stack)
486 while (*stack) {
487 struct attr_stack *elem = *stack;
488 *stack = elem->prev;
489 attr_stack_free(elem);
493 /* List of all attr_check structs; access should be surrounded by mutex */
494 static struct check_vector {
495 size_t nr;
496 size_t alloc;
497 struct attr_check **checks;
498 pthread_mutex_t mutex;
499 } check_vector;
501 static inline void vector_lock(void)
503 pthread_mutex_lock(&check_vector.mutex);
506 static inline void vector_unlock(void)
508 pthread_mutex_unlock(&check_vector.mutex);
511 static void check_vector_add(struct attr_check *c)
513 vector_lock();
515 ALLOC_GROW(check_vector.checks,
516 check_vector.nr + 1,
517 check_vector.alloc);
518 check_vector.checks[check_vector.nr++] = c;
520 vector_unlock();
523 static void check_vector_remove(struct attr_check *check)
525 int i;
527 vector_lock();
529 /* Find entry */
530 for (i = 0; i < check_vector.nr; i++)
531 if (check_vector.checks[i] == check)
532 break;
534 if (i >= check_vector.nr)
535 BUG("no entry found");
537 /* shift entries over */
538 for (; i < check_vector.nr - 1; i++)
539 check_vector.checks[i] = check_vector.checks[i + 1];
541 check_vector.nr--;
543 vector_unlock();
546 /* Iterate through all attr_check instances and drop their stacks */
547 static void drop_all_attr_stacks(void)
549 int i;
551 vector_lock();
553 for (i = 0; i < check_vector.nr; i++) {
554 drop_attr_stack(&check_vector.checks[i]->stack);
557 vector_unlock();
560 struct attr_check *attr_check_alloc(void)
562 struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
564 /* save pointer to the check struct */
565 check_vector_add(c);
567 return c;
570 struct attr_check *attr_check_initl(const char *one, ...)
572 struct attr_check *check;
573 int cnt;
574 va_list params;
575 const char *param;
577 va_start(params, one);
578 for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
580 va_end(params);
582 check = attr_check_alloc();
583 check->nr = cnt;
584 check->alloc = cnt;
585 CALLOC_ARRAY(check->items, cnt);
587 check->items[0].attr = git_attr(one);
588 va_start(params, one);
589 for (cnt = 1; cnt < check->nr; cnt++) {
590 const struct git_attr *attr;
591 param = va_arg(params, const char *);
592 if (!param)
593 BUG("counted %d != ended at %d",
594 check->nr, cnt);
595 attr = git_attr(param);
596 if (!attr)
597 BUG("%s: not a valid attribute name", param);
598 check->items[cnt].attr = attr;
600 va_end(params);
601 return check;
604 struct attr_check *attr_check_dup(const struct attr_check *check)
606 struct attr_check *ret;
608 if (!check)
609 return NULL;
611 ret = attr_check_alloc();
613 ret->nr = check->nr;
614 ret->alloc = check->alloc;
615 DUP_ARRAY(ret->items, check->items, ret->nr);
617 return ret;
620 struct attr_check_item *attr_check_append(struct attr_check *check,
621 const struct git_attr *attr)
623 struct attr_check_item *item;
625 ALLOC_GROW(check->items, check->nr + 1, check->alloc);
626 item = &check->items[check->nr++];
627 item->attr = attr;
628 return item;
631 void attr_check_reset(struct attr_check *check)
633 check->nr = 0;
636 void attr_check_clear(struct attr_check *check)
638 FREE_AND_NULL(check->items);
639 check->alloc = 0;
640 check->nr = 0;
642 FREE_AND_NULL(check->all_attrs);
643 check->all_attrs_nr = 0;
645 drop_attr_stack(&check->stack);
648 void attr_check_free(struct attr_check *check)
650 if (check) {
651 /* Remove check from the check vector */
652 check_vector_remove(check);
654 attr_check_clear(check);
655 free(check);
659 static const char *builtin_attr[] = {
660 "[attr]binary -diff -merge -text",
661 NULL,
664 static void handle_attr_line(struct attr_stack *res,
665 const char *line,
666 const char *src,
667 int lineno,
668 unsigned flags)
670 struct match_attr *a;
672 a = parse_attr_line(line, src, lineno, flags);
673 if (!a)
674 return;
675 ALLOC_GROW_BY(res->attrs, res->num_matches, 1, res->alloc);
676 res->attrs[res->num_matches - 1] = a;
679 static struct attr_stack *read_attr_from_array(const char **list)
681 struct attr_stack *res;
682 const char *line;
683 int lineno = 0;
685 CALLOC_ARRAY(res, 1);
686 while ((line = *(list++)) != NULL)
687 handle_attr_line(res, line, "[builtin]", ++lineno,
688 READ_ATTR_MACRO_OK);
689 return res;
693 * Callers into the attribute system assume there is a single, system-wide
694 * global state where attributes are read from and when the state is flipped by
695 * calling git_attr_set_direction(), the stack frames that have been
696 * constructed need to be discarded so that subsequent calls into the
697 * attribute system will lazily read from the right place. Since changing
698 * direction causes a global paradigm shift, it should not ever be called while
699 * another thread could potentially be calling into the attribute system.
701 static enum git_attr_direction direction;
703 void git_attr_set_direction(enum git_attr_direction new_direction)
705 if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
706 BUG("non-INDEX attr direction in a bare repo");
708 if (new_direction != direction)
709 drop_all_attr_stacks();
711 direction = new_direction;
714 static struct attr_stack *read_attr_from_file(const char *path, unsigned flags)
716 struct strbuf buf = STRBUF_INIT;
717 int fd;
718 FILE *fp;
719 struct attr_stack *res;
720 int lineno = 0;
721 struct stat st;
723 if (flags & READ_ATTR_NOFOLLOW)
724 fd = open_nofollow(path, O_RDONLY);
725 else
726 fd = open(path, O_RDONLY);
728 if (fd < 0) {
729 warn_on_fopen_errors(path);
730 return NULL;
732 fp = xfdopen(fd, "r");
733 if (fstat(fd, &st)) {
734 warning_errno(_("cannot fstat gitattributes file '%s'"), path);
735 fclose(fp);
736 return NULL;
738 if (st.st_size >= ATTR_MAX_FILE_SIZE) {
739 warning(_("ignoring overly large gitattributes file '%s'"), path);
740 fclose(fp);
741 return NULL;
744 CALLOC_ARRAY(res, 1);
745 while (strbuf_getline(&buf, fp) != EOF) {
746 if (!lineno && starts_with(buf.buf, utf8_bom))
747 strbuf_remove(&buf, 0, strlen(utf8_bom));
748 handle_attr_line(res, buf.buf, path, ++lineno, flags);
751 fclose(fp);
752 strbuf_release(&buf);
753 return res;
756 static struct attr_stack *read_attr_from_buf(char *buf, const char *path,
757 unsigned flags)
759 struct attr_stack *res;
760 char *sp;
761 int lineno = 0;
763 if (!buf)
764 return NULL;
766 CALLOC_ARRAY(res, 1);
767 for (sp = buf; *sp;) {
768 char *ep;
769 int more;
771 ep = strchrnul(sp, '\n');
772 more = (*ep == '\n');
773 *ep = '\0';
774 handle_attr_line(res, sp, path, ++lineno, flags);
775 sp = ep + more;
777 free(buf);
779 return res;
782 static struct attr_stack *read_attr_from_blob(struct index_state *istate,
783 const struct object_id *tree_oid,
784 const char *path, unsigned flags)
786 struct object_id oid;
787 unsigned long sz;
788 enum object_type type;
789 void *buf;
790 unsigned short mode;
792 if (!tree_oid)
793 return NULL;
795 if (get_tree_entry(istate->repo, tree_oid, path, &oid, &mode))
796 return NULL;
798 buf = repo_read_object_file(istate->repo, &oid, &type, &sz);
799 if (!buf || type != OBJ_BLOB) {
800 free(buf);
801 return NULL;
804 return read_attr_from_buf(buf, path, flags);
807 static struct attr_stack *read_attr_from_index(struct index_state *istate,
808 const char *path, unsigned flags)
810 struct attr_stack *stack = NULL;
811 char *buf;
812 unsigned long size;
813 int sparse_dir_pos = -1;
815 if (!istate)
816 return NULL;
819 * When handling sparse-checkouts, .gitattributes files
820 * may reside within a sparse directory. We distinguish
821 * whether a path exists directly in the index or not by
822 * evaluating if 'pos' is negative.
823 * If 'pos' is negative, the path is not directly present
824 * in the index and is likely within a sparse directory.
825 * For paths not in the index, The absolute value of 'pos'
826 * minus 1 gives us the position where the path would be
827 * inserted in lexicographic order within the index.
828 * We then subtract another 1 from this value
829 * (sparse_dir_pos = -pos - 2) to find the position of the
830 * last index entry which is lexicographically smaller than
831 * the path. This would be the sparse directory containing
832 * the path. By identifying the sparse directory containing
833 * the path, we can correctly read the attributes specified
834 * in the .gitattributes file from the tree object of the
835 * sparse directory.
837 if (!path_in_cone_mode_sparse_checkout(path, istate)) {
838 int pos = index_name_pos_sparse(istate, path, strlen(path));
840 if (pos < 0)
841 sparse_dir_pos = -pos - 2;
844 if (sparse_dir_pos >= 0 &&
845 S_ISSPARSEDIR(istate->cache[sparse_dir_pos]->ce_mode) &&
846 !strncmp(istate->cache[sparse_dir_pos]->name, path, ce_namelen(istate->cache[sparse_dir_pos]))) {
847 const char *relative_path = path + ce_namelen(istate->cache[sparse_dir_pos]);
848 stack = read_attr_from_blob(istate, &istate->cache[sparse_dir_pos]->oid, relative_path, flags);
849 } else {
850 buf = read_blob_data_from_index(istate, path, &size);
851 if (!buf)
852 return NULL;
853 if (size >= ATTR_MAX_FILE_SIZE) {
854 warning(_("ignoring overly large gitattributes blob '%s'"), path);
855 return NULL;
857 stack = read_attr_from_buf(buf, path, flags);
859 return stack;
862 static struct attr_stack *read_attr(struct index_state *istate,
863 const struct object_id *tree_oid,
864 const char *path, unsigned flags)
866 struct attr_stack *res = NULL;
868 if (direction == GIT_ATTR_INDEX) {
869 res = read_attr_from_index(istate, path, flags);
870 } else if (tree_oid) {
871 res = read_attr_from_blob(istate, tree_oid, path, flags);
872 } else if (!is_bare_repository()) {
873 if (direction == GIT_ATTR_CHECKOUT) {
874 res = read_attr_from_index(istate, path, flags);
875 if (!res)
876 res = read_attr_from_file(path, flags);
877 } else if (direction == GIT_ATTR_CHECKIN) {
878 res = read_attr_from_file(path, flags);
879 if (!res)
881 * There is no checked out .gitattributes file
882 * there, but we might have it in the index.
883 * We allow operation in a sparsely checked out
884 * work tree, so read from it.
886 res = read_attr_from_index(istate, path, flags);
890 if (!res)
891 CALLOC_ARRAY(res, 1);
892 return res;
895 const char *git_attr_system_file(void)
897 static const char *system_wide;
898 if (!system_wide)
899 system_wide = system_path(ETC_GITATTRIBUTES);
900 return system_wide;
903 const char *git_attr_global_file(void)
905 if (!git_attributes_file)
906 git_attributes_file = xdg_config_home("attributes");
908 return git_attributes_file;
911 int git_attr_system_is_enabled(void)
913 return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
916 static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
918 static void push_stack(struct attr_stack **attr_stack_p,
919 struct attr_stack *elem, char *origin, size_t originlen)
921 if (elem) {
922 elem->origin = origin;
923 if (origin)
924 elem->originlen = originlen;
925 elem->prev = *attr_stack_p;
926 *attr_stack_p = elem;
930 static void bootstrap_attr_stack(struct index_state *istate,
931 const struct object_id *tree_oid,
932 struct attr_stack **stack)
934 struct attr_stack *e;
935 unsigned flags = READ_ATTR_MACRO_OK;
937 if (*stack)
938 return;
940 /* builtin frame */
941 e = read_attr_from_array(builtin_attr);
942 push_stack(stack, e, NULL, 0);
944 /* system-wide frame */
945 if (git_attr_system_is_enabled()) {
946 e = read_attr_from_file(git_attr_system_file(), flags);
947 push_stack(stack, e, NULL, 0);
950 /* home directory */
951 if (git_attr_global_file()) {
952 e = read_attr_from_file(git_attr_global_file(), flags);
953 push_stack(stack, e, NULL, 0);
956 /* root directory */
957 e = read_attr(istate, tree_oid, GITATTRIBUTES_FILE, flags | READ_ATTR_NOFOLLOW);
958 push_stack(stack, e, xstrdup(""), 0);
960 /* info frame */
961 if (startup_info->have_repository)
962 e = read_attr_from_file(git_path_info_attributes(), flags);
963 else
964 e = NULL;
965 if (!e)
966 CALLOC_ARRAY(e, 1);
967 push_stack(stack, e, NULL, 0);
970 static void prepare_attr_stack(struct index_state *istate,
971 const struct object_id *tree_oid,
972 const char *path, int dirlen,
973 struct attr_stack **stack)
975 struct attr_stack *info;
976 struct strbuf pathbuf = STRBUF_INIT;
979 * At the bottom of the attribute stack is the built-in
980 * set of attribute definitions, followed by the contents
981 * of $(prefix)/etc/gitattributes and a file specified by
982 * core.attributesfile. Then, contents from
983 * .gitattributes files from directories closer to the
984 * root to the ones in deeper directories are pushed
985 * to the stack. Finally, at the very top of the stack
986 * we always keep the contents of $GIT_DIR/info/attributes.
988 * When checking, we use entries from near the top of the
989 * stack, preferring $GIT_DIR/info/attributes, then
990 * .gitattributes in deeper directories to shallower ones,
991 * and finally use the built-in set as the default.
993 bootstrap_attr_stack(istate, tree_oid, stack);
996 * Pop the "info" one that is always at the top of the stack.
998 info = *stack;
999 *stack = info->prev;
1002 * Pop the ones from directories that are not the prefix of
1003 * the path we are checking. Break out of the loop when we see
1004 * the root one (whose origin is an empty string "") or the builtin
1005 * one (whose origin is NULL) without popping it.
1007 while ((*stack)->origin) {
1008 int namelen = (*stack)->originlen;
1009 struct attr_stack *elem;
1011 elem = *stack;
1012 if (namelen <= dirlen &&
1013 !strncmp(elem->origin, path, namelen) &&
1014 (!namelen || path[namelen] == '/'))
1015 break;
1017 *stack = elem->prev;
1018 attr_stack_free(elem);
1022 * bootstrap_attr_stack() should have added, and the
1023 * above loop should have stopped before popping, the
1024 * root element whose attr_stack->origin is set to an
1025 * empty string.
1027 assert((*stack)->origin);
1029 strbuf_addstr(&pathbuf, (*stack)->origin);
1030 /* Build up to the directory 'path' is in */
1031 while (pathbuf.len < dirlen) {
1032 size_t len = pathbuf.len;
1033 struct attr_stack *next;
1034 char *origin;
1036 /* Skip path-separator */
1037 if (len < dirlen && is_dir_sep(path[len]))
1038 len++;
1039 /* Find the end of the next component */
1040 while (len < dirlen && !is_dir_sep(path[len]))
1041 len++;
1043 if (pathbuf.len > 0)
1044 strbuf_addch(&pathbuf, '/');
1045 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
1046 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
1048 next = read_attr(istate, tree_oid, pathbuf.buf, READ_ATTR_NOFOLLOW);
1050 /* reset the pathbuf to not include "/.gitattributes" */
1051 strbuf_setlen(&pathbuf, len);
1053 origin = xstrdup(pathbuf.buf);
1054 push_stack(stack, next, origin, len);
1058 * Finally push the "info" one at the top of the stack.
1060 push_stack(stack, info, NULL, 0);
1062 strbuf_release(&pathbuf);
1065 static int path_matches(const char *pathname, int pathlen,
1066 int basename_offset,
1067 const struct pattern *pat,
1068 const char *base, int baselen)
1070 const char *pattern = pat->pattern;
1071 int prefix = pat->nowildcardlen;
1072 int isdir = (pathlen && pathname[pathlen - 1] == '/');
1074 if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
1075 return 0;
1077 if (pat->flags & PATTERN_FLAG_NODIR) {
1078 return match_basename(pathname + basename_offset,
1079 pathlen - basename_offset - isdir,
1080 pattern, prefix,
1081 pat->patternlen, pat->flags);
1083 return match_pathname(pathname, pathlen - isdir,
1084 base, baselen,
1085 pattern, prefix, pat->patternlen);
1088 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
1090 static int fill_one(struct all_attrs_item *all_attrs,
1091 const struct match_attr *a, int rem)
1093 size_t i;
1095 for (i = a->num_attr; rem > 0 && i > 0; i--) {
1096 const struct git_attr *attr = a->state[i - 1].attr;
1097 const char **n = &(all_attrs[attr->attr_nr].value);
1098 const char *v = a->state[i - 1].setto;
1100 if (*n == ATTR__UNKNOWN) {
1101 *n = v;
1102 rem--;
1103 rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
1106 return rem;
1109 static int fill(const char *path, int pathlen, int basename_offset,
1110 const struct attr_stack *stack,
1111 struct all_attrs_item *all_attrs, int rem)
1113 for (; rem > 0 && stack; stack = stack->prev) {
1114 unsigned i;
1115 const char *base = stack->origin ? stack->origin : "";
1117 for (i = stack->num_matches; 0 < rem && 0 < i; i--) {
1118 const struct match_attr *a = stack->attrs[i - 1];
1119 if (a->is_macro)
1120 continue;
1121 if (path_matches(path, pathlen, basename_offset,
1122 &a->u.pat, base, stack->originlen))
1123 rem = fill_one(all_attrs, a, rem);
1127 return rem;
1130 static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
1132 const struct all_attrs_item *item = &all_attrs[nr];
1134 if (item->macro && item->value == ATTR__TRUE)
1135 return fill_one(all_attrs, item->macro, rem);
1136 else
1137 return rem;
1141 * Marks the attributes which are macros based on the attribute stack.
1142 * This prevents having to search through the attribute stack each time
1143 * a macro needs to be expanded during the fill stage.
1145 static void determine_macros(struct all_attrs_item *all_attrs,
1146 const struct attr_stack *stack)
1148 for (; stack; stack = stack->prev) {
1149 unsigned i;
1150 for (i = stack->num_matches; i > 0; i--) {
1151 const struct match_attr *ma = stack->attrs[i - 1];
1152 if (ma->is_macro) {
1153 unsigned int n = ma->u.attr->attr_nr;
1154 if (!all_attrs[n].macro) {
1155 all_attrs[n].macro = ma;
1163 * Collect attributes for path into the array pointed to by check->all_attrs.
1164 * If check->check_nr is non-zero, only attributes in check[] are collected.
1165 * Otherwise all attributes are collected.
1167 static void collect_some_attrs(struct index_state *istate,
1168 const struct object_id *tree_oid,
1169 const char *path, struct attr_check *check)
1171 int pathlen, rem, dirlen;
1172 const char *cp, *last_slash = NULL;
1173 int basename_offset;
1175 for (cp = path; *cp; cp++) {
1176 if (*cp == '/' && cp[1])
1177 last_slash = cp;
1179 pathlen = cp - path;
1180 if (last_slash) {
1181 basename_offset = last_slash + 1 - path;
1182 dirlen = last_slash - path;
1183 } else {
1184 basename_offset = 0;
1185 dirlen = 0;
1188 prepare_attr_stack(istate, tree_oid, path, dirlen, &check->stack);
1189 all_attrs_init(&g_attr_hashmap, check);
1190 determine_macros(check->all_attrs, check->stack);
1192 rem = check->all_attrs_nr;
1193 fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
1196 static const char *default_attr_source_tree_object_name;
1198 void set_git_attr_source(const char *tree_object_name)
1200 default_attr_source_tree_object_name = xstrdup(tree_object_name);
1203 static void compute_default_attr_source(struct object_id *attr_source)
1205 if (!default_attr_source_tree_object_name)
1206 default_attr_source_tree_object_name = getenv(GIT_ATTR_SOURCE_ENVIRONMENT);
1208 if (!default_attr_source_tree_object_name || !is_null_oid(attr_source))
1209 return;
1211 if (repo_get_oid_treeish(the_repository, default_attr_source_tree_object_name, attr_source))
1212 die(_("bad --attr-source or GIT_ATTR_SOURCE"));
1215 static struct object_id *default_attr_source(void)
1217 static struct object_id attr_source;
1219 if (is_null_oid(&attr_source))
1220 compute_default_attr_source(&attr_source);
1221 if (is_null_oid(&attr_source))
1222 return NULL;
1223 return &attr_source;
1226 void git_check_attr(struct index_state *istate,
1227 const char *path,
1228 struct attr_check *check)
1230 int i;
1231 const struct object_id *tree_oid = default_attr_source();
1233 collect_some_attrs(istate, tree_oid, path, check);
1235 for (i = 0; i < check->nr; i++) {
1236 unsigned int n = check->items[i].attr->attr_nr;
1237 const char *value = check->all_attrs[n].value;
1238 if (value == ATTR__UNKNOWN)
1239 value = ATTR__UNSET;
1240 check->items[i].value = value;
1244 void git_all_attrs(struct index_state *istate,
1245 const char *path, struct attr_check *check)
1247 int i;
1248 const struct object_id *tree_oid = default_attr_source();
1250 attr_check_reset(check);
1251 collect_some_attrs(istate, tree_oid, path, check);
1253 for (i = 0; i < check->all_attrs_nr; i++) {
1254 const char *name = check->all_attrs[i].attr->name;
1255 const char *value = check->all_attrs[i].value;
1256 struct attr_check_item *item;
1257 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1258 continue;
1259 item = attr_check_append(check, git_attr(name));
1260 item->value = value;
1264 void attr_start(void)
1266 pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1267 pthread_mutex_init(&check_vector.mutex, NULL);