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