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