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