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