2637804b1dd507421101e3016dbee596fa70213a
   1/*
   2 * Handle git attributes.  See gitattributes(5) for a description of
   3 * the file syntax, and Documentation/technical/api-gitattributes.txt
   4 * for a description of the API.
   5 *
   6 * One basic design decision here is that we are not going to support
   7 * an insanely large number of attributes.
   8 */
   9
  10#define NO_THE_INDEX_COMPATIBILITY_MACROS
  11#include "cache.h"
  12#include "exec_cmd.h"
  13#include "attr.h"
  14#include "dir.h"
  15#include "utf8.h"
  16#include "quote.h"
  17#include "thread-utils.h"
  18
  19const char git_attr__true[] = "(builtin)true";
  20const char git_attr__false[] = "\0(builtin)false";
  21static const char git_attr__unknown[] = "(builtin)unknown";
  22#define ATTR__TRUE git_attr__true
  23#define ATTR__FALSE git_attr__false
  24#define ATTR__UNSET NULL
  25#define ATTR__UNKNOWN git_attr__unknown
  26
  27#ifndef DEBUG_ATTR
  28#define DEBUG_ATTR 0
  29#endif
  30
  31struct git_attr {
  32        int attr_nr; /* unique attribute number */
  33        int maybe_macro;
  34        int maybe_real;
  35        char name[FLEX_ARRAY]; /* attribute name */
  36};
  37
  38/*
  39 * NEEDSWORK: maybe-real, maybe-macro are not property of
  40 * an attribute, as it depends on what .gitattributes are
  41 * read.  Once we introduce per git_attr_check attr_stack
  42 * and check_all_attr, the optimization based on them will
  43 * become unnecessary and can go away.  So is this variable.
  44 */
  45static int cannot_trust_maybe_real;
  46
  47const char *git_attr_name(const struct git_attr *attr)
  48{
  49        return attr->name;
  50}
  51
  52struct attr_hashmap {
  53        struct hashmap map;
  54#ifndef NO_PTHREADS
  55        pthread_mutex_t mutex;
  56#endif
  57};
  58
  59static inline void hashmap_lock(struct attr_hashmap *map)
  60{
  61#ifndef NO_PTHREADS
  62        pthread_mutex_lock(&map->mutex);
  63#endif
  64}
  65
  66static inline void hashmap_unlock(struct attr_hashmap *map)
  67{
  68#ifndef NO_PTHREADS
  69        pthread_mutex_unlock(&map->mutex);
  70#endif
  71}
  72
  73/*
  74 * The global dictionary of all interned attributes.  This
  75 * is a singleton object which is shared between threads.
  76 * Access to this dictionary must be surrounded with a mutex.
  77 */
  78static struct attr_hashmap g_attr_hashmap;
  79
  80/* The container for objects stored in "struct attr_hashmap" */
  81struct attr_hash_entry {
  82        struct hashmap_entry ent; /* must be the first member! */
  83        const char *key; /* the key; memory should be owned by value */
  84        size_t keylen; /* length of the key */
  85        void *value; /* the stored value */
  86};
  87
  88/* attr_hashmap comparison function */
  89static int attr_hash_entry_cmp(const struct attr_hash_entry *a,
  90                               const struct attr_hash_entry *b,
  91                               void *unused)
  92{
  93        return (a->keylen != b->keylen) || strncmp(a->key, b->key, a->keylen);
  94}
  95
  96/* Initialize an 'attr_hashmap' object */
  97static void attr_hashmap_init(struct attr_hashmap *map)
  98{
  99        hashmap_init(&map->map, (hashmap_cmp_fn) attr_hash_entry_cmp, 0);
 100}
 101
 102/*
 103 * Retrieve the 'value' stored in a hashmap given the provided 'key'.
 104 * If there is no matching entry, return NULL.
 105 */
 106static void *attr_hashmap_get(struct attr_hashmap *map,
 107                              const char *key, size_t keylen)
 108{
 109        struct attr_hash_entry k;
 110        struct attr_hash_entry *e;
 111
 112        if (!map->map.tablesize)
 113                attr_hashmap_init(map);
 114
 115        hashmap_entry_init(&k, memhash(key, keylen));
 116        k.key = key;
 117        k.keylen = keylen;
 118        e = hashmap_get(&map->map, &k, NULL);
 119
 120        return e ? e->value : NULL;
 121}
 122
 123/* Add 'value' to a hashmap based on the provided 'key'. */
 124static void attr_hashmap_add(struct attr_hashmap *map,
 125                             const char *key, size_t keylen,
 126                             void *value)
 127{
 128        struct attr_hash_entry *e;
 129
 130        if (!map->map.tablesize)
 131                attr_hashmap_init(map);
 132
 133        e = xmalloc(sizeof(struct attr_hash_entry));
 134        hashmap_entry_init(e, memhash(key, keylen));
 135        e->key = key;
 136        e->keylen = keylen;
 137        e->value = value;
 138
 139        hashmap_add(&map->map, e);
 140}
 141
 142struct all_attrs_item {
 143        const struct git_attr *attr;
 144        const char *value;
 145};
 146
 147/*
 148 * Reallocate and reinitialize the array of all attributes (which is used in
 149 * the attribute collection process) in 'check' based on the global dictionary
 150 * of attributes.
 151 */
 152static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
 153{
 154        int i;
 155
 156        hashmap_lock(map);
 157
 158        if (map->map.size < check->all_attrs_nr)
 159                die("BUG: interned attributes shouldn't be deleted");
 160
 161        /*
 162         * If the number of attributes in the global dictionary has increased
 163         * (or this attr_check instance doesn't have an initialized all_attrs
 164         * field), reallocate the provided attr_check instance's all_attrs
 165         * field and fill each entry with its corresponding git_attr.
 166         */
 167        if (map->map.size != check->all_attrs_nr) {
 168                struct attr_hash_entry *e;
 169                struct hashmap_iter iter;
 170                hashmap_iter_init(&map->map, &iter);
 171
 172                REALLOC_ARRAY(check->all_attrs, map->map.size);
 173                check->all_attrs_nr = map->map.size;
 174
 175                while ((e = hashmap_iter_next(&iter))) {
 176                        const struct git_attr *a = e->value;
 177                        check->all_attrs[a->attr_nr].attr = a;
 178                }
 179        }
 180
 181        hashmap_unlock(map);
 182
 183        /*
 184         * Re-initialize every entry in check->all_attrs.
 185         * This re-initialization can live outside of the locked region since
 186         * the attribute dictionary is no longer being accessed.
 187         */
 188        for (i = 0; i < check->all_attrs_nr; i++) {
 189                check->all_attrs[i].value = ATTR__UNKNOWN;
 190        }
 191}
 192
 193static int attr_name_valid(const char *name, size_t namelen)
 194{
 195        /*
 196         * Attribute name cannot begin with '-' and must consist of
 197         * characters from [-A-Za-z0-9_.].
 198         */
 199        if (namelen <= 0 || *name == '-')
 200                return 0;
 201        while (namelen--) {
 202                char ch = *name++;
 203                if (! (ch == '-' || ch == '.' || ch == '_' ||
 204                       ('0' <= ch && ch <= '9') ||
 205                       ('a' <= ch && ch <= 'z') ||
 206                       ('A' <= ch && ch <= 'Z')) )
 207                        return 0;
 208        }
 209        return 1;
 210}
 211
 212static void report_invalid_attr(const char *name, size_t len,
 213                                const char *src, int lineno)
 214{
 215        struct strbuf err = STRBUF_INIT;
 216        strbuf_addf(&err, _("%.*s is not a valid attribute name"),
 217                    (int) len, name);
 218        fprintf(stderr, "%s: %s:%d\n", err.buf, src, lineno);
 219        strbuf_release(&err);
 220}
 221
 222/*
 223 * Given a 'name', lookup and return the corresponding attribute in the global
 224 * dictionary.  If no entry is found, create a new attribute and store it in
 225 * the dictionary.
 226 */
 227static struct git_attr *git_attr_internal(const char *name, int namelen)
 228{
 229        struct git_attr *a;
 230
 231        if (!attr_name_valid(name, namelen))
 232                return NULL;
 233
 234        hashmap_lock(&g_attr_hashmap);
 235
 236        a = attr_hashmap_get(&g_attr_hashmap, name, namelen);
 237
 238        if (!a) {
 239                FLEX_ALLOC_MEM(a, name, name, namelen);
 240                a->attr_nr = g_attr_hashmap.map.size;
 241                a->maybe_real = 0;
 242                a->maybe_macro = 0;
 243
 244                attr_hashmap_add(&g_attr_hashmap, a->name, namelen, a);
 245                assert(a->attr_nr == (g_attr_hashmap.map.size - 1));
 246        }
 247
 248        hashmap_unlock(&g_attr_hashmap);
 249
 250        return a;
 251}
 252
 253struct git_attr *git_attr(const char *name)
 254{
 255        return git_attr_internal(name, strlen(name));
 256}
 257
 258/* What does a matched pattern decide? */
 259struct attr_state {
 260        struct git_attr *attr;
 261        const char *setto;
 262};
 263
 264struct pattern {
 265        const char *pattern;
 266        int patternlen;
 267        int nowildcardlen;
 268        unsigned flags;         /* EXC_FLAG_* */
 269};
 270
 271/*
 272 * One rule, as from a .gitattributes file.
 273 *
 274 * If is_macro is true, then u.attr is a pointer to the git_attr being
 275 * defined.
 276 *
 277 * If is_macro is false, then u.pat is the filename pattern to which the
 278 * rule applies.
 279 *
 280 * In either case, num_attr is the number of attributes affected by
 281 * this rule, and state is an array listing them.  The attributes are
 282 * listed as they appear in the file (macros unexpanded).
 283 */
 284struct match_attr {
 285        union {
 286                struct pattern pat;
 287                struct git_attr *attr;
 288        } u;
 289        char is_macro;
 290        unsigned num_attr;
 291        struct attr_state state[FLEX_ARRAY];
 292};
 293
 294static const char blank[] = " \t\r\n";
 295
 296/*
 297 * Parse a whitespace-delimited attribute state (i.e., "attr",
 298 * "-attr", "!attr", or "attr=value") from the string starting at src.
 299 * If e is not NULL, write the results to *e.  Return a pointer to the
 300 * remainder of the string (with leading whitespace removed), or NULL
 301 * if there was an error.
 302 */
 303static const char *parse_attr(const char *src, int lineno, const char *cp,
 304                              struct attr_state *e)
 305{
 306        const char *ep, *equals;
 307        int len;
 308
 309        ep = cp + strcspn(cp, blank);
 310        equals = strchr(cp, '=');
 311        if (equals && ep < equals)
 312                equals = NULL;
 313        if (equals)
 314                len = equals - cp;
 315        else
 316                len = ep - cp;
 317        if (!e) {
 318                if (*cp == '-' || *cp == '!') {
 319                        cp++;
 320                        len--;
 321                }
 322                if (!attr_name_valid(cp, len)) {
 323                        report_invalid_attr(cp, len, src, lineno);
 324                        return NULL;
 325                }
 326        } else {
 327                /*
 328                 * As this function is always called twice, once with
 329                 * e == NULL in the first pass and then e != NULL in
 330                 * the second pass, no need for attr_name_valid()
 331                 * check here.
 332                 */
 333                if (*cp == '-' || *cp == '!') {
 334                        e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
 335                        cp++;
 336                        len--;
 337                }
 338                else if (!equals)
 339                        e->setto = ATTR__TRUE;
 340                else {
 341                        e->setto = xmemdupz(equals + 1, ep - equals - 1);
 342                }
 343                e->attr = git_attr_internal(cp, len);
 344        }
 345        return ep + strspn(ep, blank);
 346}
 347
 348static struct match_attr *parse_attr_line(const char *line, const char *src,
 349                                          int lineno, int macro_ok)
 350{
 351        int namelen;
 352        int num_attr, i;
 353        const char *cp, *name, *states;
 354        struct match_attr *res = NULL;
 355        int is_macro;
 356        struct strbuf pattern = STRBUF_INIT;
 357
 358        cp = line + strspn(line, blank);
 359        if (!*cp || *cp == '#')
 360                return NULL;
 361        name = cp;
 362
 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;
 369        }
 370
 371        if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
 372            starts_with(name, ATTRIBUTE_MACRO_PREFIX)) {
 373                if (!macro_ok) {
 374                        fprintf(stderr, "%s not allowed: %s:%d\n",
 375                                name, src, lineno);
 376                        goto fail_return;
 377                }
 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;
 385                }
 386        }
 387        else
 388                is_macro = 0;
 389
 390        states += strspn(states, blank);
 391
 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;
 397        }
 398
 399        res = xcalloc(1,
 400                      sizeof(*res) +
 401                      sizeof(struct attr_state) * num_attr +
 402                      (is_macro ? 0 : namelen + 1));
 403        if (is_macro) {
 404                res->u.attr = git_attr_internal(name, namelen);
 405                res->u.attr->maybe_macro = 1;
 406        } else {
 407                char *p = (char *)&(res->state[num_attr]);
 408                memcpy(p, name, namelen);
 409                res->u.pat.pattern = p;
 410                parse_exclude_pattern(&res->u.pat.pattern,
 411                                      &res->u.pat.patternlen,
 412                                      &res->u.pat.flags,
 413                                      &res->u.pat.nowildcardlen);
 414                if (res->u.pat.flags & EXC_FLAG_NEGATIVE) {
 415                        warning(_("Negative patterns are ignored in git attributes\n"
 416                                  "Use '\\!' for literal leading exclamation."));
 417                        goto fail_return;
 418                }
 419        }
 420        res->is_macro = is_macro;
 421        res->num_attr = num_attr;
 422
 423        /* Second pass to fill the attr_states */
 424        for (cp = states, i = 0; *cp; i++) {
 425                cp = parse_attr(src, lineno, cp, &(res->state[i]));
 426                if (!is_macro)
 427                        res->state[i].attr->maybe_real = 1;
 428                if (res->state[i].attr->maybe_macro)
 429                        cannot_trust_maybe_real = 1;
 430        }
 431
 432        strbuf_release(&pattern);
 433        return res;
 434
 435fail_return:
 436        strbuf_release(&pattern);
 437        free(res);
 438        return NULL;
 439}
 440
 441/*
 442 * Like info/exclude and .gitignore, the attribute information can
 443 * come from many places.
 444 *
 445 * (1) .gitattribute file of the same directory;
 446 * (2) .gitattribute file of the parent directory if (1) does not have
 447 *      any match; this goes recursively upwards, just like .gitignore.
 448 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
 449 *
 450 * In the same file, later entries override the earlier match, so in the
 451 * global list, we would have entries from info/attributes the earliest
 452 * (reading the file from top to bottom), .gitattribute of the root
 453 * directory (again, reading the file from top to bottom) down to the
 454 * current directory, and then scan the list backwards to find the first match.
 455 * This is exactly the same as what is_excluded() does in dir.c to deal with
 456 * .gitignore file and info/excludes file as a fallback.
 457 */
 458
 459/* NEEDSWORK: This will become per git_attr_check */
 460static struct attr_stack {
 461        struct attr_stack *prev;
 462        char *origin;
 463        size_t originlen;
 464        unsigned num_matches;
 465        unsigned alloc;
 466        struct match_attr **attrs;
 467} *attr_stack;
 468
 469static void free_attr_elem(struct attr_stack *e)
 470{
 471        int i;
 472        free(e->origin);
 473        for (i = 0; i < e->num_matches; i++) {
 474                struct match_attr *a = e->attrs[i];
 475                int j;
 476                for (j = 0; j < a->num_attr; j++) {
 477                        const char *setto = a->state[j].setto;
 478                        if (setto == ATTR__TRUE ||
 479                            setto == ATTR__FALSE ||
 480                            setto == ATTR__UNSET ||
 481                            setto == ATTR__UNKNOWN)
 482                                ;
 483                        else
 484                                free((char *) setto);
 485                }
 486                free(a);
 487        }
 488        free(e->attrs);
 489        free(e);
 490}
 491
 492struct attr_check *attr_check_alloc(void)
 493{
 494        return xcalloc(1, sizeof(struct attr_check));
 495}
 496
 497struct attr_check *attr_check_initl(const char *one, ...)
 498{
 499        struct attr_check *check;
 500        int cnt;
 501        va_list params;
 502        const char *param;
 503
 504        va_start(params, one);
 505        for (cnt = 1; (param = va_arg(params, const char *)) != NULL; cnt++)
 506                ;
 507        va_end(params);
 508
 509        check = attr_check_alloc();
 510        check->nr = cnt;
 511        check->alloc = cnt;
 512        check->items = xcalloc(cnt, sizeof(struct attr_check_item));
 513
 514        check->items[0].attr = git_attr(one);
 515        va_start(params, one);
 516        for (cnt = 1; cnt < check->nr; cnt++) {
 517                const struct git_attr *attr;
 518                param = va_arg(params, const char *);
 519                if (!param)
 520                        die("BUG: counted %d != ended at %d",
 521                            check->nr, cnt);
 522                attr = git_attr(param);
 523                if (!attr)
 524                        die("BUG: %s: not a valid attribute name", param);
 525                check->items[cnt].attr = attr;
 526        }
 527        va_end(params);
 528        return check;
 529}
 530
 531struct attr_check_item *attr_check_append(struct attr_check *check,
 532                                          const struct git_attr *attr)
 533{
 534        struct attr_check_item *item;
 535
 536        ALLOC_GROW(check->items, check->nr + 1, check->alloc);
 537        item = &check->items[check->nr++];
 538        item->attr = attr;
 539        return item;
 540}
 541
 542void attr_check_reset(struct attr_check *check)
 543{
 544        check->nr = 0;
 545}
 546
 547void attr_check_clear(struct attr_check *check)
 548{
 549        free(check->items);
 550        check->items = NULL;
 551        check->alloc = 0;
 552        check->nr = 0;
 553
 554        free(check->all_attrs);
 555        check->all_attrs = NULL;
 556        check->all_attrs_nr = 0;
 557}
 558
 559void attr_check_free(struct attr_check *check)
 560{
 561        attr_check_clear(check);
 562        free(check);
 563}
 564
 565static const char *builtin_attr[] = {
 566        "[attr]binary -diff -merge -text",
 567        NULL,
 568};
 569
 570static void handle_attr_line(struct attr_stack *res,
 571                             const char *line,
 572                             const char *src,
 573                             int lineno,
 574                             int macro_ok)
 575{
 576        struct match_attr *a;
 577
 578        a = parse_attr_line(line, src, lineno, macro_ok);
 579        if (!a)
 580                return;
 581        ALLOC_GROW(res->attrs, res->num_matches + 1, res->alloc);
 582        res->attrs[res->num_matches++] = a;
 583}
 584
 585static struct attr_stack *read_attr_from_array(const char **list)
 586{
 587        struct attr_stack *res;
 588        const char *line;
 589        int lineno = 0;
 590
 591        res = xcalloc(1, sizeof(*res));
 592        while ((line = *(list++)) != NULL)
 593                handle_attr_line(res, line, "[builtin]", ++lineno, 1);
 594        return res;
 595}
 596
 597/*
 598 * NEEDSWORK: these two are tricky.  The callers assume there is a
 599 * single, system-wide global state "where we read attributes from?"
 600 * and when the state is flipped by calling git_attr_set_direction(),
 601 * attr_stack is discarded so that subsequent attr_check will lazily
 602 * read from the right place.  And they do not know or care who called
 603 * by them uses the attribute subsystem, hence have no knowledge of
 604 * existing git_attr_check instances or future ones that will be
 605 * created).
 606 *
 607 * Probably we need a thread_local that holds these two variables,
 608 * and a list of git_attr_check instances (which need to be maintained
 609 * by hooking into git_attr_check_alloc(), git_attr_check_initl(), and
 610 * git_attr_check_clear().  Then git_attr_set_direction() updates the
 611 * fields in that thread_local for these two variables, iterate over
 612 * all the active git_attr_check instances and discard the attr_stack
 613 * they hold.  Yuck, but it sounds doable.
 614 */
 615static enum git_attr_direction direction;
 616static struct index_state *use_index;
 617
 618static struct attr_stack *read_attr_from_file(const char *path, int macro_ok)
 619{
 620        FILE *fp = fopen(path, "r");
 621        struct attr_stack *res;
 622        char buf[2048];
 623        int lineno = 0;
 624
 625        if (!fp) {
 626                if (errno != ENOENT && errno != ENOTDIR)
 627                        warn_on_inaccessible(path);
 628                return NULL;
 629        }
 630        res = xcalloc(1, sizeof(*res));
 631        while (fgets(buf, sizeof(buf), fp)) {
 632                char *bufp = buf;
 633                if (!lineno)
 634                        skip_utf8_bom(&bufp, strlen(bufp));
 635                handle_attr_line(res, bufp, path, ++lineno, macro_ok);
 636        }
 637        fclose(fp);
 638        return res;
 639}
 640
 641static struct attr_stack *read_attr_from_index(const char *path, int macro_ok)
 642{
 643        struct attr_stack *res;
 644        char *buf, *sp;
 645        int lineno = 0;
 646
 647        buf = read_blob_data_from_index(use_index ? use_index : &the_index, path, NULL);
 648        if (!buf)
 649                return NULL;
 650
 651        res = xcalloc(1, sizeof(*res));
 652        for (sp = buf; *sp; ) {
 653                char *ep;
 654                int more;
 655
 656                ep = strchrnul(sp, '\n');
 657                more = (*ep == '\n');
 658                *ep = '\0';
 659                handle_attr_line(res, sp, path, ++lineno, macro_ok);
 660                sp = ep + more;
 661        }
 662        free(buf);
 663        return res;
 664}
 665
 666static struct attr_stack *read_attr(const char *path, int macro_ok)
 667{
 668        struct attr_stack *res;
 669
 670        if (direction == GIT_ATTR_CHECKOUT) {
 671                res = read_attr_from_index(path, macro_ok);
 672                if (!res)
 673                        res = read_attr_from_file(path, macro_ok);
 674        }
 675        else if (direction == GIT_ATTR_CHECKIN) {
 676                res = read_attr_from_file(path, macro_ok);
 677                if (!res)
 678                        /*
 679                         * There is no checked out .gitattributes file there, but
 680                         * we might have it in the index.  We allow operation in a
 681                         * sparsely checked out work tree, so read from it.
 682                         */
 683                        res = read_attr_from_index(path, macro_ok);
 684        }
 685        else
 686                res = read_attr_from_index(path, macro_ok);
 687        if (!res)
 688                res = xcalloc(1, sizeof(*res));
 689        return res;
 690}
 691
 692#if DEBUG_ATTR
 693static void debug_info(const char *what, struct attr_stack *elem)
 694{
 695        fprintf(stderr, "%s: %s\n", what, elem->origin ? elem->origin : "()");
 696}
 697static void debug_set(const char *what, const char *match, struct git_attr *attr, const void *v)
 698{
 699        const char *value = v;
 700
 701        if (ATTR_TRUE(value))
 702                value = "set";
 703        else if (ATTR_FALSE(value))
 704                value = "unset";
 705        else if (ATTR_UNSET(value))
 706                value = "unspecified";
 707
 708        fprintf(stderr, "%s: %s => %s (%s)\n",
 709                what, attr->name, (char *) value, match);
 710}
 711#define debug_push(a) debug_info("push", (a))
 712#define debug_pop(a) debug_info("pop", (a))
 713#else
 714#define debug_push(a) do { ; } while (0)
 715#define debug_pop(a) do { ; } while (0)
 716#define debug_set(a,b,c,d) do { ; } while (0)
 717#endif /* DEBUG_ATTR */
 718
 719static void drop_attr_stack(void)
 720{
 721        while (attr_stack) {
 722                struct attr_stack *elem = attr_stack;
 723                attr_stack = elem->prev;
 724                free_attr_elem(elem);
 725        }
 726}
 727
 728static const char *git_etc_gitattributes(void)
 729{
 730        static const char *system_wide;
 731        if (!system_wide)
 732                system_wide = system_path(ETC_GITATTRIBUTES);
 733        return system_wide;
 734}
 735
 736static int git_attr_system(void)
 737{
 738        return !git_env_bool("GIT_ATTR_NOSYSTEM", 0);
 739}
 740
 741static GIT_PATH_FUNC(git_path_info_attributes, INFOATTRIBUTES_FILE)
 742
 743static void push_stack(struct attr_stack **attr_stack_p,
 744                       struct attr_stack *elem, char *origin, size_t originlen)
 745{
 746        if (elem) {
 747                elem->origin = origin;
 748                if (origin)
 749                        elem->originlen = originlen;
 750                elem->prev = *attr_stack_p;
 751                *attr_stack_p = elem;
 752        }
 753}
 754
 755static void bootstrap_attr_stack(void)
 756{
 757        struct attr_stack *elem;
 758
 759        if (attr_stack)
 760                return;
 761
 762        push_stack(&attr_stack, read_attr_from_array(builtin_attr), NULL, 0);
 763
 764        if (git_attr_system())
 765                push_stack(&attr_stack,
 766                           read_attr_from_file(git_etc_gitattributes(), 1),
 767                           NULL, 0);
 768
 769        if (!git_attributes_file)
 770                git_attributes_file = xdg_config_home("attributes");
 771        if (git_attributes_file)
 772                push_stack(&attr_stack,
 773                           read_attr_from_file(git_attributes_file, 1),
 774                           NULL, 0);
 775
 776        if (!is_bare_repository() || direction == GIT_ATTR_INDEX) {
 777                elem = read_attr(GITATTRIBUTES_FILE, 1);
 778                push_stack(&attr_stack, elem, xstrdup(""), 0);
 779                debug_push(elem);
 780        }
 781
 782        if (startup_info->have_repository)
 783                elem = read_attr_from_file(git_path_info_attributes(), 1);
 784        else
 785                elem = NULL;
 786
 787        if (!elem)
 788                elem = xcalloc(1, sizeof(*elem));
 789        push_stack(&attr_stack, elem, NULL, 0);
 790}
 791
 792static void prepare_attr_stack(const char *path, int dirlen)
 793{
 794        struct attr_stack *elem, *info;
 795        const char *cp;
 796
 797        /*
 798         * At the bottom of the attribute stack is the built-in
 799         * set of attribute definitions, followed by the contents
 800         * of $(prefix)/etc/gitattributes and a file specified by
 801         * core.attributesfile.  Then, contents from
 802         * .gitattribute files from directories closer to the
 803         * root to the ones in deeper directories are pushed
 804         * to the stack.  Finally, at the very top of the stack
 805         * we always keep the contents of $GIT_DIR/info/attributes.
 806         *
 807         * When checking, we use entries from near the top of the
 808         * stack, preferring $GIT_DIR/info/attributes, then
 809         * .gitattributes in deeper directories to shallower ones,
 810         * and finally use the built-in set as the default.
 811         */
 812        bootstrap_attr_stack();
 813
 814        /*
 815         * Pop the "info" one that is always at the top of the stack.
 816         */
 817        info = attr_stack;
 818        attr_stack = info->prev;
 819
 820        /*
 821         * Pop the ones from directories that are not the prefix of
 822         * the path we are checking. Break out of the loop when we see
 823         * the root one (whose origin is an empty string "") or the builtin
 824         * one (whose origin is NULL) without popping it.
 825         */
 826        while (attr_stack->origin) {
 827                int namelen = strlen(attr_stack->origin);
 828
 829                elem = attr_stack;
 830                if (namelen <= dirlen &&
 831                    !strncmp(elem->origin, path, namelen) &&
 832                    (!namelen || path[namelen] == '/'))
 833                        break;
 834
 835                debug_pop(elem);
 836                attr_stack = elem->prev;
 837                free_attr_elem(elem);
 838        }
 839
 840        /*
 841         * Read from parent directories and push them down
 842         */
 843        if (!is_bare_repository() || direction == GIT_ATTR_INDEX) {
 844                /*
 845                 * bootstrap_attr_stack() should have added, and the
 846                 * above loop should have stopped before popping, the
 847                 * root element whose attr_stack->origin is set to an
 848                 * empty string.
 849                 */
 850                struct strbuf pathbuf = STRBUF_INIT;
 851
 852                assert(attr_stack->origin);
 853                while (1) {
 854                        size_t len = strlen(attr_stack->origin);
 855                        char *origin;
 856
 857                        if (dirlen <= len)
 858                                break;
 859                        cp = memchr(path + len + 1, '/', dirlen - len - 1);
 860                        if (!cp)
 861                                cp = path + dirlen;
 862                        strbuf_addf(&pathbuf,
 863                                    "%.*s/%s", (int)(cp - path), path,
 864                                    GITATTRIBUTES_FILE);
 865                        elem = read_attr(pathbuf.buf, 0);
 866                        strbuf_setlen(&pathbuf, cp - path);
 867                        origin = strbuf_detach(&pathbuf, &len);
 868                        push_stack(&attr_stack, elem, origin, len);
 869                        debug_push(elem);
 870                }
 871
 872                strbuf_release(&pathbuf);
 873        }
 874
 875        /*
 876         * Finally push the "info" one at the top of the stack.
 877         */
 878        push_stack(&attr_stack, info, NULL, 0);
 879}
 880
 881static int path_matches(const char *pathname, int pathlen,
 882                        int basename_offset,
 883                        const struct pattern *pat,
 884                        const char *base, int baselen)
 885{
 886        const char *pattern = pat->pattern;
 887        int prefix = pat->nowildcardlen;
 888        int isdir = (pathlen && pathname[pathlen - 1] == '/');
 889
 890        if ((pat->flags & EXC_FLAG_MUSTBEDIR) && !isdir)
 891                return 0;
 892
 893        if (pat->flags & EXC_FLAG_NODIR) {
 894                return match_basename(pathname + basename_offset,
 895                                      pathlen - basename_offset - isdir,
 896                                      pattern, prefix,
 897                                      pat->patternlen, pat->flags);
 898        }
 899        return match_pathname(pathname, pathlen - isdir,
 900                              base, baselen,
 901                              pattern, prefix, pat->patternlen, pat->flags);
 902}
 903
 904static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
 905
 906static int fill_one(const char *what, struct all_attrs_item *all_attrs,
 907                    struct match_attr *a, int rem)
 908{
 909        int i;
 910
 911        for (i = a->num_attr - 1; rem > 0 && i >= 0; i--) {
 912                struct git_attr *attr = a->state[i].attr;
 913                const char **n = &(all_attrs[attr->attr_nr].value);
 914                const char *v = a->state[i].setto;
 915
 916                if (*n == ATTR__UNKNOWN) {
 917                        debug_set(what,
 918                                  a->is_macro ? a->u.attr->name : a->u.pat.pattern,
 919                                  attr, v);
 920                        *n = v;
 921                        rem--;
 922                        rem = macroexpand_one(all_attrs, attr->attr_nr, rem);
 923                }
 924        }
 925        return rem;
 926}
 927
 928static int fill(const char *path, int pathlen, int basename_offset,
 929                struct attr_stack *stk, struct all_attrs_item *all_attrs,
 930                int rem)
 931{
 932        int i;
 933        const char *base = stk->origin ? stk->origin : "";
 934
 935        for (i = stk->num_matches - 1; 0 < rem && 0 <= i; i--) {
 936                struct match_attr *a = stk->attrs[i];
 937                if (a->is_macro)
 938                        continue;
 939                if (path_matches(path, pathlen, basename_offset,
 940                                 &a->u.pat, base, stk->originlen))
 941                        rem = fill_one("fill", all_attrs, a, rem);
 942        }
 943        return rem;
 944}
 945
 946static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem)
 947{
 948        struct attr_stack *stk;
 949        int i;
 950
 951        if (all_attrs[nr].value != ATTR__TRUE ||
 952            !all_attrs[nr].attr->maybe_macro)
 953                return rem;
 954
 955        for (stk = attr_stack; stk; stk = stk->prev) {
 956                for (i = stk->num_matches - 1; 0 <= i; i--) {
 957                        struct match_attr *ma = stk->attrs[i];
 958                        if (!ma->is_macro)
 959                                continue;
 960                        if (ma->u.attr->attr_nr == nr)
 961                                return fill_one("expand", all_attrs, ma, rem);
 962                }
 963        }
 964
 965        return rem;
 966}
 967
 968/*
 969 * Collect attributes for path into the array pointed to by check->all_attrs.
 970 * If check->check_nr is non-zero, only attributes in check[] are collected.
 971 * Otherwise all attributes are collected.
 972 */
 973static void collect_some_attrs(const char *path, struct attr_check *check)
 974{
 975        struct attr_stack *stk;
 976        int i, pathlen, rem, dirlen;
 977        const char *cp, *last_slash = NULL;
 978        int basename_offset;
 979
 980        for (cp = path; *cp; cp++) {
 981                if (*cp == '/' && cp[1])
 982                        last_slash = cp;
 983        }
 984        pathlen = cp - path;
 985        if (last_slash) {
 986                basename_offset = last_slash + 1 - path;
 987                dirlen = last_slash - path;
 988        } else {
 989                basename_offset = 0;
 990                dirlen = 0;
 991        }
 992
 993        prepare_attr_stack(path, dirlen);
 994        all_attrs_init(&g_attr_hashmap, check);
 995
 996        if (check->nr && !cannot_trust_maybe_real) {
 997                rem = 0;
 998                for (i = 0; i < check->nr; i++) {
 999                        const struct git_attr *a = check->items[i].attr;
1000                        if (!a->maybe_real) {
1001                                struct all_attrs_item *c;
1002                                c = check->all_attrs + a->attr_nr;
1003                                c->value = ATTR__UNSET;
1004                                rem++;
1005                        }
1006                }
1007                if (rem == check->nr)
1008                        return;
1009        }
1010
1011        rem = check->all_attrs_nr;
1012        for (stk = attr_stack; 0 < rem && stk; stk = stk->prev)
1013                rem = fill(path, pathlen, basename_offset, stk, check->all_attrs, rem);
1014}
1015
1016int git_check_attr(const char *path, struct attr_check *check)
1017{
1018        int i;
1019
1020        collect_some_attrs(path, check);
1021
1022        for (i = 0; i < check->nr; i++) {
1023                size_t n = check->items[i].attr->attr_nr;
1024                const char *value = check->all_attrs[n].value;
1025                if (value == ATTR__UNKNOWN)
1026                        value = ATTR__UNSET;
1027                check->items[i].value = value;
1028        }
1029
1030        return 0;
1031}
1032
1033void git_all_attrs(const char *path, struct attr_check *check)
1034{
1035        int i;
1036
1037        attr_check_reset(check);
1038        collect_some_attrs(path, check);
1039
1040        for (i = 0; i < check->all_attrs_nr; i++) {
1041                const char *name = check->all_attrs[i].attr->name;
1042                const char *value = check->all_attrs[i].value;
1043                struct attr_check_item *item;
1044                if (value == ATTR__UNSET || value == ATTR__UNKNOWN)
1045                        continue;
1046                item = attr_check_append(check, git_attr(name));
1047                item->value = value;
1048        }
1049}
1050
1051void git_attr_set_direction(enum git_attr_direction new, struct index_state *istate)
1052{
1053        enum git_attr_direction old = direction;
1054
1055        if (is_bare_repository() && new != GIT_ATTR_INDEX)
1056                die("BUG: non-INDEX attr direction in a bare repo");
1057
1058        direction = new;
1059        if (new != old)
1060                drop_attr_stack();
1061        use_index = istate;
1062}
1063
1064void attr_start(void)
1065{
1066#ifndef NO_PTHREADS
1067        pthread_mutex_init(&g_attr_hashmap.mutex, NULL);
1068#endif
1069}