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