65fa9d5eda94749559cd183437a5a108c6a174db
   1#include "cache.h"
   2#include "attr.h"
   3#include "run-command.h"
   4#include "quote.h"
   5
   6/*
   7 * convert.c - convert a file when checking it out and checking it in.
   8 *
   9 * This should use the pathname to decide on whether it wants to do some
  10 * more interesting conversions (automatic gzip/unzip, general format
  11 * conversions etc etc), but by default it just does automatic CRLF<->LF
  12 * translation when the "text" attribute or "auto_crlf" option is set.
  13 */
  14
  15enum crlf_action {
  16        CRLF_GUESS = -1,
  17        CRLF_BINARY = 0,
  18        CRLF_TEXT,
  19        CRLF_INPUT,
  20        CRLF_CRLF,
  21        CRLF_AUTO
  22};
  23
  24struct text_stat {
  25        /* NUL, CR, LF and CRLF counts */
  26        unsigned nul, cr, lf, crlf;
  27
  28        /* These are just approximations! */
  29        unsigned printable, nonprintable;
  30};
  31
  32static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
  33{
  34        unsigned long i;
  35
  36        memset(stats, 0, sizeof(*stats));
  37
  38        for (i = 0; i < size; i++) {
  39                unsigned char c = buf[i];
  40                if (c == '\r') {
  41                        stats->cr++;
  42                        if (i+1 < size && buf[i+1] == '\n')
  43                                stats->crlf++;
  44                        continue;
  45                }
  46                if (c == '\n') {
  47                        stats->lf++;
  48                        continue;
  49                }
  50                if (c == 127)
  51                        /* DEL */
  52                        stats->nonprintable++;
  53                else if (c < 32) {
  54                        switch (c) {
  55                                /* BS, HT, ESC and FF */
  56                        case '\b': case '\t': case '\033': case '\014':
  57                                stats->printable++;
  58                                break;
  59                        case 0:
  60                                stats->nul++;
  61                                /* fall through */
  62                        default:
  63                                stats->nonprintable++;
  64                        }
  65                }
  66                else
  67                        stats->printable++;
  68        }
  69
  70        /* If file ends with EOF then don't count this EOF as non-printable. */
  71        if (size >= 1 && buf[size-1] == '\032')
  72                stats->nonprintable--;
  73}
  74
  75/*
  76 * The same heuristics as diff.c::mmfile_is_binary()
  77 */
  78static int is_binary(unsigned long size, struct text_stat *stats)
  79{
  80
  81        if (stats->nul)
  82                return 1;
  83        if ((stats->printable >> 7) < stats->nonprintable)
  84                return 1;
  85        /*
  86         * Other heuristics? Average line length might be relevant,
  87         * as might LF vs CR vs CRLF counts..
  88         *
  89         * NOTE! It might be normal to have a low ratio of CRLF to LF
  90         * (somebody starts with a LF-only file and edits it with an editor
  91         * that adds CRLF only to lines that are added..). But do  we
  92         * want to support CR-only? Probably not.
  93         */
  94        return 0;
  95}
  96
  97static enum eol output_eol(enum crlf_action crlf_action)
  98{
  99        switch (crlf_action) {
 100        case CRLF_BINARY:
 101                return EOL_UNSET;
 102        case CRLF_CRLF:
 103                return EOL_CRLF;
 104        case CRLF_INPUT:
 105                return EOL_LF;
 106        case CRLF_GUESS:
 107                if (!auto_crlf)
 108                        return EOL_UNSET;
 109                /* fall through */
 110        case CRLF_TEXT:
 111        case CRLF_AUTO:
 112                if (auto_crlf == AUTO_CRLF_TRUE)
 113                        return EOL_CRLF;
 114                else if (auto_crlf == AUTO_CRLF_INPUT)
 115                        return EOL_LF;
 116                else if (core_eol == EOL_UNSET)
 117                        return EOL_NATIVE;
 118        }
 119        return core_eol;
 120}
 121
 122static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
 123                            struct text_stat *stats, enum safe_crlf checksafe)
 124{
 125        if (!checksafe)
 126                return;
 127
 128        if (output_eol(crlf_action) == EOL_LF) {
 129                /*
 130                 * CRLFs would not be restored by checkout:
 131                 * check if we'd remove CRLFs
 132                 */
 133                if (stats->crlf) {
 134                        if (checksafe == SAFE_CRLF_WARN)
 135                                warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
 136                        else /* i.e. SAFE_CRLF_FAIL */
 137                                die("CRLF would be replaced by LF in %s.", path);
 138                }
 139        } else if (output_eol(crlf_action) == EOL_CRLF) {
 140                /*
 141                 * CRLFs would be added by checkout:
 142                 * check if we have "naked" LFs
 143                 */
 144                if (stats->lf != stats->crlf) {
 145                        if (checksafe == SAFE_CRLF_WARN)
 146                                warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
 147                        else /* i.e. SAFE_CRLF_FAIL */
 148                                die("LF would be replaced by CRLF in %s", path);
 149                }
 150        }
 151}
 152
 153static int has_cr_in_index(const char *path)
 154{
 155        int pos, len;
 156        unsigned long sz;
 157        enum object_type type;
 158        void *data;
 159        int has_cr;
 160        struct index_state *istate = &the_index;
 161
 162        len = strlen(path);
 163        pos = index_name_pos(istate, path, len);
 164        if (pos < 0) {
 165                /*
 166                 * We might be in the middle of a merge, in which
 167                 * case we would read stage #2 (ours).
 168                 */
 169                int i;
 170                for (i = -pos - 1;
 171                     (pos < 0 && i < istate->cache_nr &&
 172                      !strcmp(istate->cache[i]->name, path));
 173                     i++)
 174                        if (ce_stage(istate->cache[i]) == 2)
 175                                pos = i;
 176        }
 177        if (pos < 0)
 178                return 0;
 179        data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
 180        if (!data || type != OBJ_BLOB) {
 181                free(data);
 182                return 0;
 183        }
 184
 185        has_cr = memchr(data, '\r', sz) != NULL;
 186        free(data);
 187        return has_cr;
 188}
 189
 190static int crlf_to_git(const char *path, const char *src, size_t len,
 191                       struct strbuf *buf,
 192                       enum crlf_action crlf_action, enum safe_crlf checksafe)
 193{
 194        struct text_stat stats;
 195        char *dst;
 196
 197        if (crlf_action == CRLF_BINARY ||
 198            (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) || !len)
 199                return 0;
 200
 201        gather_stats(src, len, &stats);
 202
 203        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
 204                /*
 205                 * We're currently not going to even try to convert stuff
 206                 * that has bare CR characters. Does anybody do that crazy
 207                 * stuff?
 208                 */
 209                if (stats.cr != stats.crlf)
 210                        return 0;
 211
 212                /*
 213                 * And add some heuristics for binary vs text, of course...
 214                 */
 215                if (is_binary(len, &stats))
 216                        return 0;
 217
 218                if (crlf_action == CRLF_GUESS) {
 219                        /*
 220                         * If the file in the index has any CR in it, do not convert.
 221                         * This is the new safer autocrlf handling.
 222                         */
 223                        if (has_cr_in_index(path))
 224                                return 0;
 225                }
 226        }
 227
 228        check_safe_crlf(path, crlf_action, &stats, checksafe);
 229
 230        /* Optimization: No CR? Nothing to convert, regardless. */
 231        if (!stats.cr)
 232                return 0;
 233
 234        /*
 235         * At this point all of our source analysis is done, and we are sure we
 236         * would convert. If we are in dry-run mode, we can give an answer.
 237         */
 238        if (!buf)
 239                return 1;
 240
 241        /* only grow if not in place */
 242        if (strbuf_avail(buf) + buf->len < len)
 243                strbuf_grow(buf, len - buf->len);
 244        dst = buf->buf;
 245        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
 246                /*
 247                 * If we guessed, we already know we rejected a file with
 248                 * lone CR, and we can strip a CR without looking at what
 249                 * follow it.
 250                 */
 251                do {
 252                        unsigned char c = *src++;
 253                        if (c != '\r')
 254                                *dst++ = c;
 255                } while (--len);
 256        } else {
 257                do {
 258                        unsigned char c = *src++;
 259                        if (! (c == '\r' && (1 < len && *src == '\n')))
 260                                *dst++ = c;
 261                } while (--len);
 262        }
 263        strbuf_setlen(buf, dst - buf->buf);
 264        return 1;
 265}
 266
 267static int crlf_to_worktree(const char *path, const char *src, size_t len,
 268                            struct strbuf *buf, enum crlf_action crlf_action)
 269{
 270        char *to_free = NULL;
 271        struct text_stat stats;
 272
 273        if (!len || output_eol(crlf_action) != EOL_CRLF)
 274                return 0;
 275
 276        gather_stats(src, len, &stats);
 277
 278        /* No LF? Nothing to convert, regardless. */
 279        if (!stats.lf)
 280                return 0;
 281
 282        /* Was it already in CRLF format? */
 283        if (stats.lf == stats.crlf)
 284                return 0;
 285
 286        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS) {
 287                if (crlf_action == CRLF_GUESS) {
 288                        /* If we have any CR or CRLF line endings, we do not touch it */
 289                        /* This is the new safer autocrlf-handling */
 290                        if (stats.cr > 0 || stats.crlf > 0)
 291                                return 0;
 292                }
 293
 294                /* If we have any bare CR characters, we're not going to touch it */
 295                if (stats.cr != stats.crlf)
 296                        return 0;
 297
 298                if (is_binary(len, &stats))
 299                        return 0;
 300        }
 301
 302        /* are we "faking" in place editing ? */
 303        if (src == buf->buf)
 304                to_free = strbuf_detach(buf, NULL);
 305
 306        strbuf_grow(buf, len + stats.lf - stats.crlf);
 307        for (;;) {
 308                const char *nl = memchr(src, '\n', len);
 309                if (!nl)
 310                        break;
 311                if (nl > src && nl[-1] == '\r') {
 312                        strbuf_add(buf, src, nl + 1 - src);
 313                } else {
 314                        strbuf_add(buf, src, nl - src);
 315                        strbuf_addstr(buf, "\r\n");
 316                }
 317                len -= nl + 1 - src;
 318                src  = nl + 1;
 319        }
 320        strbuf_add(buf, src, len);
 321
 322        free(to_free);
 323        return 1;
 324}
 325
 326struct filter_params {
 327        const char *src;
 328        unsigned long size;
 329        const char *cmd;
 330        const char *path;
 331};
 332
 333static int filter_buffer(int in, int out, void *data)
 334{
 335        /*
 336         * Spawn cmd and feed the buffer contents through its stdin.
 337         */
 338        struct child_process child_process;
 339        struct filter_params *params = (struct filter_params *)data;
 340        int write_err, status;
 341        const char *argv[] = { NULL, NULL };
 342
 343        /* apply % substitution to cmd */
 344        struct strbuf cmd = STRBUF_INIT;
 345        struct strbuf path = STRBUF_INIT;
 346        struct strbuf_expand_dict_entry dict[] = {
 347                { "f", NULL, },
 348                { NULL, NULL, },
 349        };
 350
 351        /* quote the path to preserve spaces, etc. */
 352        sq_quote_buf(&path, params->path);
 353        dict[0].value = path.buf;
 354
 355        /* expand all %f with the quoted path */
 356        strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
 357        strbuf_release(&path);
 358
 359        argv[0] = cmd.buf;
 360
 361        memset(&child_process, 0, sizeof(child_process));
 362        child_process.argv = argv;
 363        child_process.use_shell = 1;
 364        child_process.in = -1;
 365        child_process.out = out;
 366
 367        if (start_command(&child_process))
 368                return error("cannot fork to run external filter %s", params->cmd);
 369
 370        write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
 371        if (close(child_process.in))
 372                write_err = 1;
 373        if (write_err)
 374                error("cannot feed the input to external filter %s", params->cmd);
 375
 376        status = finish_command(&child_process);
 377        if (status)
 378                error("external filter %s failed %d", params->cmd, status);
 379
 380        strbuf_release(&cmd);
 381        return (write_err || status);
 382}
 383
 384static int apply_filter(const char *path, const char *src, size_t len,
 385                        struct strbuf *dst, const char *cmd)
 386{
 387        /*
 388         * Create a pipeline to have the command filter the buffer's
 389         * contents.
 390         *
 391         * (child --> cmd) --> us
 392         */
 393        int ret = 1;
 394        struct strbuf nbuf = STRBUF_INIT;
 395        struct async async;
 396        struct filter_params params;
 397
 398        if (!cmd)
 399                return 0;
 400
 401        if (!dst)
 402                return 1;
 403
 404        memset(&async, 0, sizeof(async));
 405        async.proc = filter_buffer;
 406        async.data = &params;
 407        async.out = -1;
 408        params.src = src;
 409        params.size = len;
 410        params.cmd = cmd;
 411        params.path = path;
 412
 413        fflush(NULL);
 414        if (start_async(&async))
 415                return 0;       /* error was already reported */
 416
 417        if (strbuf_read(&nbuf, async.out, len) < 0) {
 418                error("read from external filter %s failed", cmd);
 419                ret = 0;
 420        }
 421        if (close(async.out)) {
 422                error("read from external filter %s failed", cmd);
 423                ret = 0;
 424        }
 425        if (finish_async(&async)) {
 426                error("external filter %s failed", cmd);
 427                ret = 0;
 428        }
 429
 430        if (ret) {
 431                strbuf_swap(dst, &nbuf);
 432        }
 433        strbuf_release(&nbuf);
 434        return ret;
 435}
 436
 437static struct convert_driver {
 438        const char *name;
 439        struct convert_driver *next;
 440        const char *smudge;
 441        const char *clean;
 442} *user_convert, **user_convert_tail;
 443
 444static int read_convert_config(const char *var, const char *value, void *cb)
 445{
 446        const char *ep, *name;
 447        int namelen;
 448        struct convert_driver *drv;
 449
 450        /*
 451         * External conversion drivers are configured using
 452         * "filter.<name>.variable".
 453         */
 454        if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
 455                return 0;
 456        name = var + 7;
 457        namelen = ep - name;
 458        for (drv = user_convert; drv; drv = drv->next)
 459                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
 460                        break;
 461        if (!drv) {
 462                drv = xcalloc(1, sizeof(struct convert_driver));
 463                drv->name = xmemdupz(name, namelen);
 464                *user_convert_tail = drv;
 465                user_convert_tail = &(drv->next);
 466        }
 467
 468        ep++;
 469
 470        /*
 471         * filter.<name>.smudge and filter.<name>.clean specifies
 472         * the command line:
 473         *
 474         *      command-line
 475         *
 476         * The command-line will not be interpolated in any way.
 477         */
 478
 479        if (!strcmp("smudge", ep))
 480                return git_config_string(&drv->smudge, var, value);
 481
 482        if (!strcmp("clean", ep))
 483                return git_config_string(&drv->clean, var, value);
 484
 485        return 0;
 486}
 487
 488static int count_ident(const char *cp, unsigned long size)
 489{
 490        /*
 491         * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
 492         */
 493        int cnt = 0;
 494        char ch;
 495
 496        while (size) {
 497                ch = *cp++;
 498                size--;
 499                if (ch != '$')
 500                        continue;
 501                if (size < 3)
 502                        break;
 503                if (memcmp("Id", cp, 2))
 504                        continue;
 505                ch = cp[2];
 506                cp += 3;
 507                size -= 3;
 508                if (ch == '$')
 509                        cnt++; /* $Id$ */
 510                if (ch != ':')
 511                        continue;
 512
 513                /*
 514                 * "$Id: ... "; scan up to the closing dollar sign and discard.
 515                 */
 516                while (size) {
 517                        ch = *cp++;
 518                        size--;
 519                        if (ch == '$') {
 520                                cnt++;
 521                                break;
 522                        }
 523                        if (ch == '\n')
 524                                break;
 525                }
 526        }
 527        return cnt;
 528}
 529
 530static int ident_to_git(const char *path, const char *src, size_t len,
 531                        struct strbuf *buf, int ident)
 532{
 533        char *dst, *dollar;
 534
 535        if (!ident || !count_ident(src, len))
 536                return 0;
 537
 538        if (!buf)
 539                return 1;
 540
 541        /* only grow if not in place */
 542        if (strbuf_avail(buf) + buf->len < len)
 543                strbuf_grow(buf, len - buf->len);
 544        dst = buf->buf;
 545        for (;;) {
 546                dollar = memchr(src, '$', len);
 547                if (!dollar)
 548                        break;
 549                memmove(dst, src, dollar + 1 - src);
 550                dst += dollar + 1 - src;
 551                len -= dollar + 1 - src;
 552                src  = dollar + 1;
 553
 554                if (len > 3 && !memcmp(src, "Id:", 3)) {
 555                        dollar = memchr(src + 3, '$', len - 3);
 556                        if (!dollar)
 557                                break;
 558                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 559                                /* Line break before the next dollar. */
 560                                continue;
 561                        }
 562
 563                        memcpy(dst, "Id$", 3);
 564                        dst += 3;
 565                        len -= dollar + 1 - src;
 566                        src  = dollar + 1;
 567                }
 568        }
 569        memmove(dst, src, len);
 570        strbuf_setlen(buf, dst + len - buf->buf);
 571        return 1;
 572}
 573
 574static int ident_to_worktree(const char *path, const char *src, size_t len,
 575                             struct strbuf *buf, int ident)
 576{
 577        unsigned char sha1[20];
 578        char *to_free = NULL, *dollar, *spc;
 579        int cnt;
 580
 581        if (!ident)
 582                return 0;
 583
 584        cnt = count_ident(src, len);
 585        if (!cnt)
 586                return 0;
 587
 588        /* are we "faking" in place editing ? */
 589        if (src == buf->buf)
 590                to_free = strbuf_detach(buf, NULL);
 591        hash_sha1_file(src, len, "blob", sha1);
 592
 593        strbuf_grow(buf, len + cnt * 43);
 594        for (;;) {
 595                /* step 1: run to the next '$' */
 596                dollar = memchr(src, '$', len);
 597                if (!dollar)
 598                        break;
 599                strbuf_add(buf, src, dollar + 1 - src);
 600                len -= dollar + 1 - src;
 601                src  = dollar + 1;
 602
 603                /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
 604                if (len < 3 || memcmp("Id", src, 2))
 605                        continue;
 606
 607                /* step 3: skip over Id$ or Id:xxxxx$ */
 608                if (src[2] == '$') {
 609                        src += 3;
 610                        len -= 3;
 611                } else if (src[2] == ':') {
 612                        /*
 613                         * It's possible that an expanded Id has crept its way into the
 614                         * repository, we cope with that by stripping the expansion out.
 615                         * This is probably not a good idea, since it will cause changes
 616                         * on checkout, which won't go away by stash, but let's keep it
 617                         * for git-style ids.
 618                         */
 619                        dollar = memchr(src + 3, '$', len - 3);
 620                        if (!dollar) {
 621                                /* incomplete keyword, no more '$', so just quit the loop */
 622                                break;
 623                        }
 624
 625                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 626                                /* Line break before the next dollar. */
 627                                continue;
 628                        }
 629
 630                        spc = memchr(src + 4, ' ', dollar - src - 4);
 631                        if (spc && spc < dollar-1) {
 632                                /* There are spaces in unexpected places.
 633                                 * This is probably an id from some other
 634                                 * versioning system. Keep it for now.
 635                                 */
 636                                continue;
 637                        }
 638
 639                        len -= dollar + 1 - src;
 640                        src  = dollar + 1;
 641                } else {
 642                        /* it wasn't a "Id$" or "Id:xxxx$" */
 643                        continue;
 644                }
 645
 646                /* step 4: substitute */
 647                strbuf_addstr(buf, "Id: ");
 648                strbuf_add(buf, sha1_to_hex(sha1), 40);
 649                strbuf_addstr(buf, " $");
 650        }
 651        strbuf_add(buf, src, len);
 652
 653        free(to_free);
 654        return 1;
 655}
 656
 657static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
 658{
 659        const char *value = check->value;
 660
 661        if (ATTR_TRUE(value))
 662                return CRLF_TEXT;
 663        else if (ATTR_FALSE(value))
 664                return CRLF_BINARY;
 665        else if (ATTR_UNSET(value))
 666                ;
 667        else if (!strcmp(value, "input"))
 668                return CRLF_INPUT;
 669        else if (!strcmp(value, "auto"))
 670                return CRLF_AUTO;
 671        return CRLF_GUESS;
 672}
 673
 674static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
 675{
 676        const char *value = check->value;
 677
 678        if (ATTR_UNSET(value))
 679                ;
 680        else if (!strcmp(value, "lf"))
 681                return EOL_LF;
 682        else if (!strcmp(value, "crlf"))
 683                return EOL_CRLF;
 684        return EOL_UNSET;
 685}
 686
 687static struct convert_driver *git_path_check_convert(const char *path,
 688                                             struct git_attr_check *check)
 689{
 690        const char *value = check->value;
 691        struct convert_driver *drv;
 692
 693        if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
 694                return NULL;
 695        for (drv = user_convert; drv; drv = drv->next)
 696                if (!strcmp(value, drv->name))
 697                        return drv;
 698        return NULL;
 699}
 700
 701static int git_path_check_ident(const char *path, struct git_attr_check *check)
 702{
 703        const char *value = check->value;
 704
 705        return !!ATTR_TRUE(value);
 706}
 707
 708static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
 709{
 710        if (text_attr == CRLF_BINARY)
 711                return CRLF_BINARY;
 712        if (eol_attr == EOL_LF)
 713                return CRLF_INPUT;
 714        if (eol_attr == EOL_CRLF)
 715                return CRLF_CRLF;
 716        return text_attr;
 717}
 718
 719struct conv_attrs {
 720        struct convert_driver *drv;
 721        enum crlf_action crlf_action;
 722        enum eol eol_attr;
 723        int ident;
 724};
 725
 726static const char *conv_attr_name[] = {
 727        "crlf", "ident", "filter", "eol", "text",
 728};
 729#define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
 730
 731static void convert_attrs(struct conv_attrs *ca, const char *path)
 732{
 733        int i;
 734        static struct git_attr_check ccheck[NUM_CONV_ATTRS];
 735
 736        if (!ccheck[0].attr) {
 737                for (i = 0; i < NUM_CONV_ATTRS; i++)
 738                        ccheck[i].attr = git_attr(conv_attr_name[i]);
 739                user_convert_tail = &user_convert;
 740                git_config(read_convert_config, NULL);
 741        }
 742
 743        if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
 744                ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
 745                if (ca->crlf_action == CRLF_GUESS)
 746                        ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
 747                ca->ident = git_path_check_ident(path, ccheck + 1);
 748                ca->drv = git_path_check_convert(path, ccheck + 2);
 749                ca->eol_attr = git_path_check_eol(path, ccheck + 3);
 750        } else {
 751                ca->drv = NULL;
 752                ca->crlf_action = CRLF_GUESS;
 753                ca->eol_attr = EOL_UNSET;
 754                ca->ident = 0;
 755        }
 756}
 757
 758int convert_to_git(const char *path, const char *src, size_t len,
 759                   struct strbuf *dst, enum safe_crlf checksafe)
 760{
 761        int ret = 0;
 762        const char *filter = NULL;
 763        struct conv_attrs ca;
 764
 765        convert_attrs(&ca, path);
 766        if (ca.drv)
 767                filter = ca.drv->clean;
 768
 769        ret |= apply_filter(path, src, len, dst, filter);
 770        if (ret && dst) {
 771                src = dst->buf;
 772                len = dst->len;
 773        }
 774        ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
 775        ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
 776        if (ret && dst) {
 777                src = dst->buf;
 778                len = dst->len;
 779        }
 780        return ret | ident_to_git(path, src, len, dst, ca.ident);
 781}
 782
 783static int convert_to_working_tree_internal(const char *path, const char *src,
 784                                            size_t len, struct strbuf *dst,
 785                                            int normalizing)
 786{
 787        int ret = 0;
 788        const char *filter = NULL;
 789        struct conv_attrs ca;
 790
 791        convert_attrs(&ca, path);
 792        if (ca.drv)
 793                filter = ca.drv->smudge;
 794
 795        ret |= ident_to_worktree(path, src, len, dst, ca.ident);
 796        if (ret) {
 797                src = dst->buf;
 798                len = dst->len;
 799        }
 800        /*
 801         * CRLF conversion can be skipped if normalizing, unless there
 802         * is a smudge filter.  The filter might expect CRLFs.
 803         */
 804        if (filter || !normalizing) {
 805                ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
 806                ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
 807                if (ret) {
 808                        src = dst->buf;
 809                        len = dst->len;
 810                }
 811        }
 812        return ret | apply_filter(path, src, len, dst, filter);
 813}
 814
 815int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
 816{
 817        return convert_to_working_tree_internal(path, src, len, dst, 0);
 818}
 819
 820int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
 821{
 822        int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
 823        if (ret) {
 824                src = dst->buf;
 825                len = dst->len;
 826        }
 827        return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
 828}
 829
 830/*****************************************************************
 831 *
 832 * Streaming converison support
 833 *
 834 *****************************************************************/
 835
 836typedef int (*filter_fn)(struct stream_filter *,
 837                         const char *input, size_t *isize_p,
 838                         char *output, size_t *osize_p);
 839typedef void (*free_fn)(struct stream_filter *);
 840
 841struct stream_filter_vtbl {
 842        filter_fn filter;
 843        free_fn free;
 844};
 845
 846struct stream_filter {
 847        struct stream_filter_vtbl *vtbl;
 848};
 849
 850static int null_filter_fn(struct stream_filter *filter,
 851                          const char *input, size_t *isize_p,
 852                          char *output, size_t *osize_p)
 853{
 854        size_t count;
 855
 856        if (!input)
 857                return 0; /* we do not keep any states */
 858        count = *isize_p;
 859        if (*osize_p < count)
 860                count = *osize_p;
 861        if (count) {
 862                memmove(output, input, count);
 863                *isize_p -= count;
 864                *osize_p -= count;
 865        }
 866        return 0;
 867}
 868
 869static void null_free_fn(struct stream_filter *filter)
 870{
 871        ; /* nothing -- null instances are shared */
 872}
 873
 874static struct stream_filter_vtbl null_vtbl = {
 875        null_filter_fn,
 876        null_free_fn,
 877};
 878
 879static struct stream_filter null_filter_singleton = {
 880        &null_vtbl,
 881};
 882
 883int is_null_stream_filter(struct stream_filter *filter)
 884{
 885        return filter == &null_filter_singleton;
 886}
 887
 888
 889/*
 890 * LF-to-CRLF filter
 891 */
 892
 893struct lf_to_crlf_filter {
 894        struct stream_filter filter;
 895        unsigned has_held:1;
 896        char held;
 897};
 898
 899static int lf_to_crlf_filter_fn(struct stream_filter *filter,
 900                                const char *input, size_t *isize_p,
 901                                char *output, size_t *osize_p)
 902{
 903        size_t count, o = 0;
 904        struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
 905
 906        /*
 907         * We may be holding onto the CR to see if it is followed by a
 908         * LF, in which case we would need to go to the main loop.
 909         * Otherwise, just emit it to the output stream.
 910         */
 911        if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
 912                output[o++] = lf_to_crlf->held;
 913                lf_to_crlf->has_held = 0;
 914        }
 915
 916        /* We are told to drain */
 917        if (!input) {
 918                *osize_p -= o;
 919                return 0;
 920        }
 921
 922        count = *isize_p;
 923        if (count || lf_to_crlf->has_held) {
 924                size_t i;
 925                int was_cr = 0;
 926
 927                if (lf_to_crlf->has_held) {
 928                        was_cr = 1;
 929                        lf_to_crlf->has_held = 0;
 930                }
 931
 932                for (i = 0; o < *osize_p && i < count; i++) {
 933                        char ch = input[i];
 934
 935                        if (ch == '\n') {
 936                                output[o++] = '\r';
 937                        } else if (was_cr) {
 938                                /*
 939                                 * Previous round saw CR and it is not followed
 940                                 * by a LF; emit the CR before processing the
 941                                 * current character.
 942                                 */
 943                                output[o++] = '\r';
 944                        }
 945
 946                        /*
 947                         * We may have consumed the last output slot,
 948                         * in which case we need to break out of this
 949                         * loop; hold the current character before
 950                         * returning.
 951                         */
 952                        if (*osize_p <= o) {
 953                                lf_to_crlf->has_held = 1;
 954                                lf_to_crlf->held = ch;
 955                                continue; /* break but increment i */
 956                        }
 957
 958                        if (ch == '\r') {
 959                                was_cr = 1;
 960                                continue;
 961                        }
 962
 963                        was_cr = 0;
 964                        output[o++] = ch;
 965                }
 966
 967                *osize_p -= o;
 968                *isize_p -= i;
 969
 970                if (!lf_to_crlf->has_held && was_cr) {
 971                        lf_to_crlf->has_held = 1;
 972                        lf_to_crlf->held = '\r';
 973                }
 974        }
 975        return 0;
 976}
 977
 978static void lf_to_crlf_free_fn(struct stream_filter *filter)
 979{
 980        free(filter);
 981}
 982
 983static struct stream_filter_vtbl lf_to_crlf_vtbl = {
 984        lf_to_crlf_filter_fn,
 985        lf_to_crlf_free_fn,
 986};
 987
 988static struct stream_filter *lf_to_crlf_filter(void)
 989{
 990        struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
 991
 992        lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
 993        return (struct stream_filter *)lf_to_crlf;
 994}
 995
 996/*
 997 * Cascade filter
 998 */
 999#define FILTER_BUFFER 1024
