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