convert.con commit imap-send: use parse options API to determine verbosity (f1a3529)
   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        int fd;
 316        const char *cmd;
 317        const char *path;
 318};
 319
 320static int filter_buffer_or_fd(int in, int out, void *data)
 321{
 322        /*
 323         * Spawn cmd and feed the buffer contents through its stdin.
 324         */
 325        struct child_process child_process = CHILD_PROCESS_INIT;
 326        struct filter_params *params = (struct filter_params *)data;
 327        int write_err, status;
 328        const char *argv[] = { NULL, NULL };
 329
 330        /* apply % substitution to cmd */
 331        struct strbuf cmd = STRBUF_INIT;
 332        struct strbuf path = STRBUF_INIT;
 333        struct strbuf_expand_dict_entry dict[] = {
 334                { "f", NULL, },
 335                { NULL, NULL, },
 336        };
 337
 338        /* quote the path to preserve spaces, etc. */
 339        sq_quote_buf(&path, params->path);
 340        dict[0].value = path.buf;
 341
 342        /* expand all %f with the quoted path */
 343        strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
 344        strbuf_release(&path);
 345
 346        argv[0] = cmd.buf;
 347
 348        child_process.argv = argv;
 349        child_process.use_shell = 1;
 350        child_process.in = -1;
 351        child_process.out = out;
 352
 353        if (start_command(&child_process))
 354                return error("cannot fork to run external filter %s", params->cmd);
 355
 356        sigchain_push(SIGPIPE, SIG_IGN);
 357
 358        if (params->src) {
 359                write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
 360        } else {
 361                write_err = copy_fd(params->fd, child_process.in);
 362        }
 363
 364        if (close(child_process.in))
 365                write_err = 1;
 366        if (write_err)
 367                error("cannot feed the input to external filter %s", params->cmd);
 368
 369        sigchain_pop(SIGPIPE);
 370
 371        status = finish_command(&child_process);
 372        if (status)
 373                error("external filter %s failed %d", params->cmd, status);
 374
 375        strbuf_release(&cmd);
 376        return (write_err || status);
 377}
 378
 379static int apply_filter(const char *path, const char *src, size_t len, int fd,
 380                        struct strbuf *dst, const char *cmd)
 381{
 382        /*
 383         * Create a pipeline to have the command filter the buffer's
 384         * contents.
 385         *
 386         * (child --> cmd) --> us
 387         */
 388        int ret = 1;
 389        struct strbuf nbuf = STRBUF_INIT;
 390        struct async async;
 391        struct filter_params params;
 392
 393        if (!cmd)
 394                return 0;
 395
 396        if (!dst)
 397                return 1;
 398
 399        memset(&async, 0, sizeof(async));
 400        async.proc = filter_buffer_or_fd;
 401        async.data = &params;
 402        async.out = -1;
 403        params.src = src;
 404        params.size = len;
 405        params.fd = fd;
 406        params.cmd = cmd;
 407        params.path = path;
 408
 409        fflush(NULL);
 410        if (start_async(&async))
 411                return 0;       /* error was already reported */
 412
 413        if (strbuf_read(&nbuf, async.out, len) < 0) {
 414                error("read from external filter %s failed", cmd);
 415                ret = 0;
 416        }
 417        if (close(async.out)) {
 418                error("read from external filter %s failed", cmd);
 419                ret = 0;
 420        }
 421        if (finish_async(&async)) {
 422                error("external filter %s failed", cmd);
 423                ret = 0;
 424        }
 425
 426        if (ret) {
 427                strbuf_swap(dst, &nbuf);
 428        }
 429        strbuf_release(&nbuf);
 430        return ret;
 431}
 432
 433static struct convert_driver {
 434        const char *name;
 435        struct convert_driver *next;
 436        const char *smudge;
 437        const char *clean;
 438        int required;
 439} *user_convert, **user_convert_tail;
 440
 441static int read_convert_config(const char *var, const char *value, void *cb)
 442{
 443        const char *key, *name;
 444        int namelen;
 445        struct convert_driver *drv;
 446
 447        /*
 448         * External conversion drivers are configured using
 449         * "filter.<name>.variable".
 450         */
 451        if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
 452                return 0;
 453        for (drv = user_convert; drv; drv = drv->next)
 454                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
 455                        break;
 456        if (!drv) {
 457                drv = xcalloc(1, sizeof(struct convert_driver));
 458                drv->name = xmemdupz(name, namelen);
 459                *user_convert_tail = drv;
 460                user_convert_tail = &(drv->next);
 461        }
 462
 463        /*
 464         * filter.<name>.smudge and filter.<name>.clean specifies
 465         * the command line:
 466         *
 467         *      command-line
 468         *
 469         * The command-line will not be interpolated in any way.
 470         */
 471
 472        if (!strcmp("smudge", key))
 473                return git_config_string(&drv->smudge, var, value);
 474
 475        if (!strcmp("clean", key))
 476                return git_config_string(&drv->clean, var, value);
 477
 478        if (!strcmp("required", key)) {
 479                drv->required = git_config_bool(var, value);
 480                return 0;
 481        }
 482
 483        return 0;
 484}
 485
 486static int count_ident(const char *cp, unsigned long size)
 487{
 488        /*
 489         * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
 490         */
 491        int cnt = 0;
 492        char ch;
 493
 494        while (size) {
 495                ch = *cp++;
 496                size--;
 497                if (ch != '$')
 498                        continue;
 499                if (size < 3)
 500                        break;
 501                if (memcmp("Id", cp, 2))
 502                        continue;
 503                ch = cp[2];
 504                cp += 3;
 505                size -= 3;
 506                if (ch == '$')
 507                        cnt++; /* $Id$ */
 508                if (ch != ':')
 509                        continue;
 510
 511                /*
 512                 * "$Id: ... "; scan up to the closing dollar sign and discard.
 513                 */
 514                while (size) {
 515                        ch = *cp++;
 516                        size--;
 517                        if (ch == '$') {
 518                                cnt++;
 519                                break;
 520                        }
 521                        if (ch == '\n')
 522                                break;
 523                }
 524        }
 525        return cnt;
 526}
 527
 528static int ident_to_git(const char *path, const char *src, size_t len,
 529                        struct strbuf *buf, int ident)
 530{
 531        char *dst, *dollar;
 532
 533        if (!ident || (src && !count_ident(src, len)))
 534                return 0;
 535
 536        if (!buf)
 537                return 1;
 538
 539        /* only grow if not in place */
 540        if (strbuf_avail(buf) + buf->len < len)
 541                strbuf_grow(buf, len - buf->len);
 542        dst = buf->buf;
 543        for (;;) {
 544                dollar = memchr(src, '$', len);
 545                if (!dollar)
 546                        break;
 547                memmove(dst, src, dollar + 1 - src);
 548                dst += dollar + 1 - src;
 549                len -= dollar + 1 - src;
 550                src  = dollar + 1;
 551
 552                if (len > 3 && !memcmp(src, "Id:", 3)) {
 553                        dollar = memchr(src + 3, '$', len - 3);
 554                        if (!dollar)
 555                                break;
 556                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 557                                /* Line break before the next dollar. */
 558                                continue;
 559                        }
 560
 561                        memcpy(dst, "Id$", 3);
 562                        dst += 3;
 563                        len -= dollar + 1 - src;
 564                        src  = dollar + 1;
 565                }
 566        }
 567        memmove(dst, src, len);
 568        strbuf_setlen(buf, dst + len - buf->buf);
 569        return 1;
 570}
 571
 572static int ident_to_worktree(const char *path, const char *src, size_t len,
 573                             struct strbuf *buf, int ident)
 574{
 575        unsigned char sha1[20];
 576        char *to_free = NULL, *dollar, *spc;
 577        int cnt;
 578
 579        if (!ident)
 580                return 0;
 581
 582        cnt = count_ident(src, len);
 583        if (!cnt)
 584                return 0;
 585
 586        /* are we "faking" in place editing ? */
 587        if (src == buf->buf)
 588                to_free = strbuf_detach(buf, NULL);
 589        hash_sha1_file(src, len, "blob", sha1);
 590
 591        strbuf_grow(buf, len + cnt * 43);
 592        for (;;) {
 593                /* step 1: run to the next '$' */
 594                dollar = memchr(src, '$', len);
 595                if (!dollar)
 596                        break;
 597                strbuf_add(buf, src, dollar + 1 - src);
 598                len -= dollar + 1 - src;
 599                src  = dollar + 1;
 600
 601                /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
 602                if (len < 3 || memcmp("Id", src, 2))
 603                        continue;
 604
 605                /* step 3: skip over Id$ or Id:xxxxx$ */
 606                if (src[2] == '$') {
 607                        src += 3;
 608                        len -= 3;
 609                } else if (src[2] == ':') {
 610                        /*
 611                         * It's possible that an expanded Id has crept its way into the
 612                         * repository, we cope with that by stripping the expansion out.
 613                         * This is probably not a good idea, since it will cause changes
 614                         * on checkout, which won't go away by stash, but let's keep it
 615                         * for git-style ids.
 616                         */
 617                        dollar = memchr(src + 3, '$', len - 3);
 618                        if (!dollar) {
 619                                /* incomplete keyword, no more '$', so just quit the loop */
 620                                break;
 621                        }
 622
 623                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 624                                /* Line break before the next dollar. */
 625                                continue;
 626                        }
 627
 628                        spc = memchr(src + 4, ' ', dollar - src - 4);
 629                        if (spc && spc < dollar-1) {
 630                                /* There are spaces in unexpected places.
 631                                 * This is probably an id from some other
 632                                 * versioning system. Keep it for now.
 633                                 */
 634                                continue;
 635                        }
 636
 637                        len -= dollar + 1 - src;
 638                        src  = dollar + 1;
 639                } else {
 640                        /* it wasn't a "Id$" or "Id:xxxx$" */
 641                        continue;
 642                }
 643
 644                /* step 4: substitute */
 645                strbuf_addstr(buf, "Id: ");
 646                strbuf_add(buf, sha1_to_hex(sha1), 40);
 647                strbuf_addstr(buf, " $");
 648        }
 649        strbuf_add(buf, src, len);
 650
 651        free(to_free);
 652        return 1;
 653}
 654
 655static enum crlf_action git_path_check_crlf(const char *path, struct git_attr_check *check)
 656{
 657        const char *value = check->value;
 658
 659        if (ATTR_TRUE(value))
 660                return CRLF_TEXT;
 661        else if (ATTR_FALSE(value))
 662                return CRLF_BINARY;
 663        else if (ATTR_UNSET(value))
 664                ;
 665        else if (!strcmp(value, "input"))
 666                return CRLF_INPUT;
 667        else if (!strcmp(value, "auto"))
 668                return CRLF_AUTO;
 669        return CRLF_GUESS;
 670}
 671
 672static enum eol git_path_check_eol(const char *path, struct git_attr_check *check)
 673{
 674        const char *value = check->value;
 675
 676        if (ATTR_UNSET(value))
 677                ;
 678        else if (!strcmp(value, "lf"))
 679                return EOL_LF;
 680        else if (!strcmp(value, "crlf"))
 681                return EOL_CRLF;
 682        return EOL_UNSET;
 683}
 684
 685static struct convert_driver *git_path_check_convert(const char *path,
 686                                             struct git_attr_check *check)
 687{
 688        const char *value = check->value;
 689        struct convert_driver *drv;
 690
 691        if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
 692                return NULL;
 693        for (drv = user_convert; drv; drv = drv->next)
 694                if (!strcmp(value, drv->name))
 695                        return drv;
 696        return NULL;
 697}
 698
 699static int git_path_check_ident(const char *path, struct git_attr_check *check)
 700{
 701        const char *value = check->value;
 702
 703        return !!ATTR_TRUE(value);
 704}
 705
 706static enum crlf_action input_crlf_action(enum crlf_action text_attr, enum eol eol_attr)
 707{
 708        if (text_attr == CRLF_BINARY)
 709                return CRLF_BINARY;
 710        if (eol_attr == EOL_LF)
 711                return CRLF_INPUT;
 712        if (eol_attr == EOL_CRLF)
 713                return CRLF_CRLF;
 714        return text_attr;
 715}
 716
 717struct conv_attrs {
 718        struct convert_driver *drv;
 719        enum crlf_action crlf_action;
 720        enum eol eol_attr;
 721        int ident;
 722};
 723
 724static const char *conv_attr_name[] = {
 725        "crlf", "ident", "filter", "eol", "text",
 726};
 727#define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
 728
 729static void convert_attrs(struct conv_attrs *ca, const char *path)
 730{
 731        int i;
 732        static struct git_attr_check ccheck[NUM_CONV_ATTRS];
 733
 734        if (!ccheck[0].attr) {
 735                for (i = 0; i < NUM_CONV_ATTRS; i++)
 736                        ccheck[i].attr = git_attr(conv_attr_name[i]);
 737                user_convert_tail = &user_convert;
 738                git_config(read_convert_config, NULL);
 739        }
 740
 741        if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
 742                ca->crlf_action = git_path_check_crlf(path, ccheck + 4);
 743                if (ca->crlf_action == CRLF_GUESS)
 744                        ca->crlf_action = git_path_check_crlf(path, ccheck + 0);
 745                ca->ident = git_path_check_ident(path, ccheck + 1);
 746                ca->drv = git_path_check_convert(path, ccheck + 2);
 747                ca->eol_attr = git_path_check_eol(path, ccheck + 3);
 748        } else {
 749                ca->drv = NULL;
 750                ca->crlf_action = CRLF_GUESS;
 751                ca->eol_attr = EOL_UNSET;
 752                ca->ident = 0;
 753        }
 754}
 755
 756int would_convert_to_git_filter_fd(const char *path)
 757{
 758        struct conv_attrs ca;
 759
 760        convert_attrs(&ca, path);
 761        if (!ca.drv)
 762                return 0;
 763
 764        /*
 765         * Apply a filter to an fd only if the filter is required to succeed.
 766         * We must die if the filter fails, because the original data before
 767         * filtering is not available.
 768         */
 769        if (!ca.drv->required)
 770                return 0;
 771
 772        return apply_filter(path, NULL, 0, -1, NULL, ca.drv->clean);
 773}
 774
 775int convert_to_git(const char *path, const char *src, size_t len,
 776                   struct strbuf *dst, enum safe_crlf checksafe)
 777{
 778        int ret = 0;
 779        const char *filter = NULL;
 780        int required = 0;
 781        struct conv_attrs ca;
 782
 783        convert_attrs(&ca, path);
 784        if (ca.drv) {
 785                filter = ca.drv->clean;
 786                required = ca.drv->required;
 787        }
 788
 789        ret |= apply_filter(path, src, len, -1, dst, filter);
 790        if (!ret && required)
 791                die("%s: clean filter '%s' failed", path, ca.drv->name);
 792
 793        if (ret && dst) {
 794                src = dst->buf;
 795                len = dst->len;
 796        }
 797        ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
 798        ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
 799        if (ret && dst) {
 800                src = dst->buf;
 801                len = dst->len;
 802        }
 803        return ret | ident_to_git(path, src, len, dst, ca.ident);
 804}
 805
 806void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
 807                              enum safe_crlf checksafe)
 808{
 809        struct conv_attrs ca;
 810        convert_attrs(&ca, path);
 811
 812        assert(ca.drv);
 813        assert(ca.drv->clean);
 814
 815        if (!apply_filter(path, NULL, 0, fd, dst, ca.drv->clean))
 816                die("%s: clean filter '%s' failed", path, ca.drv->name);
 817
 818        ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
 819        crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
 820        ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
 821}
 822
 823static int convert_to_working_tree_internal(const char *path, const char *src,
 824                                            size_t len, struct strbuf *dst,
 825                                            int normalizing)
 826{
 827        int ret = 0, ret_filter = 0;
 828        const char *filter = NULL;
 829        int required = 0;
 830        struct conv_attrs ca;
 831
 832        convert_attrs(&ca, path);
 833        if (ca.drv) {
 834                filter = ca.drv->smudge;
 835                required = ca.drv->required;
 836        }
 837
 838        ret |= ident_to_worktree(path, src, len, dst, ca.ident);
 839        if (ret) {
 840                src = dst->buf;
 841                len = dst->len;
 842        }
 843        /*
 844         * CRLF conversion can be skipped if normalizing, unless there
 845         * is a smudge filter.  The filter might expect CRLFs.
 846         */
 847        if (filter || !normalizing) {
 848                ca.crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
 849                ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
 850                if (ret) {
 851                        src = dst->buf;
 852                        len = dst->len;
 853                }
 854        }
 855
 856        ret_filter = apply_filter(path, src, len, -1, dst, filter);
 857        if (!ret_filter && required)
 858                die("%s: smudge filter %s failed", path, ca.drv->name);
 859
 860        return ret | ret_filter;
 861}
 862
 863int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
 864{
 865        return convert_to_working_tree_internal(path, src, len, dst, 0);
 866}
 867
 868int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
 869{
 870        int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
 871        if (ret) {
 872                src = dst->buf;
 873                len = dst->len;
 874        }
 875        return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_FALSE);
 876}
 877
 878/*****************************************************************
 879 *
 880 * Streaming conversion support
 881 *
 882 *****************************************************************/
 883
 884typedef int (*filter_fn)(struct stream_filter *,
 885                         const char *input, size_t *isize_p,
 886                         char *output, size_t *osize_p);
 887typedef void (*free_fn)(struct stream_filter *);
 888
 889struct stream_filter_vtbl {
 890        filter_fn filter;
 891        free_fn free;
 892};
 893
 894struct stream_filter {
 895        struct stream_filter_vtbl *vtbl;
 896};
 897
 898static int null_filter_fn(struct stream_filter *filter,
 899                          const char *input, size_t *isize_p,
 900                          char *output, size_t *osize_p)
 901{
 902        size_t count;
 903
 904        if (!input)
 905                return 0; /* we do not keep any states */
 906        count = *isize_p;
 907        if (*osize_p < count)
 908                count = *osize_p;
 909        if (count) {
 910                memmove(output, input, count);
 911                *isize_p -= count;
 912                *osize_p -= count;
 913        }
 914        return 0;
 915}
 916
 917static void null_free_fn(struct stream_filter *filter)
 918{
 919        ; /* nothing -- null instances are shared */
 920}
 921
 922static struct stream_filter_vtbl null_vtbl = {
 923        null_filter_fn,
 924        null_free_fn,
 925};
 926
 927static struct stream_filter null_filter_singleton = {
 928        &null_vtbl,
 929};
 930
 931int is_null_stream_filter(struct stream_filter *filter)
 932{
 933        return filter == &null_filter_singleton;
 934}
 935
 936
 937/*
 938 * LF-to-CRLF filter
 939 */
 940
 941struct lf_to_crlf_filter {
 942        struct stream_filter filter;
 943        unsigned has_held:1;
 944        char held;
 945};
 946
 947static int lf_to_crlf_filter_fn(struct stream_filter *filter,
 948                                const char *input, size_t *isize_p,
 949                                char *output, size_t *osize_p)
 950{
 951        size_t count, o = 0;
 952        struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
 953
 954        /*
 955         * We may be holding onto the CR to see if it is followed by a
 956         * LF, in which case we would need to go to the main loop.
 957         * Otherwise, just emit it to the output stream.
 958         */
 959        if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
 960                output[o++] = lf_to_crlf->held;
 961                lf_to_crlf->has_held = 0;
 962        }
 963
 964        /* We are told to drain */
 965        if (!input) {
 966                *osize_p -= o;
 967                return 0;
 968        }
 969
 970        count = *isize_p;
 971        if (count || lf_to_crlf->has_held) {
 972                size_t i;
 973                int was_cr = 0;
 974
 975                if (lf_to_crlf->has_held) {
 976                        was_cr = 1;
 977                        lf_to_crlf->has_held = 0;
 978                }
 979
 980                for (i = 0; o < *osize_p && i < count; i++) {
 981                        char ch = input[i];
 982
 983                        if (ch == '\n') {
 984                                output[o++] = '\r';
 985                        } else if (was_cr) {
 986                                /*
 987                                 * Previous round saw CR and it is not followed
 988                                 * by a LF; emit the CR before processing the
 989                                 * current character.
 990                                 */
 991                                output[o++] = '\r';
 992                        }
 993
 994                        /*
 995                         * We may have consumed the last output slot,
 996                         * in which case we need to break out of this
 997                         * loop; hold the current character before
 998                         * returning.
 999                         */
1000                        if (*osize_p <= o) {
1001                                lf_to_crlf->has_held = 1;
1002                                lf_to_crlf->held = ch;
1003                                continue; /* break but increment i */
1004                        }
1005
1006                        if (ch == '\r') {
1007                                was_cr = 1;
1008                                continue;
1009                        }
1010
1011                        was_cr = 0;
1012                        output[o++] = ch;
1013                }
1014
1015                *osize_p -= o;
1016                *isize_p -= i;
1017
1018                if (!lf_to_crlf->has_held && was_cr) {
1019                        lf_to_crlf->has_held = 1;
1020                        lf_to_crlf->held = '\r';
1021                }
1022        }
1023        return 0;
1024}
1025
1026static void lf_to_crlf_free_fn(struct stream_filter *filter)
1027{
1028        free(filter);
1029}
1030
1031static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1032        lf_to_crlf_filter_fn,
1033        lf_to_crlf_free_fn,
1034};
1035
1036static struct stream_filter *lf_to_crlf_filter(void)
1037{
1038        struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1039
1040        lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1041        return (struct stream_filter *)lf_to_crlf;
1042}
1043
1044/*
1045 * Cascade filter
1046 */
1047#define FILTER_BUFFER 1024
1048struct cascade_filter {
1049        struct stream_filter filter;
1050        struct stream_filter *one;
1051        struct stream_filter *two;
1052        char buf[FILTER_BUFFER];
1053        int end, ptr;
1054};
1055
1056static int cascade_filter_fn(struct stream_filter *filter,
1057                             const char *input, size_t *isize_p,
1058                             char *output, size_t *osize_p)
1059{
1060        struct cascade_filter *cas = (struct cascade_filter *) filter;
1061        size_t filled = 0;
1062        size_t sz = *osize_p;
1063        size_t to_feed, remaining;
1064
1065        /*
1066         * input -- (one) --> buf -- (two) --> output
1067         */
1068        while (filled < sz) {
1069                remaining = sz - filled;
1070
1071                /* do we already have something to feed two with? */
1072                if (cas->ptr < cas->end) {
1073                        to_feed = cas->end - cas->ptr;
1074                        if (stream_filter(cas->two,
1075                                          cas->buf + cas->ptr, &to_feed,
1076                                          output + filled, &remaining))
1077                                return -1;
1078                        cas->ptr += (cas->end - cas->ptr) - to_feed;
1079                        filled = sz - remaining;
1080                        continue;
1081                }
1082
1083                /* feed one from upstream and have it emit into our buffer */
1084                to_feed = input ? *isize_p : 0;
1085                if (input && !to_feed)
1086                        break;
1087                remaining = sizeof(cas->buf);
1088                if (stream_filter(cas->one,
1089                                  input, &to_feed,
1090                                  cas->buf, &remaining))
1091                        return -1;
1092                cas->end = sizeof(cas->buf) - remaining;
1093                cas->ptr = 0;
1094                if (input) {
1095                        size_t fed = *isize_p - to_feed;
1096                        *isize_p -= fed;
1097                        input += fed;
1098                }
1099
1100                /* do we know that we drained one completely? */
1101                if (input || cas->end)
1102                        continue;
1103
1104                /* tell two to drain; we have nothing more to give it */
1105                to_feed = 0;
1106                remaining = sz - filled;
1107                if (stream_filter(cas->two,
1108                                  NULL, &to_feed,
1109                                  output + filled, &remaining))
1110                        return -1;
1111                if (remaining == (sz - filled))
1112                        break; /* completely drained two */
1113                filled = sz - remaining;
1114        }
1115        *osize_p -= filled;
1116        return 0;
1117}
1118
1119static void cascade_free_fn(struct stream_filter *filter)
1120{
1121        struct cascade_filter *cas = (struct cascade_filter *)filter;
1122        free_stream_filter(cas->one);
1123        free_stream_filter(cas->two);
1124        free(filter);
1125}
1126
1127static struct stream_filter_vtbl cascade_vtbl = {
1128        cascade_filter_fn,
1129        cascade_free_fn,
1130};
1131
1132static struct stream_filter *cascade_filter(struct stream_filter *one,
1133                                            struct stream_filter *two)
1134{
1135        struct cascade_filter *cascade;
1136
1137        if (!one || is_null_stream_filter(one))
1138                return two;
1139        if (!two || is_null_stream_filter(two))
1140                return one;
1141
1142        cascade = xmalloc(sizeof(*cascade));
1143        cascade->one = one;
1144        cascade->two = two;
1145        cascade->end = cascade->ptr = 0;
1146        cascade->filter.vtbl = &cascade_vtbl;
1147        return (struct stream_filter *)cascade;
1148}
1149
1150/*
1151 * ident filter
1152 */
1153#define IDENT_DRAINING (-1)
1154#define IDENT_SKIPPING (-2)
1155struct ident_filter {
1156        struct stream_filter filter;
1157        struct strbuf left;
1158        int state;
1159        char ident[45]; /* ": x40 $" */
1160};
1161
1162static int is_foreign_ident(const char *str)
1163{
1164        int i;
1165
1166        if (!skip_prefix(str, "$Id: ", &str))
1167                return 0;
1168        for (i = 0; str[i]; i++) {
1169                if (isspace(str[i]) && str[i+1] != '$')
1170                        return 1;
1171        }
1172        return 0;
1173}
1174
1175static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1176{
1177        size_t to_drain = ident->left.len;
1178
1179        if (*osize_p < to_drain)
1180                to_drain = *osize_p;
1181        if (to_drain) {
1182                memcpy(*output_p, ident->left.buf, to_drain);
1183                strbuf_remove(&ident->left, 0, to_drain);
1184                *output_p += to_drain;
1185                *osize_p -= to_drain;
1186        }
1187        if (!ident->left.len)
1188                ident->state = 0;
1189}
1190
1191static int ident_filter_fn(struct stream_filter *filter,
1192                           const char *input, size_t *isize_p,
1193                           char *output, size_t *osize_p)
1194{
1195        struct ident_filter *ident = (struct ident_filter *)filter;
1196        static const char head[] = "$Id";
1197
1198        if (!input) {
1199                /* drain upon eof */
1200                switch (ident->state) {
1201                default:
1202                        strbuf_add(&ident->left, head, ident->state);
1203                case IDENT_SKIPPING:
1204                        /* fallthru */
1205                case IDENT_DRAINING:
1206                        ident_drain(ident, &output, osize_p);
1207                }
1208                return 0;
1209        }
1210
1211        while (*isize_p || (ident->state == IDENT_DRAINING)) {
1212                int ch;
1213
1214                if (ident->state == IDENT_DRAINING) {
1215                        ident_drain(ident, &output, osize_p);
1216                        if (!*osize_p)
1217                                break;
1218                        continue;
1219                }
1220
1221                ch = *(input++);
1222                (*isize_p)--;
1223
1224                if (ident->state == IDENT_SKIPPING) {
1225                        /*
1226                         * Skipping until '$' or LF, but keeping them
1227                         * in case it is a foreign ident.
1228                         */
1229                        strbuf_addch(&ident->left, ch);
1230                        if (ch != '\n' && ch != '$')
1231                                continue;
1232                        if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1233                                strbuf_setlen(&ident->left, sizeof(head) - 1);
1234                                strbuf_addstr(&ident->left, ident->ident);
1235                        }
1236                        ident->state = IDENT_DRAINING;
1237                        continue;
1238                }
1239
1240                if (ident->state < sizeof(head) &&
1241                    head[ident->state] == ch) {
1242                        ident->state++;
1243                        continue;
1244                }
1245
1246                if (ident->state)
1247                        strbuf_add(&ident->left, head, ident->state);
1248                if (ident->state == sizeof(head) - 1) {
1249                        if (ch != ':' && ch != '$') {
1250                                strbuf_addch(&ident->left, ch);
1251                                ident->state = 0;
1252                                continue;
1253                        }
1254
1255                        if (ch == ':') {
1256                                strbuf_addch(&ident->left, ch);
1257                                ident->state = IDENT_SKIPPING;
1258                        } else {
1259                                strbuf_addstr(&ident->left, ident->ident);
1260                                ident->state = IDENT_DRAINING;
1261                        }
1262                        continue;
1263                }
1264
1265                strbuf_addch(&ident->left, ch);
1266                ident->state = IDENT_DRAINING;
1267        }
1268        return 0;
1269}
1270
1271static void ident_free_fn(struct stream_filter *filter)
1272{
1273        struct ident_filter *ident = (struct ident_filter *)filter;
1274        strbuf_release(&ident->left);
1275        free(filter);
1276}
1277
1278static struct stream_filter_vtbl ident_vtbl = {
1279        ident_filter_fn,
1280        ident_free_fn,
1281};
1282
1283static struct stream_filter *ident_filter(const unsigned char *sha1)
1284{
1285        struct ident_filter *ident = xmalloc(sizeof(*ident));
1286
1287        sprintf(ident->ident, ": %s $", sha1_to_hex(sha1));
1288        strbuf_init(&ident->left, 0);
1289        ident->filter.vtbl = &ident_vtbl;
1290        ident->state = 0;
1291        return (struct stream_filter *)ident;
1292}
1293
1294/*
1295 * Return an appropriately constructed filter for the path, or NULL if
1296 * the contents cannot be filtered without reading the whole thing
1297 * in-core.
1298 *
1299 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1300 * large binary blob you would want us not to slurp into the memory!
1301 */
1302struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1303{
1304        struct conv_attrs ca;
1305        enum crlf_action crlf_action;
1306        struct stream_filter *filter = NULL;
1307
1308        convert_attrs(&ca, path);
1309
1310        if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1311                return filter;
1312
1313        if (ca.ident)
1314                filter = ident_filter(sha1);
1315
1316        crlf_action = input_crlf_action(ca.crlf_action, ca.eol_attr);
1317
1318        if ((crlf_action == CRLF_BINARY) || (crlf_action == CRLF_INPUT) ||
1319            (crlf_action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE))
1320                filter = cascade_filter(filter, &null_filter_singleton);
1321
1322        else if (output_eol(crlf_action) == EOL_CRLF &&
1323                 !(crlf_action == CRLF_AUTO || crlf_action == CRLF_GUESS))
1324                filter = cascade_filter(filter, lf_to_crlf_filter());
1325
1326        return filter;
1327}
1328
1329void free_stream_filter(struct stream_filter *filter)
1330{
1331        filter->vtbl->free(filter);
1332}
1333
1334int stream_filter(struct stream_filter *filter,
1335                  const char *input, size_t *isize_p,
1336                  char *output, size_t *osize_p)
1337{
1338        return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
1339}