1000struct cascade_filter {
1001        struct stream_filter filter;
1002        struct stream_filter *one;
1003        struct stream_filter *two;
1004        char buf[FILTER_BUFFER];
1005        int end, ptr;
1006};
1007
1008static int cascade_filter_fn(struct stream_filter *filter,
1009                             const char *input, size_t *isize_p,
1010                             char *output, size_t *osize_p)
1011{
1012        struct cascade_filter *cas = (struct cascade_filter *) filter;
1013        size_t filled = 0;
1014        size_t sz = *osize_p;
1015        size_t to_feed, remaining;
1016
1017        /*
1018         * input -- (one) --> buf -- (two) --> output
1019         */
1020        while (filled < sz) {
1021                remaining = sz - filled;
1022
1023                /* do we already have something to feed two with? */
1024                if (cas->ptr < cas->end) {
1025                        to_feed = cas->end - cas->ptr;
1026                        if (stream_filter(cas->two,
1027                                          cas->buf + cas->ptr, &to_feed,
1028                                          output + filled, &remaining))
1029                                return -1;
1030                        cas->ptr += (cas->end - cas->ptr) - to_feed;
1031                        filled = sz - remaining;
1032                        continue;
1033                }
1034
1035                /* feed one from upstream and have it emit into our buffer */
1036                to_feed = input ? *isize_p : 0;
1037                if (input && !to_feed)
1038                        break;
1039                remaining = sizeof(cas->buf);
1040                if (stream_filter(cas->one,
1041                                  input, &to_feed,
1042                                  cas->buf, &remaining))
1043                        return -1;
1044                cas->end = sizeof(cas->buf) - remaining;
1045                cas->ptr = 0;
1046                if (input) {
1047                        size_t fed = *isize_p - to_feed;
1048                        *isize_p -= fed;
1049                        input += fed;
1050                }
1051
1052                /* do we know that we drained one completely? */
1053                if (input || cas->end)
1054                        continue;
1055
1056                /* tell two to drain; we have nothing more to give it */
1057                to_feed = 0;
1058                remaining = sz - filled;
1059                if (stream_filter(cas->two,
1060                                  NULL, &to_feed,
1061                                  output + filled, &remaining))
1062                        return -1;
1063                if (remaining == (sz - filled))
1064                        break; /* completely drained two */
1065                filled = sz - remaining;
1066        }
1067        *osize_p -= filled;
1068        return 0;
1069}
1070
1071static void cascade_free_fn(struct stream_filter *filter)
1072{
1073        struct cascade_filter *cas = (struct cascade_filter *)filter;
1074        free_stream_filter(cas->one);
1075        free_stream_filter(cas->two);
1076        free(filter);
1077}
1078
1079static struct stream_filter_vtbl cascade_vtbl = {
1080        cascade_filter_fn,
1081        cascade_free_fn,
1082};
1083
1084static struct stream_filter *cascade_filter(struct stream_filter *one,
1085                                            struct stream_filter *two)
1086{
1087        struct cascade_filter *cascade;
1088
1089        if (!one || is_null_stream_filter(one))
1090                return two;
1091        if (!two || is_null_stream_filter(two))
1092                return one;
1093
1094        cascade = xmalloc(sizeof(*cascade));
1095        cascade->one = one;
1096        cascade->two = two;
1097        cascade->end = cascade->ptr = 0;
1098        cascade->filter.vtbl = &cascade_vtbl;
1099        return (struct stream_filter *)cascade;
1100}
1101
1102/*
1103 * ident filter
1104 */
1105#define IDENT_DRAINING (-1)
1106#define IDENT_SKIPPING (-2)
1107struct ident_filter {
1108        struct stream_filter filter;
1109        struct strbuf left;
1110        int state;
1111        char ident[45]; /* ": x40 $" */
1112};
1113
1114static int is_foreign_ident(const char *str)
1115{
1116        int i;
1117
1118        if (prefixcmp(str, "$Id: "))
1119                return 0;
1120        for (i = 5; str[i]; i++) {
1121                if (isspace(str[i]) && str[i+1] != '$')
1122                        return 1;
1123        }
1124        return 0;
1125}
1126
1127static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1128{
1129        size_t to_drain = ident->left.len;
1130
1131        if (*osize_p < to_drain)
1132                to_drain = *osize_p;
1133        if (to_drain) {
1134                memcpy(*output_p, ident->left.buf, to_drain);
1135                strbuf_remove(&ident->left, 0, to_drain);
1136                *output_p += to_drain;
1137                *osize_p -= to_drain;
1138        }
1139        if (!ident->left.len)
1140                ident->state = 0;
1141}
1142
1143static int ident_filter_fn(struct stream_filter *filter,
1144                           const char *input, size_t *isize_p,
1145                           char *output, size_t *osize_p)
1146{
1147        struct ident_filter *ident = (struct ident_filter *)filter;
1148        static const char head[] = "$Id";
1149
1150        if (!input) {
1151                /* drain upon eof */
1152                switch (ident->state) {
1153                default:
1154                        strbuf_add(&ident->left, head, ident->state);
1155                case IDENT_SKIPPING:
1156                        /* fallthru */
1157                case IDENT_DRAINING:
1158                        ident_drain(ident, &output, osize_p);
1159                }
1160                return 0;
1161        }
1162
1163        while (*isize_p || (ident->state == IDENT_DRAINING)) {
1164                int ch;
1165
1166                if (ident->state == IDENT_DRAINING) {
1167                        ident_drain(ident, &output, osize_p);
1168                        if (!*osize_p)
1169                                break;
1170                        continue;
1171                }
1172
1173                ch = *(input++);
1174                (*isize_p)--;
1175
1176                if (ident->state == IDENT_SKIPPING) {
1177                        /*
1178                         * Skipping until '$' or LF, but keeping them
1179                         * in case it is a foreign ident.
1180                         */
1181                        strbuf_addch(&ident->left, ch);
1182                        if (ch != '\n' && ch != '$')
1183                                continue;
1184                        if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1185                                strbuf_setlen(&ident->left, sizeof(head) - 1);
1186                                strbuf_addstr(&ident->left, ident->ident);
1187                        }
1188                        ident->state = IDENT_DRAINING;
1189                        continue;
1190                }
1191
1192                if (ident->state < sizeof(head) &&
1193                    head[ident->state] == ch) {
1194                        ident->state++;
1195                        continue;
1196                }
1197
1198                if (ident->state)
1199                        strbuf_add(&ident->left, head, ident->state);
1200                if (ident->state == sizeof(head) - 1) {
1201                        if (ch != ':' && ch != '$') {
1202                                strbuf_addch(&ident->left, ch);
1203                                ident->state = 0;
1204                                continue;
1205                        }
1206
1207                        if (ch == ':') {
1208                                strbuf_addch(&ident->left, ch);
1209                                ident->state = IDENT_SKIPPING;
1210                        } else {
1211                                strbuf_addstr(&ident->left, ident->ident);
1212                                ident->state = IDENT_DRAINING;
1213                        }
1214                        continue;
1215                }
1216
1217                strbuf_addch(&ident->left, ch);
1218                ident->state = IDENT_DRAINING;
1219        }
1220        return 0;
1221}
1222
1223static void ident_free_fn(struct stream_filter *filter)
1224{
1225        struct ident_filter *ident = (struct ident_filter *)filter;
1226        strbuf_release(&ident->left);
1227        free(filter);
1228}
1229
1230static struct stream_filter_vtbl ident_vtbl = {
1231        ident_filter_fn,
1232        ident_free_fn,
1233};
1234
1235static struct stream_filter *ident_filter(const unsigned char *sha1)
1236{
1237        struct ident_filter *ident = xmalloc(sizeof(*ident));
1238
1239        sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1240        strbuf_init(&ident->left, 0);
1241        ident->filter.vtbl = &ident_vtbl;
1242        ident->state = 0;
1243        return (struct stream_filter *)ident;
1244}
1245
1246/*
1247 * Return an appropriately constructed filter for the path, or NULL if
1248 * the contents cannot be filtered without reading the whole thing
1249 * in-core.
1250 *
1251 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1252 * large binary blob you would want us not to slurp into the memory!
1253 */
1254struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1255{
1256        struct conv_attrs ca;
1257        enum crlf_action crlf_action;
1258        struct stream_filter *filter = NULL;
1259
1260        convert_attrs(&ca, path);
1261
1262        if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1263                return filter;
1264
1265        if (ca.ident)
1266                filter = ident_filter(sha1);
1267
1268        crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1269
1270        if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1271            (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1272                filter = cascade_filter(filter, &null_filter_singleton);
1273
1274        else if (output_eol(crlf_action) == EOL_CRLF &&
1275                 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1276                filter = cascade_filter(filter, lf_to_crlf_filter());
1277
1278        return filter;
1279}
1280
1281void free_stream_filter(struct stream_filter *filter)
1282{
1283        filter->vtbl->free(filter);
1284}
1285
1286int stream_filter(struct stream_filter *filter,
1287                  const char *input, size_t *isize_p,
1288                  char *output, size_t *osize_p)
1289{
1290        return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
1291}