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