1/*
2 * apply.c
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This applies patches on top of some (arbitrary) version of the SCM.
7 *
8 * NOTE! It does all its work in the index file, and only cares about
9 * the files in the working directory if you tell it to "merge" the
10 * patch apply.
11 *
12 * Even when merging it always takes the source from the index, and
13 * uses the working tree as a "branch" for a 3-way merge.
14 */
15#include <ctype.h>
16
17#include "cache.h"
18
19// We default to the merge behaviour, since that's what most people would
20// expect
21static int merge_patch = 1;
22static const char apply_usage[] = "git-apply <patch>";
23
24/*
25 * Various "current state", notably line numbers and what
26 * file (and how) we're patching right now.. The "is_xxxx"
27 * things are flags, where -1 means "don't know yet".
28 */
29static int linenr = 1;
30static int old_mode, new_mode;
31static char *old_name, *new_name, *def_name;
32static int is_rename, is_copy, is_new, is_delete;
33
34#define CHUNKSIZE (8192)
35#define SLOP (16)
36
37static void *read_patch_file(int fd, unsigned long *sizep)
38{
39 unsigned long size = 0, alloc = CHUNKSIZE;
40 void *buffer = xmalloc(alloc);
41
42 for (;;) {
43 int nr = alloc - size;
44 if (nr < 1024) {
45 alloc += CHUNKSIZE;
46 buffer = xrealloc(buffer, alloc);
47 nr = alloc - size;
48 }
49 nr = read(fd, buffer + size, nr);
50 if (!nr)
51 break;
52 if (nr < 0) {
53 if (errno == EAGAIN)
54 continue;
55 die("git-apply: read returned %s", strerror(errno));
56 }
57 size += nr;
58 }
59 *sizep = size;
60
61 /*
62 * Make sure that we have some slop in the buffer
63 * so that we can do speculative "memcmp" etc, and
64 * see to it that it is NUL-filled.
65 */
66 if (alloc < size + SLOP)
67 buffer = xrealloc(buffer, size + SLOP);
68 memset(buffer + size, 0, SLOP);
69 return buffer;
70}
71
72static unsigned long linelen(char *buffer, unsigned long size)
73{
74 unsigned long len = 0;
75 while (size--) {
76 len++;
77 if (*buffer++ == '\n')
78 break;
79 }
80 return len;
81}
82
83static int is_dev_null(const char *str)
84{
85 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
86}
87
88#define TERM_EXIST 1
89#define TERM_SPACE 2
90#define TERM_TAB 4
91
92static int name_terminate(const char *name, int namelen, int c, int terminate)
93{
94 if (c == ' ' && !(terminate & TERM_SPACE))
95 return 0;
96 if (c == '\t' && !(terminate & TERM_TAB))
97 return 0;
98
99 /*
100 * Do we want an existing name? Return false and
101 * continue if it's not there.
102 */
103 if (terminate & TERM_EXIST)
104 return cache_name_pos(name, namelen) >= 0;
105
106 return 1;
107}
108
109static char * find_name(const char *line, char *def, int p_value, int terminate)
110{
111 int len;
112 const char *start = line;
113 char *name;
114
115 for (;;) {
116 char c = *line;
117
118 if (isspace(c)) {
119 if (c == '\n')
120 break;
121 if (name_terminate(start, line-start, c, terminate))
122 break;
123 }
124 line++;
125 if (c == '/' && !--p_value)
126 start = line;
127 }
128 if (!start)
129 return def;
130 len = line - start;
131 if (!len)
132 return def;
133
134 /*
135 * Generally we prefer the shorter name, especially
136 * if the other one is just a variation of that with
137 * something else tacked on to the end (ie "file.orig"
138 * or "file~").
139 */
140 if (def) {
141 int deflen = strlen(def);
142 if (deflen < len && !strncmp(start, def, deflen))
143 return def;
144 }
145
146 name = xmalloc(len + 1);
147 memcpy(name, start, len);
148 name[len] = 0;
149 free(def);
150 return name;
151}
152
153/*
154 * Get the name etc info from the --/+++ lines of a traditional patch header
155 *
156 * NOTE! This hardcodes "-p1" behaviour in filename detection.
157 *
158 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
159 * files, we can happily check the index for a match, but for creating a
160 * new file we should try to match whatever "patch" does. I have no idea.
161 */
162static int parse_traditional_patch(const char *first, const char *second)
163{
164 int p_value = 1;
165 char *name;
166
167 first += 4; // skip "--- "
168 second += 4; // skip "+++ "
169 if (is_dev_null(first)) {
170 is_new = 1;
171 name = find_name(second, def_name, p_value, TERM_SPACE | TERM_TAB);
172 new_name = name;
173 } else if (is_dev_null(second)) {
174 is_delete = 1;
175 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
176 old_name = name;
177 } else {
178 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
179 name = find_name(second, name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
180 old_name = new_name = name;
181 }
182 if (!name)
183 die("unable to find filename in patch at line %d", linenr);
184}
185
186static int gitdiff_hdrend(const char *line)
187{
188 return -1;
189}
190
191static int gitdiff_oldname(const char *line)
192{
193 if (!old_name && !is_new)
194 old_name = find_name(line, NULL, 1, 0);
195 return 0;
196}
197
198static int gitdiff_newname(const char *line)
199{
200 if (!new_name && !is_delete)
201 new_name = find_name(line, NULL, 1, 0);
202 return 0;
203}
204
205static int gitdiff_oldmode(const char *line)
206{
207 old_mode = strtoul(line, NULL, 8);
208 return 0;
209}
210
211static int gitdiff_newmode(const char *line)
212{
213 new_mode = strtoul(line, NULL, 8);
214 return 0;
215}
216
217static int gitdiff_delete(const char *line)
218{
219 is_delete = 1;
220 return gitdiff_oldmode(line);
221}
222
223static int gitdiff_newfile(const char *line)
224{
225 is_new = 1;
226 return gitdiff_newmode(line);
227}
228
229static int gitdiff_copysrc(const char *line)
230{
231 is_copy = 1;
232 old_name = find_name(line, NULL, 0, 0);
233 return 0;
234}
235
236static int gitdiff_copydst(const char *line)
237{
238 is_copy = 1;
239 new_name = find_name(line, NULL, 0, 0);
240 return 0;
241}
242
243static int gitdiff_renamesrc(const char *line)
244{
245 is_rename = 1;
246 old_name = find_name(line, NULL, 0, 0);
247 return 0;
248}
249
250static int gitdiff_renamedst(const char *line)
251{
252 is_rename = 1;
253 new_name = find_name(line, NULL, 0, 0);
254 return 0;
255}
256
257static int gitdiff_similarity(const char *line)
258{
259 return 0;
260}
261
262/*
263 * This is normal for a diff that doesn't change anything: we'll fall through
264 * into the next diff. Tell the parser to break out.
265 */
266static int gitdiff_unrecognized(const char *line)
267{
268 return -1;
269}
270
271/* Verify that we recognize the lines following a git header */
272static int parse_git_header(char *line, int len, unsigned int size)
273{
274 unsigned long offset;
275
276 /* A git diff has explicit new/delete information, so we don't guess */
277 is_new = 0;
278 is_delete = 0;
279
280 line += len;
281 size -= len;
282 linenr++;
283 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
284 static const struct opentry {
285 const char *str;
286 int (*fn)(const char *);
287 } optable[] = {
288 { "@@ -", gitdiff_hdrend },
289 { "--- ", gitdiff_oldname },
290 { "+++ ", gitdiff_newname },
291 { "old mode ", gitdiff_oldmode },
292 { "new mode ", gitdiff_newmode },
293 { "deleted file mode ", gitdiff_delete },
294 { "new file mode ", gitdiff_newfile },
295 { "copy from ", gitdiff_copysrc },
296 { "copy to ", gitdiff_copydst },
297 { "rename from ", gitdiff_renamesrc },
298 { "rename to ", gitdiff_renamedst },
299 { "similarity index ", gitdiff_similarity },
300 { "", gitdiff_unrecognized },
301 };
302 int i;
303
304 len = linelen(line, size);
305 if (!len || line[len-1] != '\n')
306 break;
307 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
308 const struct opentry *p = optable + i;
309 int oplen = strlen(p->str);
310 if (len < oplen || memcmp(p->str, line, oplen))
311 continue;
312 if (p->fn(line + oplen) < 0)
313 return offset;
314 break;
315 }
316 }
317
318 return offset;
319}
320
321static int parse_num(const char *line, int len, int offset, const char *expect, unsigned long *p)
322{
323 char *ptr;
324 int digits, ex;
325
326 if (offset < 0 || offset >= len)
327 return -1;
328 line += offset;
329 len -= offset;
330
331 if (!isdigit(*line))
332 return -1;
333 *p = strtoul(line, &ptr, 10);
334
335 digits = ptr - line;
336
337 offset += digits;
338 line += digits;
339 len -= digits;
340
341 ex = strlen(expect);
342 if (ex > len)
343 return -1;
344 if (memcmp(line, expect, ex))
345 return -1;
346
347 return offset + ex;
348}
349
350/*
351 * Parse a unified diff fragment header of the
352 * form "@@ -a,b +c,d @@"
353 */
354static int parse_fragment_header(char *line, int len, unsigned long *pos)
355{
356 int offset;
357
358 if (!len || line[len-1] != '\n')
359 return -1;
360
361 /* Figure out the number of lines in a fragment */
362 offset = parse_num(line, len, 4, ",", pos);
363 offset = parse_num(line, len, offset, " +", pos+1);
364 offset = parse_num(line, len, offset, ",", pos+2);
365 offset = parse_num(line, len, offset, " @@", pos+3);
366
367 return offset;
368}
369
370static int find_header(char *line, unsigned long size, int *hdrsize)
371{
372 unsigned long offset, len;
373
374 is_rename = is_copy = 0;
375 is_new = is_delete = -1;
376 old_mode = new_mode = 0;
377 def_name = old_name = new_name = NULL;
378 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
379 unsigned long nextlen;
380
381 len = linelen(line, size);
382 if (!len)
383 break;
384
385 /* Testing this early allows us to take a few shortcuts.. */
386 if (len < 6)
387 continue;
388
389 /*
390 * Make sure we don't find any unconnected patch fragmants.
391 * That's a sign that we didn't find a header, and that a
392 * patch has become corrupted/broken up.
393 */
394 if (!memcmp("@@ -", line, 4)) {
395 unsigned long pos[4];
396 if (parse_fragment_header(line, len, pos) < 0)
397 continue;
398 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
399 }
400
401 if (size < len + 6)
402 break;
403
404 /*
405 * Git patch? It might not have a real patch, just a rename
406 * or mode change, so we handle that specially
407 */
408 if (!memcmp("diff --git ", line, 11)) {
409 int git_hdr_len = parse_git_header(line, len, size);
410 if (git_hdr_len < 0)
411 continue;
412
413 *hdrsize = git_hdr_len;
414 return offset;
415 }
416
417 /** --- followed by +++ ? */
418 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
419 continue;
420
421 /*
422 * We only accept unified patches, so we want it to
423 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
424 * minimum
425 */
426 nextlen = linelen(line + len, size - len);
427 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
428 continue;
429
430 /* Ok, we'll consider it a patch */
431 parse_traditional_patch(line, line+len);
432 *hdrsize = len + nextlen;
433 linenr += 2;
434 return offset;
435 }
436 return -1;
437}
438
439/*
440 * Parse a unified diff. Note that this really needs
441 * to parse each fragment separately, since the only
442 * way to know the difference between a "---" that is
443 * part of a patch, and a "---" that starts the next
444 * patch is to look at the line counts..
445 */
446static int apply_fragment(char *line, unsigned long size)
447{
448 int len = linelen(line, size), offset;
449 unsigned long pos[4], oldlines, newlines;
450
451 offset = parse_fragment_header(line, len, pos);
452 if (offset < 0)
453 return -1;
454 oldlines = pos[1];
455 newlines = pos[3];
456
457 if (is_new < 0 && (pos[0] || oldlines))
458 is_new = 0;
459 if (is_delete < 0 && (pos[1] || newlines))
460 is_delete = 0;
461
462 /* Parse the thing.. */
463 line += len;
464 size -= len;
465 linenr++;
466 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
467 if (!oldlines && !newlines)
468 break;
469 len = linelen(line, size);
470 if (!len || line[len-1] != '\n')
471 return -1;
472 switch (*line) {
473 default:
474 return -1;
475 case ' ':
476 oldlines--;
477 newlines--;
478 break;
479 case '-':
480 oldlines--;
481 break;
482 case '+':
483 newlines--;
484 break;
485 }
486 }
487 return offset;
488}
489
490static int apply_single_patch(char *line, unsigned long size)
491{
492 unsigned long offset = 0;
493
494 while (size > 4 && !memcmp(line, "@@ -", 4)) {
495 int len = apply_fragment(line, size);
496 if (len <= 0)
497 die("corrupt patch at line %d", linenr);
498
499printf("applying fragment:\n%.*s\n\n", len, line);
500
501 offset += len;
502 line += len;
503 size -= len;
504 }
505 return offset;
506}
507
508static int apply_chunk(char *buffer, unsigned long size)
509{
510 int hdrsize, patchsize;
511 int offset = find_header(buffer, size, &hdrsize);
512 char *header, *patch;
513
514 if (offset < 0)
515 return offset;
516 header = buffer + offset;
517
518printf("Found header:\n%.*s\n\n", hdrsize, header);
519printf("Rename: %d\n", is_rename);
520printf("Copy: %d\n", is_copy);
521printf("New: %d\n", is_new);
522printf("Delete: %d\n", is_delete);
523printf("Mode: %o:%o\n", old_mode, new_mode);
524printf("Name: '%s':'%s'\n", old_name, new_name);
525
526 if (old_name && cache_name_pos(old_name, strlen(old_name)) < 0)
527 die("file %s does not exist", old_name);
528 if (new_name && (is_new | is_rename | is_copy)) {
529 if (cache_name_pos(new_name, strlen(new_name)) >= 0)
530 die("file %s already exists", new_name);
531 }
532
533 patch = header + hdrsize;
534 patchsize = apply_single_patch(patch, size - offset - hdrsize);
535
536 return offset + hdrsize + patchsize;
537}
538
539static int apply_patch(int fd)
540{
541 unsigned long offset, size;
542 char *buffer = read_patch_file(fd, &size);
543
544 if (!buffer)
545 return -1;
546 offset = 0;
547 while (size > 0) {
548 int nr = apply_chunk(buffer + offset, size);
549 if (nr < 0)
550 break;
551 offset += nr;
552 size -= nr;
553 }
554 free(buffer);
555 return 0;
556}
557
558int main(int argc, char **argv)
559{
560 int i;
561 int read_stdin = 1;
562
563 if (read_cache() < 0)
564 die("unable to read index file");
565
566 for (i = 1; i < argc; i++) {
567 const char *arg = argv[i];
568 int fd;
569
570 if (!strcmp(arg, "-")) {
571 apply_patch(0);
572 read_stdin = 0;
573 continue;
574 }
575 if (!strcmp(arg, "--no-merge")) {
576 merge_patch = 0;
577 continue;
578 }
579 fd = open(arg, O_RDONLY);
580 if (fd < 0)
581 usage(apply_usage);
582 read_stdin = 0;
583 apply_patch(fd);
584 close(fd);
585 }
586 if (read_stdin)
587 apply_patch(0);
588 return 0;
589}