c61c02b190459bcfba60f085e103b0e99711b622
   1#include "cache.h"
   2#include "attr.h"
   3#include "run-command.h"
   4
   5/*
   6 * convert.c - convert a file when checking it out and checking it in.
   7 *
   8 * This should use the pathname to decide on whether it wants to do some
   9 * more interesting conversions (automatic gzip/unzip, general format
  10 * conversions etc etc), but by default it just does automatic CRLF<->LF
  11 * translation when the "crlf" attribute or "auto_crlf" option is set.
  12 */
  13
  14enum action {
  15        CRLF_GUESS = -1,
  16        CRLF_BINARY = 0,
  17        CRLF_TEXT,
  18        CRLF_INPUT,
  19        CRLF_CRLF,
  20        CRLF_AUTO,
  21};
  22
  23enum eol {
  24        EOL_UNSET,
  25        EOL_LF,
  26        EOL_CRLF,
  27};
  28
  29struct text_stat {
  30        /* NUL, CR, LF and CRLF counts */
  31        unsigned nul, cr, lf, crlf;
  32
  33        /* These are just approximations! */
  34        unsigned printable, nonprintable;
  35};
  36
  37static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
  38{
  39        unsigned long i;
  40
  41        memset(stats, 0, sizeof(*stats));
  42
  43        for (i = 0; i < size; i++) {
  44                unsigned char c = buf[i];
  45                if (c == '\r') {
  46                        stats->cr++;
  47                        if (i+1 < size && buf[i+1] == '\n')
  48                                stats->crlf++;
  49                        continue;
  50                }
  51                if (c == '\n') {
  52                        stats->lf++;
  53                        continue;
  54                }
  55                if (c == 127)
  56                        /* DEL */
  57                        stats->nonprintable++;
  58                else if (c < 32) {
  59                        switch (c) {
  60                                /* BS, HT, ESC and FF */
  61                        case '\b': case '\t': case '\033': case '\014':
  62                                stats->printable++;
  63                                break;
  64                        case 0:
  65                                stats->nul++;
  66                                /* fall through */
  67                        default:
  68                                stats->nonprintable++;
  69                        }
  70                }
  71                else
  72                        stats->printable++;
  73        }
  74
  75        /* If file ends with EOF then don't count this EOF as non-printable. */
  76        if (size >= 1 && buf[size-1] == '\032')
  77                stats->nonprintable--;
  78}
  79
  80/*
  81 * The same heuristics as diff.c::mmfile_is_binary()
  82 */
  83static int is_binary(unsigned long size, struct text_stat *stats)
  84{
  85
  86        if (stats->nul)
  87                return 1;
  88        if ((stats->printable >> 7) < stats->nonprintable)
  89                return 1;
  90        /*
  91         * Other heuristics? Average line length might be relevant,
  92         * as might LF vs CR vs CRLF counts..
  93         *
  94         * NOTE! It might be normal to have a low ratio of CRLF to LF
  95         * (somebody starts with a LF-only file and edits it with an editor
  96         * that adds CRLF only to lines that are added..). But do  we
  97         * want to support CR-only? Probably not.
  98         */
  99        return 0;
 100}
 101
 102static void check_safe_crlf(const char *path, enum action action,
 103                            struct text_stat *stats, enum safe_crlf checksafe)
 104{
 105        if (!checksafe)
 106                return;
 107
 108        if (action == CRLF_INPUT ||
 109            (action == CRLF_GUESS && auto_crlf == AUTO_CRLF_INPUT)) {
 110                /*
 111                 * CRLFs would not be restored by checkout:
 112                 * check if we'd remove CRLFs
 113                 */
 114                if (stats->crlf) {
 115                        if (checksafe == SAFE_CRLF_WARN)
 116                                warning("CRLF will be replaced by LF in %s.", path);
 117                        else /* i.e. SAFE_CRLF_FAIL */
 118                                die("CRLF would be replaced by LF in %s.", path);
 119                }
 120        } else if (action == CRLF_CRLF ||
 121                   (action == CRLF_GUESS && auto_crlf == AUTO_CRLF_TRUE)) {
 122                /*
 123                 * CRLFs would be added by checkout:
 124                 * check if we have "naked" LFs
 125                 */
 126                if (stats->lf != stats->crlf) {
 127                        if (checksafe == SAFE_CRLF_WARN)
 128                                warning("LF will be replaced by CRLF in %s", path);
 129                        else /* i.e. SAFE_CRLF_FAIL */
 130                                die("LF would be replaced by CRLF in %s", path);
 131                }
 132        }
 133}
 134
 135static int has_cr_in_index(const char *path)
 136{
 137        int pos, len;
 138        unsigned long sz;
 139        enum object_type type;
 140        void *data;
 141        int has_cr;
 142        struct index_state *istate = &the_index;
 143
 144        len = strlen(path);
 145        pos = index_name_pos(istate, path, len);
 146        if (pos < 0) {
 147                /*
 148                 * We might be in the middle of a merge, in which
 149                 * case we would read stage #2 (ours).
 150                 */
 151                int i;
 152                for (i = -pos - 1;
 153                     (pos < 0 && i < istate->cache_nr &&
 154                      !strcmp(istate->cache[i]->name, path));
 155                     i++)
 156                        if (ce_stage(istate->cache[i]) == 2)
 157                                pos = i;
 158        }
 159        if (pos < 0)
 160                return 0;
 161        data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
 162        if (!data || type != OBJ_BLOB) {
 163                free(data);
 164                return 0;
 165        }
 166
 167        has_cr = memchr(data, '\r', sz) != NULL;
 168        free(data);
 169        return has_cr;
 170}
 171
 172static int crlf_to_git(const char *path, const char *src, size_t len,
 173                       struct strbuf *buf, enum action action, enum safe_crlf checksafe)
 174{
 175        struct text_stat stats;
 176        char *dst;
 177
 178        if (action == CRLF_BINARY ||
 179            (action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) || !len)
 180                return 0;
 181
 182        gather_stats(src, len, &stats);
 183
 184        if (action == CRLF_AUTO || action == CRLF_GUESS) {
 185                /*
 186                 * We're currently not going to even try to convert stuff
 187                 * that has bare CR characters. Does anybody do that crazy
 188                 * stuff?
 189                 */
 190                if (stats.cr != stats.crlf)
 191                        return 0;
 192
 193                /*
 194                 * And add some heuristics for binary vs text, of course...
 195                 */
 196                if (is_binary(len, &stats))
 197                        return 0;
 198
 199                if (action == CRLF_GUESS) {
 200                        /*
 201                         * If the file in the index has any CR in it, do not convert.
 202                         * This is the new safer autocrlf handling.
 203                         */
 204                        if (has_cr_in_index(path))
 205                                return 0;
 206                }
 207        }
 208
 209        check_safe_crlf(path, action, &stats, checksafe);
 210
 211        /* Optimization: No CR? Nothing to convert, regardless. */
 212        if (!stats.cr)
 213                return 0;
 214
 215        /* only grow if not in place */
 216        if (strbuf_avail(buf) + buf->len < len)
 217                strbuf_grow(buf, len - buf->len);
 218        dst = buf->buf;
 219        if (action == CRLF_AUTO || action == CRLF_GUESS) {
 220                /*
 221                 * If we guessed, we already know we rejected a file with
 222                 * lone CR, and we can strip a CR without looking at what
 223                 * follow it.
 224                 */
 225                do {
 226                        unsigned char c = *src++;
 227                        if (c != '\r')
 228                                *dst++ = c;
 229                } while (--len);
 230        } else {
 231                do {
 232                        unsigned char c = *src++;
 233                        if (! (c == '\r' && (1 < len && *src == '\n')))
 234                                *dst++ = c;
 235                } while (--len);
 236        }
 237        strbuf_setlen(buf, dst - buf->buf);
 238        return 1;
 239}
 240
 241static int crlf_to_worktree(const char *path, const char *src, size_t len,
 242                            struct strbuf *buf, enum action action)
 243{
 244        char *to_free = NULL;
 245        struct text_stat stats;
 246
 247        if ((action == CRLF_BINARY) || (action == CRLF_INPUT) ||
 248            (action != CRLF_CRLF && auto_crlf != AUTO_CRLF_TRUE))
 249                return 0;
 250
 251        if (!len)
 252                return 0;
 253
 254        gather_stats(src, len, &stats);
 255
 256        /* No LF? Nothing to convert, regardless. */
 257        if (!stats.lf)
 258                return 0;
 259
 260        /* Was it already in CRLF format? */
 261        if (stats.lf == stats.crlf)
 262                return 0;
 263
 264        if (action == CRLF_AUTO || action == CRLF_GUESS) {
 265                if (action == CRLF_GUESS) {
 266                        /* If we have any CR or CRLF line endings, we do not touch it */
 267                        /* This is the new safer autocrlf-handling */
 268                        if (stats.cr > 0 || stats.crlf > 0)
 269                                return 0;
 270                }
 271
 272                /* If we have any bare CR characters, we're not going to touch it */
 273                if (stats.cr != stats.crlf)
 274                        return 0;
 275
 276                if (is_binary(len, &stats))
 277                        return 0;
 278        }
 279
 280        /* are we "faking" in place editing ? */
 281        if (src == buf->buf)
 282                to_free = strbuf_detach(buf, NULL);
 283
 284        strbuf_grow(buf, len + stats.lf - stats.crlf);
 285        for (;;) {
 286                const char *nl = memchr(src, '\n', len);
 287                if (!nl)
 288                        break;
 289                if (nl > src && nl[-1] == '\r') {
 290                        strbuf_add(buf, src, nl + 1 - src);
 291                } else {
 292                        strbuf_add(buf, src, nl - src);
 293                        strbuf_addstr(buf, "\r\n");
 294                }
 295                len -= nl + 1 - src;
 296                src  = nl + 1;
 297        }
 298        strbuf_add(buf, src, len);
 299
 300        free(to_free);
 301        return 1;
 302}
 303
 304struct filter_params {
 305        const char *src;
 306        unsigned long size;
 307        const char *cmd;
 308};
 309
 310static int filter_buffer(int fd, void *data)
 311{
 312        /*
 313         * Spawn cmd and feed the buffer contents through its stdin.
 314         */
 315        struct child_process child_process;
 316        struct filter_params *params = (struct filter_params *)data;
 317        int write_err, status;
 318        const char *argv[] = { params->cmd, NULL };
 319
 320        memset(&child_process, 0, sizeof(child_process));
 321        child_process.argv = argv;
 322        child_process.use_shell = 1;
 323        child_process.in = -1;
 324        child_process.out = fd;
 325
 326        if (start_command(&child_process))
 327                return error("cannot fork to run external filter %s", params->cmd);
 328
 329        write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
 330        if (close(child_process.in))
 331                write_err = 1;
 332        if (write_err)
 333                error("cannot feed the input to external filter %s", params->cmd);
 334
 335        status = finish_command(&child_process);
 336        if (status)
 337                error("external filter %s failed %d", params->cmd, status);
 338        return (write_err || status);
 339}
 340
 341static int apply_filter(const char *path, const char *src, size_t len,
 342                        struct strbuf *dst, const char *cmd)
 343{
 344        /*
 345         * Create a pipeline to have the command filter the buffer's
 346         * contents.
 347         *
 348         * (child --> cmd) --> us
 349         */
 350        int ret = 1;
 351        struct strbuf nbuf = STRBUF_INIT;
 352        struct async async;
 353        struct filter_params params;
 354
 355        if (!cmd)
 356                return 0;
 357
 358        memset(&async, 0, sizeof(async));
 359        async.proc = filter_buffer;
 360        async.data = &params;
 361        params.src = src;
 362        params.size = len;
 363        params.cmd = cmd;
 364
 365        fflush(NULL);
 366        if (start_async(&async))
 367                return 0;       /* error was already reported */
 368
 369        if (strbuf_read(&nbuf, async.out, len) < 0) {
 370                error("read from external filter %s failed", cmd);
 371                ret = 0;
 372        }
 373        if (close(async.out)) {
 374                error("read from external filter %s failed", cmd);
 375                ret = 0;
 376        }
 377        if (finish_async(&async)) {
 378                error("external filter %s failed", cmd);
 379                ret = 0;
 380        }
 381
 382        if (ret) {
 383                strbuf_swap(dst, &nbuf);
 384        }
 385        strbuf_release(&nbuf);
 386        return ret;
 387}
 388
 389static struct convert_driver {
 390        const char *name;
 391        struct convert_driver *next;
 392        const char *smudge;
 393        const char *clean;
 394} *user_convert, **user_convert_tail;
 395
 396static int read_convert_config(const char *var, const char *value, void *cb)
 397{
 398        const char *ep, *name;
 399        int namelen;
 400        struct convert_driver *drv;
 401
 402        /*
 403         * External conversion drivers are configured using
 404         * "filter.<name>.variable".
 405         */
 406        if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
 407                return 0;
 408        name = var + 7;
 409        namelen = ep - name;
 410        for (drv = user_convert; drv; drv = drv->next)
 411                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
 412                        break;
 413        if (!drv) {
 414                drv = xcalloc(1, sizeof(struct convert_driver));
 415                drv->name = xmemdupz(name, namelen);
 416                *user_convert_tail = drv;
 417                user_convert_tail = &(drv->next);
 418        }
 419
 420        ep++;
 421
 422        /*
 423         * filter.<name>.smudge and filter.<name>.clean specifies
 424         * the command line:
 425         *
 426         *      command-line
 427         *
 428         * The command-line will not be interpolated in any way.
 429         */
 430
 431        if (!strcmp("smudge", ep))
 432                return git_config_string(&drv->smudge, var, value);
 433
 434        if (!strcmp("clean", ep))
 435                return git_config_string(&drv->clean, var, value);
 436
 437        return 0;
 438}
 439
 440static void setup_convert_check(struct git_attr_check *check)
 441{
 442        static struct git_attr *attr_text;
 443        static struct git_attr *attr_crlf;
 444        static struct git_attr *attr_eol;
 445        static struct git_attr *attr_ident;
 446        static struct git_attr *attr_filter;
 447
 448        if (!attr_text) {
 449                attr_text = git_attr("text");
 450                attr_crlf = git_attr("crlf");
 451                attr_eol = git_attr("eol");
 452                attr_ident = git_attr("ident");
 453                attr_filter = git_attr("filter");
 454                user_convert_tail = &user_convert;
 455                git_config(read_convert_config, NULL);
 456        }
 457        check[0].attr = attr_crlf;
 458        check[1].attr = attr_ident;
 459        check[2].attr = attr_filter;
 460        check[3].attr = attr_eol;
 461        check[4].attr = attr_text;
 462}
 463
 464static int count_ident(const char *cp, unsigned long size)
 465{
 466        /*
 467         * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
 468         */
 469        int cnt = 0;
 470        char ch;
 471
 472        while (size) {
 473                ch = *cp++;
 474                size--;
 475                if (ch != '$')
 476                        continue;
 477                if (size < 3)
 478                        break;
 479                if (memcmp("Id", cp, 2))
 480                        continue;
 481                ch = cp[2];
 482                cp += 3;
 483                size -= 3;
 484                if (ch == '$')
 485                        cnt++; /* $Id$ */
 486                if (ch != ':')
 487                        continue;
 488
 489                /*
 490                 * "$Id: ... "; scan up to the closing dollar sign and discard.
 491                 */
 492                while (size) {
 493                        ch = *cp++;
 494                        size--;
 495                        if (ch == '$') {
 496                                cnt++;
 497                                break;
 498                        }
 499                }
 500        }
 501        return cnt;
 502}
 503
 504static int ident_to_git(const char *path, const char *src, size_t len,
 505                        struct strbuf *buf, int ident)
 506{
 507        char *dst, *dollar;
 508
 509        if (!ident || !count_ident(src, len))
 510                return 0;
 511
 512        /* only grow if not in place */
 513        if (strbuf_avail(buf) + buf->len < len)
 514                strbuf_grow(buf, len - buf->len);
 515        dst = buf->buf;
 516        for (;;) {
 517                dollar = memchr(src, '$', len);
 518                if (!dollar)
 519                        break;
 520                memcpy(dst, src, dollar + 1 - src);
 521                dst += dollar + 1 - src;
 522                len -= dollar + 1 - src;
 523                src  = dollar + 1;
 524
 525                if (len > 3 && !memcmp(src, "Id:", 3)) {
 526                        dollar = memchr(src + 3, '$', len - 3);
 527                        if (!dollar)
 528                                break;
 529                        memcpy(dst, "Id$", 3);
 530                        dst += 3;
 531                        len -= dollar + 1 - src;
 532                        src  = dollar + 1;
 533                }
 534        }
 535        memcpy(dst, src, len);
 536        strbuf_setlen(buf, dst + len - buf->buf);
 537        return 1;
 538}
 539
 540static int ident_to_worktree(const char *path, const char *src, size_t len,
 541                             struct strbuf *buf, int ident)
 542{
 543        unsigned char sha1[20];
 544        char *to_free = NULL, *dollar;
 545        int cnt;
 546
 547        if (!ident)
 548                return 0;
 549
 550        cnt = count_ident(src, len);
 551        if (!cnt)
 552                return 0;
 553
 554        /* are we "faking" in place editing ? */
 555        if (src == buf->buf)
 556                to_free = strbuf_detach(buf, NULL);
 557        hash_sha1_file(src, len, "blob", sha1);
 558
 559        strbuf_grow(buf, len + cnt * 43);
 560        for (;;) {
 561                /* step 1: run to the next '$' */
 562                dollar = memchr(src, '$', len);
 563                if (!dollar)
 564                        break;
 565                strbuf_add(buf, src, dollar + 1 - src);
 566                len -= dollar + 1 - src;
 567                src  = dollar + 1;
 568
 569                /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
 570                if (len < 3 || memcmp("Id", src, 2))
 571                        continue;
 572
 573                /* step 3: skip over Id$ or Id:xxxxx$ */
 574                if (src[2] == '$') {
 575                        src += 3;
 576                        len -= 3;
 577                } else if (src[2] == ':') {
 578                        /*
 579                         * It's possible that an expanded Id has crept its way into the
 580                         * repository, we cope with that by stripping the expansion out
 581                         */
 582                        dollar = memchr(src + 3, '$', len - 3);
 583                        if (!dollar) {
 584                                /* incomplete keyword, no more '$', so just quit the loop */
 585                                break;
 586                        }
 587
 588                        len -= dollar + 1 - src;
 589                        src  = dollar + 1;
 590                } else {
 591                        /* it wasn't a "Id$" or "Id:xxxx$" */
 592                        continue;
 593                }
 594
 595                /* step 4: substitute */
 596                strbuf_addstr(buf, "Id: ");
 597                strbuf_add(buf, sha1_to_hex(sha1), 40);
 598                strbuf_addstr(buf, " $");
 599        }
 600        strbuf_add(buf, src, len);
 601
 602        free(to_free);
 603        return 1;
 604}
 605
 606static int git_path_check_crlf(const char *path, struct git_attr_check *check)
 607{
 608        const char *value = check->value;
 609
 610        if (ATTR_TRUE(value))
 611                return CRLF_TEXT;
 612        else if (ATTR_FALSE(value))
 613                return CRLF_BINARY;
 614        else if (ATTR_UNSET(value))
 615                ;
 616        else if (!strcmp(value, "input"))
 617                return CRLF_INPUT;
 618        else if (!strcmp(value, "auto"))
 619                return CRLF_AUTO;
 620        return CRLF_GUESS;
 621}
 622
 623static int git_path_check_eol(const char *path, struct git_attr_check *check)
 624{
 625        const char *value = check->value;
 626
 627        if (ATTR_UNSET(value))
 628                ;
 629        else if (!strcmp(value, "lf"))
 630                return EOL_LF;
 631        else if (!strcmp(value, "crlf"))
 632                return EOL_CRLF;
 633        return EOL_UNSET;
 634}
 635
 636static struct convert_driver *git_path_check_convert(const char *path,
 637                                             struct git_attr_check *check)
 638{
 639        const char *value = check->value;
 640        struct convert_driver *drv;
 641
 642        if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
 643                return NULL;
 644        for (drv = user_convert; drv; drv = drv->next)
 645                if (!strcmp(value, drv->name))
 646                        return drv;
 647        return NULL;
 648}
 649
 650static int git_path_check_ident(const char *path, struct git_attr_check *check)
 651{
 652        const char *value = check->value;
 653
 654        return !!ATTR_TRUE(value);
 655}
 656
 657enum action determine_action(enum action text_attr, enum eol eol_attr) {
 658        if (text_attr == CRLF_BINARY)
 659                return CRLF_BINARY;
 660        if (eol_attr == EOL_LF)
 661                return CRLF_INPUT;
 662        if (eol_attr == EOL_CRLF)
 663                return CRLF_CRLF;
 664        return text_attr;
 665}
 666
 667int convert_to_git(const char *path, const char *src, size_t len,
 668                   struct strbuf *dst, enum safe_crlf checksafe)
 669{
 670        struct git_attr_check check[5];
 671        enum action action = CRLF_GUESS;
 672        enum eol eol = EOL_UNSET;
 673        int ident = 0, ret = 0;
 674        const char *filter = NULL;
 675
 676        setup_convert_check(check);
 677        if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
 678                struct convert_driver *drv;
 679                action = git_path_check_crlf(path, check + 4);
 680                if (action == CRLF_GUESS)
 681                        action = git_path_check_crlf(path, check + 0);
 682                ident = git_path_check_ident(path, check + 1);
 683                drv = git_path_check_convert(path, check + 2);
 684                eol = git_path_check_eol(path, check + 3);
 685                if (drv && drv->clean)
 686                        filter = drv->clean;
 687        }
 688
 689        ret |= apply_filter(path, src, len, dst, filter);
 690        if (ret) {
 691                src = dst->buf;
 692                len = dst->len;
 693        }
 694        action = determine_action(action, eol);
 695        ret |= crlf_to_git(path, src, len, dst, action, checksafe);
 696        if (ret) {
 697                src = dst->buf;
 698                len = dst->len;
 699        }
 700        return ret | ident_to_git(path, src, len, dst, ident);
 701}
 702
 703int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
 704{
 705        struct git_attr_check check[5];
 706        enum action action = CRLF_GUESS;
 707        enum eol eol = EOL_UNSET;
 708        int ident = 0, ret = 0;
 709        const char *filter = NULL;
 710
 711        setup_convert_check(check);
 712        if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
 713                struct convert_driver *drv;
 714                action = git_path_check_crlf(path, check + 4);
 715                if (action == CRLF_GUESS)
 716                        action = git_path_check_crlf(path, check + 0);
 717                ident = git_path_check_ident(path, check + 1);
 718                drv = git_path_check_convert(path, check + 2);
 719                eol = git_path_check_eol(path, check + 3);
 720                if (drv && drv->smudge)
 721                        filter = drv->smudge;
 722        }
 723
 724        ret |= ident_to_worktree(path, src, len, dst, ident);
 725        if (ret) {
 726                src = dst->buf;
 727                len = dst->len;
 728        }
 729        action = determine_action(action, eol);
 730        ret |= crlf_to_worktree(path, src, len, dst, action);
 731        if (ret) {
 732                src = dst->buf;
 733                len = dst->len;
 734        }
 735        return ret | apply_filter(path, src, len, dst, filter);
 736}