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