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