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