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