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