Windows ANSI - hook write()
[git/mingw/4msysgit/peterh.git] / convert.c
blobf24ac25c49b92e6fc8915e29e42cba46bab748f5
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 "auto_crlf" option is set.
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;
27 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
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;
41 if (c == '\n') {
42 stats->lf++;
43 continue;
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++;
61 else
62 stats->printable++;
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--;
71 * The same heuristics as diff.c::mmfile_is_binary()
73 static int is_binary(unsigned long size, struct text_stat *stats)
76 if (stats->nul)
77 return 1;
78 if ((stats->printable >> 7) < stats->nonprintable)
79 return 1;
81 * Other heuristics? Average line length might be relevant,
82 * as might LF vs CR vs CRLF counts..
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.
89 return 0;
92 static void check_safe_crlf(const char *path, int action,
93 struct text_stat *stats, enum safe_crlf checksafe)
95 if (!checksafe)
96 return;
98 if (action == CRLF_INPUT || auto_crlf <= 0) {
100 * CRLFs would not be restored by checkout:
101 * check if we'd remove CRLFs
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);
109 } else if (auto_crlf > 0) {
111 * CRLFs would be added by checkout:
112 * check if we have "naked" LFs
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);
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) {
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?
140 if (stats.cr != stats.crlf)
141 return 0;
144 * And add some heuristics for binary vs text, of course...
146 if (is_binary(len, &stats))
147 return 0;
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) {
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.
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);
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;
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");
229 len -= nl + 1 - src;
230 src = nl + 1;
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;
244 static int filter_buffer(int fd, void *data)
247 * Spawn cmd and feed the buffer contents through its stdin.
249 struct child_process child_process;
250 struct filter_params *params = (struct filter_params *)data;
251 int write_err, status;
252 const char *argv[] = { "sh", "-c", params->cmd, NULL };
254 memset(&child_process, 0, sizeof(child_process));
255 child_process.argv = argv;
256 child_process.in = -1;
257 child_process.out = fd;
259 if (start_command(&child_process))
260 return error("cannot fork to run external filter %s", params->cmd);
262 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
263 if (close(child_process.in))
264 write_err = 1;
265 if (write_err)
266 error("cannot feed the input to external filter %s", params->cmd);
268 status = finish_command(&child_process);
269 if (status)
270 error("external filter %s failed %d", params->cmd, -status);
271 return (write_err || status);
274 static int apply_filter(const char *path, const char *src, size_t len,
275 struct strbuf *dst, const char *cmd)
278 * Create a pipeline to have the command filter the buffer's
279 * contents.
281 * (child --> cmd) --> us
283 int ret = 1;
284 struct strbuf nbuf;
285 struct async async;
286 struct filter_params params;
288 if (!cmd)
289 return 0;
291 memset(&async, 0, sizeof(async));
292 async.proc = filter_buffer;
293 async.data = &params;
294 params.src = src;
295 params.size = len;
296 params.cmd = cmd;
298 fflush(NULL);
299 if (start_async(&async))
300 return 0; /* error was already reported */
302 strbuf_init(&nbuf, 0);
303 if (strbuf_read(&nbuf, async.out, len) < 0) {
304 error("read from external filter %s failed", cmd);
305 ret = 0;
307 if (close(async.out)) {
308 error("read from external filter %s failed", cmd);
309 ret = 0;
311 if (finish_async(&async)) {
312 error("external filter %s failed", cmd);
313 ret = 0;
316 if (ret) {
317 strbuf_swap(dst, &nbuf);
319 strbuf_release(&nbuf);
320 return ret;
323 static struct convert_driver {
324 const char *name;
325 struct convert_driver *next;
326 char *smudge;
327 char *clean;
328 } *user_convert, **user_convert_tail;
330 static int read_convert_config(const char *var, const char *value, void *cb)
332 const char *ep, *name;
333 int namelen;
334 struct convert_driver *drv;
337 * External conversion drivers are configured using
338 * "filter.<name>.variable".
340 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
341 return 0;
342 name = var + 7;
343 namelen = ep - name;
344 for (drv = user_convert; drv; drv = drv->next)
345 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
346 break;
347 if (!drv) {
348 drv = xcalloc(1, sizeof(struct convert_driver));
349 drv->name = xmemdupz(name, namelen);
350 *user_convert_tail = drv;
351 user_convert_tail = &(drv->next);
354 ep++;
357 * filter.<name>.smudge and filter.<name>.clean specifies
358 * the command line:
360 * command-line
362 * The command-line will not be interpolated in any way.
365 if (!strcmp("smudge", ep)) {
366 if (!value)
367 return config_error_nonbool(var);
368 drv->smudge = strdup(value);
369 return 0;
372 if (!strcmp("clean", ep)) {
373 if (!value)
374 return config_error_nonbool(var);
375 drv->clean = strdup(value);
376 return 0;
378 return 0;
381 static void setup_convert_check(struct git_attr_check *check)
383 static struct git_attr *attr_crlf;
384 static struct git_attr *attr_ident;
385 static struct git_attr *attr_filter;
387 if (!attr_crlf) {
388 attr_crlf = git_attr("crlf", 4);
389 attr_ident = git_attr("ident", 5);
390 attr_filter = git_attr("filter", 6);
391 user_convert_tail = &user_convert;
392 git_config(read_convert_config, NULL);
394 check[0].attr = attr_crlf;
395 check[1].attr = attr_ident;
396 check[2].attr = attr_filter;
399 static int count_ident(const char *cp, unsigned long size)
402 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
404 int cnt = 0;
405 char ch;
407 while (size) {
408 ch = *cp++;
409 size--;
410 if (ch != '$')
411 continue;
412 if (size < 3)
413 break;
414 if (memcmp("Id", cp, 2))
415 continue;
416 ch = cp[2];
417 cp += 3;
418 size -= 3;
419 if (ch == '$')
420 cnt++; /* $Id$ */
421 if (ch != ':')
422 continue;
425 * "$Id: ... "; scan up to the closing dollar sign and discard.
427 while (size) {
428 ch = *cp++;
429 size--;
430 if (ch == '$') {
431 cnt++;
432 break;
436 return cnt;
439 static int ident_to_git(const char *path, const char *src, size_t len,
440 struct strbuf *buf, int ident)
442 char *dst, *dollar;
444 if (!ident || !count_ident(src, len))
445 return 0;
447 /* only grow if not in place */
448 if (strbuf_avail(buf) + buf->len < len)
449 strbuf_grow(buf, len - buf->len);
450 dst = buf->buf;
451 for (;;) {
452 dollar = memchr(src, '$', len);
453 if (!dollar)
454 break;
455 memcpy(dst, src, dollar + 1 - src);
456 dst += dollar + 1 - src;
457 len -= dollar + 1 - src;
458 src = dollar + 1;
460 if (len > 3 && !memcmp(src, "Id:", 3)) {
461 dollar = memchr(src + 3, '$', len - 3);
462 if (!dollar)
463 break;
464 memcpy(dst, "Id$", 3);
465 dst += 3;
466 len -= dollar + 1 - src;
467 src = dollar + 1;
470 memcpy(dst, src, len);
471 strbuf_setlen(buf, dst + len - buf->buf);
472 return 1;
475 static int ident_to_worktree(const char *path, const char *src, size_t len,
476 struct strbuf *buf, int ident)
478 unsigned char sha1[20];
479 char *to_free = NULL, *dollar;
480 int cnt;
482 if (!ident)
483 return 0;
485 cnt = count_ident(src, len);
486 if (!cnt)
487 return 0;
489 /* are we "faking" in place editing ? */
490 if (src == buf->buf)
491 to_free = strbuf_detach(buf, NULL);
492 hash_sha1_file(src, len, "blob", sha1);
494 strbuf_grow(buf, len + cnt * 43);
495 for (;;) {
496 /* step 1: run to the next '$' */
497 dollar = memchr(src, '$', len);
498 if (!dollar)
499 break;
500 strbuf_add(buf, src, dollar + 1 - src);
501 len -= dollar + 1 - src;
502 src = dollar + 1;
504 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
505 if (len < 3 || memcmp("Id", src, 2))
506 continue;
508 /* step 3: skip over Id$ or Id:xxxxx$ */
509 if (src[2] == '$') {
510 src += 3;
511 len -= 3;
512 } else if (src[2] == ':') {
514 * It's possible that an expanded Id has crept its way into the
515 * repository, we cope with that by stripping the expansion out
517 dollar = memchr(src + 3, '$', len - 3);
518 if (!dollar) {
519 /* incomplete keyword, no more '$', so just quit the loop */
520 break;
523 len -= dollar + 1 - src;
524 src = dollar + 1;
525 } else {
526 /* it wasn't a "Id$" or "Id:xxxx$" */
527 continue;
530 /* step 4: substitute */
531 strbuf_addstr(buf, "Id: ");
532 strbuf_add(buf, sha1_to_hex(sha1), 40);
533 strbuf_addstr(buf, " $");
535 strbuf_add(buf, src, len);
537 free(to_free);
538 return 1;
541 static int git_path_check_crlf(const char *path, struct git_attr_check *check)
543 const char *value = check->value;
545 if (ATTR_TRUE(value))
546 return CRLF_TEXT;
547 else if (ATTR_FALSE(value))
548 return CRLF_BINARY;
549 else if (ATTR_UNSET(value))
551 else if (!strcmp(value, "input"))
552 return CRLF_INPUT;
553 return CRLF_GUESS;
556 static struct convert_driver *git_path_check_convert(const char *path,
557 struct git_attr_check *check)
559 const char *value = check->value;
560 struct convert_driver *drv;
562 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
563 return NULL;
564 for (drv = user_convert; drv; drv = drv->next)
565 if (!strcmp(value, drv->name))
566 return drv;
567 return NULL;
570 static int git_path_check_ident(const char *path, struct git_attr_check *check)
572 const char *value = check->value;
574 return !!ATTR_TRUE(value);
577 int convert_to_git(const char *path, const char *src, size_t len,
578 struct strbuf *dst, enum safe_crlf checksafe)
580 struct git_attr_check check[3];
581 int crlf = CRLF_GUESS;
582 int ident = 0, ret = 0;
583 char *filter = NULL;
585 setup_convert_check(check);
586 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
587 struct convert_driver *drv;
588 crlf = git_path_check_crlf(path, check + 0);
589 ident = git_path_check_ident(path, check + 1);
590 drv = git_path_check_convert(path, check + 2);
591 if (drv && drv->clean)
592 filter = drv->clean;
595 ret |= apply_filter(path, src, len, dst, filter);
596 if (ret) {
597 src = dst->buf;
598 len = dst->len;
600 ret |= crlf_to_git(path, src, len, dst, crlf, checksafe);
601 if (ret) {
602 src = dst->buf;
603 len = dst->len;
605 return ret | ident_to_git(path, src, len, dst, ident);
608 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
610 struct git_attr_check check[3];
611 int crlf = CRLF_GUESS;
612 int ident = 0, ret = 0;
613 char *filter = NULL;
615 setup_convert_check(check);
616 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
617 struct convert_driver *drv;
618 crlf = git_path_check_crlf(path, check + 0);
619 ident = git_path_check_ident(path, check + 1);
620 drv = git_path_check_convert(path, check + 2);
621 if (drv && drv->smudge)
622 filter = drv->smudge;
625 ret |= ident_to_worktree(path, src, len, dst, ident);
626 if (ret) {
627 src = dst->buf;
628 len = dst->len;
630 ret |= crlf_to_worktree(path, src, len, dst, crlf);
631 if (ret) {
632 src = dst->buf;
633 len = dst->len;
635 return ret | apply_filter(path, src, len, dst, filter);