Merge branch 'maint'
[git/mingw/4msysgit/kblees.git] / convert.c
blob01de9a84c21b31a0120065a32a386f27321cdf7b
1 #include "cache.h"
2 #include "attr.h"
3 #include "run-command.h"
5 /*
6 * convert.c - convert a file when checking it out and checking it in.
8 * This should use the pathname to decide on whether it wants to do some
9 * more interesting conversions (automatic gzip/unzip, general format
10 * conversions etc etc), but by default it just does automatic CRLF<->LF
11 * translation when the "text" attribute or "auto_crlf" option is set.
14 enum action {
15 CRLF_GUESS = -1,
16 CRLF_BINARY = 0,
17 CRLF_TEXT,
18 CRLF_INPUT,
19 CRLF_CRLF,
20 CRLF_AUTO,
23 struct text_stat {
24 /* NUL, CR, LF and CRLF counts */
25 unsigned nul, cr, lf, crlf;
27 /* These are just approximations! */
28 unsigned printable, nonprintable;
31 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
33 unsigned long i;
35 memset(stats, 0, sizeof(*stats));
37 for (i = 0; i < size; i++) {
38 unsigned char c = buf[i];
39 if (c == '\r') {
40 stats->cr++;
41 if (i+1 < size && buf[i+1] == '\n')
42 stats->crlf++;
43 continue;
45 if (c == '\n') {
46 stats->lf++;
47 continue;
49 if (c == 127)
50 /* DEL */
51 stats->nonprintable++;
52 else if (c < 32) {
53 switch (c) {
54 /* BS, HT, ESC and FF */
55 case '\b': case '\t': case '\033': case '\014':
56 stats->printable++;
57 break;
58 case 0:
59 stats->nul++;
60 /* fall through */
61 default:
62 stats->nonprintable++;
65 else
66 stats->printable++;
69 /* If file ends with EOF then don't count this EOF as non-printable. */
70 if (size >= 1 && buf[size-1] == '\032')
71 stats->nonprintable--;
75 * The same heuristics as diff.c::mmfile_is_binary()
77 static int is_binary(unsigned long size, struct text_stat *stats)
80 if (stats->nul)
81 return 1;
82 if ((stats->printable >> 7) < stats->nonprintable)
83 return 1;
85 * Other heuristics? Average line length might be relevant,
86 * as might LF vs CR vs CRLF counts..
88 * NOTE! It might be normal to have a low ratio of CRLF to LF
89 * (somebody starts with a LF-only file and edits it with an editor
90 * that adds CRLF only to lines that are added..). But do we
91 * want to support CR-only? Probably not.
93 return 0;
96 static enum eol determine_output_conversion(enum action action)
98 switch (action) {
99 case CRLF_BINARY:
100 return EOL_UNSET;
101 case CRLF_CRLF:
102 return EOL_CRLF;
103 case CRLF_INPUT:
104 return EOL_LF;
105 case CRLF_GUESS:
106 if (!auto_crlf)
107 return EOL_UNSET;
108 /* fall through */
109 case CRLF_TEXT:
110 case CRLF_AUTO:
111 if (auto_crlf == AUTO_CRLF_TRUE)
112 return EOL_CRLF;
113 else if (auto_crlf == AUTO_CRLF_INPUT)
114 return EOL_LF;
115 else if (eol == EOL_UNSET)
116 return EOL_NATIVE;
118 return eol;
121 static void check_safe_crlf(const char *path, enum action action,
122 struct text_stat *stats, enum safe_crlf checksafe)
124 if (!checksafe)
125 return;
127 if (determine_output_conversion(action) == EOL_LF) {
129 * CRLFs would not be restored by checkout:
130 * check if we'd remove CRLFs
132 if (stats->crlf) {
133 if (checksafe == SAFE_CRLF_WARN)
134 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
135 else /* i.e. SAFE_CRLF_FAIL */
136 die("CRLF would be replaced by LF in %s.", path);
138 } else if (determine_output_conversion(action) == EOL_CRLF) {
140 * CRLFs would be added by checkout:
141 * check if we have "naked" LFs
143 if (stats->lf != stats->crlf) {
144 if (checksafe == SAFE_CRLF_WARN)
145 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
146 else /* i.e. SAFE_CRLF_FAIL */
147 die("LF would be replaced by CRLF in %s", path);
152 static int has_cr_in_index(const char *path)
154 int pos, len;
155 unsigned long sz;
156 enum object_type type;
157 void *data;
158 int has_cr;
159 struct index_state *istate = &the_index;
161 len = strlen(path);
162 pos = index_name_pos(istate, path, len);
163 if (pos < 0) {
165 * We might be in the middle of a merge, in which
166 * case we would read stage #2 (ours).
168 int i;
169 for (i = -pos - 1;
170 (pos < 0 && i < istate->cache_nr &&
171 !strcmp(istate->cache[i]->name, path));
172 i++)
173 if (ce_stage(istate->cache[i]) == 2)
174 pos = i;
176 if (pos < 0)
177 return 0;
178 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
179 if (!data || type != OBJ_BLOB) {
180 free(data);
181 return 0;
184 has_cr = memchr(data, '\r', sz) != NULL;
185 free(data);
186 return has_cr;
189 static int crlf_to_git(const char *path, const char *src, size_t len,
190 struct strbuf *buf, enum action action, enum safe_crlf checksafe)
192 struct text_stat stats;
193 char *dst;
195 if (action == CRLF_BINARY ||
196 (action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) || !len)
197 return 0;
199 gather_stats(src, len, &stats);
201 if (action == CRLF_AUTO || action == CRLF_GUESS) {
203 * We're currently not going to even try to convert stuff
204 * that has bare CR characters. Does anybody do that crazy
205 * stuff?
207 if (stats.cr != stats.crlf)
208 return 0;
211 * And add some heuristics for binary vs text, of course...
213 if (is_binary(len, &stats))
214 return 0;
216 if (action == CRLF_GUESS) {
218 * If the file in the index has any CR in it, do not convert.
219 * This is the new safer autocrlf handling.
221 if (has_cr_in_index(path))
222 return 0;
226 check_safe_crlf(path, action, &stats, checksafe);
228 /* Optimization: No CR? Nothing to convert, regardless. */
229 if (!stats.cr)
230 return 0;
232 /* only grow if not in place */
233 if (strbuf_avail(buf) + buf->len < len)
234 strbuf_grow(buf, len - buf->len);
235 dst = buf->buf;
236 if (action == CRLF_AUTO || action == CRLF_GUESS) {
238 * If we guessed, we already know we rejected a file with
239 * lone CR, and we can strip a CR without looking at what
240 * follow it.
242 do {
243 unsigned char c = *src++;
244 if (c != '\r')
245 *dst++ = c;
246 } while (--len);
247 } else {
248 do {
249 unsigned char c = *src++;
250 if (! (c == '\r' && (1 < len && *src == '\n')))
251 *dst++ = c;
252 } while (--len);
254 strbuf_setlen(buf, dst - buf->buf);
255 return 1;
258 static int crlf_to_worktree(const char *path, const char *src, size_t len,
259 struct strbuf *buf, enum action action)
261 char *to_free = NULL;
262 struct text_stat stats;
264 if (!len || determine_output_conversion(action) != EOL_CRLF)
265 return 0;
267 gather_stats(src, len, &stats);
269 /* No LF? Nothing to convert, regardless. */
270 if (!stats.lf)
271 return 0;
273 /* Was it already in CRLF format? */
274 if (stats.lf == stats.crlf)
275 return 0;
277 if (action == CRLF_AUTO || action == CRLF_GUESS) {
278 if (action == CRLF_GUESS) {
279 /* If we have any CR or CRLF line endings, we do not touch it */
280 /* This is the new safer autocrlf-handling */
281 if (stats.cr > 0 || stats.crlf > 0)
282 return 0;
285 /* If we have any bare CR characters, we're not going to touch it */
286 if (stats.cr != stats.crlf)
287 return 0;
289 if (is_binary(len, &stats))
290 return 0;
293 /* are we "faking" in place editing ? */
294 if (src == buf->buf)
295 to_free = strbuf_detach(buf, NULL);
297 strbuf_grow(buf, len + stats.lf - stats.crlf);
298 for (;;) {
299 const char *nl = memchr(src, '\n', len);
300 if (!nl)
301 break;
302 if (nl > src && nl[-1] == '\r') {
303 strbuf_add(buf, src, nl + 1 - src);
304 } else {
305 strbuf_add(buf, src, nl - src);
306 strbuf_addstr(buf, "\r\n");
308 len -= nl + 1 - src;
309 src = nl + 1;
311 strbuf_add(buf, src, len);
313 free(to_free);
314 return 1;
317 struct filter_params {
318 const char *src;
319 unsigned long size;
320 const char *cmd;
323 static int filter_buffer(int in, int out, void *data)
326 * Spawn cmd and feed the buffer contents through its stdin.
328 struct child_process child_process;
329 struct filter_params *params = (struct filter_params *)data;
330 int write_err, status;
331 const char *argv[] = { NULL, NULL };
333 argv[0] = params->cmd;
335 memset(&child_process, 0, sizeof(child_process));
336 child_process.argv = argv;
337 child_process.use_shell = 1;
338 child_process.in = -1;
339 child_process.out = out;
341 if (start_command(&child_process))
342 return error("cannot fork to run external filter %s", params->cmd);
344 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
345 if (close(child_process.in))
346 write_err = 1;
347 if (write_err)
348 error("cannot feed the input to external filter %s", params->cmd);
350 status = finish_command(&child_process);
351 if (status)
352 error("external filter %s failed %d", params->cmd, status);
353 return (write_err || status);
356 static int apply_filter(const char *path, const char *src, size_t len,
357 struct strbuf *dst, const char *cmd)
360 * Create a pipeline to have the command filter the buffer's
361 * contents.
363 * (child --> cmd) --> us
365 int ret = 1;
366 struct strbuf nbuf = STRBUF_INIT;
367 struct async async;
368 struct filter_params params;
370 if (!cmd)
371 return 0;
373 memset(&async, 0, sizeof(async));
374 async.proc = filter_buffer;
375 async.data = &params;
376 async.out = -1;
377 params.src = src;
378 params.size = len;
379 params.cmd = cmd;
381 fflush(NULL);
382 if (start_async(&async))
383 return 0; /* error was already reported */
385 if (strbuf_read(&nbuf, async.out, len) < 0) {
386 error("read from external filter %s failed", cmd);
387 ret = 0;
389 if (close(async.out)) {
390 error("read from external filter %s failed", cmd);
391 ret = 0;
393 if (finish_async(&async)) {
394 error("external filter %s failed", cmd);
395 ret = 0;
398 if (ret) {
399 strbuf_swap(dst, &nbuf);
401 strbuf_release(&nbuf);
402 return ret;
405 static struct convert_driver {
406 const char *name;
407 struct convert_driver *next;
408 const char *smudge;
409 const char *clean;
410 } *user_convert, **user_convert_tail;
412 static int read_convert_config(const char *var, const char *value, void *cb)
414 const char *ep, *name;
415 int namelen;
416 struct convert_driver *drv;
419 * External conversion drivers are configured using
420 * "filter.<name>.variable".
422 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
423 return 0;
424 name = var + 7;
425 namelen = ep - name;
426 for (drv = user_convert; drv; drv = drv->next)
427 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
428 break;
429 if (!drv) {
430 drv = xcalloc(1, sizeof(struct convert_driver));
431 drv->name = xmemdupz(name, namelen);
432 *user_convert_tail = drv;
433 user_convert_tail = &(drv->next);
436 ep++;
439 * filter.<name>.smudge and filter.<name>.clean specifies
440 * the command line:
442 * command-line
444 * The command-line will not be interpolated in any way.
447 if (!strcmp("smudge", ep))
448 return git_config_string(&drv->smudge, var, value);
450 if (!strcmp("clean", ep))
451 return git_config_string(&drv->clean, var, value);
453 return 0;
456 static void setup_convert_check(struct git_attr_check *check)
458 static struct git_attr *attr_text;
459 static struct git_attr *attr_crlf;
460 static struct git_attr *attr_eol;
461 static struct git_attr *attr_ident;
462 static struct git_attr *attr_filter;
464 if (!attr_text) {
465 attr_text = git_attr("text");
466 attr_crlf = git_attr("crlf");
467 attr_eol = git_attr("eol");
468 attr_ident = git_attr("ident");
469 attr_filter = git_attr("filter");
470 user_convert_tail = &user_convert;
471 git_config(read_convert_config, NULL);
473 check[0].attr = attr_crlf;
474 check[1].attr = attr_ident;
475 check[2].attr = attr_filter;
476 check[3].attr = attr_eol;
477 check[4].attr = attr_text;
480 static int count_ident(const char *cp, unsigned long size)
483 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
485 int cnt = 0;
486 char ch;
488 while (size) {
489 ch = *cp++;
490 size--;
491 if (ch != '$')
492 continue;
493 if (size < 3)
494 break;
495 if (memcmp("Id", cp, 2))
496 continue;
497 ch = cp[2];
498 cp += 3;
499 size -= 3;
500 if (ch == '$')
501 cnt++; /* $Id$ */
502 if (ch != ':')
503 continue;
506 * "$Id: ... "; scan up to the closing dollar sign and discard.
508 while (size) {
509 ch = *cp++;
510 size--;
511 if (ch == '$') {
512 cnt++;
513 break;
515 if (ch == '\n')
516 break;
519 return cnt;
522 static int ident_to_git(const char *path, const char *src, size_t len,
523 struct strbuf *buf, int ident)
525 char *dst, *dollar;
527 if (!ident || !count_ident(src, len))
528 return 0;
530 /* only grow if not in place */
531 if (strbuf_avail(buf) + buf->len < len)
532 strbuf_grow(buf, len - buf->len);
533 dst = buf->buf;
534 for (;;) {
535 dollar = memchr(src, '$', len);
536 if (!dollar)
537 break;
538 memcpy(dst, src, dollar + 1 - src);
539 dst += dollar + 1 - src;
540 len -= dollar + 1 - src;
541 src = dollar + 1;
543 if (len > 3 && !memcmp(src, "Id:", 3)) {
544 dollar = memchr(src + 3, '$', len - 3);
545 if (!dollar)
546 break;
547 if (memchr(src + 3, '\n', dollar - src - 3)) {
548 /* Line break before the next dollar. */
549 continue;
552 memcpy(dst, "Id$", 3);
553 dst += 3;
554 len -= dollar + 1 - src;
555 src = dollar + 1;
558 memcpy(dst, src, len);
559 strbuf_setlen(buf, dst + len - buf->buf);
560 return 1;
563 static int ident_to_worktree(const char *path, const char *src, size_t len,
564 struct strbuf *buf, int ident)
566 unsigned char sha1[20];
567 char *to_free = NULL, *dollar, *spc;
568 int cnt;
570 if (!ident)
571 return 0;
573 cnt = count_ident(src, len);
574 if (!cnt)
575 return 0;
577 /* are we "faking" in place editing ? */
578 if (src == buf->buf)
579 to_free = strbuf_detach(buf, NULL);
580 hash_sha1_file(src, len, "blob", sha1);
582 strbuf_grow(buf, len + cnt * 43);
583 for (;;) {
584 /* step 1: run to the next '$' */
585 dollar = memchr(src, '$', len);
586 if (!dollar)
587 break;
588 strbuf_add(buf, src, dollar + 1 - src);
589 len -= dollar + 1 - src;
590 src = dollar + 1;
592 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
593 if (len < 3 || memcmp("Id", src, 2))
594 continue;
596 /* step 3: skip over Id$ or Id:xxxxx$ */
597 if (src[2] == '$') {
598 src += 3;
599 len -= 3;
600 } else if (src[2] == ':') {
602 * It's possible that an expanded Id has crept its way into the
603 * repository, we cope with that by stripping the expansion out.
604 * This is probably not a good idea, since it will cause changes
605 * on checkout, which won't go away by stash, but let's keep it
606 * for git-style ids.
608 dollar = memchr(src + 3, '$', len - 3);
609 if (!dollar) {
610 /* incomplete keyword, no more '$', so just quit the loop */
611 break;
614 if (memchr(src + 3, '\n', dollar - src - 3)) {
615 /* Line break before the next dollar. */
616 continue;
619 spc = memchr(src + 4, ' ', dollar - src - 4);
620 if (spc && spc < dollar-1) {
621 /* There are spaces in unexpected places.
622 * This is probably an id from some other
623 * versioning system. Keep it for now.
625 continue;
628 len -= dollar + 1 - src;
629 src = dollar + 1;
630 } else {
631 /* it wasn't a "Id$" or "Id:xxxx$" */
632 continue;
635 /* step 4: substitute */
636 strbuf_addstr(buf, "Id: ");
637 strbuf_add(buf, sha1_to_hex(sha1), 40);
638 strbuf_addstr(buf, " $");
640 strbuf_add(buf, src, len);
642 free(to_free);
643 return 1;
646 static int git_path_check_crlf(const char *path, struct git_attr_check *check)
648 const char *value = check->value;
650 if (ATTR_TRUE(value))
651 return CRLF_TEXT;
652 else if (ATTR_FALSE(value))
653 return CRLF_BINARY;
654 else if (ATTR_UNSET(value))
656 else if (!strcmp(value, "input"))
657 return CRLF_INPUT;
658 else if (!strcmp(value, "auto"))
659 return CRLF_AUTO;
660 return CRLF_GUESS;
663 static int git_path_check_eol(const char *path, struct git_attr_check *check)
665 const char *value = check->value;
667 if (ATTR_UNSET(value))
669 else if (!strcmp(value, "lf"))
670 return EOL_LF;
671 else if (!strcmp(value, "crlf"))
672 return EOL_CRLF;
673 return EOL_UNSET;
676 static struct convert_driver *git_path_check_convert(const char *path,
677 struct git_attr_check *check)
679 const char *value = check->value;
680 struct convert_driver *drv;
682 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
683 return NULL;
684 for (drv = user_convert; drv; drv = drv->next)
685 if (!strcmp(value, drv->name))
686 return drv;
687 return NULL;
690 static int git_path_check_ident(const char *path, struct git_attr_check *check)
692 const char *value = check->value;
694 return !!ATTR_TRUE(value);
697 static enum action determine_action(enum action text_attr, enum eol eol_attr)
699 if (text_attr == CRLF_BINARY)
700 return CRLF_BINARY;
701 if (eol_attr == EOL_LF)
702 return CRLF_INPUT;
703 if (eol_attr == EOL_CRLF)
704 return CRLF_CRLF;
705 return text_attr;
708 int convert_to_git(const char *path, const char *src, size_t len,
709 struct strbuf *dst, enum safe_crlf checksafe)
711 struct git_attr_check check[5];
712 enum action action = CRLF_GUESS;
713 enum eol eol_attr = EOL_UNSET;
714 int ident = 0, ret = 0;
715 const char *filter = NULL;
717 setup_convert_check(check);
718 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
719 struct convert_driver *drv;
720 action = git_path_check_crlf(path, check + 4);
721 if (action == CRLF_GUESS)
722 action = git_path_check_crlf(path, check + 0);
723 ident = git_path_check_ident(path, check + 1);
724 drv = git_path_check_convert(path, check + 2);
725 eol_attr = git_path_check_eol(path, check + 3);
726 if (drv && drv->clean)
727 filter = drv->clean;
730 ret |= apply_filter(path, src, len, dst, filter);
731 if (ret) {
732 src = dst->buf;
733 len = dst->len;
735 action = determine_action(action, eol_attr);
736 ret |= crlf_to_git(path, src, len, dst, action, checksafe);
737 if (ret) {
738 src = dst->buf;
739 len = dst->len;
741 return ret | ident_to_git(path, src, len, dst, ident);
744 static int convert_to_working_tree_internal(const char *path, const char *src,
745 size_t len, struct strbuf *dst,
746 int normalizing)
748 struct git_attr_check check[5];
749 enum action action = CRLF_GUESS;
750 enum eol eol_attr = EOL_UNSET;
751 int ident = 0, ret = 0;
752 const char *filter = NULL;
754 setup_convert_check(check);
755 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
756 struct convert_driver *drv;
757 action = git_path_check_crlf(path, check + 4);
758 if (action == CRLF_GUESS)
759 action = git_path_check_crlf(path, check + 0);
760 ident = git_path_check_ident(path, check + 1);
761 drv = git_path_check_convert(path, check + 2);
762 eol_attr = git_path_check_eol(path, check + 3);
763 if (drv && drv->smudge)
764 filter = drv->smudge;
767 ret |= ident_to_worktree(path, src, len, dst, ident);
768 if (ret) {
769 src = dst->buf;
770 len = dst->len;
773 * CRLF conversion can be skipped if normalizing, unless there
774 * is a smudge filter. The filter might expect CRLFs.
776 if (filter || !normalizing) {
777 action = determine_action(action, eol_attr);
778 ret |= crlf_to_worktree(path, src, len, dst, action);
779 if (ret) {
780 src = dst->buf;
781 len = dst->len;
784 return ret | apply_filter(path, src, len, dst, filter);
787 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
789 return convert_to_working_tree_internal(path, src, len, dst, 0);
792 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
794 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
795 if (ret) {
796 src = dst->buf;
797 len = dst->len;
799 return ret | convert_to_git(path, src, len, dst, 0);