]> git.ipfire.org Git - thirdparty/git.git/blame - attr.c
log-tree: replace include of revision.h with simple forward declaration
[thirdparty/git.git] / attr.c
CommitLineData
86ab7f0c
MH
1/*
2 * Handle git attributes. See gitattributes(5) for a description of
3a1b3415 3 * the file syntax, and attr.h for a description of the API.
86ab7f0c
MH
4 *
5 * One basic design decision here is that we are not going to support
6 * an insanely large number of attributes.
7 */
8
bc5c5ec0 9#include "git-compat-util.h"
36bf1958 10#include "alloc.h"
b2141fc1 11#include "config.h"
32a8f510 12#include "environment.h"
d807c4a0 13#include "exec-cmd.h"
d0bfd026 14#include "attr.h"
6eba6210 15#include "dir.h"
f394e093 16#include "gettext.h"
27547e5f 17#include "utf8.h"
860a74d9 18#include "quote.h"
08c46a49 19#include "read-cache-ll.h"
47cfc9bd
KN
20#include "revision.h"
21#include "object-store.h"
e38da487 22#include "setup.h"
1a600b75 23#include "thread-utils.h"
0e312eaa 24#include "tree-walk.h"
44451a2e 25#include "object-name.h"
d0bfd026 26
a5e92abd
JH
27const char git_attr__true[] = "(builtin)true";
28const char git_attr__false[] = "\0(builtin)false";
29static 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
515106fa 34
d0bfd026 35struct git_attr {
e1e12e97 36 unsigned int attr_nr; /* unique attribute number */
1a600b75 37 char name[FLEX_ARRAY]; /* attribute name */
d0bfd026 38};
7d42ec54 39
ec4d77aa 40const char *git_attr_name(const struct git_attr *attr)
352404ac
MH
41{
42 return attr->name;
43}
44
1a600b75
BW
45struct attr_hashmap {
46 struct hashmap map;
1a600b75 47 pthread_mutex_t mutex;
1a600b75
BW
48};
49
50static inline void hashmap_lock(struct attr_hashmap *map)
51{
1a600b75 52 pthread_mutex_lock(&map->mutex);
1a600b75
BW
53}
54
55static inline void hashmap_unlock(struct attr_hashmap *map)
d0bfd026 56{
1a600b75 57 pthread_mutex_unlock(&map->mutex);
1a600b75 58}
d0bfd026 59
1a600b75
BW
60/* The container for objects stored in "struct attr_hashmap" */
61struct attr_hash_entry {
e2b5038d 62 struct hashmap_entry ent;
1a600b75
BW
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 */
66};
67
68/* attr_hashmap comparison function */
5cf88fd8 69static int attr_hash_entry_cmp(const void *cmp_data UNUSED,
939af16e
EW
70 const struct hashmap_entry *eptr,
71 const struct hashmap_entry *entry_or_key,
5cf88fd8 72 const void *keydata UNUSED)
1a600b75 73{
939af16e
EW
74 const struct attr_hash_entry *a, *b;
75
76 a = container_of(eptr, const struct attr_hash_entry, ent);
77 b = container_of(entry_or_key, const struct attr_hash_entry, ent);
1a600b75
BW
78 return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
79}
80
b19315d8
EN
81/*
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.
85 */
86static struct attr_hashmap g_attr_hashmap = {
50103649 87 .map = HASHMAP_INIT(attr_hash_entry_cmp, NULL),
b19315d8 88};
1a600b75
BW
89
90/*
91 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
92 * If there is no matching entry, return NULL.
93 */
94static void *attr_hashmap_get(struct attr_hashmap *map,
95 const char *key, size_t keylen)
96{
97 struct attr_hash_entry k;
98 struct attr_hash_entry *e;
99
d22245a2 100 hashmap_entry_init(&k.ent, memhash(key, keylen));
1a600b75
BW
101 k.key = key;
102 k.keylen = keylen;
404ab78e 103 e = hashmap_get_entry(&map->map, &k, ent, NULL);
1a600b75
BW
104
105 return e ? e->value : NULL;
106}
107
108/* Add 'value' to a hashmap based on the provided 'key'. */
109static void attr_hashmap_add(struct attr_hashmap *map,
110 const char *key, size_t keylen,
111 void *value)
112{
113 struct attr_hash_entry *e;
114
1a600b75 115 e = xmalloc(sizeof(struct attr_hash_entry));
d22245a2 116 hashmap_entry_init(&e->ent, memhash(key, keylen));
1a600b75
BW
117 e->key = key;
118 e->keylen = keylen;
119 e->value = value;
120
b94e5c1d 121 hashmap_add(&map->map, &e->ent);
d0bfd026
JH
122}
123
685b2925
BW
124struct all_attrs_item {
125 const struct git_attr *attr;
126 const char *value;
60a12722
BW
127 /*
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
131 */
132 const struct match_attr *macro;
685b2925
BW
133};
134
135/*
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.
139 */
140static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
141{
142 int i;
8b604d19 143 unsigned int size;
685b2925
BW
144
145 hashmap_lock(map);
146
8b604d19
JH
147 size = hashmap_get_size(&map->map);
148 if (size < check->all_attrs_nr)
033abf97 149 BUG("interned attributes shouldn't be deleted");
685b2925
BW
150
151 /*
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.
156 */
8b604d19 157 if (size != check->all_attrs_nr) {
685b2925
BW
158 struct attr_hash_entry *e;
159 struct hashmap_iter iter;
685b2925 160
8b604d19
JH
161 REALLOC_ARRAY(check->all_attrs, size);
162 check->all_attrs_nr = size;
685b2925 163
87571c3f 164 hashmap_for_each_entry(&map->map, &iter, e,
87571c3f 165 ent /* member name */) {
685b2925
BW
166 const struct git_attr *a = e->value;
167 check->all_attrs[a->attr_nr].attr = a;
168 }
169 }
170
171 hashmap_unlock(map);
172
173 /*
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.
177 */
178 for (i = 0; i < check->all_attrs_nr; i++) {
179 check->all_attrs[i].value = ATTR__UNKNOWN;
60a12722 180 check->all_attrs[i].macro = NULL;
685b2925
BW
181 }
182}
183
428103c7 184static int attr_name_valid(const char *name, size_t namelen)
e4aee10a
JH
185{
186 /*
d42453ab
MH
187 * Attribute name cannot begin with '-' and must consist of
188 * characters from [-A-Za-z0-9_.].
e4aee10a 189 */
c0b13b21 190 if (namelen <= 0 || *name == '-')
428103c7 191 return 0;
e4aee10a
JH
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')) )
428103c7 198 return 0;
e4aee10a 199 }
428103c7
JH
200 return 1;
201}
202
203static void report_invalid_attr(const char *name, size_t len,
204 const char *src, int lineno)
205{
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);
e4aee10a
JH
211}
212
1a600b75
BW
213/*
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.
217 */
eb22e7df 218static const struct git_attr *git_attr_internal(const char *name, size_t namelen)
d0bfd026 219{
d0bfd026
JH
220 struct git_attr *a;
221
1a600b75 222 if (!attr_name_valid(name, namelen))
e4aee10a
JH
223 return NULL;
224
1a600b75
BW
225 hashmap_lock(&g_attr_hashmap);
226
227 a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
228
229 if (!a) {
230 FLEX_ALLOC_MEM(a, name, name, namelen);
8b604d19 231 a->attr_nr = hashmap_get_size(&g_attr_hashmap.map);
1a600b75
BW
232
233 attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
e1e12e97
PS
234 if (a->attr_nr != hashmap_get_size(&g_attr_hashmap.map) - 1)
235 die(_("unable to add additional attribute"));
1a600b75
BW
236 }
237
238 hashmap_unlock(&g_attr_hashmap);
f48fd688 239
d0bfd026
JH
240 return a;
241}
242
e810e063 243const struct git_attr *git_attr(const char *name)
7fb0eaa2
JH
244{
245 return git_attr_internal(name, strlen(name));
246}
247
515106fa 248/* What does a matched pattern decide? */
d0bfd026 249struct attr_state {
e810e063 250 const struct git_attr *attr;
a5e92abd 251 const char *setto;
d0bfd026
JH
252};
253
82dce998
NTND
254struct pattern {
255 const char *pattern;
256 int patternlen;
257 int nowildcardlen;
4ff89ee5 258 unsigned flags; /* PATTERN_FLAG_* */
82dce998
NTND
259};
260
ba845b75
MH
261/*
262 * One rule, as from a .gitattributes file.
263 *
264 * If is_macro is true, then u.attr is a pointer to the git_attr being
265 * defined.
266 *
4894f4ff
JH
267 * If is_macro is false, then u.pat is the filename pattern to which the
268 * rule applies.
ba845b75
MH
269 *
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).
273 */
d0bfd026 274struct match_attr {
f48fd688 275 union {
82dce998 276 struct pattern pat;
e810e063 277 const struct git_attr *attr;
f48fd688
JH
278 } u;
279 char is_macro;
34ace8ba 280 size_t num_attr;
d0bfd026
JH
281 struct attr_state state[FLEX_ARRAY];
282};
283
284static const char blank[] = " \t\r\n";
285
dbf387d5
JK
286/* Flags usable in read_attr() and parse_attr_line() family of functions. */
287#define READ_ATTR_MACRO_OK (1<<0)
2ef579e2 288#define READ_ATTR_NOFOLLOW (1<<1)
dbf387d5 289
d1751298
MH
290/*
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.
296 */
515106fa 297static const char *parse_attr(const char *src, int lineno, const char *cp,
d1751298 298 struct attr_state *e)
515106fa
JH
299{
300 const char *ep, *equals;
24557209 301 size_t len;
515106fa
JH
302
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;
d1751298 311 if (!e) {
515106fa
JH
312 if (*cp == '-' || *cp == '!') {
313 cp++;
314 len--;
315 }
428103c7
JH
316 if (!attr_name_valid(cp, len)) {
317 report_invalid_attr(cp, len, src, lineno);
515106fa
JH
318 return NULL;
319 }
320 } else {
5a884019
JH
321 /*
322 * As this function is always called twice, once with
323 * e == NULL in the first pass and then e != NULL in
428103c7 324 * the second pass, no need for attr_name_valid()
5a884019
JH
325 * check here.
326 */
515106fa
JH
327 if (*cp == '-' || *cp == '!') {
328 e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
329 cp++;
330 len--;
331 }
332 else if (!equals)
333 e->setto = ATTR__TRUE;
334 else {
182af834 335 e->setto = xmemdupz(equals + 1, ep - equals - 1);
515106fa 336 }
7fb0eaa2 337 e->attr = git_attr_internal(cp, len);
515106fa 338 }
515106fa
JH
339 return ep + strspn(ep, blank);
340}
341
f48fd688 342static struct match_attr *parse_attr_line(const char *line, const char *src,
dbf387d5 343 int lineno, unsigned flags)
d0bfd026 344{
34ace8ba 345 size_t namelen, num_attr, i;
85c4a0d0 346 const char *cp, *name, *states;
515106fa 347 struct match_attr *res = NULL;
f48fd688 348 int is_macro;
860a74d9 349 struct strbuf pattern = STRBUF_INIT;
d0bfd026
JH
350
351 cp = line + strspn(line, blank);
352 if (!*cp || *cp == '#')
353 return NULL;
354 name = cp;
860a74d9 355
dfa6b32b
PS
356 if (strlen(line) >= ATTR_MAX_LINE_LENGTH) {
357 warning(_("ignoring overly long attributes line %d"), lineno);
358 return NULL;
359 }
360
860a74d9
NTND
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;
367 }
368
f48fd688 369 if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
59556548 370 starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
dbf387d5 371 if (!(flags & READ_ATTR_MACRO_OK)) {
ad8f8f4a
NTND
372 fprintf_ln(stderr, _("%s not allowed: %s:%d"),
373 name, src, lineno);
62af8969 374 goto fail_return;
f48fd688
JH
375 }
376 is_macro = 1;
377 name += strlen(ATTRIBUTE_MACRO_PREFIX);
378 name += strspn(name, blank);
379 namelen = strcspn(name, blank);
428103c7
JH
380 if (!attr_name_valid(name, namelen)) {
381 report_invalid_attr(name, namelen, src, lineno);
62af8969 382 goto fail_return;
e4aee10a 383 }
f48fd688
JH
384 }
385 else
386 is_macro = 0;
d0bfd026 387
85c4a0d0
MH
388 states += strspn(states, blank);
389
d68e1c18
MH
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)
62af8969 394 goto fail_return;
d0bfd026 395 }
d68e1c18 396
a60a66e4
PS
397 res = xcalloc(1, st_add3(sizeof(*res),
398 st_mult(sizeof(struct attr_state), num_attr),
399 is_macro ? 0 : namelen + 1));
fad32bcd 400 if (is_macro) {
d68e1c18 401 res->u.attr = git_attr_internal(name, namelen);
fad32bcd 402 } else {
82dce998
NTND
403 char *p = (char *)&(res->state[num_attr]);
404 memcpy(p, name, namelen);
405 res->u.pat.pattern = p;
65edd96a 406 parse_path_pattern(&res->u.pat.pattern,
82dce998
NTND
407 &res->u.pat.patternlen,
408 &res->u.pat.flags,
409 &res->u.pat.nowildcardlen);
4ff89ee5 410 if (res->u.pat.flags & PATTERN_FLAG_NEGATIVE) {
8b1bd024
TR
411 warning(_("Negative patterns are ignored in git attributes\n"
412 "Use '\\!' for literal leading exclamation."));
62af8969 413 goto fail_return;
8b1bd024 414 }
d0bfd026 415 }
d68e1c18
MH
416 res->is_macro = is_macro;
417 res->num_attr = num_attr;
418
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]));
422 }
423
860a74d9 424 strbuf_release(&pattern);
d0bfd026 425 return res;
62af8969
JH
426
427fail_return:
860a74d9 428 strbuf_release(&pattern);
62af8969
JH
429 free(res);
430 return NULL;
d0bfd026
JH
431}
432
433/*
434 * Like info/exclude and .gitignore, the attribute information can
435 * come from many places.
436 *
bb101aaf
RD
437 * (1) .gitattributes file of the same directory;
438 * (2) .gitattributes file of the parent directory if (1) does not have
515106fa
JH
439 * any match; this goes recursively upwards, just like .gitignore.
440 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
d0bfd026
JH
441 *
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
bb101aaf 444 * (reading the file from top to bottom), .gitattributes of the root
d0bfd026
JH
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.
6d24e7a8 447 * This is exactly the same as what is_excluded() does in dir.c to deal with
6f416cba 448 * .gitignore file and info/excludes file as a fallback.
d0bfd026
JH
449 */
450
dc81cf37 451struct attr_stack {
d0bfd026
JH
452 struct attr_stack *prev;
453 char *origin;
cd6a0b26 454 size_t originlen;
d0bfd026 455 unsigned num_matches;
a4413118 456 unsigned alloc;
d0bfd026 457 struct match_attr **attrs;
dc81cf37 458};
d0bfd026 459
dc81cf37 460static void attr_stack_free(struct attr_stack *e)
d0bfd026 461{
447ac906 462 unsigned i;
d0bfd026 463 free(e->origin);
515106fa
JH
464 for (i = 0; i < e->num_matches; i++) {
465 struct match_attr *a = e->attrs[i];
34ace8ba
PS
466 size_t j;
467
515106fa 468 for (j = 0; j < a->num_attr; j++) {
a5e92abd 469 const char *setto = a->state[j].setto;
515106fa
JH
470 if (setto == ATTR__TRUE ||
471 setto == ATTR__FALSE ||
472 setto == ATTR__UNSET ||
473 setto == ATTR__UNKNOWN)
474 ;
475 else
4b25d091 476 free((char *) setto);
515106fa
JH
477 }
478 free(a);
479 }
37475f97 480 free(e->attrs);
d0bfd026
JH
481 free(e);
482}
483
dc81cf37
BW
484static void drop_attr_stack(struct attr_stack **stack)
485{
486 while (*stack) {
487 struct attr_stack *elem = *stack;
488 *stack = elem->prev;
489 attr_stack_free(elem);
490 }
491}
492
493/* List of all attr_check structs; access should be surrounded by mutex */
494static struct check_vector {
495 size_t nr;
496 size_t alloc;
497 struct attr_check **checks;
dc81cf37 498 pthread_mutex_t mutex;
dc81cf37
BW
499} check_vector;
500
501static inline void vector_lock(void)
502{
dc81cf37 503 pthread_mutex_lock(&check_vector.mutex);
dc81cf37
BW
504}
505
506static inline void vector_unlock(void)
507{
dc81cf37 508 pthread_mutex_unlock(&check_vector.mutex);
dc81cf37
BW
509}
510
511static void check_vector_add(struct attr_check *c)
512{
513 vector_lock();
514
515 ALLOC_GROW(check_vector.checks,
516 check_vector.nr + 1,
517 check_vector.alloc);
518 check_vector.checks[check_vector.nr++] = c;
519
520 vector_unlock();
521}
522
523static void check_vector_remove(struct attr_check *check)
524{
525 int i;
526
527 vector_lock();
528
529 /* Find entry */
530 for (i = 0; i < check_vector.nr; i++)
531 if (check_vector.checks[i] == check)
532 break;
533
534 if (i >= check_vector.nr)
033abf97 535 BUG("no entry found");
dc81cf37
BW
536
537 /* shift entries over */
538 for (; i < check_vector.nr - 1; i++)
539 check_vector.checks[i] = check_vector.checks[i + 1];
540
541 check_vector.nr--;
542
543 vector_unlock();
544}
545
546/* Iterate through all attr_check instances and drop their stacks */
547static void drop_all_attr_stacks(void)
548{
549 int i;
550
551 vector_lock();
552
553 for (i = 0; i < check_vector.nr; i++) {
554 drop_attr_stack(&check_vector.checks[i]->stack);
555 }
556
557 vector_unlock();
558}
559
37293768
JH
560struct attr_check *attr_check_alloc(void)
561{
dc81cf37
BW
562 struct attr_check *c = xcalloc(1, sizeof(struct attr_check));
563
564 /* save pointer to the check struct */
565 check_vector_add(c);
566
567 return c;
37293768
JH
568}
569
570struct attr_check *attr_check_initl(const char *one, ...)
571{
572 struct attr_check *check;
573 int cnt;
574 va_list params;
575 const char *param;
576
577 va_start(params, one);
578 for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
579 ;
580 va_end(params);
581
582 check = attr_check_alloc();
583 check->nr = cnt;
584 check->alloc = cnt;
ca56dadb 585 CALLOC_ARRAY(check->items, cnt);
37293768
JH
586
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)
033abf97 593 BUG("counted %d != ended at %d",
37293768
JH
594 check->nr, cnt);
595 attr = git_attr(param);
596 if (!attr)
033abf97 597 BUG("%s: not a valid attribute name", param);
37293768
JH
598 check->items[cnt].attr = attr;
599 }
600 va_end(params);
601 return check;
602}
603
b0db7046
BW
604struct attr_check *attr_check_dup(const struct attr_check *check)
605{
606 struct attr_check *ret;
607
608 if (!check)
609 return NULL;
610
611 ret = attr_check_alloc();
612
613 ret->nr = check->nr;
614 ret->alloc = check->alloc;
6e578410 615 DUP_ARRAY(ret->items, check->items, ret->nr);
b0db7046
BW
616
617 return ret;
618}
619
37293768
JH
620struct attr_check_item *attr_check_append(struct attr_check *check,
621 const struct git_attr *attr)
622{
623 struct attr_check_item *item;
624
625 ALLOC_GROW(check->items, check->nr + 1, check->alloc);
626 item = &check->items[check->nr++];
627 item->attr = attr;
628 return item;
629}
630
631void attr_check_reset(struct attr_check *check)
632{
633 check->nr = 0;
634}
635
636void attr_check_clear(struct attr_check *check)
637{
6a83d902 638 FREE_AND_NULL(check->items);
37293768
JH
639 check->alloc = 0;
640 check->nr = 0;
685b2925 641
6a83d902 642 FREE_AND_NULL(check->all_attrs);
685b2925 643 check->all_attrs_nr = 0;
dc81cf37
BW
644
645 drop_attr_stack(&check->stack);
37293768
JH
646}
647
648void attr_check_free(struct attr_check *check)
649{
dc81cf37
BW
650 if (check) {
651 /* Remove check from the check vector */
652 check_vector_remove(check);
653
654 attr_check_clear(check);
655 free(check);
656 }
37293768
JH
657}
658
d0bfd026 659static const char *builtin_attr[] = {
155a4b71 660 "[attr]binary -diff -merge -text",
d0bfd026
JH
661 NULL,
662};
663
a4413118
JH
664static void handle_attr_line(struct attr_stack *res,
665 const char *line,
666 const char *src,
667 int lineno,
dbf387d5 668 unsigned flags)
a4413118
JH
669{
670 struct match_attr *a;
671
dbf387d5 672 a = parse_attr_line(line, src, lineno, flags);
a4413118
JH
673 if (!a)
674 return;
447ac906
PS
675 ALLOC_GROW_BY(res->attrs, res->num_matches, 1, res->alloc);
676 res->attrs[res->num_matches - 1] = a;
a4413118
JH
677}
678
d0bfd026
JH
679static struct attr_stack *read_attr_from_array(const char **list)
680{
681 struct attr_stack *res;
682 const char *line;
f48fd688 683 int lineno = 0;
d0bfd026 684
ca56dadb 685 CALLOC_ARRAY(res, 1);
a4413118 686 while ((line = *(list++)) != NULL)
dbf387d5
JK
687 handle_attr_line(res, line, "[builtin]", ++lineno,
688 READ_ATTR_MACRO_OK);
d0bfd026
JH
689 return res;
690}
691
7d42ec54 692/*
f0dd0421
BW
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
abcb66c6 696 * constructed need to be discarded so that subsequent calls into the
f0dd0421
BW
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.
7d42ec54 700 */
06f33c17 701static enum git_attr_direction direction;
06f33c17 702
c4500e25 703void git_attr_set_direction(enum git_attr_direction new_direction)
f0dd0421
BW
704{
705 if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
033abf97 706 BUG("non-INDEX attr direction in a bare repo");
f0dd0421
BW
707
708 if (new_direction != direction)
709 drop_all_attr_stacks();
710
711 direction = new_direction;
f0dd0421
BW
712}
713
dbf387d5 714static struct attr_stack *read_attr_from_file(const char *path, unsigned flags)
d0bfd026 715{
d74b1fd5 716 struct strbuf buf = STRBUF_INIT;
2ef579e2
JK
717 int fd;
718 FILE *fp;
d0bfd026 719 struct attr_stack *res;
f48fd688 720 int lineno = 0;
3c50032f 721 struct stat st;
d0bfd026 722
2ef579e2
JK
723 if (flags & READ_ATTR_NOFOLLOW)
724 fd = open_nofollow(path, O_RDONLY);
725 else
726 fd = open(path, O_RDONLY);
727
728 if (fd < 0) {
729 warn_on_fopen_errors(path);
a4413118 730 return NULL;
2ef579e2
JK
731 }
732 fp = xfdopen(fd, "r");
3c50032f
PS
733 if (fstat(fd, &st)) {
734 warning_errno(_("cannot fstat gitattributes file '%s'"), path);
735 fclose(fp);
736 return NULL;
737 }
738 if (st.st_size >= ATTR_MAX_FILE_SIZE) {
739 warning(_("ignoring overly large gitattributes file '%s'"), path);
740 fclose(fp);
741 return NULL;
742 }
2ef579e2 743
ca56dadb 744 CALLOC_ARRAY(res, 1);
d74b1fd5
PS
745 while (strbuf_getline(&buf, fp) != EOF) {
746 if (!lineno && starts_with(buf.buf, utf8_bom))
747 strbuf_remove(&buf, 0, strlen(utf8_bom));
8a755edd 748 handle_attr_line(res, buf.buf, path, ++lineno, flags);
27547e5f 749 }
d74b1fd5 750
a4413118 751 fclose(fp);
d74b1fd5 752 strbuf_release(&buf);
a4413118
JH
753 return res;
754}
d0bfd026 755
47cfc9bd
KN
756static struct attr_stack *read_attr_from_buf(char *buf, const char *path,
757 unsigned flags)
a4413118
JH
758{
759 struct attr_stack *res;
47cfc9bd 760 char *sp;
1a9d7e9b 761 int lineno = 0;
f48fd688 762
47cfc9bd
KN
763 if (!buf)
764 return NULL;
765
766 CALLOC_ARRAY(res, 1);
767 for (sp = buf; *sp;) {
768 char *ep;
769 int more;
770
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;
776 }
777 free(buf);
778
779 return res;
780}
781
782static struct attr_stack *read_attr_from_blob(struct index_state *istate,
783 const struct object_id *tree_oid,
784 const char *path, unsigned flags)
785{
786 struct object_id oid;
787 unsigned long sz;
788 enum object_type type;
789 void *buf;
790 unsigned short mode;
791
792 if (!tree_oid)
793 return NULL;
794
795 if (get_tree_entry(istate->repo, tree_oid, path, &oid, &mode))
796 return NULL;
797
798 buf = repo_read_object_file(istate->repo, &oid, &type, &sz);
799 if (!buf || type != OBJ_BLOB) {
800 free(buf);
801 return NULL;
802 }
803
804 return read_attr_from_buf(buf, path, flags);
805}
806
807static struct attr_stack *read_attr_from_index(struct index_state *istate,
808 const char *path, unsigned flags)
809{
810 char *buf;
37537d64 811 unsigned long size;
f48fd688 812
c4500e25 813 if (!istate)
7a400a2c
NTND
814 return NULL;
815
77efbb36
DS
816 /*
817 * The .gitattributes file only applies to files within its
818 * parent directory. In the case of cone-mode sparse-checkout,
819 * the .gitattributes file is sparse if and only if all paths
820 * within that directory are also sparse. Thus, don't load the
821 * .gitattributes file since it will not matter.
822 *
823 * In the case of a sparse index, it is critical that we don't go
824 * looking for a .gitattributes file, as doing so would cause the
825 * index to expand.
826 */
827 if (!path_in_cone_mode_sparse_checkout(path, istate))
828 return NULL;
829
3c50032f 830 buf = read_blob_data_from_index(istate, path, &size);
1a9d7e9b 831 if (!buf)
06f33c17 832 return NULL;
3c50032f
PS
833 if (size >= ATTR_MAX_FILE_SIZE) {
834 warning(_("ignoring overly large gitattributes blob '%s'"), path);
835 return NULL;
836 }
1a9d7e9b 837
47cfc9bd 838 return read_attr_from_buf(buf, path, flags);
d0bfd026
JH
839}
840
847a9e5d 841static struct attr_stack *read_attr(struct index_state *istate,
47cfc9bd 842 const struct object_id *tree_oid,
dbf387d5 843 const char *path, unsigned flags)
06f33c17 844{
0787dafd 845 struct attr_stack *res = NULL;
06f33c17 846
0787dafd 847 if (direction == GIT_ATTR_INDEX) {
dbf387d5 848 res = read_attr_from_index(istate, path, flags);
47cfc9bd
KN
849 } else if (tree_oid) {
850 res = read_attr_from_blob(istate, tree_oid, path, flags);
0787dafd
BW
851 } else if (!is_bare_repository()) {
852 if (direction == GIT_ATTR_CHECKOUT) {
dbf387d5 853 res = read_attr_from_index(istate, path, flags);
0787dafd 854 if (!res)
dbf387d5 855 res = read_attr_from_file(path, flags);
0787dafd 856 } else if (direction == GIT_ATTR_CHECKIN) {
dbf387d5 857 res = read_attr_from_file(path, flags);
0787dafd
BW
858 if (!res)
859 /*
860 * There is no checked out .gitattributes file
861 * there, but we might have it in the index.
862 * We allow operation in a sparsely checked out
863 * work tree, so read from it.
864 */
dbf387d5 865 res = read_attr_from_index(istate, path, flags);
0787dafd 866 }
06f33c17 867 }
0787dafd 868
06f33c17 869 if (!res)
ca56dadb 870 CALLOC_ARRAY(res, 1);
06f33c17
JH
871 return res;
872}
873
c5147722 874static const char *git_etc_gitattributes(void)
6df42ab9
PO
875{
876 static const char *system_wide;
877 if (!system_wide)
878 system_wide = system_path(ETC_GITATTRIBUTES);
879 return system_wide;
880}
881
dc81cf37
BW
882static const char *get_home_gitattributes(void)
883{
884 if (!git_attributes_file)
885 git_attributes_file = xdg_config_home("attributes");
886
887 return git_attributes_file;
888}
889
c5147722 890static int git_attr_system(void)
6df42ab9
PO
891{
892 return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
893}
894
f932729c
JK
895static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
896
4c0ce074
JH
897static void push_stack(struct attr_stack **attr_stack_p,
898 struct attr_stack *elem, char *origin, size_t originlen)
899{
900 if (elem) {
901 elem->origin = origin;
902 if (origin)
903 elem->originlen = originlen;
904 elem->prev = *attr_stack_p;
905 *attr_stack_p = elem;
906 }
907}
908
847a9e5d 909static void bootstrap_attr_stack(struct index_state *istate,
47cfc9bd 910 const struct object_id *tree_oid,
7a400a2c 911 struct attr_stack **stack)
f48fd688 912{
dc81cf37 913 struct attr_stack *e;
dbf387d5 914 unsigned flags = READ_ATTR_MACRO_OK;
f48fd688 915
dc81cf37 916 if (*stack)
909ca7b9 917 return;
f48fd688 918
dc81cf37
BW
919 /* builtin frame */
920 e = read_attr_from_array(builtin_attr);
921 push_stack(stack, e, NULL, 0);
6df42ab9 922
dc81cf37
BW
923 /* system-wide frame */
924 if (git_attr_system()) {
dbf387d5 925 e = read_attr_from_file(git_etc_gitattributes(), flags);
dc81cf37
BW
926 push_stack(stack, e, NULL, 0);
927 }
f48fd688 928
dc81cf37
BW
929 /* home directory */
930 if (get_home_gitattributes()) {
dbf387d5 931 e = read_attr_from_file(get_home_gitattributes(), flags);
dc81cf37 932 push_stack(stack, e, NULL, 0);
f48fd688 933 }
909ca7b9 934
dc81cf37 935 /* root directory */
47cfc9bd 936 e = read_attr(istate, tree_oid, GITATTRIBUTES_FILE, flags | READ_ATTR_NOFOLLOW);
dc81cf37 937 push_stack(stack, e, xstrdup(""), 0);
f0056f64 938
dc81cf37
BW
939 /* info frame */
940 if (startup_info->have_repository)
dbf387d5 941 e = read_attr_from_file(git_path_info_attributes(), flags);
dc81cf37
BW
942 else
943 e = NULL;
944 if (!e)
ca56dadb 945 CALLOC_ARRAY(e, 1);
dc81cf37 946 push_stack(stack, e, NULL, 0);
f48fd688
JH
947}
948
847a9e5d 949static void prepare_attr_stack(struct index_state *istate,
47cfc9bd 950 const struct object_id *tree_oid,
7a400a2c 951 const char *path, int dirlen,
dc81cf37 952 struct attr_stack **stack)
d0bfd026 953{
dc81cf37 954 struct attr_stack *info;
0787dafd 955 struct strbuf pathbuf = STRBUF_INIT;
a8727017 956
d0bfd026
JH
957 /*
958 * At the bottom of the attribute stack is the built-in
6df42ab9
PO
959 * set of attribute definitions, followed by the contents
960 * of $(prefix)/etc/gitattributes and a file specified by
961 * core.attributesfile. Then, contents from
bb101aaf 962 * .gitattributes files from directories closer to the
d0bfd026
JH
963 * root to the ones in deeper directories are pushed
964 * to the stack. Finally, at the very top of the stack
965 * we always keep the contents of $GIT_DIR/info/attributes.
966 *
967 * When checking, we use entries from near the top of the
968 * stack, preferring $GIT_DIR/info/attributes, then
969 * .gitattributes in deeper directories to shallower ones,
970 * and finally use the built-in set as the default.
971 */
47cfc9bd 972 bootstrap_attr_stack(istate, tree_oid, stack);
d0bfd026
JH
973
974 /*
975 * Pop the "info" one that is always at the top of the stack.
976 */
dc81cf37
BW
977 info = *stack;
978 *stack = info->prev;
d0bfd026
JH
979
980 /*
981 * Pop the ones from directories that are not the prefix of
c432ef99
JH
982 * the path we are checking. Break out of the loop when we see
983 * the root one (whose origin is an empty string "") or the builtin
984 * one (whose origin is NULL) without popping it.
d0bfd026 985 */
dc81cf37
BW
986 while ((*stack)->origin) {
987 int namelen = (*stack)->originlen;
988 struct attr_stack *elem;
d0bfd026 989
dc81cf37 990 elem = *stack;
d0bfd026 991 if (namelen <= dirlen &&
1afca444
JK
992 !strncmp(elem->origin, path, namelen) &&
993 (!namelen || path[namelen] == '/'))
d0bfd026
JH
994 break;
995
dc81cf37
BW
996 *stack = elem->prev;
997 attr_stack_free(elem);
d0bfd026
JH
998 }
999
1000 /*
0787dafd
BW
1001 * bootstrap_attr_stack() should have added, and the
1002 * above loop should have stopped before popping, the
1003 * root element whose attr_stack->origin is set to an
1004 * empty string.
d0bfd026 1005 */
0787dafd
BW
1006 assert((*stack)->origin);
1007
1008 strbuf_addstr(&pathbuf, (*stack)->origin);
1009 /* Build up to the directory 'path' is in */
1010 while (pathbuf.len < dirlen) {
1011 size_t len = pathbuf.len;
1012 struct attr_stack *next;
1013 char *origin;
1014
1015 /* Skip path-separator */
1016 if (len < dirlen && is_dir_sep(path[len]))
1017 len++;
1018 /* Find the end of the next component */
1019 while (len < dirlen && !is_dir_sep(path[len]))
1020 len++;
1021
1022 if (pathbuf.len > 0)
1023 strbuf_addch(&pathbuf, '/');
1024 strbuf_add(&pathbuf, path + pathbuf.len, (len - pathbuf.len));
1025 strbuf_addf(&pathbuf, "/%s", GITATTRIBUTES_FILE);
1026
47cfc9bd 1027 next = read_attr(istate, tree_oid, pathbuf.buf, READ_ATTR_NOFOLLOW);
0787dafd
BW
1028
1029 /* reset the pathbuf to not include "/.gitattributes" */
1030 strbuf_setlen(&pathbuf, len);
1031
1032 origin = xstrdup(pathbuf.buf);
1033 push_stack(stack, next, origin, len);
97410b27 1034 }
d4c98565 1035
d0bfd026
JH
1036 /*
1037 * Finally push the "info" one at the top of the stack.
1038 */
dc81cf37 1039 push_stack(stack, info, NULL, 0);
0787dafd
BW
1040
1041 strbuf_release(&pathbuf);
d0bfd026
JH
1042}
1043
1044static int path_matches(const char *pathname, int pathlen,
bd2f371d 1045 int basename_offset,
82dce998 1046 const struct pattern *pat,
d0bfd026
JH
1047 const char *base, int baselen)
1048{
82dce998
NTND
1049 const char *pattern = pat->pattern;
1050 int prefix = pat->nowildcardlen;
dc09e9ec 1051 int isdir = (pathlen && pathname[pathlen - 1] == '/');
82dce998 1052
4ff89ee5 1053 if ((pat->flags & PATTERN_FLAG_MUSTBEDIR) && !isdir)
94bc671a
JNA
1054 return 0;
1055
4ff89ee5 1056 if (pat->flags & PATTERN_FLAG_NODIR) {
bd2f371d 1057 return match_basename(pathname + basename_offset,
dc09e9ec 1058 pathlen - basename_offset - isdir,
82dce998
NTND
1059 pattern, prefix,
1060 pat->patternlen, pat->flags);
d0bfd026 1061 }
dc09e9ec 1062 return match_pathname(pathname, pathlen - isdir,
82dce998 1063 base, baselen,
77651c03 1064 pattern, prefix, pat->patternlen);
d0bfd026
JH
1065}
1066
685b2925 1067static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
ec775c41 1068
69c5f17f 1069static int fill_one(struct all_attrs_item *all_attrs,
60a12722 1070 const struct match_attr *a, int rem)
515106fa 1071{
34ace8ba 1072 size_t i;
515106fa 1073
34ace8ba
PS
1074 for (i = a->num_attr; rem > 0 && i > 0; i--) {
1075 const struct git_attr *attr = a->state[i - 1].attr;
685b2925 1076 const char **n = &(all_attrs[attr->attr_nr].value);
34ace8ba 1077 const char *v = a->state[i - 1].setto;
515106fa
JH
1078
1079 if (*n == ATTR__UNKNOWN) {
515106fa
JH
1080 *n = v;
1081 rem--;
685b2925 1082 rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
515106fa
JH
1083 }
1084 }
1085 return rem;
1086}
1087
bd2f371d 1088static int fill(const char *path, int pathlen, int basename_offset,
dc81cf37
BW
1089 const struct attr_stack *stack,
1090 struct all_attrs_item *all_attrs, int rem)
d0bfd026 1091{
dc81cf37 1092 for (; rem > 0 && stack; stack = stack->prev) {
447ac906 1093 unsigned i;
dc81cf37
BW
1094 const char *base = stack->origin ? stack->origin : "";
1095
447ac906
PS
1096 for (i = stack->num_matches; 0 < rem && 0 < i; i--) {
1097 const struct match_attr *a = stack->attrs[i - 1];
dc81cf37
BW
1098 if (a->is_macro)
1099 continue;
1100 if (path_matches(path, pathlen, basename_offset,
1101 &a->u.pat, base, stack->originlen))
69c5f17f 1102 rem = fill_one(all_attrs, a, rem);
dc81cf37 1103 }
d0bfd026 1104 }
dc81cf37 1105
d0bfd026
JH
1106 return rem;
1107}
1108
685b2925 1109static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
f48fd688 1110{
60a12722 1111 const struct all_attrs_item *item = &all_attrs[nr];
f48fd688 1112
60a12722 1113 if (item->macro && item->value == ATTR__TRUE)
69c5f17f 1114 return fill_one(all_attrs, item->macro, rem);
60a12722 1115 else
ec775c41 1116 return rem;
60a12722 1117}
ec775c41 1118
60a12722
BW
1119/*
1120 * Marks the attributes which are macros based on the attribute stack.
1121 * This prevents having to search through the attribute stack each time
1122 * a macro needs to be expanded during the fill stage.
1123 */
1124static void determine_macros(struct all_attrs_item *all_attrs,
1125 const struct attr_stack *stack)
1126{
1127 for (; stack; stack = stack->prev) {
447ac906
PS
1128 unsigned i;
1129 for (i = stack->num_matches; i > 0; i--) {
1130 const struct match_attr *ma = stack->attrs[i - 1];
60a12722 1131 if (ma->is_macro) {
e1e12e97 1132 unsigned int n = ma->u.attr->attr_nr;
60a12722
BW
1133 if (!all_attrs[n].macro) {
1134 all_attrs[n].macro = ma;
1135 }
1136 }
ec775c41 1137 }
4b0c6961 1138 }
f48fd688
JH
1139}
1140
2d721744 1141/*
685b2925
BW
1142 * Collect attributes for path into the array pointed to by check->all_attrs.
1143 * If check->check_nr is non-zero, only attributes in check[] are collected.
1144 * Otherwise all attributes are collected.
2d721744 1145 */
847a9e5d 1146static void collect_some_attrs(struct index_state *istate,
47cfc9bd
KN
1147 const struct object_id *tree_oid,
1148 const char *path, struct attr_check *check)
d0bfd026 1149{
7b95849b 1150 int pathlen, rem, dirlen;
bd2f371d
JH
1151 const char *cp, *last_slash = NULL;
1152 int basename_offset;
9db9eecf
NTND
1153
1154 for (cp = path; *cp; cp++) {
1155 if (*cp == '/' && cp[1])
1156 last_slash = cp;
1157 }
1158 pathlen = cp - path;
1159 if (last_slash) {
bd2f371d 1160 basename_offset = last_slash + 1 - path;
9db9eecf
NTND
1161 dirlen = last_slash - path;
1162 } else {
bd2f371d 1163 basename_offset = 0;
9db9eecf
NTND
1164 dirlen = 0;
1165 }
d0bfd026 1166
47cfc9bd 1167 prepare_attr_stack(istate, tree_oid, path, dirlen, &check->stack);
685b2925 1168 all_attrs_init(&g_attr_hashmap, check);
dc81cf37 1169 determine_macros(check->all_attrs, check->stack);
685b2925 1170
685b2925 1171 rem = check->all_attrs_nr;
dc81cf37 1172 fill(path, pathlen, basename_offset, check->stack, check->all_attrs, rem);
2d721744
MH
1173}
1174
44451a2e
JC
1175static const char *default_attr_source_tree_object_name;
1176
1177void set_git_attr_source(const char *tree_object_name)
1178{
1179 default_attr_source_tree_object_name = xstrdup(tree_object_name);
1180}
1181
1182static void compute_default_attr_source(struct object_id *attr_source)
1183{
1184 if (!default_attr_source_tree_object_name)
1185 default_attr_source_tree_object_name = getenv(GIT_ATTR_SOURCE_ENVIRONMENT);
1186
1187 if (!default_attr_source_tree_object_name || !is_null_oid(attr_source))
1188 return;
1189
1190 if (repo_get_oid_treeish(the_repository, default_attr_source_tree_object_name, attr_source))
1191 die(_("bad --attr-source or GIT_ATTR_SOURCE"));
1192}
1193
1194static struct object_id *default_attr_source(void)
1195{
1196 static struct object_id attr_source;
1197
1198 if (is_null_oid(&attr_source))
1199 compute_default_attr_source(&attr_source);
1200 if (is_null_oid(&attr_source))
1201 return NULL;
1202 return &attr_source;
1203}
1204
847a9e5d 1205void git_check_attr(struct index_state *istate,
44451a2e 1206 const char *path,
d64324cb 1207 struct attr_check *check)
2d721744
MH
1208{
1209 int i;
44451a2e 1210 const struct object_id *tree_oid = default_attr_source();
2d721744 1211
47cfc9bd 1212 collect_some_attrs(istate, tree_oid, path, check);
f48fd688 1213
6bc2e3f7 1214 for (i = 0; i < check->nr; i++) {
e1e12e97 1215 unsigned int n = check->items[i].attr->attr_nr;
685b2925 1216 const char *value = check->all_attrs[n].value;
515106fa
JH
1217 if (value == ATTR__UNKNOWN)
1218 value = ATTR__UNSET;
6bc2e3f7 1219 check->items[i].value = value;
515106fa 1220 }
d0bfd026 1221}
06f33c17 1222
44451a2e 1223void git_all_attrs(struct index_state *istate,
7a400a2c 1224 const char *path, struct attr_check *check)
ee548df3 1225{
7f864111 1226 int i;
44451a2e 1227 const struct object_id *tree_oid = default_attr_source();
ee548df3 1228
7f864111 1229 attr_check_reset(check);
47cfc9bd 1230 collect_some_attrs(istate, tree_oid, path, check);
ee548df3 1231
685b2925
BW
1232 for (i = 0; i < check->all_attrs_nr; i++) {
1233 const char *name = check->all_attrs[i].attr->name;
1234 const char *value = check->all_attrs[i].value;
7f864111
JH
1235 struct attr_check_item *item;
1236 if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1237 continue;
1238 item = attr_check_append(check, git_attr(name));
1239 item->value = value;
ee548df3 1240 }
ee548df3
MH
1241}
1242
1a600b75
BW
1243void attr_start(void)
1244{
1a600b75 1245 pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
dc81cf37 1246 pthread_mutex_init(&check_vector.mutex, NULL);
1a600b75 1247}