]> git.ipfire.org Git - thirdparty/git.git/blame - convert.c
path: add repo_worktree_path and strbuf_repo_worktree_path
[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)
504
1b0b46ee
BP
505struct cmd2process {
506 struct subprocess_entry subprocess; /* must be the first member! */
507 unsigned int supported_capabilities;
508};
509
f514d7d1
BP
510static int subprocess_map_initialized;
511static struct hashmap subprocess_map;
edcc8581 512
7ddb9b2c 513static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
edcc8581
LS
514{
515 int err;
7ddb9b2c 516 struct cmd2process *entry = (struct cmd2process *)subprocess;
edcc8581
LS
517 struct string_list cap_list = STRING_LIST_INIT_NODUP;
518 char *cap_buf;
519 const char *cap_name;
7ddb9b2c
BP
520 struct child_process *process = &subprocess->process;
521 const char *cmd = subprocess->cmd;
edcc8581
LS
522
523 sigchain_push(SIGPIPE, SIG_IGN);
524
c0c70f7a 525 err = packet_writel(process->in, "git-filter-client", "version=2", NULL);
edcc8581
LS
526 if (err)
527 goto done;
528
529 err = strcmp(packet_read_line(process->out, NULL), "git-filter-server");
530 if (err) {
531 error("external filter '%s' does not support filter protocol version 2", cmd);
532 goto done;
533 }
534 err = strcmp(packet_read_line(process->out, NULL), "version=2");
535 if (err)
536 goto done;
537 err = packet_read_line(process->out, NULL) != NULL;
538 if (err)
539 goto done;
540
c0c70f7a 541 err = packet_writel(process->in, "capability=clean", "capability=smudge", NULL);
edcc8581
LS
542
543 for (;;) {
544 cap_buf = packet_read_line(process->out, NULL);
545 if (!cap_buf)
546 break;
547 string_list_split_in_place(&cap_list, cap_buf, '=', 1);
548
549 if (cap_list.nr != 2 || strcmp(cap_list.items[0].string, "capability"))
550 continue;
551
552 cap_name = cap_list.items[1].string;
553 if (!strcmp(cap_name, "clean")) {
554 entry->supported_capabilities |= CAP_CLEAN;
555 } else if (!strcmp(cap_name, "smudge")) {
556 entry->supported_capabilities |= CAP_SMUDGE;
557 } else {
558 warning(
559 "external filter '%s' requested unsupported filter capability '%s'",
560 cmd, cap_name
561 );
562 }
563
564 string_list_clear(&cap_list, 0);
565 }
566
567done:
568 sigchain_pop(SIGPIPE);
569
a810ea99
BP
570 return err;
571}
572
edcc8581
LS
573static int apply_multi_file_filter(const char *path, const char *src, size_t len,
574 int fd, struct strbuf *dst, const char *cmd,
575 const unsigned int wanted_capability)
576{
577 int err;
578 struct cmd2process *entry;
579 struct child_process *process;
580 struct strbuf nbuf = STRBUF_INIT;
581 struct strbuf filter_status = STRBUF_INIT;
582 const char *filter_type;
583
f514d7d1
BP
584 if (!subprocess_map_initialized) {
585 subprocess_map_initialized = 1;
586 hashmap_init(&subprocess_map, (hashmap_cmp_fn) cmd2process_cmp, 0);
edcc8581
LS
587 entry = NULL;
588 } else {
f514d7d1 589 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
edcc8581
LS
590 }
591
592 fflush(NULL);
593
594 if (!entry) {
7ddb9b2c
BP
595 entry = xmalloc(sizeof(*entry));
596 entry->supported_capabilities = 0;
597
f514d7d1 598 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
7ddb9b2c 599 free(entry);
edcc8581 600 return 0;
7ddb9b2c 601 }
edcc8581 602 }
1b0b46ee 603 process = &entry->subprocess.process;
edcc8581
LS
604
605 if (!(wanted_capability & entry->supported_capabilities))
606 return 0;
607
608 if (CAP_CLEAN & wanted_capability)
609 filter_type = "clean";
610 else if (CAP_SMUDGE & wanted_capability)
611 filter_type = "smudge";
612 else
613 die("unexpected filter type");
614
615 sigchain_push(SIGPIPE, SIG_IGN);
616
617 assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
618 err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
619 if (err)
620 goto done;
621
622 err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
623 if (err) {
624 error("path name too long for external filter");
625 goto done;
626 }
627
628 err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
629 if (err)
630 goto done;
631
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
edcc8581
LS
647 err = strcmp(filter_status.buf, "success");
648 if (err)
649 goto done;
650
651 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
652 if (err)
653 goto done;
654
4f2a2e9f
BP
655 err = subprocess_read_status(process->out, &filter_status);
656 if (err)
657 goto done;
658
edcc8581
LS
659 err = strcmp(filter_status.buf, "success");
660
661done:
662 sigchain_pop(SIGPIPE);
663
070e5f72 664 if (err) {
edcc8581
LS
665 if (!strcmp(filter_status.buf, "error")) {
666 /* The filter signaled a problem with the file. */
667 } else if (!strcmp(filter_status.buf, "abort")) {
668 /*
669 * The filter signaled a permanent problem. Don't try to filter
670 * files with the same command for the lifetime of the current
671 * Git process.
672 */
673 entry->supported_capabilities &= ~wanted_capability;
674 } else {
675 /*
676 * Something went wrong with the protocol filter.
677 * Force shutdown and restart if another blob requires filtering.
678 */
679 error("external filter '%s' failed", cmd);
f514d7d1 680 subprocess_stop(&subprocess_map, &entry->subprocess);
7ddb9b2c 681 free(entry);
edcc8581
LS
682 }
683 } else {
684 strbuf_swap(dst, &nbuf);
685 }
686 strbuf_release(&nbuf);
687 return !err;
aa4ed402
JH
688}
689
690static struct convert_driver {
691 const char *name;
692 struct convert_driver *next;
cd8be6c9
BH
693 const char *smudge;
694 const char *clean;
edcc8581 695 const char *process;
36daaaca 696 int required;
aa4ed402
JH
697} *user_convert, **user_convert_tail;
698
234fa07e
LS
699static int apply_filter(const char *path, const char *src, size_t len,
700 int fd, struct strbuf *dst, struct convert_driver *drv,
701 const unsigned int wanted_capability)
702{
703 const char *cmd = NULL;
704
705 if (!drv)
706 return 0;
707
708 if (!dst)
709 return 1;
710
edcc8581 711 if ((CAP_CLEAN & wanted_capability) && !drv->process && drv->clean)
234fa07e 712 cmd = drv->clean;
edcc8581 713 else if ((CAP_SMUDGE & wanted_capability) && !drv->process && drv->smudge)
234fa07e
LS
714 cmd = drv->smudge;
715
716 if (cmd && *cmd)
717 return apply_single_file_filter(path, src, len, fd, dst, cmd);
edcc8581
LS
718 else if (drv->process && *drv->process)
719 return apply_multi_file_filter(path, src, len, fd, dst, drv->process, wanted_capability);
234fa07e
LS
720
721 return 0;
722}
723
ef90d6d4 724static int read_convert_config(const char *var, const char *value, void *cb)
aa4ed402 725{
d731f0ad 726 const char *key, *name;
aa4ed402
JH
727 int namelen;
728 struct convert_driver *drv;
729
730 /*
731 * External conversion drivers are configured using
732 * "filter.<name>.variable".
733 */
d731f0ad 734 if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
aa4ed402 735 return 0;
aa4ed402
JH
736 for (drv = user_convert; drv; drv = drv->next)
737 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
738 break;
739 if (!drv) {
aa4ed402 740 drv = xcalloc(1, sizeof(struct convert_driver));
182af834 741 drv->name = xmemdupz(name, namelen);
aa4ed402
JH
742 *user_convert_tail = drv;
743 user_convert_tail = &(drv->next);
744 }
745
aa4ed402
JH
746 /*
747 * filter.<name>.smudge and filter.<name>.clean specifies
748 * the command line:
749 *
750 * command-line
751 *
752 * The command-line will not be interpolated in any way.
753 */
754
d731f0ad 755 if (!strcmp("smudge", key))
cd8be6c9
BH
756 return git_config_string(&drv->smudge, var, value);
757
d731f0ad 758 if (!strcmp("clean", key))
cd8be6c9 759 return git_config_string(&drv->clean, var, value);
aa4ed402 760
edcc8581
LS
761 if (!strcmp("process", key))
762 return git_config_string(&drv->process, var, value);
763
d731f0ad 764 if (!strcmp("required", key)) {
36daaaca
JB
765 drv->required = git_config_bool(var, value);
766 return 0;
767 }
768
aa4ed402
JH
769 return 0;
770}
771
3fed15f5
JH
772static int count_ident(const char *cp, unsigned long size)
773{
774 /*
af9b54bb 775 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
3fed15f5
JH
776 */
777 int cnt = 0;
778 char ch;
779
780 while (size) {
781 ch = *cp++;
782 size--;
783 if (ch != '$')
784 continue;
af9b54bb 785 if (size < 3)
3fed15f5 786 break;
af9b54bb 787 if (memcmp("Id", cp, 2))
3fed15f5 788 continue;
af9b54bb
AP
789 ch = cp[2];
790 cp += 3;
791 size -= 3;
3fed15f5 792 if (ch == '$')
af9b54bb 793 cnt++; /* $Id$ */
3fed15f5
JH
794 if (ch != ':')
795 continue;
796
797 /*
af9b54bb 798 * "$Id: ... "; scan up to the closing dollar sign and discard.
3fed15f5
JH
799 */
800 while (size) {
801 ch = *cp++;
802 size--;
803 if (ch == '$') {
804 cnt++;
805 break;
806 }
a9f3049f
HG
807 if (ch == '\n')
808 break;
3fed15f5
JH
809 }
810 }
811 return cnt;
812}
813
5ecd293d
PH
814static int ident_to_git(const char *path, const char *src, size_t len,
815 struct strbuf *buf, int ident)
3fed15f5 816{
5ecd293d 817 char *dst, *dollar;
3fed15f5 818
4c3b57b9 819 if (!ident || (src && !count_ident(src, len)))
5ecd293d
PH
820 return 0;
821
92ac3197
JK
822 if (!buf)
823 return 1;
824
90d16ec0
PH
825 /* only grow if not in place */
826 if (strbuf_avail(buf) + buf->len < len)
827 strbuf_grow(buf, len - buf->len);
5ecd293d
PH
828 dst = buf->buf;
829 for (;;) {
830 dollar = memchr(src, '$', len);
831 if (!dollar)
832 break;
77321184 833 memmove(dst, src, dollar + 1 - src);
5ecd293d
PH
834 dst += dollar + 1 - src;
835 len -= dollar + 1 - src;
836 src = dollar + 1;
837
838 if (len > 3 && !memcmp(src, "Id:", 3)) {
839 dollar = memchr(src + 3, '$', len - 3);
840 if (!dollar)
841 break;
a9f3049f
HG
842 if (memchr(src + 3, '\n', dollar - src - 3)) {
843 /* Line break before the next dollar. */
844 continue;
845 }
846
af9b54bb
AP
847 memcpy(dst, "Id$", 3);
848 dst += 3;
5ecd293d
PH
849 len -= dollar + 1 - src;
850 src = dollar + 1;
3fed15f5
JH
851 }
852 }
77321184 853 memmove(dst, src, len);
5ecd293d
PH
854 strbuf_setlen(buf, dst + len - buf->buf);
855 return 1;
3fed15f5
JH
856}
857
5ecd293d
PH
858static int ident_to_worktree(const char *path, const char *src, size_t len,
859 struct strbuf *buf, int ident)
3fed15f5 860{
3fed15f5 861 unsigned char sha1[20];
07814d90 862 char *to_free = NULL, *dollar, *spc;
5ecd293d 863 int cnt;
3fed15f5
JH
864
865 if (!ident)
5ecd293d 866 return 0;
3fed15f5 867
5ecd293d 868 cnt = count_ident(src, len);
3fed15f5 869 if (!cnt)
5ecd293d 870 return 0;
3fed15f5 871
5ecd293d
PH
872 /* are we "faking" in place editing ? */
873 if (src == buf->buf)
b315c5c0 874 to_free = strbuf_detach(buf, NULL);
5ecd293d 875 hash_sha1_file(src, len, "blob", sha1);
3fed15f5 876
5ecd293d
PH
877 strbuf_grow(buf, len + cnt * 43);
878 for (;;) {
879 /* step 1: run to the next '$' */
880 dollar = memchr(src, '$', len);
881 if (!dollar)
882 break;
883 strbuf_add(buf, src, dollar + 1 - src);
884 len -= dollar + 1 - src;
885 src = dollar + 1;
c23290d5 886
5ecd293d
PH
887 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
888 if (len < 3 || memcmp("Id", src, 2))
3fed15f5
JH
889 continue;
890
5ecd293d
PH
891 /* step 3: skip over Id$ or Id:xxxxx$ */
892 if (src[2] == '$') {
893 src += 3;
894 len -= 3;
895 } else if (src[2] == ':') {
896 /*
897 * It's possible that an expanded Id has crept its way into the
07814d90
HG
898 * repository, we cope with that by stripping the expansion out.
899 * This is probably not a good idea, since it will cause changes
900 * on checkout, which won't go away by stash, but let's keep it
901 * for git-style ids.
5ecd293d
PH
902 */
903 dollar = memchr(src + 3, '$', len - 3);
904 if (!dollar) {
905 /* incomplete keyword, no more '$', so just quit the loop */
906 break;
907 }
c23290d5 908
a9f3049f
HG
909 if (memchr(src + 3, '\n', dollar - src - 3)) {
910 /* Line break before the next dollar. */
911 continue;
912 }
913
07814d90
HG
914 spc = memchr(src + 4, ' ', dollar - src - 4);
915 if (spc && spc < dollar-1) {
916 /* There are spaces in unexpected places.
917 * This is probably an id from some other
918 * versioning system. Keep it for now.
919 */
920 continue;
921 }
922
5ecd293d
PH
923 len -= dollar + 1 - src;
924 src = dollar + 1;
925 } else {
926 /* it wasn't a "Id$" or "Id:xxxx$" */
927 continue;
928 }
c23290d5 929
5ecd293d
PH
930 /* step 4: substitute */
931 strbuf_addstr(buf, "Id: ");
932 strbuf_add(buf, sha1_to_hex(sha1), 40);
933 strbuf_addstr(buf, " $");
3fed15f5 934 }
5ecd293d 935 strbuf_add(buf, src, len);
3fed15f5 936
5ecd293d
PH
937 free(to_free);
938 return 1;
35ebfd6a
JH
939}
940
7bd18054 941static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
35ebfd6a 942{
6073ee85
JH
943 const char *value = check->value;
944
945 if (ATTR_TRUE(value))
946 return CRLF_TEXT;
947 else if (ATTR_FALSE(value))
948 return CRLF_BINARY;
949 else if (ATTR_UNSET(value))
950 ;
951 else if (!strcmp(value, "input"))
df747b81 952 return CRLF_TEXT_INPUT;
fd6cce9e
EB
953 else if (!strcmp(value, "auto"))
954 return CRLF_AUTO;
df747b81 955 return CRLF_UNDEFINED;
35ebfd6a
JH
956}
957
7bd18054 958static enum eol git_path_check_eol(struct attr_check_item *check)
fd6cce9e
EB
959{
960 const char *value = check->value;
961
962 if (ATTR_UNSET(value))
963 ;
964 else if (!strcmp(value, "lf"))
965 return EOL_LF;
966 else if (!strcmp(value, "crlf"))
967 return EOL_CRLF;
968 return EOL_UNSET;
969}
970
7bd18054 971static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
aa4ed402
JH
972{
973 const char *value = check->value;
974 struct convert_driver *drv;
975
976 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
977 return NULL;
978 for (drv = user_convert; drv; drv = drv->next)
979 if (!strcmp(value, drv->name))
980 return drv;
981 return NULL;
982}
983
7bd18054 984static int git_path_check_ident(struct attr_check_item *check)
3fed15f5
JH
985{
986 const char *value = check->value;
987
988 return !!ATTR_TRUE(value);
989}
990
3bfba20d
JH
991struct conv_attrs {
992 struct convert_driver *drv;
bb211b4d
TB
993 enum crlf_action attr_action; /* What attr says */
994 enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
3bfba20d
JH
995 int ident;
996};
997
3bfba20d 998static void convert_attrs(struct conv_attrs *ca, const char *path)
83295964 999{
2aef63d3 1000 static struct attr_check *check;
83295964 1001
2aef63d3
JH
1002 if (!check) {
1003 check = attr_check_initl("crlf", "ident", "filter",
1004 "eol", "text", NULL);
83295964
JH
1005 user_convert_tail = &user_convert;
1006 git_config(read_convert_config, NULL);
1007 }
3bfba20d 1008
2aef63d3
JH
1009 if (!git_check_attr(path, check)) {
1010 struct attr_check_item *ccheck = check->items;
bb211b4d 1011 ca->crlf_action = git_path_check_crlf(ccheck + 4);
df747b81 1012 if (ca->crlf_action == CRLF_UNDEFINED)
92cce135 1013 ca->crlf_action = git_path_check_crlf(ccheck + 0);
bb211b4d 1014 ca->attr_action = ca->crlf_action;
92cce135
TB
1015 ca->ident = git_path_check_ident(ccheck + 1);
1016 ca->drv = git_path_check_convert(ccheck + 2);
817a0c79
TB
1017 if (ca->crlf_action != CRLF_BINARY) {
1018 enum eol eol_attr = git_path_check_eol(ccheck + 3);
65237284
TB
1019 if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1020 ca->crlf_action = CRLF_AUTO_INPUT;
1021 else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1022 ca->crlf_action = CRLF_AUTO_CRLF;
1023 else if (eol_attr == EOL_LF)
817a0c79
TB
1024 ca->crlf_action = CRLF_TEXT_INPUT;
1025 else if (eol_attr == EOL_CRLF)
1026 ca->crlf_action = CRLF_TEXT_CRLF;
1027 }
1028 ca->attr_action = ca->crlf_action;
3bfba20d
JH
1029 } else {
1030 ca->drv = NULL;
df747b81 1031 ca->crlf_action = CRLF_UNDEFINED;
3bfba20d
JH
1032 ca->ident = 0;
1033 }
df747b81
TB
1034 if (ca->crlf_action == CRLF_TEXT)
1035 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1036 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1037 ca->crlf_action = CRLF_BINARY;
1038 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1039 ca->crlf_action = CRLF_AUTO_CRLF;
1040 if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1041 ca->crlf_action = CRLF_AUTO_INPUT;
83295964
JH
1042}
1043
9035d75a
SP
1044int would_convert_to_git_filter_fd(const char *path)
1045{
1046 struct conv_attrs ca;
1047
1048 convert_attrs(&ca, path);
1049 if (!ca.drv)
1050 return 0;
1051
1052 /*
1053 * Apply a filter to an fd only if the filter is required to succeed.
1054 * We must die if the filter fails, because the original data before
1055 * filtering is not available.
1056 */
1057 if (!ca.drv->required)
1058 return 0;
1059
234fa07e 1060 return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN);
9035d75a
SP
1061}
1062
a7630bd4
TB
1063const char *get_convert_attr_ascii(const char *path)
1064{
1065 struct conv_attrs ca;
a7630bd4
TB
1066
1067 convert_attrs(&ca, path);
bb211b4d 1068 switch (ca.attr_action) {
df747b81 1069 case CRLF_UNDEFINED:
a7630bd4
TB
1070 return "";
1071 case CRLF_BINARY:
1072 return "-text";
1073 case CRLF_TEXT:
1074 return "text";
df747b81 1075 case CRLF_TEXT_INPUT:
a7630bd4 1076 return "text eol=lf";
df747b81
TB
1077 case CRLF_TEXT_CRLF:
1078 return "text eol=crlf";
a7630bd4
TB
1079 case CRLF_AUTO:
1080 return "text=auto";
df747b81 1081 case CRLF_AUTO_CRLF:
65237284 1082 return "text=auto eol=crlf";
df747b81 1083 case CRLF_AUTO_INPUT:
65237284 1084 return "text=auto eol=lf";
a7630bd4
TB
1085 }
1086 return "";
1087}
1088
82b474e0
BW
1089int convert_to_git(const struct index_state *istate,
1090 const char *path, const char *src, size_t len,
21e5ad50 1091 struct strbuf *dst, enum safe_crlf checksafe)
35ebfd6a 1092{
3bfba20d 1093 int ret = 0;
3bfba20d 1094 struct conv_attrs ca;
6073ee85 1095
3bfba20d 1096 convert_attrs(&ca, path);
3fed15f5 1097
234fa07e
LS
1098 ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN);
1099 if (!ret && ca.drv && ca.drv->required)
36daaaca
JB
1100 die("%s: clean filter '%s' failed", path, ca.drv->name);
1101
92ac3197 1102 if (ret && dst) {
5ecd293d
PH
1103 src = dst->buf;
1104 len = dst->len;
aa4ed402 1105 }
82b474e0 1106 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, checksafe);
92ac3197 1107 if (ret && dst) {
5ecd293d
PH
1108 src = dst->buf;
1109 len = dst->len;
6073ee85 1110 }
3bfba20d 1111 return ret | ident_to_git(path, src, len, dst, ca.ident);
35ebfd6a
JH
1112}
1113
d6c41c20
BW
1114void convert_to_git_filter_fd(const struct index_state *istate,
1115 const char *path, int fd, struct strbuf *dst,
9035d75a
SP
1116 enum safe_crlf checksafe)
1117{
1118 struct conv_attrs ca;
1119 convert_attrs(&ca, path);
1120
1121 assert(ca.drv);
edcc8581 1122 assert(ca.drv->clean || ca.drv->process);
9035d75a 1123
234fa07e 1124 if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN))
9035d75a
SP
1125 die("%s: clean filter '%s' failed", path, ca.drv->name);
1126
d6c41c20 1127 crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
9035d75a
SP
1128 ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1129}
1130
43dd2332
EB
1131static int convert_to_working_tree_internal(const char *path, const char *src,
1132 size_t len, struct strbuf *dst,
1133 int normalizing)
35ebfd6a 1134{
36daaaca 1135 int ret = 0, ret_filter = 0;
3bfba20d 1136 struct conv_attrs ca;
6073ee85 1137
3bfba20d 1138 convert_attrs(&ca, path);
3fed15f5 1139
3bfba20d 1140 ret |= ident_to_worktree(path, src, len, dst, ca.ident);
5ecd293d
PH
1141 if (ret) {
1142 src = dst->buf;
1143 len = dst->len;
3fed15f5 1144 }
43dd2332
EB
1145 /*
1146 * CRLF conversion can be skipped if normalizing, unless there
edcc8581
LS
1147 * is a smudge or process filter (even if the process filter doesn't
1148 * support smudge). The filters might expect CRLFs.
43dd2332 1149 */
edcc8581 1150 if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
3bfba20d 1151 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
43dd2332
EB
1152 if (ret) {
1153 src = dst->buf;
1154 len = dst->len;
1155 }
aa4ed402 1156 }
36daaaca 1157
234fa07e
LS
1158 ret_filter = apply_filter(path, src, len, -1, dst, ca.drv, CAP_SMUDGE);
1159 if (!ret_filter && ca.drv && ca.drv->required)
36daaaca
JB
1160 die("%s: smudge filter %s failed", path, ca.drv->name);
1161
1162 return ret | ret_filter;
35ebfd6a 1163}
f217f0e8 1164
43dd2332
EB
1165int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1166{
1167 return convert_to_working_tree_internal(path, src, len, dst, 0);
1168}
1169
a33e0b2a
BW
1170int renormalize_buffer(const struct index_state *istate, const char *path,
1171 const char *src, size_t len, struct strbuf *dst)
f217f0e8 1172{
43dd2332 1173 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
f217f0e8
EB
1174 if (ret) {
1175 src = dst->buf;
1176 len = dst->len;
1177 }
a33e0b2a 1178 return ret | convert_to_git(istate, path, src, len, dst, SAFE_CRLF_RENORMALIZE);
f217f0e8 1179}
dd8e9121 1180
b6691092
JH
1181/*****************************************************************
1182 *
749f763d 1183 * Streaming conversion support
b6691092
JH
1184 *
1185 *****************************************************************/
1186
1187typedef int (*filter_fn)(struct stream_filter *,
1188 const char *input, size_t *isize_p,
1189 char *output, size_t *osize_p);
1190typedef void (*free_fn)(struct stream_filter *);
1191
1192struct stream_filter_vtbl {
1193 filter_fn filter;
1194 free_fn free;
1195};
1196
1197struct stream_filter {
1198 struct stream_filter_vtbl *vtbl;
1199};
1200
1201static int null_filter_fn(struct stream_filter *filter,
1202 const char *input, size_t *isize_p,
1203 char *output, size_t *osize_p)
1204{
4ae66704
JH
1205 size_t count;
1206
1207 if (!input)
1208 return 0; /* we do not keep any states */
1209 count = *isize_p;
b6691092
JH
1210 if (*osize_p < count)
1211 count = *osize_p;
1212 if (count) {
1213 memmove(output, input, count);
1214 *isize_p -= count;
1215 *osize_p -= count;
1216 }
1217 return 0;
1218}
1219
1220static void null_free_fn(struct stream_filter *filter)
1221{
1222 ; /* nothing -- null instances are shared */
1223}
1224
1225static struct stream_filter_vtbl null_vtbl = {
1226 null_filter_fn,
1227 null_free_fn,
1228};
1229
1230static struct stream_filter null_filter_singleton = {
1231 &null_vtbl,
1232};
1233
1234int is_null_stream_filter(struct stream_filter *filter)
1235{
1236 return filter == &null_filter_singleton;
1237}
1238
b84c7839
JH
1239
1240/*
1241 * LF-to-CRLF filter
1242 */
284e3d28
CMN
1243
1244struct lf_to_crlf_filter {
1245 struct stream_filter filter;
8496f568
JH
1246 unsigned has_held:1;
1247 char held;
284e3d28
CMN
1248};
1249
e322ee38
JH
1250static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1251 const char *input, size_t *isize_p,
1252 char *output, size_t *osize_p)
1253{
284e3d28
CMN
1254 size_t count, o = 0;
1255 struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1256
8496f568
JH
1257 /*
1258 * We may be holding onto the CR to see if it is followed by a
1259 * LF, in which case we would need to go to the main loop.
1260 * Otherwise, just emit it to the output stream.
1261 */
1262 if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1263 output[o++] = lf_to_crlf->held;
1264 lf_to_crlf->has_held = 0;
284e3d28 1265 }
e322ee38 1266
87afe9a5
JH
1267 /* We are told to drain */
1268 if (!input) {
1269 *osize_p -= o;
1270 return 0;
1271 }
e322ee38 1272
e322ee38 1273 count = *isize_p;
8496f568 1274 if (count || lf_to_crlf->has_held) {
284e3d28 1275 size_t i;
8496f568
JH
1276 int was_cr = 0;
1277
1278 if (lf_to_crlf->has_held) {
1279 was_cr = 1;
1280 lf_to_crlf->has_held = 0;
1281 }
1282
284e3d28 1283 for (i = 0; o < *osize_p && i < count; i++) {
e322ee38 1284 char ch = input[i];
8496f568 1285
e322ee38 1286 if (ch == '\n') {
284e3d28 1287 output[o++] = '\r';
8496f568
JH
1288 } else if (was_cr) {
1289 /*
1290 * Previous round saw CR and it is not followed
1291 * by a LF; emit the CR before processing the
1292 * current character.
1293 */
1294 output[o++] = '\r';
e322ee38 1295 }
8496f568
JH
1296
1297 /*
1298 * We may have consumed the last output slot,
1299 * in which case we need to break out of this
1300 * loop; hold the current character before
1301 * returning.
1302 */
1303 if (*osize_p <= o) {
1304 lf_to_crlf->has_held = 1;
1305 lf_to_crlf->held = ch;
1306 continue; /* break but increment i */
1307 }
1308
1309 if (ch == '\r') {
1310 was_cr = 1;
1311 continue;
1312 }
1313
1314 was_cr = 0;
e322ee38
JH
1315 output[o++] = ch;
1316 }
1317
1318 *osize_p -= o;
1319 *isize_p -= i;
8496f568
JH
1320
1321 if (!lf_to_crlf->has_held && was_cr) {
1322 lf_to_crlf->has_held = 1;
1323 lf_to_crlf->held = '\r';
1324 }
e322ee38
JH
1325 }
1326 return 0;
1327}
1328
284e3d28
CMN
1329static void lf_to_crlf_free_fn(struct stream_filter *filter)
1330{
1331 free(filter);
1332}
1333
e322ee38
JH
1334static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1335 lf_to_crlf_filter_fn,
284e3d28 1336 lf_to_crlf_free_fn,
e322ee38
JH
1337};
1338
284e3d28
CMN
1339static struct stream_filter *lf_to_crlf_filter(void)
1340{
87afe9a5 1341 struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
e322ee38 1342
284e3d28 1343 lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
284e3d28
CMN
1344 return (struct stream_filter *)lf_to_crlf;
1345}
b84c7839 1346
a265a7f9
JH
1347/*
1348 * Cascade filter
1349 */
1350#define FILTER_BUFFER 1024
1351struct cascade_filter {
1352 struct stream_filter filter;
1353 struct stream_filter *one;
1354 struct stream_filter *two;
1355 char buf[FILTER_BUFFER];
1356 int end, ptr;
1357};
1358
1359static int cascade_filter_fn(struct stream_filter *filter,
1360 const char *input, size_t *isize_p,
1361 char *output, size_t *osize_p)
1362{
1363 struct cascade_filter *cas = (struct cascade_filter *) filter;
1364 size_t filled = 0;
1365 size_t sz = *osize_p;
1366 size_t to_feed, remaining;
1367
1368 /*
1369 * input -- (one) --> buf -- (two) --> output
1370 */
1371 while (filled < sz) {
1372 remaining = sz - filled;
1373
1374 /* do we already have something to feed two with? */
1375 if (cas->ptr < cas->end) {
1376 to_feed = cas->end - cas->ptr;
1377 if (stream_filter(cas->two,
1378 cas->buf + cas->ptr, &to_feed,
1379 output + filled, &remaining))
1380 return -1;
1381 cas->ptr += (cas->end - cas->ptr) - to_feed;
1382 filled = sz - remaining;
1383 continue;
1384 }
1385
1386 /* feed one from upstream and have it emit into our buffer */
1387 to_feed = input ? *isize_p : 0;
1388 if (input && !to_feed)
1389 break;
1390 remaining = sizeof(cas->buf);
1391 if (stream_filter(cas->one,
1392 input, &to_feed,
1393 cas->buf, &remaining))
1394 return -1;
1395 cas->end = sizeof(cas->buf) - remaining;
1396 cas->ptr = 0;
1397 if (input) {
1398 size_t fed = *isize_p - to_feed;
1399 *isize_p -= fed;
1400 input += fed;
1401 }
1402
1403 /* do we know that we drained one completely? */
1404 if (input || cas->end)
1405 continue;
1406
1407 /* tell two to drain; we have nothing more to give it */
1408 to_feed = 0;
1409 remaining = sz - filled;
1410 if (stream_filter(cas->two,
1411 NULL, &to_feed,
1412 output + filled, &remaining))
1413 return -1;
1414 if (remaining == (sz - filled))
1415 break; /* completely drained two */
1416 filled = sz - remaining;
1417 }
1418 *osize_p -= filled;
1419 return 0;
1420}
1421
1422static void cascade_free_fn(struct stream_filter *filter)
1423{
1424 struct cascade_filter *cas = (struct cascade_filter *)filter;
1425 free_stream_filter(cas->one);
1426 free_stream_filter(cas->two);
1427 free(filter);
1428}
1429
1430static struct stream_filter_vtbl cascade_vtbl = {
1431 cascade_filter_fn,
1432 cascade_free_fn,
1433};
1434
1435static struct stream_filter *cascade_filter(struct stream_filter *one,
1436 struct stream_filter *two)
1437{
1438 struct cascade_filter *cascade;
1439
1440 if (!one || is_null_stream_filter(one))
1441 return two;
1442 if (!two || is_null_stream_filter(two))
1443 return one;
1444
1445 cascade = xmalloc(sizeof(*cascade));
1446 cascade->one = one;
1447 cascade->two = two;
1448 cascade->end = cascade->ptr = 0;
1449 cascade->filter.vtbl = &cascade_vtbl;
1450 return (struct stream_filter *)cascade;
1451}
1452
b84c7839
JH
1453/*
1454 * ident filter
1455 */
1456#define IDENT_DRAINING (-1)
1457#define IDENT_SKIPPING (-2)
1458struct ident_filter {
1459 struct stream_filter filter;
1460 struct strbuf left;
1461 int state;
1462 char ident[45]; /* ": x40 $" */
1463};
1464
1465static int is_foreign_ident(const char *str)
1466{
1467 int i;
1468
ae021d87 1469 if (!skip_prefix(str, "$Id: ", &str))
b84c7839 1470 return 0;
ae021d87 1471 for (i = 0; str[i]; i++) {
b84c7839
JH
1472 if (isspace(str[i]) && str[i+1] != '$')
1473 return 1;
1474 }
1475 return 0;
1476}
1477
1478static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1479{
1480 size_t to_drain = ident->left.len;
1481
1482 if (*osize_p < to_drain)
1483 to_drain = *osize_p;
1484 if (to_drain) {
1485 memcpy(*output_p, ident->left.buf, to_drain);
1486 strbuf_remove(&ident->left, 0, to_drain);
1487 *output_p += to_drain;
1488 *osize_p -= to_drain;
1489 }
1490 if (!ident->left.len)
1491 ident->state = 0;
1492}
1493
1494static int ident_filter_fn(struct stream_filter *filter,
1495 const char *input, size_t *isize_p,
1496 char *output, size_t *osize_p)
1497{
1498 struct ident_filter *ident = (struct ident_filter *)filter;
1499 static const char head[] = "$Id";
1500
1501 if (!input) {
1502 /* drain upon eof */
1503 switch (ident->state) {
1504 default:
1505 strbuf_add(&ident->left, head, ident->state);
1506 case IDENT_SKIPPING:
1507 /* fallthru */
1508 case IDENT_DRAINING:
1509 ident_drain(ident, &output, osize_p);
1510 }
1511 return 0;
1512 }
1513
1514 while (*isize_p || (ident->state == IDENT_DRAINING)) {
1515 int ch;
1516
1517 if (ident->state == IDENT_DRAINING) {
1518 ident_drain(ident, &output, osize_p);
1519 if (!*osize_p)
1520 break;
1521 continue;
1522 }
1523
1524 ch = *(input++);
1525 (*isize_p)--;
1526
1527 if (ident->state == IDENT_SKIPPING) {
1528 /*
1529 * Skipping until '$' or LF, but keeping them
1530 * in case it is a foreign ident.
1531 */
1532 strbuf_addch(&ident->left, ch);
1533 if (ch != '\n' && ch != '$')
1534 continue;
1535 if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1536 strbuf_setlen(&ident->left, sizeof(head) - 1);
1537 strbuf_addstr(&ident->left, ident->ident);
1538 }
1539 ident->state = IDENT_DRAINING;
1540 continue;
1541 }
1542
1543 if (ident->state < sizeof(head) &&
1544 head[ident->state] == ch) {
1545 ident->state++;
1546 continue;
1547 }
1548
1549 if (ident->state)
1550 strbuf_add(&ident->left, head, ident->state);
1551 if (ident->state == sizeof(head) - 1) {
1552 if (ch != ':' && ch != '$') {
1553 strbuf_addch(&ident->left, ch);
1554 ident->state = 0;
1555 continue;
1556 }
1557
1558 if (ch == ':') {
1559 strbuf_addch(&ident->left, ch);
1560 ident->state = IDENT_SKIPPING;
1561 } else {
1562 strbuf_addstr(&ident->left, ident->ident);
1563 ident->state = IDENT_DRAINING;
1564 }
1565 continue;
1566 }
1567
1568 strbuf_addch(&ident->left, ch);
1569 ident->state = IDENT_DRAINING;
1570 }
1571 return 0;
1572}
1573
1574static void ident_free_fn(struct stream_filter *filter)
1575{
1576 struct ident_filter *ident = (struct ident_filter *)filter;
1577 strbuf_release(&ident->left);
1578 free(filter);
1579}
1580
1581static struct stream_filter_vtbl ident_vtbl = {
1582 ident_filter_fn,
1583 ident_free_fn,
1584};
1585
1586static struct stream_filter *ident_filter(const unsigned char *sha1)
1587{
1588 struct ident_filter *ident = xmalloc(sizeof(*ident));
1589
5096d490
JK
1590 xsnprintf(ident->ident, sizeof(ident->ident),
1591 ": %s $", sha1_to_hex(sha1));
b84c7839
JH
1592 strbuf_init(&ident->left, 0);
1593 ident->filter.vtbl = &ident_vtbl;
1594 ident->state = 0;
1595 return (struct stream_filter *)ident;
1596}
1597
dd8e9121 1598/*
b6691092
JH
1599 * Return an appropriately constructed filter for the path, or NULL if
1600 * the contents cannot be filtered without reading the whole thing
1601 * in-core.
1602 *
1603 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1604 * large binary blob you would want us not to slurp into the memory!
dd8e9121 1605 */
b6691092 1606struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
dd8e9121
JH
1607{
1608 struct conv_attrs ca;
b84c7839 1609 struct stream_filter *filter = NULL;
dd8e9121
JH
1610
1611 convert_attrs(&ca, path);
edcc8581 1612 if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
caa47adc
TB
1613 return NULL;
1614
1615 if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1616 return NULL;
b84c7839
JH
1617
1618 if (ca.ident)
1619 filter = ident_filter(sha1);
dd8e9121 1620
caa47adc 1621 if (output_eol(ca.crlf_action) == EOL_CRLF)
284e3d28 1622 filter = cascade_filter(filter, lf_to_crlf_filter());
caa47adc
TB
1623 else
1624 filter = cascade_filter(filter, &null_filter_singleton);
e322ee38 1625
b84c7839 1626 return filter;
b6691092
JH
1627}
1628
1629void free_stream_filter(struct stream_filter *filter)
1630{
1631 filter->vtbl->free(filter);
1632}
1633
1634int stream_filter(struct stream_filter *filter,
1635 const char *input, size_t *isize_p,
1636 char *output, size_t *osize_p)
1637{
1638 return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
dd8e9121 1639}