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