attr.con commit Merge branch 'maint' of git://repo.or.cz/git-gui into maint (7468c29)
   1#include "cache.h"
   2#include "attr.h"
   3
   4const char git_attr__true[] = "(builtin)true";
   5const char git_attr__false[] = "\0(builtin)false";
   6static const char git_attr__unknown[] = "(builtin)unknown";
   7#define ATTR__TRUE git_attr__true
   8#define ATTR__FALSE git_attr__false
   9#define ATTR__UNSET NULL
  10#define ATTR__UNKNOWN git_attr__unknown
  11
  12/*
  13 * The basic design decision here is that we are not going to have
  14 * insanely large number of attributes.
  15 *
  16 * This is a randomly chosen prime.
  17 */
  18#define HASHSIZE 257
  19
  20#ifndef DEBUG_ATTR
  21#define DEBUG_ATTR 0
  22#endif
  23
  24struct git_attr {
  25        struct git_attr *next;
  26        unsigned h;
  27        int attr_nr;
  28        char name[FLEX_ARRAY];
  29};
  30static int attr_nr;
  31
  32static struct git_attr_check *check_all_attr;
  33static struct git_attr *(git_attr_hash[HASHSIZE]);
  34
  35static unsigned hash_name(const char *name, int namelen)
  36{
  37        unsigned val = 0;
  38        unsigned char c;
  39
  40        while (namelen--) {
  41                c = *name++;
  42                val = ((val << 7) | (val >> 22)) ^ c;
  43        }
  44        return val;
  45}
  46
  47static int invalid_attr_name(const char *name, int namelen)
  48{
  49        /*
  50         * Attribute name cannot begin with '-' and from
  51         * [-A-Za-z0-9_.].  We'd specifically exclude '=' for now,
  52         * as we might later want to allow non-binary value for
  53         * attributes, e.g. "*.svg      merge=special-merge-program-for-svg"
  54         */
  55        if (*name == '-')
  56                return -1;
  57        while (namelen--) {
  58                char ch = *name++;
  59                if (! (ch == '-' || ch == '.' || ch == '_' ||
  60                       ('0' <= ch && ch <= '9') ||
  61                       ('a' <= ch && ch <= 'z') ||
  62                       ('A' <= ch && ch <= 'Z')) )
  63                        return -1;
  64        }
  65        return 0;
  66}
  67
  68struct git_attr *git_attr(const char *name, int len)
  69{
  70        unsigned hval = hash_name(name, len);
  71        unsigned pos = hval % HASHSIZE;
  72        struct git_attr *a;
  73
  74        for (a = git_attr_hash[pos]; a; a = a->next) {
  75                if (a->h == hval &&
  76                    !memcmp(a->name, name, len) && !a->name[len])
  77                        return a;
  78        }
  79
  80        if (invalid_attr_name(name, len))
  81                return NULL;
  82
  83        a = xmalloc(sizeof(*a) + len + 1);
  84        memcpy(a->name, name, len);
  85        a->name[len] = 0;
  86        a->h = hval;
  87        a->next = git_attr_hash[pos];
  88        a->attr_nr = attr_nr++;
  89        git_attr_hash[pos] = a;
  90
  91        check_all_attr = xrealloc(check_all_attr,
  92                                  sizeof(*check_all_attr) * attr_nr);
  93        check_all_attr[a->attr_nr].attr = a;
  94        check_all_attr[a->attr_nr].value = ATTR__UNKNOWN;
  95        return a;
  96}
  97
  98/*
  99 * .gitattributes file is one line per record, each of which is
 100 *
 101 * (1) glob pattern.
 102 * (2) whitespace
 103 * (3) whitespace separated list of attribute names, each of which
 104 *     could be prefixed with '-' to mean "set to false", '!' to mean
 105 *     "unset".
 106 */
 107
 108/* What does a matched pattern decide? */
 109struct attr_state {
 110        struct git_attr *attr;
 111        const char *setto;
 112};
 113
 114struct match_attr {
 115        union {
 116                char *pattern;
 117                struct git_attr *attr;
 118        } u;
 119        char is_macro;
 120        unsigned num_attr;
 121        struct attr_state state[FLEX_ARRAY];
 122};
 123
 124static const char blank[] = " \t\r\n";
 125
 126static const char *parse_attr(const char *src, int lineno, const char *cp,
 127                              int *num_attr, struct match_attr *res)
 128{
 129        const char *ep, *equals;
 130        int len;
 131
 132        ep = cp + strcspn(cp, blank);
 133        equals = strchr(cp, '=');
 134        if (equals && ep < equals)
 135                equals = NULL;
 136        if (equals)
 137                len = equals - cp;
 138        else
 139                len = ep - cp;
 140        if (!res) {
 141                if (*cp == '-' || *cp == '!') {
 142                        cp++;
 143                        len--;
 144                }
 145                if (invalid_attr_name(cp, len)) {
 146                        fprintf(stderr,
 147                                "%.*s is not a valid attribute name: %s:%d\n",
 148                                len, cp, src, lineno);
 149                        return NULL;
 150                }
 151        } else {
 152                struct attr_state *e;
 153
 154                e = &(res->state[*num_attr]);
 155                if (*cp == '-' || *cp == '!') {
 156                        e->setto = (*cp == '-') ? ATTR__FALSE : ATTR__UNSET;
 157                        cp++;
 158                        len--;
 159                }
 160                else if (!equals)
 161                        e->setto = ATTR__TRUE;
 162                else {
 163                        char *value;
 164                        int vallen = ep - equals;
 165                        value = xmalloc(vallen);
 166                        memcpy(value, equals+1, vallen-1);
 167                        value[vallen-1] = 0;
 168                        e->setto = value;
 169                }
 170                e->attr = git_attr(cp, len);
 171        }
 172        (*num_attr)++;
 173        return ep + strspn(ep, blank);
 174}
 175
 176static struct match_attr *parse_attr_line(const char *line, const char *src,
 177                                          int lineno, int macro_ok)
 178{
 179        int namelen;
 180        int num_attr;
 181        const char *cp, *name;
 182        struct match_attr *res = NULL;
 183        int pass;
 184        int is_macro;
 185
 186        cp = line + strspn(line, blank);
 187        if (!*cp || *cp == '#')
 188                return NULL;
 189        name = cp;
 190        namelen = strcspn(name, blank);
 191        if (strlen(ATTRIBUTE_MACRO_PREFIX) < namelen &&
 192            !prefixcmp(name, ATTRIBUTE_MACRO_PREFIX)) {
 193                if (!macro_ok) {
 194                        fprintf(stderr, "%s not allowed: %s:%d\n",
 195                                name, src, lineno);
 196                        return NULL;
 197                }
 198                is_macro = 1;
 199                name += strlen(ATTRIBUTE_MACRO_PREFIX);
 200                name += strspn(name, blank);
 201                namelen = strcspn(name, blank);
 202                if (invalid_attr_name(name, namelen)) {
 203                        fprintf(stderr,
 204                                "%.*s is not a valid attribute name: %s:%d\n",
 205                                namelen, name, src, lineno);
 206                        return NULL;
 207                }
 208        }
 209        else
 210                is_macro = 0;
 211
 212        for (pass = 0; pass < 2; pass++) {
 213                /* pass 0 counts and allocates, pass 1 fills */
 214                num_attr = 0;
 215                cp = name + namelen;
 216                cp = cp + strspn(cp, blank);
 217                while (*cp) {
 218                        cp = parse_attr(src, lineno, cp, &num_attr, res);
 219                        if (!cp)
 220                                return NULL;
 221                }
 222                if (pass)
 223                        break;
 224                res = xcalloc(1,
 225                              sizeof(*res) +
 226                              sizeof(struct attr_state) * num_attr +
 227                              (is_macro ? 0 : namelen + 1));
 228                if (is_macro)
 229                        res->u.attr = git_attr(name, namelen);
 230                else {
 231                        res->u.pattern = (char*)&(res->state[num_attr]);
 232                        memcpy(res->u.pattern, name, namelen);
 233                        res->u.pattern[namelen] = 0;
 234                }
 235                res->is_macro = is_macro;
 236                res->num_attr = num_attr;
 237        }
 238        return res;
 239}
 240
 241/*
 242 * Like info/exclude and .gitignore, the attribute information can
 243 * come from many places.
 244 *
 245 * (1) .gitattribute file of the same directory;
 246 * (2) .gitattribute file of the parent directory if (1) does not have
 247 *      any match; this goes recursively upwards, just like .gitignore.
 248 * (3) $GIT_DIR/info/attributes, which overrides both of the above.
 249 *
 250 * In the same file, later entries override the earlier match, so in the
 251 * global list, we would have entries from info/attributes the earliest
 252 * (reading the file from top to bottom), .gitattribute of the root
 253 * directory (again, reading the file from top to bottom) down to the
 254 * current directory, and then scan the list backwards to find the first match.
 255 * This is exactly the same as what excluded() does in dir.c to deal with
 256 * .gitignore
 257 */
 258
 259static struct attr_stack {
 260        struct attr_stack *prev;
 261        char *origin;
 262        unsigned num_matches;
 263        unsigned alloc;
 264        struct match_attr **attrs;
 265} *attr_stack;
 266
 267static void free_attr_elem(struct attr_stack *e)
 268{
 269        int i;
 270        free(e->origin);
 271        for (i = 0; i < e->num_matches; i++) {
 272                struct match_attr *a = e->attrs[i];
 273                int j;
 274                for (j = 0; j < a->num_attr; j++) {
 275                        const char *setto = a->state[j].setto;
 276                        if (setto == ATTR__TRUE ||
 277                            setto == ATTR__FALSE ||
 278                            setto == ATTR__UNSET ||
 279                            setto == ATTR__UNKNOWN)
 280                                ;
 281                        else
 282                                free((char*) setto);
 283                }
 284                free(a);
 285        }
 286        free(e);
 287}
 288
 289static const char *builtin_attr[] = {
 290        "[attr]binary -diff -crlf",
 291        NULL,
 292};
 293
 294static void handle_attr_line(struct attr_stack *res,
 295                             const char *line,
 296                             const char *src,
 297                             int lineno,
 298                             int macro_ok)
 299{
 300        struct match_attr *a;
 301
 302        a = parse_attr_line(line, src, lineno, macro_ok);
 303        if (!a)
 304                return;
 305        if (res->alloc <= res->num_matches) {
 306                res->alloc = alloc_nr(res->num_matches);
 307                res->attrs = xrealloc(res->attrs,
 308                                      sizeof(struct match_attr *) *
 309                                      res->alloc);
 310        }
 311        res->attrs[res->num_matches++] = a;
 312}
 313
 314static struct attr_stack *read_attr_from_array(const char **list)
 315{
 316        struct attr_stack *res;
 317        const char *line;
 318        int lineno = 0;
 319
 320        res = xcalloc(1, sizeof(*res));
 321        while ((line = *(list++)) != NULL)
 322                handle_attr_line(res, line, "[builtin]", ++lineno, 1);
 323        return res;
 324}
 325
 326static struct attr_stack *read_attr_from_file(const char *path, int macro_ok)
 327{
 328        FILE *fp = fopen(path, "r");
 329        struct attr_stack *res;
 330        char buf[2048];
 331        int lineno = 0;
 332
 333        if (!fp)
 334                return NULL;
 335        res = xcalloc(1, sizeof(*res));
 336        while (fgets(buf, sizeof(buf), fp))
 337                handle_attr_line(res, buf, path, ++lineno, macro_ok);
 338        fclose(fp);
 339        return res;
 340}
 341
 342static void *read_index_data(const char *path)
 343{
 344        int pos, len;
 345        unsigned long sz;
 346        enum object_type type;
 347        void *data;
 348
 349        len = strlen(path);
 350        pos = cache_name_pos(path, len);
 351        if (pos < 0) {
 352                /*
 353                 * We might be in the middle of a merge, in which
 354                 * case we would read stage #2 (ours).
 355                 */
 356                int i;
 357                for (i = -pos - 1;
 358                     (pos < 0 && i < active_nr &&
 359                      !strcmp(active_cache[i]->name, path));
 360                     i++)
 361                        if (ce_stage(active_cache[i]) == 2)
 362                                pos = i;
 363        }
 364        if (pos < 0)
 365                return NULL;
 366        data = read_sha1_file(active_cache[pos]->sha1, &type, &sz);
 367        if (!data || type != OBJ_BLOB) {
 368                free(data);
 369                return NULL;
 370        }
 371        return data;
 372}
 373
 374static struct attr_stack *read_attr(const char *path, int macro_ok)
 375{
 376        struct attr_stack *res;
 377        char *buf, *sp;
 378        int lineno = 0;
 379
 380        res = read_attr_from_file(path, macro_ok);
 381        if (res)
 382                return res;
 383
 384        res = xcalloc(1, sizeof(*res));
 385
 386        /*
 387         * There is no checked out .gitattributes file there, but
 388         * we might have it in the index.  We allow operation in a
 389         * sparsely checked out work tree, so read from it.
 390         */
 391        buf = read_index_data(path);
 392        if (!buf)
 393                return res;
 394
 395        for (sp = buf; *sp; ) {
 396                char *ep;
 397                int more;
 398                for (ep = sp; *ep && *ep != '\n'; ep++)
 399                        ;
 400                more = (*ep == '\n');
 401                *ep = '\0';
 402                handle_attr_line(res, sp, path, ++lineno, macro_ok);
 403                sp = ep + more;
 404        }
 405        free(buf);
 406        return res;
 407}
 408
 409#if DEBUG_ATTR
 410static void debug_info(const char *what, struct attr_stack *elem)
 411{
 412        fprintf(stderr, "%s: %s\n", what, elem->origin ? elem->origin : "()");
 413}
 414static void debug_set(const char *what, const char *match, struct git_attr *attr, void *v)
 415{
 416        const char *value = v;
 417
 418        if (ATTR_TRUE(value))
 419                value = "set";
 420        else if (ATTR_FALSE(value))
 421                value = "unset";
 422        else if (ATTR_UNSET(value))
 423                value = "unspecified";
 424
 425        fprintf(stderr, "%s: %s => %s (%s)\n",
 426                what, attr->name, (char *) value, match);
 427}
 428#define debug_push(a) debug_info("push", (a))
 429#define debug_pop(a) debug_info("pop", (a))
 430#else
 431#define debug_push(a) do { ; } while (0)
 432#define debug_pop(a) do { ; } while (0)
 433#define debug_set(a,b,c,d) do { ; } while (0)
 434#endif
 435
 436static void bootstrap_attr_stack(void)
 437{
 438        if (!attr_stack) {
 439                struct attr_stack *elem;
 440
 441                elem = read_attr_from_array(builtin_attr);
 442                elem->origin = NULL;
 443                elem->prev = attr_stack;
 444                attr_stack = elem;
 445
 446                elem = read_attr(GITATTRIBUTES_FILE, 1);
 447                elem->origin = strdup("");
 448                elem->prev = attr_stack;
 449                attr_stack = elem;
 450                debug_push(elem);
 451
 452                elem = read_attr_from_file(git_path(INFOATTRIBUTES_FILE), 1);
 453                if (!elem)
 454                        elem = xcalloc(1, sizeof(*elem));
 455                elem->origin = NULL;
 456                elem->prev = attr_stack;
 457                attr_stack = elem;
 458        }
 459}
 460
 461static void prepare_attr_stack(const char *path, int dirlen)
 462{
 463        struct attr_stack *elem, *info;
 464        int len;
 465        char pathbuf[PATH_MAX];
 466
 467        /*
 468         * At the bottom of the attribute stack is the built-in
 469         * set of attribute definitions.  Then, contents from
 470         * .gitattribute files from directories closer to the
 471         * root to the ones in deeper directories are pushed
 472         * to the stack.  Finally, at the very top of the stack
 473         * we always keep the contents of $GIT_DIR/info/attributes.
 474         *
 475         * When checking, we use entries from near the top of the
 476         * stack, preferring $GIT_DIR/info/attributes, then
 477         * .gitattributes in deeper directories to shallower ones,
 478         * and finally use the built-in set as the default.
 479         */
 480        if (!attr_stack)
 481                bootstrap_attr_stack();
 482
 483        /*
 484         * Pop the "info" one that is always at the top of the stack.
 485         */
 486        info = attr_stack;
 487        attr_stack = info->prev;
 488
 489        /*
 490         * Pop the ones from directories that are not the prefix of
 491         * the path we are checking.
 492         */
 493        while (attr_stack && attr_stack->origin) {
 494                int namelen = strlen(attr_stack->origin);
 495
 496                elem = attr_stack;
 497                if (namelen <= dirlen &&
 498                    !strncmp(elem->origin, path, namelen))
 499                        break;
 500
 501                debug_pop(elem);
 502                attr_stack = elem->prev;
 503                free_attr_elem(elem);
 504        }
 505
 506        /*
 507         * Read from parent directories and push them down
 508         */
 509        while (1) {
 510                char *cp;
 511
 512                len = strlen(attr_stack->origin);
 513                if (dirlen <= len)
 514                        break;
 515                memcpy(pathbuf, path, dirlen);
 516                memcpy(pathbuf + dirlen, "/", 2);
 517                cp = strchr(pathbuf + len + 1, '/');
 518                strcpy(cp + 1, GITATTRIBUTES_FILE);
 519                elem = read_attr(pathbuf, 0);
 520                *cp = '\0';
 521                elem->origin = strdup(pathbuf);
 522                elem->prev = attr_stack;
 523                attr_stack = elem;
 524                debug_push(elem);
 525        }
 526
 527        /*
 528         * Finally push the "info" one at the top of the stack.
 529         */
 530        info->prev = attr_stack;
 531        attr_stack = info;
 532}
 533
 534static int path_matches(const char *pathname, int pathlen,
 535                        const char *pattern,
 536                        const char *base, int baselen)
 537{
 538        if (!strchr(pattern, '/')) {
 539                /* match basename */
 540                const char *basename = strrchr(pathname, '/');
 541                basename = basename ? basename + 1 : pathname;
 542                return (fnmatch(pattern, basename, 0) == 0);
 543        }
 544        /*
 545         * match with FNM_PATHNAME; the pattern has base implicitly
 546         * in front of it.
 547         */
 548        if (*pattern == '/')
 549                pattern++;
 550        if (pathlen < baselen ||
 551            (baselen && pathname[baselen - 1] != '/') ||
 552            strncmp(pathname, base, baselen))
 553                return 0;
 554        return fnmatch(pattern, pathname + baselen, FNM_PATHNAME) == 0;
 555}
 556
 557static int fill_one(const char *what, struct match_attr *a, int rem)
 558{
 559        struct git_attr_check *check = check_all_attr;
 560        int i;
 561
 562        for (i = 0; 0 < rem && i < a->num_attr; i++) {
 563                struct git_attr *attr = a->state[i].attr;
 564                const char **n = &(check[attr->attr_nr].value);
 565                const char *v = a->state[i].setto;
 566
 567                if (*n == ATTR__UNKNOWN) {
 568                        debug_set(what, a->u.pattern, attr, v);
 569                        *n = v;
 570                        rem--;
 571                }
 572        }
 573        return rem;
 574}
 575
 576static int fill(const char *path, int pathlen, struct attr_stack *stk, int rem)
 577{
 578        int i;
 579        const char *base = stk->origin ? stk->origin : "";
 580
 581        for (i = stk->num_matches - 1; 0 < rem && 0 <= i; i--) {
 582                struct match_attr *a = stk->attrs[i];
 583                if (a->is_macro)
 584                        continue;
 585                if (path_matches(path, pathlen,
 586                                 a->u.pattern, base, strlen(base)))
 587                        rem = fill_one("fill", a, rem);
 588        }
 589        return rem;
 590}
 591
 592static int macroexpand(struct attr_stack *stk, int rem)
 593{
 594        int i;
 595        struct git_attr_check *check = check_all_attr;
 596
 597        for (i = stk->num_matches - 1; 0 < rem && 0 <= i; i--) {
 598                struct match_attr *a = stk->attrs[i];
 599                if (!a->is_macro)
 600                        continue;
 601                if (check[a->u.attr->attr_nr].value != ATTR__TRUE)
 602                        continue;
 603                rem = fill_one("expand", a, rem);
 604        }
 605        return rem;
 606}
 607
 608int git_checkattr(const char *path, int num, struct git_attr_check *check)
 609{
 610        struct attr_stack *stk;
 611        const char *cp;
 612        int dirlen, pathlen, i, rem;
 613
 614        bootstrap_attr_stack();
 615        for (i = 0; i < attr_nr; i++)
 616                check_all_attr[i].value = ATTR__UNKNOWN;
 617
 618        pathlen = strlen(path);
 619        cp = strrchr(path, '/');
 620        if (!cp)
 621                dirlen = 0;
 622        else
 623                dirlen = cp - path;
 624        prepare_attr_stack(path, dirlen);
 625        rem = attr_nr;
 626        for (stk = attr_stack; 0 < rem && stk; stk = stk->prev)
 627                rem = fill(path, pathlen, stk, rem);
 628
 629        for (stk = attr_stack; 0 < rem && stk; stk = stk->prev)
 630                rem = macroexpand(stk, rem);
 631
 632        for (i = 0; i < num; i++) {
 633                const char *value = check_all_attr[check[i].attr->attr_nr].value;
 634                if (value == ATTR__UNKNOWN)
 635                        value = ATTR__UNSET;
 636                check[i].value = value;
 637        }
 638
 639        return 0;
 640}