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