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