Merge branch 'wd/rebase-conflict-guide'
[git/debian.git] / convert.c
blobdeaf0ba7b30ffa4e0003649985ef1594ee2ac049
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"
12 * convert.c - convert a file when checking it out and checking it in.
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.
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
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
36 struct text_stat {
37 /* NUL, CR, LF and CRLF counts */
38 unsigned nul, lonecr, lonelf, crlf;
40 /* These are just approximations! */
41 unsigned printable, nonprintable;
44 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
46 unsigned long i;
48 memset(stats, 0, sizeof(*stats));
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;
60 if (c == '\n') {
61 stats->lonelf++;
62 continue;
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++;
80 else
81 stats->printable++;
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--;
90 * The same heuristics as diff.c::mmfile_is_binary()
91 * We treat files with bare CR as binary
93 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
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;
104 static unsigned int gather_convert_stats(const char *data, unsigned long size)
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;
118 return ret;
121 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
123 unsigned int convert_stats = gather_convert_stats(data, size);
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";
139 const char *get_cached_convert_stats_ascii(const struct index_state *istate,
140 const char *path)
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;
150 const char *get_wt_convert_stats_ascii(const char *path)
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;
160 static int text_eol_is_crlf(void)
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;
173 static enum eol output_eol(enum crlf_action crlf_action)
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;
192 warning("Illegal crlf_action %d\n", (int)crlf_action);
193 return core_eol;
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)
200 if (old_stats->crlf && !new_stats->crlf ) {
202 * CRLFs would not be restored by checkout
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 ) {
212 * CRLFs would be added by checkout
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);
223 static int has_cr_in_index(const struct index_state *istate, const char *path)
225 unsigned long sz;
226 void *data;
227 int has_cr;
229 data = read_blob_data_from_index(istate, path, &sz);
230 if (!data)
231 return 0;
232 has_cr = memchr(data, '\r', sz) != NULL;
233 free(data);
234 return has_cr;
237 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
238 enum crlf_action crlf_action)
240 if (output_eol(crlf_action) != EOL_CRLF)
241 return 0;
242 /* No "naked" LF? Nothing to convert, regardless. */
243 if (!stats->lonelf)
244 return 0;
246 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
247 /* If we have any CR or CRLF line endings, we do not touch it */
248 /* This is the new safer autocrlf-handling */
249 if (stats->lonecr || stats->crlf)
250 return 0;
252 if (convert_is_binary(len, stats))
253 return 0;
255 return 1;
259 static int crlf_to_git(const struct index_state *istate,
260 const char *path, const char *src, size_t len,
261 struct strbuf *buf,
262 enum crlf_action crlf_action, enum safe_crlf checksafe)
264 struct text_stat stats;
265 char *dst;
266 int convert_crlf_into_lf;
268 if (crlf_action == CRLF_BINARY ||
269 (src && !len))
270 return 0;
273 * If we are doing a dry-run and have no source buffer, there is
274 * nothing to analyze; we must assume we would convert.
276 if (!buf && !src)
277 return 1;
279 gather_stats(src, len, &stats);
280 /* Optimization: No CRLF? Nothing to convert, regardless. */
281 convert_crlf_into_lf = !!stats.crlf;
283 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
284 if (convert_is_binary(len, &stats))
285 return 0;
287 * If the file in the index has any CR in it, do not
288 * convert. This is the new safer autocrlf handling,
289 * unless we want to renormalize in a merge or
290 * cherry-pick.
292 if ((checksafe != SAFE_CRLF_RENORMALIZE) &&
293 has_cr_in_index(istate, path))
294 convert_crlf_into_lf = 0;
296 if ((checksafe == SAFE_CRLF_WARN ||
297 (checksafe == SAFE_CRLF_FAIL)) && len) {
298 struct text_stat new_stats;
299 memcpy(&new_stats, &stats, sizeof(new_stats));
300 /* simulate "git add" */
301 if (convert_crlf_into_lf) {
302 new_stats.lonelf += new_stats.crlf;
303 new_stats.crlf = 0;
305 /* simulate "git checkout" */
306 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
307 new_stats.crlf += new_stats.lonelf;
308 new_stats.lonelf = 0;
310 check_safe_crlf(path, crlf_action, &stats, &new_stats, checksafe);
312 if (!convert_crlf_into_lf)
313 return 0;
316 * At this point all of our source analysis is done, and we are sure we
317 * would convert. If we are in dry-run mode, we can give an answer.
319 if (!buf)
320 return 1;
322 /* only grow if not in place */
323 if (strbuf_avail(buf) + buf->len < len)
324 strbuf_grow(buf, len - buf->len);
325 dst = buf->buf;
326 if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
328 * If we guessed, we already know we rejected a file with
329 * lone CR, and we can strip a CR without looking at what
330 * follow it.
332 do {
333 unsigned char c = *src++;
334 if (c != '\r')
335 *dst++ = c;
336 } while (--len);
337 } else {
338 do {
339 unsigned char c = *src++;
340 if (! (c == '\r' && (1 < len && *src == '\n')))
341 *dst++ = c;
342 } while (--len);
344 strbuf_setlen(buf, dst - buf->buf);
345 return 1;
348 static int crlf_to_worktree(const char *path, const char *src, size_t len,
349 struct strbuf *buf, enum crlf_action crlf_action)
351 char *to_free = NULL;
352 struct text_stat stats;
354 if (!len || output_eol(crlf_action) != EOL_CRLF)
355 return 0;
357 gather_stats(src, len, &stats);
358 if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
359 return 0;
361 /* are we "faking" in place editing ? */
362 if (src == buf->buf)
363 to_free = strbuf_detach(buf, NULL);
365 strbuf_grow(buf, len + stats.lonelf);
366 for (;;) {
367 const char *nl = memchr(src, '\n', len);
368 if (!nl)
369 break;
370 if (nl > src && nl[-1] == '\r') {
371 strbuf_add(buf, src, nl + 1 - src);
372 } else {
373 strbuf_add(buf, src, nl - src);
374 strbuf_addstr(buf, "\r\n");
376 len -= nl + 1 - src;
377 src = nl + 1;
379 strbuf_add(buf, src, len);
381 free(to_free);
382 return 1;
385 struct filter_params {
386 const char *src;
387 unsigned long size;
388 int fd;
389 const char *cmd;
390 const char *path;
393 static int filter_buffer_or_fd(int in, int out, void *data)
396 * Spawn cmd and feed the buffer contents through its stdin.
398 struct child_process child_process = CHILD_PROCESS_INIT;
399 struct filter_params *params = (struct filter_params *)data;
400 int write_err, status;
401 const char *argv[] = { NULL, NULL };
403 /* apply % substitution to cmd */
404 struct strbuf cmd = STRBUF_INIT;
405 struct strbuf path = STRBUF_INIT;
406 struct strbuf_expand_dict_entry dict[] = {
407 { "f", NULL, },
408 { NULL, NULL, },
411 /* quote the path to preserve spaces, etc. */
412 sq_quote_buf(&path, params->path);
413 dict[0].value = path.buf;
415 /* expand all %f with the quoted path */
416 strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
417 strbuf_release(&path);
419 argv[0] = cmd.buf;
421 child_process.argv = argv;
422 child_process.use_shell = 1;
423 child_process.in = -1;
424 child_process.out = out;
426 if (start_command(&child_process))
427 return error("cannot fork to run external filter '%s'", params->cmd);
429 sigchain_push(SIGPIPE, SIG_IGN);
431 if (params->src) {
432 write_err = (write_in_full(child_process.in,
433 params->src, params->size) < 0);
434 if (errno == EPIPE)
435 write_err = 0;
436 } else {
437 write_err = copy_fd(params->fd, child_process.in);
438 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
439 write_err = 0;
442 if (close(child_process.in))
443 write_err = 1;
444 if (write_err)
445 error("cannot feed the input to external filter '%s'", params->cmd);
447 sigchain_pop(SIGPIPE);
449 status = finish_command(&child_process);
450 if (status)
451 error("external filter '%s' failed %d", params->cmd, status);
453 strbuf_release(&cmd);
454 return (write_err || status);
457 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
458 struct strbuf *dst, const char *cmd)
461 * Create a pipeline to have the command filter the buffer's
462 * contents.
464 * (child --> cmd) --> us
466 int err = 0;
467 struct strbuf nbuf = STRBUF_INIT;
468 struct async async;
469 struct filter_params params;
471 memset(&async, 0, sizeof(async));
472 async.proc = filter_buffer_or_fd;
473 async.data = &params;
474 async.out = -1;
475 params.src = src;
476 params.size = len;
477 params.fd = fd;
478 params.cmd = cmd;
479 params.path = path;
481 fflush(NULL);
482 if (start_async(&async))
483 return 0; /* error was already reported */
485 if (strbuf_read(&nbuf, async.out, len) < 0) {
486 err = error("read from external filter '%s' failed", cmd);
488 if (close(async.out)) {
489 err = error("read from external filter '%s' failed", cmd);
491 if (finish_async(&async)) {
492 err = error("external filter '%s' failed", cmd);
495 if (!err) {
496 strbuf_swap(dst, &nbuf);
498 strbuf_release(&nbuf);
499 return !err;
502 #define CAP_CLEAN (1u<<0)
503 #define CAP_SMUDGE (1u<<1)
505 struct cmd2process {
506 struct subprocess_entry subprocess; /* must be the first member! */
507 unsigned int supported_capabilities;
510 static int subprocess_map_initialized;
511 static struct hashmap subprocess_map;
513 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
515 int err;
516 struct cmd2process *entry = (struct cmd2process *)subprocess;
517 struct string_list cap_list = STRING_LIST_INIT_NODUP;
518 char *cap_buf;
519 const char *cap_name;
520 struct child_process *process = &subprocess->process;
521 const char *cmd = subprocess->cmd;
523 sigchain_push(SIGPIPE, SIG_IGN);
525 err = packet_writel(process->in, "git-filter-client", "version=2", NULL);
526 if (err)
527 goto done;
529 err = strcmp(packet_read_line(process->out, NULL), "git-filter-server");
530 if (err) {
531 error("external filter '%s' does not support filter protocol version 2", cmd);
532 goto done;
534 err = strcmp(packet_read_line(process->out, NULL), "version=2");
535 if (err)
536 goto done;
537 err = packet_read_line(process->out, NULL) != NULL;
538 if (err)
539 goto done;
541 err = packet_writel(process->in, "capability=clean", "capability=smudge", NULL);
543 for (;;) {
544 cap_buf = packet_read_line(process->out, NULL);
545 if (!cap_buf)
546 break;
547 string_list_split_in_place(&cap_list, cap_buf, '=', 1);
549 if (cap_list.nr != 2 || strcmp(cap_list.items[0].string, "capability"))
550 continue;
552 cap_name = cap_list.items[1].string;
553 if (!strcmp(cap_name, "clean")) {
554 entry->supported_capabilities |= CAP_CLEAN;
555 } else if (!strcmp(cap_name, "smudge")) {
556 entry->supported_capabilities |= CAP_SMUDGE;
557 } else {
558 warning(
559 "external filter '%s' requested unsupported filter capability '%s'",
560 cmd, cap_name
564 string_list_clear(&cap_list, 0);
567 done:
568 sigchain_pop(SIGPIPE);
570 return err;
573 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
574 int fd, struct strbuf *dst, const char *cmd,
575 const unsigned int wanted_capability)
577 int err;
578 struct cmd2process *entry;
579 struct child_process *process;
580 struct strbuf nbuf = STRBUF_INIT;
581 struct strbuf filter_status = STRBUF_INIT;
582 const char *filter_type;
584 if (!subprocess_map_initialized) {
585 subprocess_map_initialized = 1;
586 hashmap_init(&subprocess_map, (hashmap_cmp_fn) cmd2process_cmp,
587 NULL, 0);
588 entry = NULL;
589 } else {
590 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
593 fflush(NULL);
595 if (!entry) {
596 entry = xmalloc(sizeof(*entry));
597 entry->supported_capabilities = 0;
599 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
600 free(entry);
601 return 0;
604 process = &entry->subprocess.process;
606 if (!(wanted_capability & entry->supported_capabilities))
607 return 0;
609 if (CAP_CLEAN & wanted_capability)
610 filter_type = "clean";
611 else if (CAP_SMUDGE & wanted_capability)
612 filter_type = "smudge";
613 else
614 die("unexpected filter type");
616 sigchain_push(SIGPIPE, SIG_IGN);
618 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
619 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
620 if (err)
621 goto done;
623 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
624 if (err) {
625 error("path name too long for external filter");
626 goto done;
629 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
630 if (err)
631 goto done;
633 err = packet_flush_gently(process->in);
634 if (err)
635 goto done;
637 if (fd >= 0)
638 err = write_packetized_from_fd(fd, process->in);
639 else
640 err = write_packetized_from_buf(src, len, process->in);
641 if (err)
642 goto done;
644 err = subprocess_read_status(process->out, &filter_status);
645 if (err)
646 goto done;
648 err = strcmp(filter_status.buf, "success");
649 if (err)
650 goto done;
652 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
653 if (err)
654 goto done;
656 err = subprocess_read_status(process->out, &filter_status);
657 if (err)
658 goto done;
660 err = strcmp(filter_status.buf, "success");
662 done:
663 sigchain_pop(SIGPIPE);
665 if (err) {
666 if (!strcmp(filter_status.buf, "error")) {
667 /* The filter signaled a problem with the file. */
668 } else if (!strcmp(filter_status.buf, "abort")) {
670 * The filter signaled a permanent problem. Don't try to filter
671 * files with the same command for the lifetime of the current
672 * Git process.
674 entry->supported_capabilities &= ~wanted_capability;
675 } else {
677 * Something went wrong with the protocol filter.
678 * Force shutdown and restart if another blob requires filtering.
680 error("external filter '%s' failed", cmd);
681 subprocess_stop(&subprocess_map, &entry->subprocess);
682 free(entry);
684 } else {
685 strbuf_swap(dst, &nbuf);
687 strbuf_release(&nbuf);
688 return !err;
691 static struct convert_driver {
692 const char *name;
693 struct convert_driver *next;
694 const char *smudge;
695 const char *clean;
696 const char *process;
697 int required;
698 } *user_convert, **user_convert_tail;
700 static int apply_filter(const char *path, const char *src, size_t len,
701 int fd, struct strbuf *dst, struct convert_driver *drv,
702 const unsigned int wanted_capability)
704 const char *cmd = NULL;
706 if (!drv)
707 return 0;
709 if (!dst)
710 return 1;
712 if ((CAP_CLEAN & wanted_capability) && !drv->process && drv->clean)
713 cmd = drv->clean;
714 else if ((CAP_SMUDGE & wanted_capability) && !drv->process && drv->smudge)
715 cmd = drv->smudge;
717 if (cmd && *cmd)
718 return apply_single_file_filter(path, src, len, fd, dst, cmd);
719 else if (drv->process && *drv->process)
720 return apply_multi_file_filter(path, src, len, fd, dst, drv->process, wanted_capability);
722 return 0;
725 static int read_convert_config(const char *var, const char *value, void *cb)
727 const char *key, *name;
728 int namelen;
729 struct convert_driver *drv;
732 * External conversion drivers are configured using
733 * "filter.<name>.variable".
735 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
736 return 0;
737 for (drv = user_convert; drv; drv = drv->next)
738 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
739 break;
740 if (!drv) {
741 drv = xcalloc(1, sizeof(struct convert_driver));
742 drv->name = xmemdupz(name, namelen);
743 *user_convert_tail = drv;
744 user_convert_tail = &(drv->next);
748 * filter.<name>.smudge and filter.<name>.clean specifies
749 * the command line:
751 * command-line
753 * The command-line will not be interpolated in any way.
756 if (!strcmp("smudge", key))
757 return git_config_string(&drv->smudge, var, value);
759 if (!strcmp("clean", key))
760 return git_config_string(&drv->clean, var, value);
762 if (!strcmp("process", key))
763 return git_config_string(&drv->process, var, value);
765 if (!strcmp("required", key)) {
766 drv->required = git_config_bool(var, value);
767 return 0;
770 return 0;
773 static int count_ident(const char *cp, unsigned long size)
776 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
778 int cnt = 0;
779 char ch;
781 while (size) {
782 ch = *cp++;
783 size--;
784 if (ch != '$')
785 continue;
786 if (size < 3)
787 break;
788 if (memcmp("Id", cp, 2))
789 continue;
790 ch = cp[2];
791 cp += 3;
792 size -= 3;
793 if (ch == '$')
794 cnt++; /* $Id$ */
795 if (ch != ':')
796 continue;
799 * "$Id: ... "; scan up to the closing dollar sign and discard.
801 while (size) {
802 ch = *cp++;
803 size--;
804 if (ch == '$') {
805 cnt++;
806 break;
808 if (ch == '\n')
809 break;
812 return cnt;
815 static int ident_to_git(const char *path, const char *src, size_t len,
816 struct strbuf *buf, int ident)
818 char *dst, *dollar;
820 if (!ident || (src && !count_ident(src, len)))
821 return 0;
823 if (!buf)
824 return 1;
826 /* only grow if not in place */
827 if (strbuf_avail(buf) + buf->len < len)
828 strbuf_grow(buf, len - buf->len);
829 dst = buf->buf;
830 for (;;) {
831 dollar = memchr(src, '$', len);
832 if (!dollar)
833 break;
834 memmove(dst, src, dollar + 1 - src);
835 dst += dollar + 1 - src;
836 len -= dollar + 1 - src;
837 src = dollar + 1;
839 if (len > 3 && !memcmp(src, "Id:", 3)) {
840 dollar = memchr(src + 3, '$', len - 3);
841 if (!dollar)
842 break;
843 if (memchr(src + 3, '\n', dollar - src - 3)) {
844 /* Line break before the next dollar. */
845 continue;
848 memcpy(dst, "Id$", 3);
849 dst += 3;
850 len -= dollar + 1 - src;
851 src = dollar + 1;
854 memmove(dst, src, len);
855 strbuf_setlen(buf, dst + len - buf->buf);
856 return 1;
859 static int ident_to_worktree(const char *path, const char *src, size_t len,
860 struct strbuf *buf, int ident)
862 unsigned char sha1[20];
863 char *to_free = NULL, *dollar, *spc;
864 int cnt;
866 if (!ident)
867 return 0;
869 cnt = count_ident(src, len);
870 if (!cnt)
871 return 0;
873 /* are we "faking" in place editing ? */
874 if (src == buf->buf)
875 to_free = strbuf_detach(buf, NULL);
876 hash_sha1_file(src, len, "blob", sha1);
878 strbuf_grow(buf, len + cnt * 43);
879 for (;;) {
880 /* step 1: run to the next '$' */
881 dollar = memchr(src, '$', len);
882 if (!dollar)
883 break;
884 strbuf_add(buf, src, dollar + 1 - src);
885 len -= dollar + 1 - src;
886 src = dollar + 1;
888 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
889 if (len < 3 || memcmp("Id", src, 2))
890 continue;
892 /* step 3: skip over Id$ or Id:xxxxx$ */
893 if (src[2] == '$') {
894 src += 3;
895 len -= 3;
896 } else if (src[2] == ':') {
898 * It's possible that an expanded Id has crept its way into the
899 * repository, we cope with that by stripping the expansion out.
900 * This is probably not a good idea, since it will cause changes
901 * on checkout, which won't go away by stash, but let's keep it
902 * for git-style ids.
904 dollar = memchr(src + 3, '$', len - 3);
905 if (!dollar) {
906 /* incomplete keyword, no more '$', so just quit the loop */
907 break;
910 if (memchr(src + 3, '\n', dollar - src - 3)) {
911 /* Line break before the next dollar. */
912 continue;
915 spc = memchr(src + 4, ' ', dollar - src - 4);
916 if (spc && spc < dollar-1) {
917 /* There are spaces in unexpected places.
918 * This is probably an id from some other
919 * versioning system. Keep it for now.
921 continue;
924 len -= dollar + 1 - src;
925 src = dollar + 1;
926 } else {
927 /* it wasn't a "Id$" or "Id:xxxx$" */
928 continue;
931 /* step 4: substitute */
932 strbuf_addstr(buf, "Id: ");
933 strbuf_add(buf, sha1_to_hex(sha1), 40);
934 strbuf_addstr(buf, " $");
936 strbuf_add(buf, src, len);
938 free(to_free);
939 return 1;
942 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
944 const char *value = check->value;
946 if (ATTR_TRUE(value))
947 return CRLF_TEXT;
948 else if (ATTR_FALSE(value))
949 return CRLF_BINARY;
950 else if (ATTR_UNSET(value))
952 else if (!strcmp(value, "input"))
953 return CRLF_TEXT_INPUT;
954 else if (!strcmp(value, "auto"))
955 return CRLF_AUTO;
956 return CRLF_UNDEFINED;
959 static enum eol git_path_check_eol(struct attr_check_item *check)
961 const char *value = check->value;
963 if (ATTR_UNSET(value))
965 else if (!strcmp(value, "lf"))
966 return EOL_LF;
967 else if (!strcmp(value, "crlf"))
968 return EOL_CRLF;
969 return EOL_UNSET;
972 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
974 const char *value = check->value;
975 struct convert_driver *drv;
977 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
978 return NULL;
979 for (drv = user_convert; drv; drv = drv->next)
980 if (!strcmp(value, drv->name))
981 return drv;
982 return NULL;
985 static int git_path_check_ident(struct attr_check_item *check)
987 const char *value = check->value;
989 return !!ATTR_TRUE(value);
992 struct conv_attrs {
993 struct convert_driver *drv;
994 enum crlf_action attr_action; /* What attr says */
995 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
996 int ident;
999 static void convert_attrs(struct conv_attrs *ca, const char *path)
1001 static struct attr_check *check;
1003 if (!check) {
1004 check = attr_check_initl("crlf", "ident", "filter",
1005 "eol", "text", NULL);
1006 user_convert_tail = &user_convert;
1007 git_config(read_convert_config, NULL);
1010 if (!git_check_attr(path, check)) {
1011 struct attr_check_item *ccheck = check->items;
1012 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1013 if (ca->crlf_action == CRLF_UNDEFINED)
1014 ca->crlf_action = git_path_check_crlf(ccheck + 0);
1015 ca->attr_action = ca->crlf_action;
1016 ca->ident = git_path_check_ident(ccheck + 1);
1017 ca->drv = git_path_check_convert(ccheck + 2);
1018 if (ca->crlf_action != CRLF_BINARY) {
1019 enum eol eol_attr = git_path_check_eol(ccheck + 3);
1020 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1021 ca->crlf_action = CRLF_AUTO_INPUT;
1022 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1023 ca->crlf_action = CRLF_AUTO_CRLF;
1024 else if (eol_attr == EOL_LF)
1025 ca->crlf_action = CRLF_TEXT_INPUT;
1026 else if (eol_attr == EOL_CRLF)
1027 ca->crlf_action = CRLF_TEXT_CRLF;
1029 ca->attr_action = ca->crlf_action;
1030 } else {
1031 ca->drv = NULL;
1032 ca->crlf_action = CRLF_UNDEFINED;
1033 ca->ident = 0;
1035 if (ca->crlf_action == CRLF_TEXT)
1036 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1037 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1038 ca->crlf_action = CRLF_BINARY;
1039 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1040 ca->crlf_action = CRLF_AUTO_CRLF;
1041 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1042 ca->crlf_action = CRLF_AUTO_INPUT;
1045 int would_convert_to_git_filter_fd(const char *path)
1047 struct conv_attrs ca;
1049 convert_attrs(&ca, path);
1050 if (!ca.drv)
1051 return 0;
1054 * Apply a filter to an fd only if the filter is required to succeed.
1055 * We must die if the filter fails, because the original data before
1056 * filtering is not available.
1058 if (!ca.drv->required)
1059 return 0;
1061 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN);
1064 const char *get_convert_attr_ascii(const char *path)
1066 struct conv_attrs ca;
1068 convert_attrs(&ca, path);
1069 switch (ca.attr_action) {
1070 case CRLF_UNDEFINED:
1071 return "";
1072 case CRLF_BINARY:
1073 return "-text";
1074 case CRLF_TEXT:
1075 return "text";
1076 case CRLF_TEXT_INPUT:
1077 return "text eol=lf";
1078 case CRLF_TEXT_CRLF:
1079 return "text eol=crlf";
1080 case CRLF_AUTO:
1081 return "text=auto";
1082 case CRLF_AUTO_CRLF:
1083 return "text=auto eol=crlf";
1084 case CRLF_AUTO_INPUT:
1085 return "text=auto eol=lf";
1087 return "";
1090 int convert_to_git(const struct index_state *istate,
1091 const char *path, const char *src, size_t len,
1092 struct strbuf *dst, enum safe_crlf checksafe)
1094 int ret = 0;
1095 struct conv_attrs ca;
1097 convert_attrs(&ca, path);
1099 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN);
1100 if (!ret && ca.drv && ca.drv->required)
1101 die("%s: clean filter '%s' failed", path, ca.drv->name);
1103 if (ret && dst) {
1104 src = dst->buf;
1105 len = dst->len;
1107 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, checksafe);
1108 if (ret && dst) {
1109 src = dst->buf;
1110 len = dst->len;
1112 return ret | ident_to_git(path, src, len, dst, ca.ident);
1115 void convert_to_git_filter_fd(const struct index_state *istate,
1116 const char *path, int fd, struct strbuf *dst,
1117 enum safe_crlf checksafe)
1119 struct conv_attrs ca;
1120 convert_attrs(&ca, path);
1122 assert(ca.drv);
1123 assert(ca.drv->clean || ca.drv->process);
1125 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN))
1126 die("%s: clean filter '%s' failed", path, ca.drv->name);
1128 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
1129 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1132 static int convert_to_working_tree_internal(const char *path, const char *src,
1133 size_t len, struct strbuf *dst,
1134 int normalizing)
1136 int ret = 0, ret_filter = 0;
1137 struct conv_attrs ca;
1139 convert_attrs(&ca, path);
1141 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1142 if (ret) {
1143 src = dst->buf;
1144 len = dst->len;
1147 * CRLF conversion can be skipped if normalizing, unless there
1148 * is a smudge or process filter (even if the process filter doesn't
1149 * support smudge). The filters might expect CRLFs.
1151 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1152 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1153 if (ret) {
1154 src = dst->buf;
1155 len = dst->len;
1159 ret_filter = apply_filter(path, src, len, -1, dst, ca.drv, CAP_SMUDGE);
1160 if (!ret_filter && ca.drv && ca.drv->required)
1161 die("%s: smudge filter %s failed", path, ca.drv->name);
1163 return ret | ret_filter;
1166 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1168 return convert_to_working_tree_internal(path, src, len, dst, 0);
1171 int renormalize_buffer(const struct index_state *istate, const char *path,
1172 const char *src, size_t len, struct strbuf *dst)
1174 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
1175 if (ret) {
1176 src = dst->buf;
1177 len = dst->len;
1179 return ret | convert_to_git(istate, path, src, len, dst, SAFE_CRLF_RENORMALIZE);
1182 /*****************************************************************
1184 * Streaming conversion support
1186 *****************************************************************/
1188 typedef int (*filter_fn)(struct stream_filter *,
1189 const char *input, size_t *isize_p,
1190 char *output, size_t *osize_p);
1191 typedef void (*free_fn)(struct stream_filter *);
1193 struct stream_filter_vtbl {
1194 filter_fn filter;
1195 free_fn free;
1198 struct stream_filter {
1199 struct stream_filter_vtbl *vtbl;
1202 static int null_filter_fn(struct stream_filter *filter,
1203 const char *input, size_t *isize_p,
1204 char *output, size_t *osize_p)
1206 size_t count;
1208 if (!input)
1209 return 0; /* we do not keep any states */
1210 count = *isize_p;
1211 if (*osize_p < count)
1212 count = *osize_p;
1213 if (count) {
1214 memmove(output, input, count);
1215 *isize_p -= count;
1216 *osize_p -= count;
1218 return 0;
1221 static void null_free_fn(struct stream_filter *filter)
1223 ; /* nothing -- null instances are shared */
1226 static struct stream_filter_vtbl null_vtbl = {
1227 null_filter_fn,
1228 null_free_fn,
1231 static struct stream_filter null_filter_singleton = {
1232 &null_vtbl,
1235 int is_null_stream_filter(struct stream_filter *filter)
1237 return filter == &null_filter_singleton;
1242 * LF-to-CRLF filter
1245 struct lf_to_crlf_filter {
1246 struct stream_filter filter;
1247 unsigned has_held:1;
1248 char held;
1251 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1252 const char *input, size_t *isize_p,
1253 char *output, size_t *osize_p)
1255 size_t count, o = 0;
1256 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1259 * We may be holding onto the CR to see if it is followed by a
1260 * LF, in which case we would need to go to the main loop.
1261 * Otherwise, just emit it to the output stream.
1263 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1264 output[o++] = lf_to_crlf->held;
1265 lf_to_crlf->has_held = 0;
1268 /* We are told to drain */
1269 if (!input) {
1270 *osize_p -= o;
1271 return 0;
1274 count = *isize_p;
1275 if (count || lf_to_crlf->has_held) {
1276 size_t i;
1277 int was_cr = 0;
1279 if (lf_to_crlf->has_held) {
1280 was_cr = 1;
1281 lf_to_crlf->has_held = 0;
1284 for (i = 0; o < *osize_p && i < count; i++) {
1285 char ch = input[i];
1287 if (ch == '\n') {
1288 output[o++] = '\r';
1289 } else if (was_cr) {
1291 * Previous round saw CR and it is not followed
1292 * by a LF; emit the CR before processing the
1293 * current character.
1295 output[o++] = '\r';
1299 * We may have consumed the last output slot,
1300 * in which case we need to break out of this
1301 * loop; hold the current character before
1302 * returning.
1304 if (*osize_p <= o) {
1305 lf_to_crlf->has_held = 1;
1306 lf_to_crlf->held = ch;
1307 continue; /* break but increment i */
1310 if (ch == '\r') {
1311 was_cr = 1;
1312 continue;
1315 was_cr = 0;
1316 output[o++] = ch;
1319 *osize_p -= o;
1320 *isize_p -= i;
1322 if (!lf_to_crlf->has_held && was_cr) {
1323 lf_to_crlf->has_held = 1;
1324 lf_to_crlf->held = '\r';
1327 return 0;
1330 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1332 free(filter);
1335 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1336 lf_to_crlf_filter_fn,
1337 lf_to_crlf_free_fn,
1340 static struct stream_filter *lf_to_crlf_filter(void)
1342 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1344 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1345 return (struct stream_filter *)lf_to_crlf;
1349 * Cascade filter
1351 #define FILTER_BUFFER 1024
1352 struct cascade_filter {
1353 struct stream_filter filter;
1354 struct stream_filter *one;
1355 struct stream_filter *two;
1356 char buf[FILTER_BUFFER];
1357 int end, ptr;
1360 static int cascade_filter_fn(struct stream_filter *filter,
1361 const char *input, size_t *isize_p,
1362 char *output, size_t *osize_p)
1364 struct cascade_filter *cas = (struct cascade_filter *) filter;
1365 size_t filled = 0;
1366 size_t sz = *osize_p;
1367 size_t to_feed, remaining;
1370 * input -- (one) --> buf -- (two) --> output
1372 while (filled < sz) {
1373 remaining = sz - filled;
1375 /* do we already have something to feed two with? */
1376 if (cas->ptr < cas->end) {
1377 to_feed = cas->end - cas->ptr;
1378 if (stream_filter(cas->two,
1379 cas->buf + cas->ptr, &to_feed,
1380 output + filled, &remaining))
1381 return -1;
1382 cas->ptr += (cas->end - cas->ptr) - to_feed;
1383 filled = sz - remaining;
1384 continue;
1387 /* feed one from upstream and have it emit into our buffer */
1388 to_feed = input ? *isize_p : 0;
1389 if (input && !to_feed)
1390 break;
1391 remaining = sizeof(cas->buf);
1392 if (stream_filter(cas->one,
1393 input, &to_feed,
1394 cas->buf, &remaining))
1395 return -1;
1396 cas->end = sizeof(cas->buf) - remaining;
1397 cas->ptr = 0;
1398 if (input) {
1399 size_t fed = *isize_p - to_feed;
1400 *isize_p -= fed;
1401 input += fed;
1404 /* do we know that we drained one completely? */
1405 if (input || cas->end)
1406 continue;
1408 /* tell two to drain; we have nothing more to give it */
1409 to_feed = 0;
1410 remaining = sz - filled;
1411 if (stream_filter(cas->two,
1412 NULL, &to_feed,
1413 output + filled, &remaining))
1414 return -1;
1415 if (remaining == (sz - filled))
1416 break; /* completely drained two */
1417 filled = sz - remaining;
1419 *osize_p -= filled;
1420 return 0;
1423 static void cascade_free_fn(struct stream_filter *filter)
1425 struct cascade_filter *cas = (struct cascade_filter *)filter;
1426 free_stream_filter(cas->one);
1427 free_stream_filter(cas->two);
1428 free(filter);
1431 static struct stream_filter_vtbl cascade_vtbl = {
1432 cascade_filter_fn,
1433 cascade_free_fn,
1436 static struct stream_filter *cascade_filter(struct stream_filter *one,
1437 struct stream_filter *two)
1439 struct cascade_filter *cascade;
1441 if (!one || is_null_stream_filter(one))
1442 return two;
1443 if (!two || is_null_stream_filter(two))
1444 return one;
1446 cascade = xmalloc(sizeof(*cascade));
1447 cascade->one = one;
1448 cascade->two = two;
1449 cascade->end = cascade->ptr = 0;
1450 cascade->filter.vtbl = &cascade_vtbl;
1451 return (struct stream_filter *)cascade;
1455 * ident filter
1457 #define IDENT_DRAINING (-1)
1458 #define IDENT_SKIPPING (-2)
1459 struct ident_filter {
1460 struct stream_filter filter;
1461 struct strbuf left;
1462 int state;
1463 char ident[45]; /* ": x40 $" */
1466 static int is_foreign_ident(const char *str)
1468 int i;
1470 if (!skip_prefix(str, "$Id: ", &str))
1471 return 0;
1472 for (i = 0; str[i]; i++) {
1473 if (isspace(str[i]) && str[i+1] != '$')
1474 return 1;
1476 return 0;
1479 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1481 size_t to_drain = ident->left.len;
1483 if (*osize_p < to_drain)
1484 to_drain = *osize_p;
1485 if (to_drain) {
1486 memcpy(*output_p, ident->left.buf, to_drain);
1487 strbuf_remove(&ident->left, 0, to_drain);
1488 *output_p += to_drain;
1489 *osize_p -= to_drain;
1491 if (!ident->left.len)
1492 ident->state = 0;
1495 static int ident_filter_fn(struct stream_filter *filter,
1496 const char *input, size_t *isize_p,
1497 char *output, size_t *osize_p)
1499 struct ident_filter *ident = (struct ident_filter *)filter;
1500 static const char head[] = "$Id";
1502 if (!input) {
1503 /* drain upon eof */
1504 switch (ident->state) {
1505 default:
1506 strbuf_add(&ident->left, head, ident->state);
1507 case IDENT_SKIPPING:
1508 /* fallthru */
1509 case IDENT_DRAINING:
1510 ident_drain(ident, &output, osize_p);
1512 return 0;
1515 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1516 int ch;
1518 if (ident->state == IDENT_DRAINING) {
1519 ident_drain(ident, &output, osize_p);
1520 if (!*osize_p)
1521 break;
1522 continue;
1525 ch = *(input++);
1526 (*isize_p)--;
1528 if (ident->state == IDENT_SKIPPING) {
1530 * Skipping until '$' or LF, but keeping them
1531 * in case it is a foreign ident.
1533 strbuf_addch(&ident->left, ch);
1534 if (ch != '\n' && ch != '$')
1535 continue;
1536 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1537 strbuf_setlen(&ident->left, sizeof(head) - 1);
1538 strbuf_addstr(&ident->left, ident->ident);
1540 ident->state = IDENT_DRAINING;
1541 continue;
1544 if (ident->state < sizeof(head) &&
1545 head[ident->state] == ch) {
1546 ident->state++;
1547 continue;
1550 if (ident->state)
1551 strbuf_add(&ident->left, head, ident->state);
1552 if (ident->state == sizeof(head) - 1) {
1553 if (ch != ':' && ch != '$') {
1554 strbuf_addch(&ident->left, ch);
1555 ident->state = 0;
1556 continue;
1559 if (ch == ':') {
1560 strbuf_addch(&ident->left, ch);
1561 ident->state = IDENT_SKIPPING;
1562 } else {
1563 strbuf_addstr(&ident->left, ident->ident);
1564 ident->state = IDENT_DRAINING;
1566 continue;
1569 strbuf_addch(&ident->left, ch);
1570 ident->state = IDENT_DRAINING;
1572 return 0;
1575 static void ident_free_fn(struct stream_filter *filter)
1577 struct ident_filter *ident = (struct ident_filter *)filter;
1578 strbuf_release(&ident->left);
1579 free(filter);
1582 static struct stream_filter_vtbl ident_vtbl = {
1583 ident_filter_fn,
1584 ident_free_fn,
1587 static struct stream_filter *ident_filter(const unsigned char *sha1)
1589 struct ident_filter *ident = xmalloc(sizeof(*ident));
1591 xsnprintf(ident->ident, sizeof(ident->ident),
1592 ": %s $", sha1_to_hex(sha1));
1593 strbuf_init(&ident->left, 0);
1594 ident->filter.vtbl = &ident_vtbl;
1595 ident->state = 0;
1596 return (struct stream_filter *)ident;
1600 * Return an appropriately constructed filter for the path, or NULL if
1601 * the contents cannot be filtered without reading the whole thing
1602 * in-core.
1604 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1605 * large binary blob you would want us not to slurp into the memory!
1607 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1609 struct conv_attrs ca;
1610 struct stream_filter *filter = NULL;
1612 convert_attrs(&ca, path);
1613 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1614 return NULL;
1616 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1617 return NULL;
1619 if (ca.ident)
1620 filter = ident_filter(sha1);
1622 if (output_eol(ca.crlf_action) == EOL_CRLF)
1623 filter = cascade_filter(filter, lf_to_crlf_filter());
1624 else
1625 filter = cascade_filter(filter, &null_filter_singleton);
1627 return filter;
1630 void free_stream_filter(struct stream_filter *filter)
1632 filter->vtbl->free(filter);
1635 int stream_filter(struct stream_filter *filter,
1636 const char *input, size_t *isize_p,
1637 char *output, size_t *osize_p)
1639 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);