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