Code

Merge branch 'rr/parse-date-refactor'
[git.git] / convert.c
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.
7  *
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 "auto_crlf" option is set.
12  */
14 #define CRLF_GUESS      (-1)
15 #define CRLF_BINARY     0
16 #define CRLF_TEXT       1
17 #define CRLF_INPUT      2
19 struct text_stat {
20         /* NUL, CR, LF and CRLF counts */
21         unsigned nul, cr, lf, crlf;
23         /* These are just approximations! */
24         unsigned printable, nonprintable;
25 };
27 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
28 {
29         unsigned long i;
31         memset(stats, 0, sizeof(*stats));
33         for (i = 0; i < size; i++) {
34                 unsigned char c = buf[i];
35                 if (c == '\r') {
36                         stats->cr++;
37                         if (i+1 < size && buf[i+1] == '\n')
38                                 stats->crlf++;
39                         continue;
40                 }
41                 if (c == '\n') {
42                         stats->lf++;
43                         continue;
44                 }
45                 if (c == 127)
46                         /* DEL */
47                         stats->nonprintable++;
48                 else if (c < 32) {
49                         switch (c) {
50                                 /* BS, HT, ESC and FF */
51                         case '\b': case '\t': case '\033': case '\014':
52                                 stats->printable++;
53                                 break;
54                         case 0:
55                                 stats->nul++;
56                                 /* fall through */
57                         default:
58                                 stats->nonprintable++;
59                         }
60                 }
61                 else
62                         stats->printable++;
63         }
65         /* If file ends with EOF then don't count this EOF as non-printable. */
66         if (size >= 1 && buf[size-1] == '\032')
67                 stats->nonprintable--;
68 }
70 /*
71  * The same heuristics as diff.c::mmfile_is_binary()
72  */
73 static int is_binary(unsigned long size, struct text_stat *stats)
74 {
76         if (stats->nul)
77                 return 1;
78         if ((stats->printable >> 7) < stats->nonprintable)
79                 return 1;
80         /*
81          * Other heuristics? Average line length might be relevant,
82          * as might LF vs CR vs CRLF counts..
83          *
84          * NOTE! It might be normal to have a low ratio of CRLF to LF
85          * (somebody starts with a LF-only file and edits it with an editor
86          * that adds CRLF only to lines that are added..). But do  we
87          * want to support CR-only? Probably not.
88          */
89         return 0;
90 }
92 static void check_safe_crlf(const char *path, int action,
93                             struct text_stat *stats, enum safe_crlf checksafe)
94 {
95         if (!checksafe)
96                 return;
98         if (action == CRLF_INPUT || auto_crlf <= 0) {
99                 /*
100                  * CRLFs would not be restored by checkout:
101                  * check if we'd remove CRLFs
102                  */
103                 if (stats->crlf) {
104                         if (checksafe == SAFE_CRLF_WARN)
105                                 warning("CRLF will be replaced by LF in %s.", path);
106                         else /* i.e. SAFE_CRLF_FAIL */
107                                 die("CRLF would be replaced by LF in %s.", path);
108                 }
109         } else if (auto_crlf > 0) {
110                 /*
111                  * CRLFs would be added by checkout:
112                  * check if we have "naked" LFs
113                  */
114                 if (stats->lf != stats->crlf) {
115                         if (checksafe == SAFE_CRLF_WARN)
116                                 warning("LF will be replaced by CRLF in %s", path);
117                         else /* i.e. SAFE_CRLF_FAIL */
118                                 die("LF would be replaced by CRLF in %s", path);
119                 }
120         }
123 static int crlf_to_git(const char *path, const char *src, size_t len,
124                        struct strbuf *buf, int action, enum safe_crlf checksafe)
126         struct text_stat stats;
127         char *dst;
129         if ((action == CRLF_BINARY) || !auto_crlf || !len)
130                 return 0;
132         gather_stats(src, len, &stats);
134         if (action == CRLF_GUESS) {
135                 /*
136                  * We're currently not going to even try to convert stuff
137                  * that has bare CR characters. Does anybody do that crazy
138                  * stuff?
139                  */
140                 if (stats.cr != stats.crlf)
141                         return 0;
143                 /*
144                  * And add some heuristics for binary vs text, of course...
145                  */
146                 if (is_binary(len, &stats))
147                         return 0;
148         }
150         check_safe_crlf(path, action, &stats, checksafe);
152         /* Optimization: No CR? Nothing to convert, regardless. */
153         if (!stats.cr)
154                 return 0;
156         /* only grow if not in place */
157         if (strbuf_avail(buf) + buf->len < len)
158                 strbuf_grow(buf, len - buf->len);
159         dst = buf->buf;
160         if (action == CRLF_GUESS) {
161                 /*
162                  * If we guessed, we already know we rejected a file with
163                  * lone CR, and we can strip a CR without looking at what
164                  * follow it.
165                  */
166                 do {
167                         unsigned char c = *src++;
168                         if (c != '\r')
169                                 *dst++ = c;
170                 } while (--len);
171         } else {
172                 do {
173                         unsigned char c = *src++;
174                         if (! (c == '\r' && (1 < len && *src == '\n')))
175                                 *dst++ = c;
176                 } while (--len);
177         }
178         strbuf_setlen(buf, dst - buf->buf);
179         return 1;
182 static int crlf_to_worktree(const char *path, const char *src, size_t len,
183                             struct strbuf *buf, int action)
185         char *to_free = NULL;
186         struct text_stat stats;
188         if ((action == CRLF_BINARY) || (action == CRLF_INPUT) ||
189             auto_crlf <= 0)
190                 return 0;
192         if (!len)
193                 return 0;
195         gather_stats(src, len, &stats);
197         /* No LF? Nothing to convert, regardless. */
198         if (!stats.lf)
199                 return 0;
201         /* Was it already in CRLF format? */
202         if (stats.lf == stats.crlf)
203                 return 0;
205         if (action == CRLF_GUESS) {
206                 /* If we have any bare CR characters, we're not going to touch it */
207                 if (stats.cr != stats.crlf)
208                         return 0;
210                 if (is_binary(len, &stats))
211                         return 0;
212         }
214         /* are we "faking" in place editing ? */
215         if (src == buf->buf)
216                 to_free = strbuf_detach(buf, NULL);
218         strbuf_grow(buf, len + stats.lf - stats.crlf);
219         for (;;) {
220                 const char *nl = memchr(src, '\n', len);
221                 if (!nl)
222                         break;
223                 if (nl > src && nl[-1] == '\r') {
224                         strbuf_add(buf, src, nl + 1 - src);
225                 } else {
226                         strbuf_add(buf, src, nl - src);
227                         strbuf_addstr(buf, "\r\n");
228                 }
229                 len -= nl + 1 - src;
230                 src  = nl + 1;
231         }
232         strbuf_add(buf, src, len);
234         free(to_free);
235         return 1;
238 struct filter_params {
239         const char *src;
240         unsigned long size;
241         const char *cmd;
242 };
244 static int filter_buffer(int in, int out, void *data)
246         /*
247          * Spawn cmd and feed the buffer contents through its stdin.
248          */
249         struct child_process child_process;
250         struct filter_params *params = (struct filter_params *)data;
251         int write_err, status;
252         const char *argv[] = { NULL, NULL };
254         argv[0] = params->cmd;
256         memset(&child_process, 0, sizeof(child_process));
257         child_process.argv = argv;
258         child_process.use_shell = 1;
259         child_process.in = -1;
260         child_process.out = out;
262         if (start_command(&child_process))
263                 return error("cannot fork to run external filter %s", params->cmd);
265         write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
266         if (close(child_process.in))
267                 write_err = 1;
268         if (write_err)
269                 error("cannot feed the input to external filter %s", params->cmd);
271         status = finish_command(&child_process);
272         if (status)
273                 error("external filter %s failed %d", params->cmd, status);
274         return (write_err || status);
277 static int apply_filter(const char *path, const char *src, size_t len,
278                         struct strbuf *dst, const char *cmd)
280         /*
281          * Create a pipeline to have the command filter the buffer's
282          * contents.
283          *
284          * (child --> cmd) --> us
285          */
286         int ret = 1;
287         struct strbuf nbuf = STRBUF_INIT;
288         struct async async;
289         struct filter_params params;
291         if (!cmd)
292                 return 0;
294         memset(&async, 0, sizeof(async));
295         async.proc = filter_buffer;
296         async.data = &params;
297         async.out = -1;
298         params.src = src;
299         params.size = len;
300         params.cmd = cmd;
302         fflush(NULL);
303         if (start_async(&async))
304                 return 0;       /* error was already reported */
306         if (strbuf_read(&nbuf, async.out, len) < 0) {
307                 error("read from external filter %s failed", cmd);
308                 ret = 0;
309         }
310         if (close(async.out)) {
311                 error("read from external filter %s failed", cmd);
312                 ret = 0;
313         }
314         if (finish_async(&async)) {
315                 error("external filter %s failed", cmd);
316                 ret = 0;
317         }
319         if (ret) {
320                 strbuf_swap(dst, &nbuf);
321         }
322         strbuf_release(&nbuf);
323         return ret;
326 static struct convert_driver {
327         const char *name;
328         struct convert_driver *next;
329         const char *smudge;
330         const char *clean;
331 } *user_convert, **user_convert_tail;
333 static int read_convert_config(const char *var, const char *value, void *cb)
335         const char *ep, *name;
336         int namelen;
337         struct convert_driver *drv;
339         /*
340          * External conversion drivers are configured using
341          * "filter.<name>.variable".
342          */
343         if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
344                 return 0;
345         name = var + 7;
346         namelen = ep - name;
347         for (drv = user_convert; drv; drv = drv->next)
348                 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
349                         break;
350         if (!drv) {
351                 drv = xcalloc(1, sizeof(struct convert_driver));
352                 drv->name = xmemdupz(name, namelen);
353                 *user_convert_tail = drv;
354                 user_convert_tail = &(drv->next);
355         }
357         ep++;
359         /*
360          * filter.<name>.smudge and filter.<name>.clean specifies
361          * the command line:
362          *
363          *      command-line
364          *
365          * The command-line will not be interpolated in any way.
366          */
368         if (!strcmp("smudge", ep))
369                 return git_config_string(&drv->smudge, var, value);
371         if (!strcmp("clean", ep))
372                 return git_config_string(&drv->clean, var, value);
374         return 0;
377 static void setup_convert_check(struct git_attr_check *check)
379         static struct git_attr *attr_crlf;
380         static struct git_attr *attr_ident;
381         static struct git_attr *attr_filter;
383         if (!attr_crlf) {
384                 attr_crlf = git_attr("crlf");
385                 attr_ident = git_attr("ident");
386                 attr_filter = git_attr("filter");
387                 user_convert_tail = &user_convert;
388                 git_config(read_convert_config, NULL);
389         }
390         check[0].attr = attr_crlf;
391         check[1].attr = attr_ident;
392         check[2].attr = attr_filter;
395 static int count_ident(const char *cp, unsigned long size)
397         /*
398          * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
399          */
400         int cnt = 0;
401         char ch;
403         while (size) {
404                 ch = *cp++;
405                 size--;
406                 if (ch != '$')
407                         continue;
408                 if (size < 3)
409                         break;
410                 if (memcmp("Id", cp, 2))
411                         continue;
412                 ch = cp[2];
413                 cp += 3;
414                 size -= 3;
415                 if (ch == '$')
416                         cnt++; /* $Id$ */
417                 if (ch != ':')
418                         continue;
420                 /*
421                  * "$Id: ... "; scan up to the closing dollar sign and discard.
422                  */
423                 while (size) {
424                         ch = *cp++;
425                         size--;
426                         if (ch == '$') {
427                                 cnt++;
428                                 break;
429                         }
430                         if (ch == '\n')
431                                 break;
432                 }
433         }
434         return cnt;
437 static int ident_to_git(const char *path, const char *src, size_t len,
438                         struct strbuf *buf, int ident)
440         char *dst, *dollar;
442         if (!ident || !count_ident(src, len))
443                 return 0;
445         /* only grow if not in place */
446         if (strbuf_avail(buf) + buf->len < len)
447                 strbuf_grow(buf, len - buf->len);
448         dst = buf->buf;
449         for (;;) {
450                 dollar = memchr(src, '$', len);
451                 if (!dollar)
452                         break;
453                 memcpy(dst, src, dollar + 1 - src);
454                 dst += dollar + 1 - src;
455                 len -= dollar + 1 - src;
456                 src  = dollar + 1;
458                 if (len > 3 && !memcmp(src, "Id:", 3)) {
459                         dollar = memchr(src + 3, '$', len - 3);
460                         if (!dollar)
461                                 break;
462                         if (memchr(src + 3, '\n', dollar - src - 3)) {
463                                 /* Line break before the next dollar. */
464                                 continue;
465                         }
467                         memcpy(dst, "Id$", 3);
468                         dst += 3;
469                         len -= dollar + 1 - src;
470                         src  = dollar + 1;
471                 }
472         }
473         memcpy(dst, src, len);
474         strbuf_setlen(buf, dst + len - buf->buf);
475         return 1;
478 static int ident_to_worktree(const char *path, const char *src, size_t len,
479                              struct strbuf *buf, int ident)
481         unsigned char sha1[20];
482         char *to_free = NULL, *dollar, *spc;
483         int cnt;
485         if (!ident)
486                 return 0;
488         cnt = count_ident(src, len);
489         if (!cnt)
490                 return 0;
492         /* are we "faking" in place editing ? */
493         if (src == buf->buf)
494                 to_free = strbuf_detach(buf, NULL);
495         hash_sha1_file(src, len, "blob", sha1);
497         strbuf_grow(buf, len + cnt * 43);
498         for (;;) {
499                 /* step 1: run to the next '$' */
500                 dollar = memchr(src, '$', len);
501                 if (!dollar)
502                         break;
503                 strbuf_add(buf, src, dollar + 1 - src);
504                 len -= dollar + 1 - src;
505                 src  = dollar + 1;
507                 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
508                 if (len < 3 || memcmp("Id", src, 2))
509                         continue;
511                 /* step 3: skip over Id$ or Id:xxxxx$ */
512                 if (src[2] == '$') {
513                         src += 3;
514                         len -= 3;
515                 } else if (src[2] == ':') {
516                         /*
517                          * It's possible that an expanded Id has crept its way into the
518                          * repository, we cope with that by stripping the expansion out.
519                          * This is probably not a good idea, since it will cause changes
520                          * on checkout, which won't go away by stash, but let's keep it
521                          * for git-style ids.
522                          */
523                         dollar = memchr(src + 3, '$', len - 3);
524                         if (!dollar) {
525                                 /* incomplete keyword, no more '$', so just quit the loop */
526                                 break;
527                         }
529                         if (memchr(src + 3, '\n', dollar - src - 3)) {
530                                 /* Line break before the next dollar. */
531                                 continue;
532                         }
534                         spc = memchr(src + 4, ' ', dollar - src - 4);
535                         if (spc && spc < dollar-1) {
536                                 /* There are spaces in unexpected places.
537                                  * This is probably an id from some other
538                                  * versioning system. Keep it for now.
539                                  */
540                                 continue;
541                         }
543                         len -= dollar + 1 - src;
544                         src  = dollar + 1;
545                 } else {
546                         /* it wasn't a "Id$" or "Id:xxxx$" */
547                         continue;
548                 }
550                 /* step 4: substitute */
551                 strbuf_addstr(buf, "Id: ");
552                 strbuf_add(buf, sha1_to_hex(sha1), 40);
553                 strbuf_addstr(buf, " $");
554         }
555         strbuf_add(buf, src, len);
557         free(to_free);
558         return 1;
561 static int git_path_check_crlf(const char *path, struct git_attr_check *check)
563         const char *value = check->value;
565         if (ATTR_TRUE(value))
566                 return CRLF_TEXT;
567         else if (ATTR_FALSE(value))
568                 return CRLF_BINARY;
569         else if (ATTR_UNSET(value))
570                 ;
571         else if (!strcmp(value, "input"))
572                 return CRLF_INPUT;
573         return CRLF_GUESS;
576 static struct convert_driver *git_path_check_convert(const char *path,
577                                              struct git_attr_check *check)
579         const char *value = check->value;
580         struct convert_driver *drv;
582         if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
583                 return NULL;
584         for (drv = user_convert; drv; drv = drv->next)
585                 if (!strcmp(value, drv->name))
586                         return drv;
587         return NULL;
590 static int git_path_check_ident(const char *path, struct git_attr_check *check)
592         const char *value = check->value;
594         return !!ATTR_TRUE(value);
597 int convert_to_git(const char *path, const char *src, size_t len,
598                    struct strbuf *dst, enum safe_crlf checksafe)
600         struct git_attr_check check[3];
601         int crlf = CRLF_GUESS;
602         int ident = 0, ret = 0;
603         const char *filter = NULL;
605         setup_convert_check(check);
606         if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
607                 struct convert_driver *drv;
608                 crlf = git_path_check_crlf(path, check + 0);
609                 ident = git_path_check_ident(path, check + 1);
610                 drv = git_path_check_convert(path, check + 2);
611                 if (drv && drv->clean)
612                         filter = drv->clean;
613         }
615         ret |= apply_filter(path, src, len, dst, filter);
616         if (ret) {
617                 src = dst->buf;
618                 len = dst->len;
619         }
620         ret |= crlf_to_git(path, src, len, dst, crlf, checksafe);
621         if (ret) {
622                 src = dst->buf;
623                 len = dst->len;
624         }
625         return ret | ident_to_git(path, src, len, dst, ident);
628 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
630         struct git_attr_check check[3];
631         int crlf = CRLF_GUESS;
632         int ident = 0, ret = 0;
633         const char *filter = NULL;
635         setup_convert_check(check);
636         if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
637                 struct convert_driver *drv;
638                 crlf = git_path_check_crlf(path, check + 0);
639                 ident = git_path_check_ident(path, check + 1);
640                 drv = git_path_check_convert(path, check + 2);
641                 if (drv && drv->smudge)
642                         filter = drv->smudge;
643         }
645         ret |= ident_to_worktree(path, src, len, dst, ident);
646         if (ret) {
647                 src = dst->buf;
648                 len = dst->len;
649         }
650         ret |= crlf_to_worktree(path, src, len, dst, crlf);
651         if (ret) {
652                 src = dst->buf;
653                 len = dst->len;
654         }
655         return ret | apply_filter(path, src, len, dst, filter);