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