Coverage Report

Created: 2026-03-21 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/apply.c
Line
Count
Source
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
 */
9
10
#define USE_THE_REPOSITORY_VARIABLE
11
#define DISABLE_SIGN_COMPARE_WARNINGS
12
13
#include "git-compat-util.h"
14
#include "abspath.h"
15
#include "base85.h"
16
#include "config.h"
17
#include "odb.h"
18
#include "delta.h"
19
#include "diff.h"
20
#include "dir.h"
21
#include "environment.h"
22
#include "gettext.h"
23
#include "hex.h"
24
#include "xdiff-interface.h"
25
#include "merge-ll.h"
26
#include "lockfile.h"
27
#include "name-hash.h"
28
#include "object-name.h"
29
#include "object-file.h"
30
#include "parse-options.h"
31
#include "path.h"
32
#include "quote.h"
33
#include "read-cache.h"
34
#include "repository.h"
35
#include "rerere.h"
36
#include "apply.h"
37
#include "entry.h"
38
#include "setup.h"
39
#include "symlinks.h"
40
#include "wildmatch.h"
41
#include "ws.h"
42
43
struct gitdiff_data {
44
  struct strbuf *root;
45
  int linenr;
46
  int p_value;
47
};
48
49
static void git_apply_config(void)
50
0
{
51
0
  repo_config_get_string(the_repository, "apply.whitespace", &apply_default_whitespace);
52
0
  repo_config_get_string(the_repository, "apply.ignorewhitespace", &apply_default_ignorewhitespace);
53
0
  repo_config(the_repository, git_xmerge_config, NULL);
54
0
}
55
56
static int parse_whitespace_option(struct apply_state *state, const char *option)
57
0
{
58
0
  if (!option) {
59
0
    state->ws_error_action = warn_on_ws_error;
60
0
    return 0;
61
0
  }
62
0
  if (!strcmp(option, "warn")) {
63
0
    state->ws_error_action = warn_on_ws_error;
64
0
    return 0;
65
0
  }
66
0
  if (!strcmp(option, "nowarn")) {
67
0
    state->ws_error_action = nowarn_ws_error;
68
0
    return 0;
69
0
  }
70
0
  if (!strcmp(option, "error")) {
71
0
    state->ws_error_action = die_on_ws_error;
72
0
    return 0;
73
0
  }
74
0
  if (!strcmp(option, "error-all")) {
75
0
    state->ws_error_action = die_on_ws_error;
76
0
    state->squelch_whitespace_errors = 0;
77
0
    return 0;
78
0
  }
79
0
  if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
80
0
    state->ws_error_action = correct_ws_error;
81
0
    return 0;
82
0
  }
83
  /*
84
   * Please update $__git_whitespacelist in git-completion.bash,
85
   * Documentation/git-apply.adoc, and Documentation/git-am.adoc
86
   * when you add new options.
87
   */
88
0
  return error(_("unrecognized whitespace option '%s'"), option);
89
0
}
90
91
static int parse_ignorewhitespace_option(struct apply_state *state,
92
             const char *option)
93
0
{
94
0
  if (!option || !strcmp(option, "no") ||
95
0
      !strcmp(option, "false") || !strcmp(option, "never") ||
96
0
      !strcmp(option, "none")) {
97
0
    state->ws_ignore_action = ignore_ws_none;
98
0
    return 0;
99
0
  }
100
0
  if (!strcmp(option, "change")) {
101
0
    state->ws_ignore_action = ignore_ws_change;
102
0
    return 0;
103
0
  }
104
0
  return error(_("unrecognized whitespace ignore option '%s'"), option);
105
0
}
106
107
int init_apply_state(struct apply_state *state,
108
         struct repository *repo,
109
         const char *prefix)
110
0
{
111
0
  memset(state, 0, sizeof(*state));
112
0
  state->prefix = prefix;
113
0
  state->repo = repo;
114
0
  state->apply = 1;
115
0
  state->line_termination = '\n';
116
0
  state->p_value = 1;
117
0
  state->p_context = UINT_MAX;
118
0
  state->squelch_whitespace_errors = 5;
119
0
  state->ws_error_action = warn_on_ws_error;
120
0
  state->ws_ignore_action = ignore_ws_none;
121
0
  state->linenr = 1;
122
0
  string_list_init_nodup(&state->fn_table);
123
0
  string_list_init_nodup(&state->limit_by_name);
124
0
  strset_init(&state->removed_symlinks);
125
0
  strset_init(&state->kept_symlinks);
126
0
  strbuf_init(&state->root, 0);
127
128
0
  git_apply_config();
129
0
  if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
130
0
    return -1;
131
0
  if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
132
0
    return -1;
133
0
  return 0;
134
0
}
135
136
void clear_apply_state(struct apply_state *state)
137
0
{
138
0
  string_list_clear(&state->limit_by_name, 0);
139
0
  strset_clear(&state->removed_symlinks);
140
0
  strset_clear(&state->kept_symlinks);
141
0
  strbuf_release(&state->root);
142
0
  FREE_AND_NULL(state->fake_ancestor);
143
144
  /* &state->fn_table is cleared at the end of apply_patch() */
145
0
}
146
147
static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
148
0
{
149
  /* do nothing */
150
0
}
151
152
int check_apply_state(struct apply_state *state, int force_apply)
153
0
{
154
0
  int is_not_gitdir = !startup_info->have_repository;
155
156
0
  if (state->apply_with_reject && state->threeway)
157
0
    return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
158
0
  if (state->threeway) {
159
0
    if (is_not_gitdir)
160
0
      return error(_("'%s' outside a repository"), "--3way");
161
0
    state->check_index = 1;
162
0
  }
163
0
  if (state->apply_with_reject) {
164
0
    state->apply = 1;
165
0
    if (state->apply_verbosity == verbosity_normal)
166
0
      state->apply_verbosity = verbosity_verbose;
167
0
  }
168
0
  if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
169
0
    state->apply = 0;
170
0
  if (state->check_index && is_not_gitdir)
171
0
    return error(_("'%s' outside a repository"), "--index");
172
0
  if (state->cached) {
173
0
    if (is_not_gitdir)
174
0
      return error(_("'%s' outside a repository"), "--cached");
175
0
    state->check_index = 1;
176
0
  }
177
0
  if (state->ita_only && (state->check_index || is_not_gitdir))
178
0
    state->ita_only = 0;
179
0
  if (state->check_index)
180
0
    state->unsafe_paths = 0;
181
182
0
  if (state->apply_verbosity <= verbosity_silent) {
183
0
    state->saved_error_routine = get_error_routine();
184
0
    state->saved_warn_routine = get_warn_routine();
185
0
    set_error_routine(mute_routine);
186
0
    set_warn_routine(mute_routine);
187
0
  }
188
189
0
  return 0;
190
0
}
191
192
static void set_default_whitespace_mode(struct apply_state *state)
193
0
{
194
0
  if (!state->whitespace_option && !apply_default_whitespace)
195
0
    state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
196
0
}
197
198
/*
199
 * This represents one "hunk" from a patch, starting with
200
 * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
201
 * patch text is pointed at by patch, and its byte length
202
 * is stored in size.  leading and trailing are the number
203
 * of context lines.
204
 */
205
struct fragment {
206
  unsigned long leading, trailing;
207
  unsigned long oldpos, oldlines;
208
  unsigned long newpos, newlines;
209
  /*
210
   * 'patch' is usually borrowed from buf in apply_patch(),
211
   * but some codepaths store an allocated buffer.
212
   */
213
  const char *patch;
214
  unsigned free_patch:1,
215
    rejected:1;
216
  int size;
217
  int linenr;
218
  struct fragment *next;
219
};
220
221
/*
222
 * When dealing with a binary patch, we reuse "leading" field
223
 * to store the type of the binary hunk, either deflated "delta"
224
 * or deflated "literal".
225
 */
226
0
#define binary_patch_method leading
227
0
#define BINARY_DELTA_DEFLATED 1
228
0
#define BINARY_LITERAL_DEFLATED 2
229
230
static void free_fragment_list(struct fragment *list)
231
0
{
232
0
  while (list) {
233
0
    struct fragment *next = list->next;
234
0
    if (list->free_patch)
235
0
      free((char *)list->patch);
236
0
    free(list);
237
0
    list = next;
238
0
  }
239
0
}
240
241
void release_patch(struct patch *patch)
242
0
{
243
0
  free_fragment_list(patch->fragments);
244
0
  free(patch->def_name);
245
0
  free(patch->old_name);
246
0
  free(patch->new_name);
247
0
  free(patch->result);
248
0
}
249
250
static void free_patch(struct patch *patch)
251
0
{
252
0
  release_patch(patch);
253
0
  free(patch);
254
0
}
255
256
static void free_patch_list(struct patch *list)
257
0
{
258
0
  while (list) {
259
0
    struct patch *next = list->next;
260
0
    free_patch(list);
261
0
    list = next;
262
0
  }
263
0
}
264
265
/*
266
 * A line in a file, len-bytes long (includes the terminating LF,
267
 * except for an incomplete line at the end if the file ends with
268
 * one), and its contents hashes to 'hash'.
269
 */
270
struct line {
271
  size_t len;
272
  unsigned hash : 24;
273
  unsigned flag : 8;
274
0
#define LINE_COMMON     1
275
0
#define LINE_PATCHED  2
276
};
277
278
/*
279
 * This represents a "file", which is an array of "lines".
280
 */
281
struct image {
282
  struct strbuf buf;
283
  struct line *line;
284
  size_t line_nr, line_alloc;
285
};
286
0
#define IMAGE_INIT { \
287
0
  .buf = STRBUF_INIT, \
288
0
}
289
290
static void image_init(struct image *image)
291
0
{
292
0
  struct image empty = IMAGE_INIT;
293
0
  memcpy(image, &empty, sizeof(*image));
294
0
}
295
296
static void image_clear(struct image *image)
297
0
{
298
0
  strbuf_release(&image->buf);
299
0
  free(image->line);
300
0
  image_init(image);
301
0
}
302
303
static uint32_t hash_line(const char *cp, size_t len)
304
0
{
305
0
  size_t i;
306
0
  uint32_t h;
307
0
  for (i = 0, h = 0; i < len; i++) {
308
0
    if (!isspace(cp[i])) {
309
0
      h = h * 3 + (cp[i] & 0xff);
310
0
    }
311
0
  }
312
0
  return h;
313
0
}
314
315
static void image_add_line(struct image *img, const char *bol, size_t len, unsigned flag)
316
0
{
317
0
  ALLOC_GROW(img->line, img->line_nr + 1, img->line_alloc);
318
0
  img->line[img->line_nr].len = len;
319
0
  img->line[img->line_nr].hash = hash_line(bol, len);
320
0
  img->line[img->line_nr].flag = flag;
321
0
  img->line_nr++;
322
0
}
323
324
/*
325
 * "buf" has the file contents to be patched (read from various sources).
326
 * attach it to "image" and add line-based index to it.
327
 * "image" now owns the "buf".
328
 */
329
static void image_prepare(struct image *image, char *buf, size_t len,
330
        int prepare_linetable)
331
0
{
332
0
  const char *cp, *ep;
333
334
0
  image_clear(image);
335
0
  strbuf_attach(&image->buf, buf, len, len + 1);
336
337
0
  if (!prepare_linetable)
338
0
    return;
339
340
0
  ep = image->buf.buf + image->buf.len;
341
0
  cp = image->buf.buf;
342
0
  while (cp < ep) {
343
0
    const char *next;
344
0
    for (next = cp; next < ep && *next != '\n'; next++)
345
0
      ;
346
0
    if (next < ep)
347
0
      next++;
348
0
    image_add_line(image, cp, next - cp, 0);
349
0
    cp = next;
350
0
  }
351
0
}
352
353
static void image_remove_first_line(struct image *img)
354
0
{
355
0
  strbuf_remove(&img->buf, 0, img->line[0].len);
356
0
  img->line_nr--;
357
0
  if (img->line_nr)
358
0
    MOVE_ARRAY(img->line, img->line + 1, img->line_nr);
359
0
}
360
361
static void image_remove_last_line(struct image *img)
362
0
{
363
0
  size_t last_line_len = img->line[img->line_nr - 1].len;
364
0
  strbuf_setlen(&img->buf, img->buf.len - last_line_len);
365
0
  img->line_nr--;
366
0
}
367
368
/* fmt must contain _one_ %s and no other substitution */
369
static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
370
0
{
371
0
  struct strbuf sb = STRBUF_INIT;
372
373
0
  if (patch->old_name && patch->new_name &&
374
0
      strcmp(patch->old_name, patch->new_name)) {
375
0
    quote_c_style(patch->old_name, &sb, NULL, 0);
376
0
    strbuf_addstr(&sb, " => ");
377
0
    quote_c_style(patch->new_name, &sb, NULL, 0);
378
0
  } else {
379
0
    const char *n = patch->new_name;
380
0
    if (!n)
381
0
      n = patch->old_name;
382
0
    quote_c_style(n, &sb, NULL, 0);
383
0
  }
384
0
  fprintf(output, fmt, sb.buf);
385
0
  fputc('\n', output);
386
0
  strbuf_release(&sb);
387
0
}
388
389
0
#define SLOP (16)
390
391
/*
392
 * apply.c isn't equipped to handle arbitrarily large patches, because
393
 * it intermingles `unsigned long` with `int` for the type used to store
394
 * buffer lengths.
395
 *
396
 * Only process patches that are just shy of 1 GiB large in order to
397
 * avoid any truncation or overflow issues.
398
 */
399
0
#define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
400
401
static int read_patch_file(struct strbuf *sb, int fd)
402
0
{
403
0
  if (strbuf_read(sb, fd, 0) < 0)
404
0
    return error_errno(_("failed to read patch"));
405
0
  else if (sb->len >= MAX_APPLY_SIZE)
406
0
    return error(_("patch too large"));
407
  /*
408
   * Make sure that we have some slop in the buffer
409
   * so that we can do speculative "memcmp" etc, and
410
   * see to it that it is NUL-filled.
411
   */
412
0
  strbuf_grow(sb, SLOP);
413
0
  memset(sb->buf + sb->len, 0, SLOP);
414
0
  return 0;
415
0
}
416
417
static unsigned long linelen(const char *buffer, unsigned long size)
418
0
{
419
0
  unsigned long len = 0;
420
0
  while (size--) {
421
0
    len++;
422
0
    if (*buffer++ == '\n')
423
0
      break;
424
0
  }
425
0
  return len;
426
0
}
427
428
static int is_dev_null(const char *str)
429
0
{
430
0
  return skip_prefix(str, "/dev/null", &str) && isspace(*str);
431
0
}
432
433
0
#define TERM_SPACE  1
434
0
#define TERM_TAB  2
435
436
static int name_terminate(int c, int terminate)
437
0
{
438
0
  if (c == ' ' && !(terminate & TERM_SPACE))
439
0
    return 0;
440
0
  if (c == '\t' && !(terminate & TERM_TAB))
441
0
    return 0;
442
443
0
  return 1;
444
0
}
445
446
/* remove double slashes to make --index work with such filenames */
447
static char *squash_slash(char *name)
448
0
{
449
0
  int i = 0, j = 0;
450
451
0
  if (!name)
452
0
    return NULL;
453
454
0
  while (name[i]) {
455
0
    if ((name[j++] = name[i++]) == '/')
456
0
      while (name[i] == '/')
457
0
        i++;
458
0
  }
459
0
  name[j] = '\0';
460
0
  return name;
461
0
}
462
463
static char *find_name_gnu(struct strbuf *root,
464
         const char *line,
465
         int p_value)
466
0
{
467
0
  struct strbuf name = STRBUF_INIT;
468
0
  char *cp;
469
470
  /*
471
   * Proposed "new-style" GNU patch/diff format; see
472
   * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
473
   */
474
0
  if (unquote_c_style(&name, line, NULL)) {
475
0
    strbuf_release(&name);
476
0
    return NULL;
477
0
  }
478
479
0
  for (cp = name.buf; p_value; p_value--) {
480
0
    cp = strchr(cp, '/');
481
0
    if (!cp) {
482
0
      strbuf_release(&name);
483
0
      return NULL;
484
0
    }
485
0
    cp++;
486
0
  }
487
488
0
  strbuf_remove(&name, 0, cp - name.buf);
489
0
  if (root->len)
490
0
    strbuf_insert(&name, 0, root->buf, root->len);
491
0
  return squash_slash(strbuf_detach(&name, NULL));
492
0
}
493
494
static size_t sane_tz_len(const char *line, size_t len)
495
0
{
496
0
  const char *tz, *p;
497
498
0
  if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
499
0
    return 0;
500
0
  tz = line + len - strlen(" +0500");
501
502
0
  if (tz[1] != '+' && tz[1] != '-')
503
0
    return 0;
504
505
0
  for (p = tz + 2; p != line + len; p++)
506
0
    if (!isdigit(*p))
507
0
      return 0;
508
509
0
  return line + len - tz;
510
0
}
511
512
static size_t tz_with_colon_len(const char *line, size_t len)
513
0
{
514
0
  const char *tz, *p;
515
516
0
  if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
517
0
    return 0;
518
0
  tz = line + len - strlen(" +08:00");
519
520
0
  if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
521
0
    return 0;
522
0
  p = tz + 2;
523
0
  if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
524
0
      !isdigit(*p++) || !isdigit(*p++))
525
0
    return 0;
526
527
0
  return line + len - tz;
528
0
}
529
530
static size_t date_len(const char *line, size_t len)
531
0
{
532
0
  const char *date, *p;
533
534
0
  if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
535
0
    return 0;
536
0
  p = date = line + len - strlen("72-02-05");
537
538
0
  if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
539
0
      !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
540
0
      !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
541
0
    return 0;
542
543
0
  if (date - line >= strlen("19") &&
544
0
      isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
545
0
    date -= strlen("19");
546
547
0
  return line + len - date;
548
0
}
549
550
static size_t short_time_len(const char *line, size_t len)
551
0
{
552
0
  const char *time, *p;
553
554
0
  if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
555
0
    return 0;
556
0
  p = time = line + len - strlen(" 07:01:32");
557
558
  /* Permit 1-digit hours? */
559
0
  if (*p++ != ' ' ||
560
0
      !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
561
0
      !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
562
0
      !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
563
0
    return 0;
564
565
0
  return line + len - time;
566
0
}
567
568
static size_t fractional_time_len(const char *line, size_t len)
569
0
{
570
0
  const char *p;
571
0
  size_t n;
572
573
  /* Expected format: 19:41:17.620000023 */
574
0
  if (!len || !isdigit(line[len - 1]))
575
0
    return 0;
576
0
  p = line + len - 1;
577
578
  /* Fractional seconds. */
579
0
  while (p > line && isdigit(*p))
580
0
    p--;
581
0
  if (*p != '.')
582
0
    return 0;
583
584
  /* Hours, minutes, and whole seconds. */
585
0
  n = short_time_len(line, p - line);
586
0
  if (!n)
587
0
    return 0;
588
589
0
  return line + len - p + n;
590
0
}
591
592
static size_t trailing_spaces_len(const char *line, size_t len)
593
0
{
594
0
  const char *p;
595
596
  /* Expected format: ' ' x (1 or more)  */
597
0
  if (!len || line[len - 1] != ' ')
598
0
    return 0;
599
600
0
  p = line + len;
601
0
  while (p != line) {
602
0
    p--;
603
0
    if (*p != ' ')
604
0
      return line + len - (p + 1);
605
0
  }
606
607
  /* All spaces! */
608
0
  return len;
609
0
}
610
611
static size_t diff_timestamp_len(const char *line, size_t len)
612
0
{
613
0
  const char *end = line + len;
614
0
  size_t n;
615
616
  /*
617
   * Posix: 2010-07-05 19:41:17
618
   * GNU: 2010-07-05 19:41:17.620000023 -0500
619
   */
620
621
0
  if (!isdigit(end[-1]))
622
0
    return 0;
623
624
0
  n = sane_tz_len(line, end - line);
625
0
  if (!n)
626
0
    n = tz_with_colon_len(line, end - line);
627
0
  end -= n;
628
629
0
  n = short_time_len(line, end - line);
630
0
  if (!n)
631
0
    n = fractional_time_len(line, end - line);
632
0
  end -= n;
633
634
0
  n = date_len(line, end - line);
635
0
  if (!n) /* No date.  Too bad. */
636
0
    return 0;
637
0
  end -= n;
638
639
0
  if (end == line) /* No space before date. */
640
0
    return 0;
641
0
  if (end[-1] == '\t') { /* Success! */
642
0
    end--;
643
0
    return line + len - end;
644
0
  }
645
0
  if (end[-1] != ' ') /* No space before date. */
646
0
    return 0;
647
648
  /* Whitespace damage. */
649
0
  end -= trailing_spaces_len(line, end - line);
650
0
  return line + len - end;
651
0
}
652
653
static char *find_name_common(struct strbuf *root,
654
            const char *line,
655
            const char *def,
656
            int p_value,
657
            const char *end,
658
            int terminate)
659
0
{
660
0
  int len;
661
0
  const char *start = NULL;
662
663
0
  if (p_value == 0)
664
0
    start = line;
665
0
  while (line != end) {
666
0
    char c = *line;
667
668
0
    if (!end && isspace(c)) {
669
0
      if (c == '\n')
670
0
        break;
671
0
      if (name_terminate(c, terminate))
672
0
        break;
673
0
    }
674
0
    line++;
675
0
    if (c == '/' && !--p_value)
676
0
      start = line;
677
0
  }
678
0
  if (!start)
679
0
    return squash_slash(xstrdup_or_null(def));
680
0
  len = line - start;
681
0
  if (!len)
682
0
    return squash_slash(xstrdup_or_null(def));
683
684
  /*
685
   * Generally we prefer the shorter name, especially
686
   * if the other one is just a variation of that with
687
   * something else tacked on to the end (ie "file.orig"
688
   * or "file~").
689
   */
690
0
  if (def) {
691
0
    int deflen = strlen(def);
692
0
    if (deflen < len && !strncmp(start, def, deflen))
693
0
      return squash_slash(xstrdup(def));
694
0
  }
695
696
0
  if (root->len) {
697
0
    char *ret = xstrfmt("%s%.*s", root->buf, len, start);
698
0
    return squash_slash(ret);
699
0
  }
700
701
0
  return squash_slash(xmemdupz(start, len));
702
0
}
703
704
static char *find_name(struct strbuf *root,
705
           const char *line,
706
           char *def,
707
           int p_value,
708
           int terminate)
709
0
{
710
0
  if (*line == '"') {
711
0
    char *name = find_name_gnu(root, line, p_value);
712
0
    if (name)
713
0
      return name;
714
0
  }
715
716
0
  return find_name_common(root, line, def, p_value, NULL, terminate);
717
0
}
718
719
static char *find_name_traditional(struct strbuf *root,
720
           const char *line,
721
           char *def,
722
           int p_value)
723
0
{
724
0
  size_t len;
725
0
  size_t date_len;
726
727
0
  if (*line == '"') {
728
0
    char *name = find_name_gnu(root, line, p_value);
729
0
    if (name)
730
0
      return name;
731
0
  }
732
733
0
  len = strchrnul(line, '\n') - line;
734
0
  date_len = diff_timestamp_len(line, len);
735
0
  if (!date_len)
736
0
    return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
737
0
  len -= date_len;
738
739
0
  return find_name_common(root, line, def, p_value, line + len, 0);
740
0
}
741
742
/*
743
 * Given the string after "--- " or "+++ ", guess the appropriate
744
 * p_value for the given patch.
745
 */
746
static int guess_p_value(struct apply_state *state, const char *nameline)
747
0
{
748
0
  char *name, *cp;
749
0
  int val = -1;
750
751
0
  if (is_dev_null(nameline))
752
0
    return -1;
753
0
  name = find_name_traditional(&state->root, nameline, NULL, 0);
754
0
  if (!name)
755
0
    return -1;
756
0
  cp = strchr(name, '/');
757
0
  if (!cp)
758
0
    val = 0;
759
0
  else if (state->prefix) {
760
    /*
761
     * Does it begin with "a/$our-prefix" and such?  Then this is
762
     * very likely to apply to our directory.
763
     */
764
0
    if (starts_with(name, state->prefix))
765
0
      val = count_slashes(state->prefix);
766
0
    else {
767
0
      cp++;
768
0
      if (starts_with(cp, state->prefix))
769
0
        val = count_slashes(state->prefix) + 1;
770
0
    }
771
0
  }
772
0
  free(name);
773
0
  return val;
774
0
}
775
776
/*
777
 * Does the ---/+++ line have the POSIX timestamp after the last HT?
778
 * GNU diff puts epoch there to signal a creation/deletion event.  Is
779
 * this such a timestamp?
780
 */
781
static int has_epoch_timestamp(const char *nameline)
782
0
{
783
  /*
784
   * We are only interested in epoch timestamp; any non-zero
785
   * fraction cannot be one, hence "(\.0+)?" in the regexp below.
786
   * For the same reason, the date must be either 1969-12-31 or
787
   * 1970-01-01, and the seconds part must be "00".
788
   */
789
0
  const char stamp_regexp[] =
790
0
    "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
791
0
    " "
792
0
    "([-+][0-2][0-9]:?[0-5][0-9])\n";
793
0
  const char *timestamp = NULL, *cp, *colon;
794
0
  static regex_t *stamp;
795
0
  regmatch_t m[10];
796
0
  int zoneoffset, epoch_hour, hour, minute;
797
0
  int status;
798
799
0
  for (cp = nameline; *cp != '\n'; cp++) {
800
0
    if (*cp == '\t')
801
0
      timestamp = cp + 1;
802
0
  }
803
0
  if (!timestamp)
804
0
    return 0;
805
806
  /*
807
   * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
808
   * (west of GMT) or 1970-01-01 (east of GMT)
809
   */
810
0
  if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
811
0
    epoch_hour = 24;
812
0
  else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
813
0
    epoch_hour = 0;
814
0
  else
815
0
    return 0;
816
817
0
  if (!stamp) {
818
0
    stamp = xmalloc(sizeof(*stamp));
819
0
    if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
820
0
      warning(_("Cannot prepare timestamp regexp %s"),
821
0
        stamp_regexp);
822
0
      return 0;
823
0
    }
824
0
  }
825
826
0
  status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
827
0
  if (status) {
828
0
    if (status != REG_NOMATCH)
829
0
      warning(_("regexec returned %d for input: %s"),
830
0
        status, timestamp);
831
0
    return 0;
832
0
  }
833
834
0
  hour = strtol(timestamp, NULL, 10);
835
0
  minute = strtol(timestamp + m[1].rm_so, NULL, 10);
836
837
0
  zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
838
0
  if (*colon == ':')
839
0
    zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
840
0
  else
841
0
    zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
842
0
  if (timestamp[m[3].rm_so] == '-')
843
0
    zoneoffset = -zoneoffset;
844
845
0
  return hour * 60 + minute - zoneoffset == epoch_hour * 60;
846
0
}
847
848
/*
849
 * Get the name etc info from the ---/+++ lines of a traditional patch header
850
 *
851
 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
852
 * files, we can happily check the index for a match, but for creating a
853
 * new file we should try to match whatever "patch" does. I have no idea.
854
 */
855
static int parse_traditional_patch(struct apply_state *state,
856
           const char *first,
857
           const char *second,
858
           struct patch *patch)
859
0
{
860
0
  char *name;
861
862
0
  first += 4; /* skip "--- " */
863
0
  second += 4;  /* skip "+++ " */
864
0
  if (!state->p_value_known) {
865
0
    int p, q;
866
0
    p = guess_p_value(state, first);
867
0
    q = guess_p_value(state, second);
868
0
    if (p < 0) p = q;
869
0
    if (0 <= p && p == q) {
870
0
      state->p_value = p;
871
0
      state->p_value_known = 1;
872
0
    }
873
0
  }
874
0
  if (is_dev_null(first)) {
875
0
    patch->is_new = 1;
876
0
    patch->is_delete = 0;
877
0
    name = find_name_traditional(&state->root, second, NULL, state->p_value);
878
0
    patch->new_name = name;
879
0
  } else if (is_dev_null(second)) {
880
0
    patch->is_new = 0;
881
0
    patch->is_delete = 1;
882
0
    name = find_name_traditional(&state->root, first, NULL, state->p_value);
883
0
    patch->old_name = name;
884
0
  } else {
885
0
    char *first_name;
886
0
    first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
887
0
    name = find_name_traditional(&state->root, second, first_name, state->p_value);
888
0
    free(first_name);
889
0
    if (has_epoch_timestamp(first)) {
890
0
      patch->is_new = 1;
891
0
      patch->is_delete = 0;
892
0
      patch->new_name = name;
893
0
    } else if (has_epoch_timestamp(second)) {
894
0
      patch->is_new = 0;
895
0
      patch->is_delete = 1;
896
0
      patch->old_name = name;
897
0
    } else {
898
0
      patch->old_name = name;
899
0
      patch->new_name = xstrdup_or_null(name);
900
0
    }
901
0
  }
902
0
  if (!name)
903
0
    return error(_("unable to find filename in patch at line %d"), state->linenr);
904
905
0
  return 0;
906
0
}
907
908
static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
909
        const char *line UNUSED,
910
        struct patch *patch UNUSED)
911
0
{
912
0
  return 1;
913
0
}
914
915
/*
916
 * We're anal about diff header consistency, to make
917
 * sure that we don't end up having strange ambiguous
918
 * patches floating around.
919
 *
920
 * As a result, gitdiff_{old|new}name() will check
921
 * their names against any previous information, just
922
 * to make sure..
923
 */
924
0
#define DIFF_OLD_NAME 0
925
0
#define DIFF_NEW_NAME 1
926
927
static int gitdiff_verify_name(struct gitdiff_data *state,
928
             const char *line,
929
             int isnull,
930
             char **name,
931
             int side)
932
0
{
933
0
  if (!*name && !isnull) {
934
0
    *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
935
0
    return 0;
936
0
  }
937
938
0
  if (*name) {
939
0
    char *another;
940
0
    if (isnull)
941
0
      return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
942
0
             *name, state->linenr);
943
0
    another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
944
0
    if (!another || strcmp(another, *name)) {
945
0
      free(another);
946
0
      return error((side == DIFF_NEW_NAME) ?
947
0
          _("git apply: bad git-diff - inconsistent new filename on line %d") :
948
0
          _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
949
0
    }
950
0
    free(another);
951
0
  } else {
952
0
    if (!is_dev_null(line))
953
0
      return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
954
0
  }
955
956
0
  return 0;
957
0
}
958
959
static int gitdiff_oldname(struct gitdiff_data *state,
960
         const char *line,
961
         struct patch *patch)
962
0
{
963
0
  return gitdiff_verify_name(state, line,
964
0
           patch->is_new, &patch->old_name,
965
0
           DIFF_OLD_NAME);
966
0
}
967
968
static int gitdiff_newname(struct gitdiff_data *state,
969
         const char *line,
970
         struct patch *patch)
971
0
{
972
0
  return gitdiff_verify_name(state, line,
973
0
           patch->is_delete, &patch->new_name,
974
0
           DIFF_NEW_NAME);
975
0
}
976
977
static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
978
0
{
979
0
  char *end;
980
0
  *mode = strtoul(line, &end, 8);
981
0
  if (end == line || !isspace(*end))
982
0
    return error(_("invalid mode on line %d: %s"), linenr, line);
983
0
  *mode = canon_mode(*mode);
984
0
  return 0;
985
0
}
986
987
static int gitdiff_oldmode(struct gitdiff_data *state,
988
         const char *line,
989
         struct patch *patch)
990
0
{
991
0
  return parse_mode_line(line, state->linenr, &patch->old_mode);
992
0
}
993
994
static int gitdiff_newmode(struct gitdiff_data *state,
995
         const char *line,
996
         struct patch *patch)
997
0
{
998
0
  return parse_mode_line(line, state->linenr, &patch->new_mode);
999
0
}
1000
1001
static int gitdiff_delete(struct gitdiff_data *state,
1002
        const char *line,
1003
        struct patch *patch)
1004
0
{
1005
0
  patch->is_delete = 1;
1006
0
  free(patch->old_name);
1007
0
  patch->old_name = xstrdup_or_null(patch->def_name);
1008
0
  return gitdiff_oldmode(state, line, patch);
1009
0
}
1010
1011
static int gitdiff_newfile(struct gitdiff_data *state,
1012
         const char *line,
1013
         struct patch *patch)
1014
0
{
1015
0
  patch->is_new = 1;
1016
0
  free(patch->new_name);
1017
0
  patch->new_name = xstrdup_or_null(patch->def_name);
1018
0
  return gitdiff_newmode(state, line, patch);
1019
0
}
1020
1021
static int gitdiff_copysrc(struct gitdiff_data *state,
1022
         const char *line,
1023
         struct patch *patch)
1024
0
{
1025
0
  patch->is_copy = 1;
1026
0
  free(patch->old_name);
1027
0
  patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1028
0
  return 0;
1029
0
}
1030
1031
static int gitdiff_copydst(struct gitdiff_data *state,
1032
         const char *line,
1033
         struct patch *patch)
1034
0
{
1035
0
  patch->is_copy = 1;
1036
0
  free(patch->new_name);
1037
0
  patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1038
0
  return 0;
1039
0
}
1040
1041
static int gitdiff_renamesrc(struct gitdiff_data *state,
1042
           const char *line,
1043
           struct patch *patch)
1044
0
{
1045
0
  patch->is_rename = 1;
1046
0
  free(patch->old_name);
1047
0
  patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1048
0
  return 0;
1049
0
}
1050
1051
static int gitdiff_renamedst(struct gitdiff_data *state,
1052
           const char *line,
1053
           struct patch *patch)
1054
0
{
1055
0
  patch->is_rename = 1;
1056
0
  free(patch->new_name);
1057
0
  patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1058
0
  return 0;
1059
0
}
1060
1061
static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1062
            const char *line,
1063
            struct patch *patch)
1064
0
{
1065
0
  unsigned long val = strtoul(line, NULL, 10);
1066
0
  if (val <= 100)
1067
0
    patch->score = val;
1068
0
  return 0;
1069
0
}
1070
1071
static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1072
         const char *line,
1073
         struct patch *patch)
1074
0
{
1075
0
  unsigned long val = strtoul(line, NULL, 10);
1076
0
  if (val <= 100)
1077
0
    patch->score = val;
1078
0
  return 0;
1079
0
}
1080
1081
static int gitdiff_index(struct gitdiff_data *state,
1082
       const char *line,
1083
       struct patch *patch)
1084
0
{
1085
  /*
1086
   * index line is N hexadecimal, "..", N hexadecimal,
1087
   * and optional space with octal mode.
1088
   */
1089
0
  const char *ptr, *eol;
1090
0
  int len;
1091
0
  const unsigned hexsz = the_hash_algo->hexsz;
1092
1093
0
  ptr = strchr(line, '.');
1094
0
  if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1095
0
    return 0;
1096
0
  len = ptr - line;
1097
0
  memcpy(patch->old_oid_prefix, line, len);
1098
0
  patch->old_oid_prefix[len] = 0;
1099
1100
0
  line = ptr + 2;
1101
0
  ptr = strchr(line, ' ');
1102
0
  eol = strchrnul(line, '\n');
1103
1104
0
  if (!ptr || eol < ptr)
1105
0
    ptr = eol;
1106
0
  len = ptr - line;
1107
1108
0
  if (hexsz < len)
1109
0
    return 0;
1110
0
  memcpy(patch->new_oid_prefix, line, len);
1111
0
  patch->new_oid_prefix[len] = 0;
1112
0
  if (*ptr == ' ')
1113
0
    return gitdiff_oldmode(state, ptr + 1, patch);
1114
0
  return 0;
1115
0
}
1116
1117
/*
1118
 * This is normal for a diff that doesn't change anything: we'll fall through
1119
 * into the next diff. Tell the parser to break out.
1120
 */
1121
static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1122
        const char *line UNUSED,
1123
        struct patch *patch UNUSED)
1124
0
{
1125
0
  return 1;
1126
0
}
1127
1128
/*
1129
 * Skip p_value leading components from "line"; as we do not accept
1130
 * absolute paths, return NULL in that case.
1131
 */
1132
static const char *skip_tree_prefix(int p_value,
1133
            const char *line,
1134
            int llen)
1135
0
{
1136
0
  int nslash;
1137
0
  int i;
1138
1139
0
  if (!p_value)
1140
0
    return (llen && line[0] == '/') ? NULL : line;
1141
1142
0
  nslash = p_value;
1143
0
  for (i = 0; i < llen; i++) {
1144
0
    int ch = line[i];
1145
0
    if (ch == '/' && --nslash <= 0)
1146
0
      return (i == 0) ? NULL : &line[i + 1];
1147
0
  }
1148
0
  return NULL;
1149
0
}
1150
1151
/*
1152
 * This is to extract the same name that appears on "diff --git"
1153
 * line.  We do not find and return anything if it is a rename
1154
 * patch, and it is OK because we will find the name elsewhere.
1155
 * We need to reliably find name only when it is mode-change only,
1156
 * creation or deletion of an empty file.  In any of these cases,
1157
 * both sides are the same name under a/ and b/ respectively.
1158
 */
1159
static char *git_header_name(int p_value,
1160
           const char *line,
1161
           int llen)
1162
0
{
1163
0
  const char *name;
1164
0
  const char *second = NULL;
1165
0
  size_t len, line_len;
1166
1167
0
  line += strlen("diff --git ");
1168
0
  llen -= strlen("diff --git ");
1169
1170
0
  if (*line == '"') {
1171
0
    const char *cp;
1172
0
    struct strbuf first = STRBUF_INIT;
1173
0
    struct strbuf sp = STRBUF_INIT;
1174
1175
0
    if (unquote_c_style(&first, line, &second))
1176
0
      goto free_and_fail1;
1177
1178
    /* strip the a/b prefix including trailing slash */
1179
0
    cp = skip_tree_prefix(p_value, first.buf, first.len);
1180
0
    if (!cp)
1181
0
      goto free_and_fail1;
1182
0
    strbuf_remove(&first, 0, cp - first.buf);
1183
1184
    /*
1185
     * second points at one past closing dq of name.
1186
     * find the second name.
1187
     */
1188
0
    while ((second < line + llen) && isspace(*second))
1189
0
      second++;
1190
1191
0
    if (line + llen <= second)
1192
0
      goto free_and_fail1;
1193
0
    if (*second == '"') {
1194
0
      if (unquote_c_style(&sp, second, NULL))
1195
0
        goto free_and_fail1;
1196
0
      cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1197
0
      if (!cp)
1198
0
        goto free_and_fail1;
1199
      /* They must match, otherwise ignore */
1200
0
      if (strcmp(cp, first.buf))
1201
0
        goto free_and_fail1;
1202
0
      strbuf_release(&sp);
1203
0
      return strbuf_detach(&first, NULL);
1204
0
    }
1205
1206
    /* unquoted second */
1207
0
    cp = skip_tree_prefix(p_value, second, line + llen - second);
1208
0
    if (!cp)
1209
0
      goto free_and_fail1;
1210
0
    if (line + llen - cp != first.len ||
1211
0
        memcmp(first.buf, cp, first.len))
1212
0
      goto free_and_fail1;
1213
0
    return strbuf_detach(&first, NULL);
1214
1215
0
  free_and_fail1:
1216
0
    strbuf_release(&first);
1217
0
    strbuf_release(&sp);
1218
0
    return NULL;
1219
0
  }
1220
1221
  /* unquoted first name */
1222
0
  name = skip_tree_prefix(p_value, line, llen);
1223
0
  if (!name)
1224
0
    return NULL;
1225
1226
  /*
1227
   * since the first name is unquoted, a dq if exists must be
1228
   * the beginning of the second name.
1229
   */
1230
0
  for (second = name; second < line + llen; second++) {
1231
0
    if (*second == '"') {
1232
0
      struct strbuf sp = STRBUF_INIT;
1233
0
      const char *np;
1234
1235
0
      if (unquote_c_style(&sp, second, NULL))
1236
0
        goto free_and_fail2;
1237
1238
0
      np = skip_tree_prefix(p_value, sp.buf, sp.len);
1239
0
      if (!np)
1240
0
        goto free_and_fail2;
1241
1242
0
      len = sp.buf + sp.len - np;
1243
0
      if (len < second - name &&
1244
0
          !strncmp(np, name, len) &&
1245
0
          isspace(name[len])) {
1246
        /* Good */
1247
0
        strbuf_remove(&sp, 0, np - sp.buf);
1248
0
        return strbuf_detach(&sp, NULL);
1249
0
      }
1250
1251
0
    free_and_fail2:
1252
0
      strbuf_release(&sp);
1253
0
      return NULL;
1254
0
    }
1255
0
  }
1256
1257
  /*
1258
   * Accept a name only if it shows up twice, exactly the same
1259
   * form.
1260
   */
1261
0
  second = strchr(name, '\n');
1262
0
  if (!second)
1263
0
    return NULL;
1264
0
  line_len = second - name;
1265
0
  for (len = 0 ; ; len++) {
1266
0
    switch (name[len]) {
1267
0
    default:
1268
0
      continue;
1269
0
    case '\n':
1270
0
      return NULL;
1271
0
    case '\t': case ' ':
1272
      /*
1273
       * Is this the separator between the preimage
1274
       * and the postimage pathname?  Again, we are
1275
       * only interested in the case where there is
1276
       * no rename, as this is only to set def_name
1277
       * and a rename patch has the names elsewhere
1278
       * in an unambiguous form.
1279
       */
1280
0
      if (!name[len + 1])
1281
0
        return NULL; /* no postimage name */
1282
0
      second = skip_tree_prefix(p_value, name + len + 1,
1283
0
              line_len - (len + 1));
1284
      /*
1285
       * If we are at the SP at the end of a directory,
1286
       * skip_tree_prefix() may return NULL as that makes
1287
       * it appears as if we have an absolute path.
1288
       * Keep going to find another SP.
1289
       */
1290
0
      if (!second)
1291
0
        continue;
1292
1293
      /*
1294
       * Does len bytes starting at "name" and "second"
1295
       * (that are separated by one HT or SP we just
1296
       * found) exactly match?
1297
       */
1298
0
      if (second[len] == '\n' && !strncmp(name, second, len))
1299
0
        return xmemdupz(name, len);
1300
0
    }
1301
0
  }
1302
0
}
1303
1304
static int check_header_line(int linenr, struct patch *patch)
1305
0
{
1306
0
  int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1307
0
       (patch->is_rename == 1) + (patch->is_copy == 1);
1308
0
  if (extensions > 1)
1309
0
    return error(_("inconsistent header lines %d and %d"),
1310
0
           patch->extension_linenr, linenr);
1311
0
  if (extensions && !patch->extension_linenr)
1312
0
    patch->extension_linenr = linenr;
1313
0
  return 0;
1314
0
}
1315
1316
int parse_git_diff_header(struct strbuf *root,
1317
        int *linenr,
1318
        int p_value,
1319
        const char *line,
1320
        int len,
1321
        unsigned int size,
1322
        struct patch *patch)
1323
0
{
1324
0
  unsigned long offset;
1325
0
  struct gitdiff_data parse_hdr_state;
1326
1327
  /* A git diff has explicit new/delete information, so we don't guess */
1328
0
  patch->is_new = 0;
1329
0
  patch->is_delete = 0;
1330
1331
  /*
1332
   * Some things may not have the old name in the
1333
   * rest of the headers anywhere (pure mode changes,
1334
   * or removing or adding empty files), so we get
1335
   * the default name from the header.
1336
   */
1337
0
  patch->def_name = git_header_name(p_value, line, len);
1338
0
  if (patch->def_name && root->len) {
1339
0
    char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1340
0
    free(patch->def_name);
1341
0
    patch->def_name = s;
1342
0
  }
1343
1344
0
  line += len;
1345
0
  size -= len;
1346
0
  (*linenr)++;
1347
0
  parse_hdr_state.root = root;
1348
0
  parse_hdr_state.linenr = *linenr;
1349
0
  parse_hdr_state.p_value = p_value;
1350
1351
0
  for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1352
0
    static const struct opentry {
1353
0
      const char *str;
1354
0
      int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1355
0
    } optable[] = {
1356
0
      { "@@ -", gitdiff_hdrend },
1357
0
      { "--- ", gitdiff_oldname },
1358
0
      { "+++ ", gitdiff_newname },
1359
0
      { "old mode ", gitdiff_oldmode },
1360
0
      { "new mode ", gitdiff_newmode },
1361
0
      { "deleted file mode ", gitdiff_delete },
1362
0
      { "new file mode ", gitdiff_newfile },
1363
0
      { "copy from ", gitdiff_copysrc },
1364
0
      { "copy to ", gitdiff_copydst },
1365
0
      { "rename old ", gitdiff_renamesrc },
1366
0
      { "rename new ", gitdiff_renamedst },
1367
0
      { "rename from ", gitdiff_renamesrc },
1368
0
      { "rename to ", gitdiff_renamedst },
1369
0
      { "similarity index ", gitdiff_similarity },
1370
0
      { "dissimilarity index ", gitdiff_dissimilarity },
1371
0
      { "index ", gitdiff_index },
1372
0
      { "", gitdiff_unrecognized },
1373
0
    };
1374
0
    int i;
1375
1376
0
    len = linelen(line, size);
1377
0
    if (!len || line[len-1] != '\n')
1378
0
      break;
1379
0
    for (i = 0; i < ARRAY_SIZE(optable); i++) {
1380
0
      const struct opentry *p = optable + i;
1381
0
      int oplen = strlen(p->str);
1382
0
      int res;
1383
0
      if (len < oplen || memcmp(p->str, line, oplen))
1384
0
        continue;
1385
0
      res = p->fn(&parse_hdr_state, line + oplen, patch);
1386
0
      if (res < 0)
1387
0
        return -1;
1388
0
      if (check_header_line(*linenr, patch))
1389
0
        return -1;
1390
0
      if (res > 0)
1391
0
        goto done;
1392
0
      break;
1393
0
    }
1394
0
  }
1395
1396
0
done:
1397
0
  if (!patch->old_name && !patch->new_name) {
1398
0
    if (!patch->def_name) {
1399
0
      error(Q_("git diff header lacks filename information when removing "
1400
0
         "%d leading pathname component (line %d)",
1401
0
         "git diff header lacks filename information when removing "
1402
0
         "%d leading pathname components (line %d)",
1403
0
         parse_hdr_state.p_value),
1404
0
            parse_hdr_state.p_value, *linenr);
1405
0
      return -128;
1406
0
    }
1407
0
    patch->old_name = xstrdup(patch->def_name);
1408
0
    patch->new_name = xstrdup(patch->def_name);
1409
0
  }
1410
0
  if ((!patch->new_name && !patch->is_delete) ||
1411
0
      (!patch->old_name && !patch->is_new)) {
1412
0
    error(_("git diff header lacks filename information "
1413
0
      "(line %d)"), *linenr);
1414
0
    return -128;
1415
0
  }
1416
0
  patch->is_toplevel_relative = 1;
1417
0
  return offset;
1418
0
}
1419
1420
static int parse_num(const char *line, unsigned long *p)
1421
0
{
1422
0
  char *ptr;
1423
1424
0
  if (!isdigit(*line))
1425
0
    return 0;
1426
0
  errno = 0;
1427
0
  *p = strtoul(line, &ptr, 10);
1428
0
  if (errno)
1429
0
    return 0;
1430
0
  return ptr - line;
1431
0
}
1432
1433
static int parse_range(const char *line, int len, int offset, const char *expect,
1434
           unsigned long *p1, unsigned long *p2)
1435
0
{
1436
0
  int digits, ex;
1437
1438
0
  if (offset < 0 || offset >= len)
1439
0
    return -1;
1440
0
  line += offset;
1441
0
  len -= offset;
1442
1443
0
  digits = parse_num(line, p1);
1444
0
  if (!digits)
1445
0
    return -1;
1446
1447
0
  offset += digits;
1448
0
  line += digits;
1449
0
  len -= digits;
1450
1451
0
  *p2 = 1;
1452
0
  if (*line == ',') {
1453
0
    digits = parse_num(line+1, p2);
1454
0
    if (!digits)
1455
0
      return -1;
1456
1457
0
    offset += digits+1;
1458
0
    line += digits+1;
1459
0
    len -= digits+1;
1460
0
  }
1461
1462
0
  ex = strlen(expect);
1463
0
  if (ex > len)
1464
0
    return -1;
1465
0
  if (memcmp(line, expect, ex))
1466
0
    return -1;
1467
1468
0
  return offset + ex;
1469
0
}
1470
1471
static void recount_diff(const char *line, int size, struct fragment *fragment)
1472
0
{
1473
0
  int oldlines = 0, newlines = 0, ret = 0;
1474
1475
0
  if (size < 1) {
1476
0
    warning("recount: ignore empty hunk");
1477
0
    return;
1478
0
  }
1479
1480
0
  for (;;) {
1481
0
    int len = linelen(line, size);
1482
0
    size -= len;
1483
0
    line += len;
1484
1485
0
    if (size < 1)
1486
0
      break;
1487
1488
0
    switch (*line) {
1489
0
    case ' ': case '\n':
1490
0
      newlines++;
1491
      /* fall through */
1492
0
    case '-':
1493
0
      oldlines++;
1494
0
      continue;
1495
0
    case '+':
1496
0
      newlines++;
1497
0
      continue;
1498
0
    case '\\':
1499
0
      continue;
1500
0
    case '@':
1501
0
      ret = size < 3 || !starts_with(line, "@@ ");
1502
0
      break;
1503
0
    case 'd':
1504
0
      ret = size < 5 || !starts_with(line, "diff ");
1505
0
      break;
1506
0
    default:
1507
0
      ret = -1;
1508
0
      break;
1509
0
    }
1510
0
    if (ret) {
1511
0
      warning(_("recount: unexpected line: %.*s"),
1512
0
        (int)linelen(line, size), line);
1513
0
      return;
1514
0
    }
1515
0
    break;
1516
0
  }
1517
0
  fragment->oldlines = oldlines;
1518
0
  fragment->newlines = newlines;
1519
0
}
1520
1521
/*
1522
 * Parse a unified diff fragment header of the
1523
 * form "@@ -a,b +c,d @@"
1524
 */
1525
static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1526
0
{
1527
0
  int offset;
1528
1529
0
  if (!len || line[len-1] != '\n')
1530
0
    return -1;
1531
1532
  /* Figure out the number of lines in a fragment */
1533
0
  offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1534
0
  offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1535
1536
0
  return offset;
1537
0
}
1538
1539
/*
1540
 * Find file diff header
1541
 *
1542
 * Returns:
1543
 *  -1 if no header was found
1544
 *  -128 in case of error
1545
 *   the size of the header in bytes (called "offset") otherwise
1546
 */
1547
static int find_header(struct apply_state *state,
1548
           const char *line,
1549
           unsigned long size,
1550
           int *hdrsize,
1551
           struct patch *patch)
1552
0
{
1553
0
  unsigned long offset, len;
1554
1555
0
  patch->is_toplevel_relative = 0;
1556
0
  patch->is_rename = patch->is_copy = 0;
1557
0
  patch->is_new = patch->is_delete = -1;
1558
0
  patch->old_mode = patch->new_mode = 0;
1559
0
  patch->old_name = patch->new_name = NULL;
1560
0
  for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1561
0
    unsigned long nextlen;
1562
1563
0
    len = linelen(line, size);
1564
0
    if (!len)
1565
0
      break;
1566
1567
    /* Testing this early allows us to take a few shortcuts.. */
1568
0
    if (len < 6)
1569
0
      continue;
1570
1571
    /*
1572
     * Make sure we don't find any unconnected patch fragments.
1573
     * That's a sign that we didn't find a header, and that a
1574
     * patch has become corrupted/broken up.
1575
     */
1576
0
    if (!memcmp("@@ -", line, 4)) {
1577
0
      struct fragment dummy;
1578
0
      if (parse_fragment_header(line, len, &dummy) < 0)
1579
0
        continue;
1580
0
      error(_("patch fragment without header at line %d: %.*s"),
1581
0
             state->linenr, (int)len-1, line);
1582
0
      return -128;
1583
0
    }
1584
1585
0
    if (size < len + 6)
1586
0
      break;
1587
1588
    /*
1589
     * Git patch? It might not have a real patch, just a rename
1590
     * or mode change, so we handle that specially
1591
     */
1592
0
    if (!memcmp("diff --git ", line, 11)) {
1593
0
      int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1594
0
                state->p_value, line, len,
1595
0
                size, patch);
1596
0
      if (git_hdr_len < 0)
1597
0
        return -128;
1598
0
      if (git_hdr_len <= len)
1599
0
        continue;
1600
0
      *hdrsize = git_hdr_len;
1601
0
      return offset;
1602
0
    }
1603
1604
    /* --- followed by +++ ? */
1605
0
    if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
1606
0
      continue;
1607
1608
    /*
1609
     * We only accept unified patches, so we want it to
1610
     * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1611
     * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1612
     */
1613
0
    nextlen = linelen(line + len, size - len);
1614
0
    if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1615
0
      continue;
1616
1617
    /* Ok, we'll consider it a patch */
1618
0
    if (parse_traditional_patch(state, line, line+len, patch))
1619
0
      return -128;
1620
0
    *hdrsize = len + nextlen;
1621
0
    state->linenr += 2;
1622
0
    return offset;
1623
0
  }
1624
0
  return -1;
1625
0
}
1626
1627
static void record_ws_error(struct apply_state *state,
1628
          unsigned result,
1629
          const char *line,
1630
          int len,
1631
          int linenr)
1632
0
{
1633
0
  char *err;
1634
1635
0
  if (!result)
1636
0
    return;
1637
1638
0
  state->whitespace_error++;
1639
0
  if (state->squelch_whitespace_errors &&
1640
0
      state->squelch_whitespace_errors < state->whitespace_error)
1641
0
    return;
1642
1643
  /*
1644
   * line[len] for an incomplete line points at the "\n" at the end
1645
   * of patch input line, so "%.*s" would drop the last letter on line;
1646
   * compensate for it.
1647
   */
1648
0
  if (result & WS_INCOMPLETE_LINE)
1649
0
    len++;
1650
1651
0
  err = whitespace_error_string(result);
1652
0
  if (state->apply_verbosity > verbosity_silent)
1653
0
    fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1654
0
      state->patch_input_file, linenr, err, len, line);
1655
0
  free(err);
1656
0
}
1657
1658
static void check_whitespace(struct apply_state *state,
1659
           const char *line,
1660
           int len,
1661
           unsigned ws_rule)
1662
0
{
1663
0
  unsigned result = ws_check(line + 1, len - 1, ws_rule);
1664
1665
0
  record_ws_error(state, result, line + 1, len - 2, state->linenr);
1666
0
}
1667
1668
/*
1669
 * Check if the patch has context lines with CRLF or
1670
 * the patch wants to remove lines with CRLF.
1671
 */
1672
static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1673
0
{
1674
0
  if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1675
0
    patch->ws_rule |= WS_CR_AT_EOL;
1676
0
    patch->crlf_in_old = 1;
1677
0
  }
1678
0
}
1679
1680
1681
/*
1682
 * Just saw a single line in a fragment.  If it is a part of this hunk
1683
 * that is a context " ", an added "+", or a removed "-" line, it may
1684
 * be followed by "\\ No newline..." to signal that the last "\n" on
1685
 * this line needs to be dropped.  Depending on locale settings when
1686
 * the patch was produced we don't know what this line would exactly
1687
 * say. The only thing we do know is that it begins with "\ ".
1688
 * Checking for 12 is just for sanity check; "\ No newline..." would
1689
 * be at least that long in any l10n.
1690
 *
1691
 * Return 0 if the line we saw is not followed by "\ No newline...",
1692
 * or length of that line.  The caller will use it to skip over the
1693
 * "\ No newline..." line.
1694
 */
1695
static int adjust_incomplete(const char *line, int len,
1696
           unsigned long size)
1697
0
{
1698
0
  int nextlen;
1699
1700
0
  if (*line != '\n' && *line != ' ' && *line != '+' && *line != '-')
1701
0
    return 0;
1702
0
  if (size - len < 12 || memcmp(line + len, "\\ ", 2))
1703
0
    return 0;
1704
0
  nextlen = linelen(line + len, size - len);
1705
0
  if (nextlen < 12)
1706
0
    return 0;
1707
0
  return nextlen;
1708
0
}
1709
1710
/*
1711
 * Parse a unified diff. Note that this really needs to parse each
1712
 * fragment separately, since the only way to know the difference
1713
 * between a "---" that is part of a patch, and a "---" that starts
1714
 * the next patch is to look at the line counts..
1715
 */
1716
static int parse_fragment(struct apply_state *state,
1717
        const char *line,
1718
        unsigned long size,
1719
        struct patch *patch,
1720
        struct fragment *fragment)
1721
0
{
1722
0
  int added, deleted;
1723
0
  int len = linelen(line, size), offset;
1724
0
  int skip_len = 0;
1725
0
  unsigned long oldlines, newlines;
1726
0
  unsigned long leading, trailing;
1727
1728
  /* do not complain a symbolic link being an incomplete line */
1729
0
  if (patch->ws_rule & WS_INCOMPLETE_LINE) {
1730
    /*
1731
     * We want to figure out if the postimage is a
1732
     * symbolic link when applying the patch normally, or
1733
     * if the preimage is a symbolic link when applying
1734
     * the patch in reverse.  A normal patch only has
1735
     * old_mode without new_mode.  If it changes the
1736
     * filemode, new_mode has value, which is different
1737
     * from old_mode.
1738
     */
1739
0
    unsigned mode = (state->apply_in_reverse
1740
0
         ? patch->old_mode
1741
0
         : patch->new_mode
1742
0
         ? patch->new_mode
1743
0
         : patch->old_mode);
1744
0
    if (mode && S_ISLNK(mode))
1745
0
      patch->ws_rule &= ~WS_INCOMPLETE_LINE;
1746
0
  }
1747
1748
0
  offset = parse_fragment_header(line, len, fragment);
1749
0
  if (offset < 0)
1750
0
    return -1;
1751
0
  if (offset > 0 && patch->recount)
1752
0
    recount_diff(line + offset, size - offset, fragment);
1753
0
  oldlines = fragment->oldlines;
1754
0
  newlines = fragment->newlines;
1755
0
  leading = 0;
1756
0
  trailing = 0;
1757
1758
  /* Parse the thing.. */
1759
0
  line += len;
1760
0
  size -= len;
1761
0
  state->linenr++;
1762
0
  added = deleted = 0;
1763
0
  for (offset = len;
1764
0
       0 < size;
1765
0
       offset += len, size -= len, line += len, state->linenr++) {
1766
0
    if (!oldlines && !newlines)
1767
0
      break;
1768
0
    len = linelen(line, size);
1769
0
    if (!len || line[len-1] != '\n')
1770
0
      return -1;
1771
1772
    /*
1773
     * For an incomplete line, skip_len counts the bytes
1774
     * on "\\ No newline..." marker line that comes next
1775
     * to the current line.
1776
     *
1777
     * Reduce "len" to drop the newline at the end of
1778
     * line[], but add one to "skip_len", which will be
1779
     * added back to "len" for the next iteration, to
1780
     * compensate.
1781
     */
1782
0
    skip_len = adjust_incomplete(line, len, size);
1783
0
    if (skip_len) {
1784
0
      len--;
1785
0
      skip_len++;
1786
0
    }
1787
0
    switch (*line) {
1788
0
    default:
1789
0
      return -1;
1790
0
    case '\n': /* newer GNU diff, an empty context line */
1791
0
    case ' ':
1792
0
      oldlines--;
1793
0
      newlines--;
1794
0
      if (!deleted && !added)
1795
0
        leading++;
1796
0
      trailing++;
1797
0
      check_old_for_crlf(patch, line, len);
1798
0
      if (!state->apply_in_reverse &&
1799
0
          state->ws_error_action == correct_ws_error)
1800
0
        check_whitespace(state, line, len, patch->ws_rule);
1801
0
      break;
1802
0
    case '-':
1803
0
      if (!state->apply_in_reverse)
1804
0
        check_old_for_crlf(patch, line, len);
1805
0
      if (state->apply_in_reverse &&
1806
0
          state->ws_error_action != nowarn_ws_error)
1807
0
        check_whitespace(state, line, len, patch->ws_rule);
1808
0
      deleted++;
1809
0
      oldlines--;
1810
0
      trailing = 0;
1811
0
      break;
1812
0
    case '+':
1813
0
      if (state->apply_in_reverse)
1814
0
        check_old_for_crlf(patch, line, len);
1815
0
      if (!state->apply_in_reverse &&
1816
0
          state->ws_error_action != nowarn_ws_error)
1817
0
        check_whitespace(state, line, len, patch->ws_rule);
1818
0
      added++;
1819
0
      newlines--;
1820
0
      trailing = 0;
1821
0
      break;
1822
0
    }
1823
1824
    /* eat the "\\ No newline..." as well, if exists */
1825
0
    if (skip_len) {
1826
0
      len += skip_len;
1827
0
      state->linenr++;
1828
0
    }
1829
0
  }
1830
0
  if (oldlines || newlines)
1831
0
    return -1;
1832
0
  if (!patch->recount && !deleted && !added)
1833
0
    return -1;
1834
1835
0
  fragment->leading = leading;
1836
0
  fragment->trailing = trailing;
1837
1838
0
  patch->lines_added += added;
1839
0
  patch->lines_deleted += deleted;
1840
1841
0
  if (0 < patch->is_new && oldlines)
1842
0
    return error(_("new file depends on old contents"));
1843
0
  if (0 < patch->is_delete && newlines)
1844
0
    return error(_("deleted file still has contents"));
1845
0
  return offset;
1846
0
}
1847
1848
/*
1849
 * We have seen "diff --git a/... b/..." header (or a traditional patch
1850
 * header).  Read hunks that belong to this patch into fragments and hang
1851
 * them to the given patch structure.
1852
 *
1853
 * The (fragment->patch, fragment->size) pair points into the memory given
1854
 * by the caller, not a copy, when we return.
1855
 *
1856
 * Returns:
1857
 *   -1 in case of error,
1858
 *   the number of bytes in the patch otherwise.
1859
 */
1860
static int parse_single_patch(struct apply_state *state,
1861
            const char *line,
1862
            unsigned long size,
1863
            struct patch *patch)
1864
0
{
1865
0
  unsigned long offset = 0;
1866
0
  unsigned long oldlines = 0, newlines = 0, context = 0;
1867
0
  struct fragment **fragp = &patch->fragments;
1868
1869
0
  while (size > 4 && !memcmp(line, "@@ -", 4)) {
1870
0
    struct fragment *fragment;
1871
0
    int len;
1872
1873
0
    CALLOC_ARRAY(fragment, 1);
1874
0
    fragment->linenr = state->linenr;
1875
0
    len = parse_fragment(state, line, size, patch, fragment);
1876
0
    if (len <= 0) {
1877
0
      free(fragment);
1878
0
      return error(_("corrupt patch at line %d"), state->linenr);
1879
0
    }
1880
0
    fragment->patch = line;
1881
0
    fragment->size = len;
1882
0
    oldlines += fragment->oldlines;
1883
0
    newlines += fragment->newlines;
1884
0
    context += fragment->leading + fragment->trailing;
1885
1886
0
    *fragp = fragment;
1887
0
    fragp = &fragment->next;
1888
1889
0
    offset += len;
1890
0
    line += len;
1891
0
    size -= len;
1892
0
  }
1893
1894
  /*
1895
   * If something was removed (i.e. we have old-lines) it cannot
1896
   * be creation, and if something was added it cannot be
1897
   * deletion.  However, the reverse is not true; --unified=0
1898
   * patches that only add are not necessarily creation even
1899
   * though they do not have any old lines, and ones that only
1900
   * delete are not necessarily deletion.
1901
   *
1902
   * Unfortunately, a real creation/deletion patch do _not_ have
1903
   * any context line by definition, so we cannot safely tell it
1904
   * apart with --unified=0 insanity.  At least if the patch has
1905
   * more than one hunk it is not creation or deletion.
1906
   */
1907
0
  if (patch->is_new < 0 &&
1908
0
      (oldlines || (patch->fragments && patch->fragments->next)))
1909
0
    patch->is_new = 0;
1910
0
  if (patch->is_delete < 0 &&
1911
0
      (newlines || (patch->fragments && patch->fragments->next)))
1912
0
    patch->is_delete = 0;
1913
1914
0
  if (0 < patch->is_new && oldlines)
1915
0
    return error(_("new file %s depends on old contents"), patch->new_name);
1916
0
  if (0 < patch->is_delete && newlines)
1917
0
    return error(_("deleted file %s still has contents"), patch->old_name);
1918
0
  if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1919
0
    fprintf_ln(stderr,
1920
0
         _("** warning: "
1921
0
           "file %s becomes empty but is not deleted"),
1922
0
         patch->new_name);
1923
1924
0
  return offset;
1925
0
}
1926
1927
static inline int metadata_changes(struct patch *patch)
1928
0
{
1929
0
  return  patch->is_rename > 0 ||
1930
0
    patch->is_copy > 0 ||
1931
0
    patch->is_new > 0 ||
1932
0
    patch->is_delete ||
1933
0
    (patch->old_mode && patch->new_mode &&
1934
0
     patch->old_mode != patch->new_mode);
1935
0
}
1936
1937
static char *inflate_it(const void *data, unsigned long size,
1938
      unsigned long inflated_size)
1939
0
{
1940
0
  git_zstream stream;
1941
0
  void *out;
1942
0
  int st;
1943
1944
0
  memset(&stream, 0, sizeof(stream));
1945
1946
0
  stream.next_in = (unsigned char *)data;
1947
0
  stream.avail_in = size;
1948
0
  stream.next_out = out = xmalloc(inflated_size);
1949
0
  stream.avail_out = inflated_size;
1950
0
  git_inflate_init(&stream);
1951
0
  st = git_inflate(&stream, Z_FINISH);
1952
0
  git_inflate_end(&stream);
1953
0
  if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1954
0
    free(out);
1955
0
    return NULL;
1956
0
  }
1957
0
  return out;
1958
0
}
1959
1960
/*
1961
 * Read a binary hunk and return a new fragment; fragment->patch
1962
 * points at an allocated memory that the caller must free, so
1963
 * it is marked as "->free_patch = 1".
1964
 */
1965
static struct fragment *parse_binary_hunk(struct apply_state *state,
1966
            char **buf_p,
1967
            unsigned long *sz_p,
1968
            int *status_p,
1969
            int *used_p)
1970
0
{
1971
  /*
1972
   * Expect a line that begins with binary patch method ("literal"
1973
   * or "delta"), followed by the length of data before deflating.
1974
   * a sequence of 'length-byte' followed by base-85 encoded data
1975
   * should follow, terminated by a newline.
1976
   *
1977
   * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1978
   * and we would limit the patch line to 66 characters,
1979
   * so one line can fit up to 13 groups that would decode
1980
   * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1981
   * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1982
   */
1983
0
  int llen, used;
1984
0
  unsigned long size = *sz_p;
1985
0
  char *buffer = *buf_p;
1986
0
  int patch_method;
1987
0
  unsigned long origlen;
1988
0
  char *data = NULL;
1989
0
  int hunk_size = 0;
1990
0
  struct fragment *frag;
1991
1992
0
  llen = linelen(buffer, size);
1993
0
  used = llen;
1994
1995
0
  *status_p = 0;
1996
1997
0
  if (starts_with(buffer, "delta ")) {
1998
0
    patch_method = BINARY_DELTA_DEFLATED;
1999
0
    origlen = strtoul(buffer + 6, NULL, 10);
2000
0
  }
2001
0
  else if (starts_with(buffer, "literal ")) {
2002
0
    patch_method = BINARY_LITERAL_DEFLATED;
2003
0
    origlen = strtoul(buffer + 8, NULL, 10);
2004
0
  }
2005
0
  else
2006
0
    return NULL;
2007
2008
0
  state->linenr++;
2009
0
  buffer += llen;
2010
0
  size -= llen;
2011
0
  while (1) {
2012
0
    int byte_length, max_byte_length, newsize;
2013
0
    llen = linelen(buffer, size);
2014
0
    used += llen;
2015
0
    state->linenr++;
2016
0
    if (llen == 1) {
2017
      /* consume the blank line */
2018
0
      buffer++;
2019
0
      size--;
2020
0
      break;
2021
0
    }
2022
    /*
2023
     * Minimum line is "A00000\n" which is 7-byte long,
2024
     * and the line length must be multiple of 5 plus 2.
2025
     */
2026
0
    if ((llen < 7) || (llen-2) % 5)
2027
0
      goto corrupt;
2028
0
    max_byte_length = (llen - 2) / 5 * 4;
2029
0
    byte_length = *buffer;
2030
0
    if ('A' <= byte_length && byte_length <= 'Z')
2031
0
      byte_length = byte_length - 'A' + 1;
2032
0
    else if ('a' <= byte_length && byte_length <= 'z')
2033
0
      byte_length = byte_length - 'a' + 27;
2034
0
    else
2035
0
      goto corrupt;
2036
    /* if the input length was not multiple of 4, we would
2037
     * have filler at the end but the filler should never
2038
     * exceed 3 bytes
2039
     */
2040
0
    if (max_byte_length < byte_length ||
2041
0
        byte_length <= max_byte_length - 4)
2042
0
      goto corrupt;
2043
0
    newsize = hunk_size + byte_length;
2044
0
    data = xrealloc(data, newsize);
2045
0
    if (decode_85(data + hunk_size, buffer + 1, byte_length))
2046
0
      goto corrupt;
2047
0
    hunk_size = newsize;
2048
0
    buffer += llen;
2049
0
    size -= llen;
2050
0
  }
2051
2052
0
  CALLOC_ARRAY(frag, 1);
2053
0
  frag->patch = inflate_it(data, hunk_size, origlen);
2054
0
  frag->free_patch = 1;
2055
0
  if (!frag->patch)
2056
0
    goto corrupt;
2057
0
  free(data);
2058
0
  frag->size = origlen;
2059
0
  *buf_p = buffer;
2060
0
  *sz_p = size;
2061
0
  *used_p = used;
2062
0
  frag->binary_patch_method = patch_method;
2063
0
  return frag;
2064
2065
0
 corrupt:
2066
0
  free(data);
2067
0
  *status_p = -1;
2068
0
  error(_("corrupt binary patch at line %d: %.*s"),
2069
0
        state->linenr-1, llen-1, buffer);
2070
0
  return NULL;
2071
0
}
2072
2073
/*
2074
 * Returns:
2075
 *   -1 in case of error,
2076
 *   the length of the parsed binary patch otherwise
2077
 */
2078
static int parse_binary(struct apply_state *state,
2079
      char *buffer,
2080
      unsigned long size,
2081
      struct patch *patch)
2082
0
{
2083
  /*
2084
   * We have read "GIT binary patch\n"; what follows is a line
2085
   * that says the patch method (currently, either "literal" or
2086
   * "delta") and the length of data before deflating; a
2087
   * sequence of 'length-byte' followed by base-85 encoded data
2088
   * follows.
2089
   *
2090
   * When a binary patch is reversible, there is another binary
2091
   * hunk in the same format, starting with patch method (either
2092
   * "literal" or "delta") with the length of data, and a sequence
2093
   * of length-byte + base-85 encoded data, terminated with another
2094
   * empty line.  This data, when applied to the postimage, produces
2095
   * the preimage.
2096
   */
2097
0
  struct fragment *forward;
2098
0
  struct fragment *reverse;
2099
0
  int status;
2100
0
  int used, used_1;
2101
2102
0
  forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2103
0
  if (!forward && !status)
2104
    /* there has to be one hunk (forward hunk) */
2105
0
    return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2106
0
  if (status)
2107
    /* otherwise we already gave an error message */
2108
0
    return status;
2109
2110
0
  reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2111
0
  if (reverse)
2112
0
    used += used_1;
2113
0
  else if (status) {
2114
    /*
2115
     * Not having reverse hunk is not an error, but having
2116
     * a corrupt reverse hunk is.
2117
     */
2118
0
    free((void*) forward->patch);
2119
0
    free(forward);
2120
0
    return status;
2121
0
  }
2122
0
  forward->next = reverse;
2123
0
  patch->fragments = forward;
2124
0
  patch->is_binary = 1;
2125
0
  return used;
2126
0
}
2127
2128
static void prefix_one(struct apply_state *state, char **name)
2129
0
{
2130
0
  char *old_name = *name;
2131
0
  if (!old_name)
2132
0
    return;
2133
0
  *name = prefix_filename(state->prefix, *name);
2134
0
  free(old_name);
2135
0
}
2136
2137
static void prefix_patch(struct apply_state *state, struct patch *p)
2138
0
{
2139
0
  if (!state->prefix || p->is_toplevel_relative)
2140
0
    return;
2141
0
  prefix_one(state, &p->new_name);
2142
0
  prefix_one(state, &p->old_name);
2143
0
}
2144
2145
/*
2146
 * include/exclude
2147
 */
2148
2149
static void add_name_limit(struct apply_state *state,
2150
         const char *name,
2151
         int exclude)
2152
0
{
2153
0
  struct string_list_item *it;
2154
2155
0
  it = string_list_append(&state->limit_by_name, name);
2156
0
  it->util = exclude ? NULL : (void *) 1;
2157
0
}
2158
2159
static int use_patch(struct apply_state *state, struct patch *p)
2160
0
{
2161
0
  const char *pathname = p->new_name ? p->new_name : p->old_name;
2162
0
  int i;
2163
2164
  /* Paths outside are not touched regardless of "--include" */
2165
0
  if (state->prefix && *state->prefix) {
2166
0
    const char *rest;
2167
0
    if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2168
0
      return 0;
2169
0
  }
2170
2171
  /* See if it matches any of exclude/include rule */
2172
0
  for (i = 0; i < state->limit_by_name.nr; i++) {
2173
0
    struct string_list_item *it = &state->limit_by_name.items[i];
2174
0
    if (!wildmatch(it->string, pathname, 0))
2175
0
      return (it->util != NULL);
2176
0
  }
2177
2178
  /*
2179
   * If we had any include, a path that does not match any rule is
2180
   * not used.  Otherwise, we saw bunch of exclude rules (or none)
2181
   * and such a path is used.
2182
   */
2183
0
  return !state->has_include;
2184
0
}
2185
2186
/*
2187
 * Read the patch text in "buffer" that extends for "size" bytes; stop
2188
 * reading after seeing a single patch (i.e. changes to a single file).
2189
 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2190
 *
2191
 * Returns:
2192
 *   -1 if no header was found or parse_binary() failed,
2193
 *   -128 on another error,
2194
 *   the number of bytes consumed otherwise,
2195
 *     so that the caller can call us again for the next patch.
2196
 */
2197
static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2198
0
{
2199
0
  int hdrsize, patchsize;
2200
0
  int offset = find_header(state, buffer, size, &hdrsize, patch);
2201
2202
0
  if (offset < 0)
2203
0
    return offset;
2204
2205
0
  prefix_patch(state, patch);
2206
2207
0
  if (!use_patch(state, patch))
2208
0
    patch->ws_rule = 0;
2209
0
  else if (patch->new_name)
2210
0
    patch->ws_rule = whitespace_rule(state->repo->index,
2211
0
             patch->new_name);
2212
0
  else
2213
0
    patch->ws_rule = whitespace_rule(state->repo->index,
2214
0
             patch->old_name);
2215
2216
0
  patchsize = parse_single_patch(state,
2217
0
               buffer + offset + hdrsize,
2218
0
               size - offset - hdrsize,
2219
0
               patch);
2220
2221
0
  if (patchsize < 0)
2222
0
    return -128;
2223
2224
0
  if (!patchsize) {
2225
0
    static const char git_binary[] = "GIT binary patch\n";
2226
0
    int hd = hdrsize + offset;
2227
0
    unsigned long llen = linelen(buffer + hd, size - hd);
2228
2229
0
    if (llen == sizeof(git_binary) - 1 &&
2230
0
        !memcmp(git_binary, buffer + hd, llen)) {
2231
0
      int used;
2232
0
      state->linenr++;
2233
0
      used = parse_binary(state, buffer + hd + llen,
2234
0
              size - hd - llen, patch);
2235
0
      if (used < 0)
2236
0
        return -1;
2237
0
      if (used)
2238
0
        patchsize = used + llen;
2239
0
      else
2240
0
        patchsize = 0;
2241
0
    }
2242
0
    else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2243
0
      static const char *binhdr[] = {
2244
0
        "Binary files ",
2245
0
        "Files ",
2246
0
        NULL,
2247
0
      };
2248
0
      int i;
2249
0
      for (i = 0; binhdr[i]; i++) {
2250
0
        int len = strlen(binhdr[i]);
2251
0
        if (len < size - hd &&
2252
0
            !memcmp(binhdr[i], buffer + hd, len)) {
2253
0
          state->linenr++;
2254
0
          patch->is_binary = 1;
2255
0
          patchsize = llen;
2256
0
          break;
2257
0
        }
2258
0
      }
2259
0
    }
2260
2261
    /* Empty patch cannot be applied if it is a text patch
2262
     * without metadata change.  A binary patch appears
2263
     * empty to us here.
2264
     */
2265
0
    if ((state->apply || state->check) &&
2266
0
        (!patch->is_binary && !metadata_changes(patch))) {
2267
0
      error(_("patch with only garbage at line %d"), state->linenr);
2268
0
      return -128;
2269
0
    }
2270
0
  }
2271
2272
0
  return offset + hdrsize + patchsize;
2273
0
}
2274
2275
static void reverse_patches(struct patch *p)
2276
0
{
2277
0
  for (; p; p = p->next) {
2278
0
    struct fragment *frag = p->fragments;
2279
2280
0
    SWAP(p->new_name, p->old_name);
2281
0
    if (p->new_mode || p->is_delete)
2282
0
      SWAP(p->new_mode, p->old_mode);
2283
0
    SWAP(p->is_new, p->is_delete);
2284
0
    SWAP(p->lines_added, p->lines_deleted);
2285
0
    SWAP(p->old_oid_prefix, p->new_oid_prefix);
2286
2287
0
    for (; frag; frag = frag->next) {
2288
0
      SWAP(frag->newpos, frag->oldpos);
2289
0
      SWAP(frag->newlines, frag->oldlines);
2290
0
    }
2291
0
  }
2292
0
}
2293
2294
static const char pluses[] =
2295
"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2296
static const char minuses[]=
2297
"----------------------------------------------------------------------";
2298
2299
static void show_stats(struct apply_state *state, struct patch *patch)
2300
0
{
2301
0
  struct strbuf qname = STRBUF_INIT;
2302
0
  char *cp = patch->new_name ? patch->new_name : patch->old_name;
2303
0
  int max, add, del;
2304
2305
0
  quote_c_style(cp, &qname, NULL, 0);
2306
2307
  /*
2308
   * "scale" the filename
2309
   */
2310
0
  max = state->max_len;
2311
0
  if (max > 50)
2312
0
    max = 50;
2313
2314
0
  if (qname.len > max) {
2315
0
    cp = strchr(qname.buf + qname.len + 3 - max, '/');
2316
0
    if (!cp)
2317
0
      cp = qname.buf + qname.len + 3 - max;
2318
0
    strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2319
0
  }
2320
2321
0
  if (patch->is_binary) {
2322
0
    printf(" %-*s |  Bin\n", max, qname.buf);
2323
0
    strbuf_release(&qname);
2324
0
    return;
2325
0
  }
2326
2327
0
  printf(" %-*s |", max, qname.buf);
2328
0
  strbuf_release(&qname);
2329
2330
  /*
2331
   * scale the add/delete
2332
   */
2333
0
  max = max + state->max_change > 70 ? 70 - max : state->max_change;
2334
0
  add = patch->lines_added;
2335
0
  del = patch->lines_deleted;
2336
2337
0
  if (state->max_change > 0) {
2338
0
    int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2339
0
    add = (add * max + state->max_change / 2) / state->max_change;
2340
0
    del = total - add;
2341
0
  }
2342
0
  printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2343
0
    add, pluses, del, minuses);
2344
0
}
2345
2346
static int read_old_data(struct stat *st, struct patch *patch,
2347
       const char *path, struct strbuf *buf)
2348
0
{
2349
0
  int conv_flags = patch->crlf_in_old ?
2350
0
    CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2351
0
  switch (st->st_mode & S_IFMT) {
2352
0
  case S_IFLNK:
2353
0
    if (strbuf_readlink(buf, path, st->st_size) < 0)
2354
0
      return error(_("unable to read symlink %s"), path);
2355
0
    return 0;
2356
0
  case S_IFREG:
2357
0
    if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2358
0
      return error(_("unable to open or read %s"), path);
2359
    /*
2360
     * "git apply" without "--index/--cached" should never look
2361
     * at the index; the target file may not have been added to
2362
     * the index yet, and we may not even be in any Git repository.
2363
     * Pass NULL to convert_to_git() to stress this; the function
2364
     * should never look at the index when explicit crlf option
2365
     * is given.
2366
     */
2367
0
    convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2368
0
    return 0;
2369
0
  default:
2370
0
    return -1;
2371
0
  }
2372
0
}
2373
2374
/*
2375
 * Update the preimage, and the common lines in postimage,
2376
 * from buffer buf of length len.
2377
 */
2378
static void update_pre_post_images(struct image *preimage,
2379
           struct image *postimage,
2380
           char *buf, size_t len)
2381
0
{
2382
0
  struct image fixed_preimage = IMAGE_INIT;
2383
0
  size_t insert_pos = 0;
2384
0
  int i, ctx, reduced;
2385
0
  const char *fixed;
2386
2387
  /*
2388
   * Update the preimage with whitespace fixes.  Note that we
2389
   * are not losing preimage->buf -- apply_one_fragment() will
2390
   * free "oldlines".
2391
   */
2392
0
  image_prepare(&fixed_preimage, buf, len, 1);
2393
0
  for (i = 0; i < fixed_preimage.line_nr; i++)
2394
0
    fixed_preimage.line[i].flag = preimage->line[i].flag;
2395
0
  image_clear(preimage);
2396
0
  *preimage = fixed_preimage;
2397
0
  fixed = preimage->buf.buf;
2398
2399
  /*
2400
   * Adjust the common context lines in postimage.
2401
   */
2402
0
  for (i = reduced = ctx = 0; i < postimage->line_nr; i++) {
2403
0
    size_t l_len = postimage->line[i].len;
2404
2405
0
    if (!(postimage->line[i].flag & LINE_COMMON)) {
2406
      /* an added line -- no counterparts in preimage */
2407
0
      insert_pos += l_len;
2408
0
      continue;
2409
0
    }
2410
2411
    /* and find the corresponding one in the fixed preimage */
2412
0
    while (ctx < preimage->line_nr &&
2413
0
           !(preimage->line[ctx].flag & LINE_COMMON)) {
2414
0
      fixed += preimage->line[ctx].len;
2415
0
      ctx++;
2416
0
    }
2417
2418
    /*
2419
     * preimage is expected to run out, if the caller
2420
     * fixed addition of trailing blank lines.
2421
     */
2422
0
    if (preimage->line_nr <= ctx) {
2423
0
      reduced++;
2424
0
      continue;
2425
0
    }
2426
2427
    /* and copy it in, while fixing the line length */
2428
0
    l_len = preimage->line[ctx].len;
2429
0
    strbuf_splice(&postimage->buf, insert_pos, postimage->line[i].len,
2430
0
            fixed, l_len);
2431
0
    insert_pos += l_len;
2432
0
    fixed += l_len;
2433
0
    postimage->line[i].len = l_len;
2434
0
    ctx++;
2435
0
  }
2436
2437
  /* Fix the length of the whole thing */
2438
0
  postimage->line_nr -= reduced;
2439
0
}
2440
2441
/*
2442
 * Compare lines s1 of length n1 and s2 of length n2, ignoring
2443
 * whitespace difference. Returns 1 if they match, 0 otherwise
2444
 */
2445
static int fuzzy_matchlines(const char *s1, size_t n1,
2446
          const char *s2, size_t n2)
2447
0
{
2448
0
  const char *end1 = s1 + n1;
2449
0
  const char *end2 = s2 + n2;
2450
2451
  /* ignore line endings */
2452
0
  while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
2453
0
    end1--;
2454
0
  while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
2455
0
    end2--;
2456
2457
0
  while (s1 < end1 && s2 < end2) {
2458
0
    if (isspace(*s1)) {
2459
      /*
2460
       * Skip whitespace. We check on both buffers
2461
       * because we don't want "a b" to match "ab".
2462
       */
2463
0
      if (!isspace(*s2))
2464
0
        return 0;
2465
0
      while (s1 < end1 && isspace(*s1))
2466
0
        s1++;
2467
0
      while (s2 < end2 && isspace(*s2))
2468
0
        s2++;
2469
0
    } else if (*s1++ != *s2++)
2470
0
      return 0;
2471
0
  }
2472
2473
  /* If we reached the end on one side only, lines don't match. */
2474
0
  return s1 == end1 && s2 == end2;
2475
0
}
2476
2477
static int line_by_line_fuzzy_match(struct image *img,
2478
            struct image *preimage,
2479
            struct image *postimage,
2480
            unsigned long current,
2481
            int current_lno,
2482
            int preimage_limit)
2483
0
{
2484
0
  int i;
2485
0
  size_t imgoff = 0;
2486
0
  size_t preoff = 0;
2487
0
  size_t extra_chars;
2488
0
  char *buf;
2489
0
  char *preimage_eof;
2490
0
  char *preimage_end;
2491
0
  struct strbuf fixed;
2492
0
  char *fixed_buf;
2493
0
  size_t fixed_len;
2494
2495
0
  for (i = 0; i < preimage_limit; i++) {
2496
0
    size_t prelen = preimage->line[i].len;
2497
0
    size_t imglen = img->line[current_lno+i].len;
2498
2499
0
    if (!fuzzy_matchlines(img->buf.buf + current + imgoff, imglen,
2500
0
              preimage->buf.buf + preoff, prelen))
2501
0
      return 0;
2502
0
    imgoff += imglen;
2503
0
    preoff += prelen;
2504
0
  }
2505
2506
  /*
2507
   * Ok, the preimage matches with whitespace fuzz.
2508
   *
2509
   * imgoff now holds the true length of the target that
2510
   * matches the preimage before the end of the file.
2511
   *
2512
   * Count the number of characters in the preimage that fall
2513
   * beyond the end of the file and make sure that all of them
2514
   * are whitespace characters. (This can only happen if
2515
   * we are removing blank lines at the end of the file.)
2516
   */
2517
0
  buf = preimage_eof = preimage->buf.buf + preoff;
2518
0
  for ( ; i < preimage->line_nr; i++)
2519
0
    preoff += preimage->line[i].len;
2520
0
  preimage_end = preimage->buf.buf + preoff;
2521
0
  for ( ; buf < preimage_end; buf++)
2522
0
    if (!isspace(*buf))
2523
0
      return 0;
2524
2525
  /*
2526
   * Update the preimage and the common postimage context
2527
   * lines to use the same whitespace as the target.
2528
   * If whitespace is missing in the target (i.e.
2529
   * if the preimage extends beyond the end of the file),
2530
   * use the whitespace from the preimage.
2531
   */
2532
0
  extra_chars = preimage_end - preimage_eof;
2533
0
  strbuf_init(&fixed, imgoff + extra_chars);
2534
0
  strbuf_add(&fixed, img->buf.buf + current, imgoff);
2535
0
  strbuf_add(&fixed, preimage_eof, extra_chars);
2536
0
  fixed_buf = strbuf_detach(&fixed, &fixed_len);
2537
0
  update_pre_post_images(preimage, postimage,
2538
0
             fixed_buf, fixed_len);
2539
0
  return 1;
2540
0
}
2541
2542
static int match_fragment(struct apply_state *state,
2543
        struct image *img,
2544
        struct image *preimage,
2545
        struct image *postimage,
2546
        unsigned long current,
2547
        int current_lno,
2548
        unsigned ws_rule,
2549
        int match_beginning, int match_end)
2550
0
{
2551
0
  int i;
2552
0
  const char *orig, *target;
2553
0
  struct strbuf fixed = STRBUF_INIT;
2554
0
  char *fixed_buf;
2555
0
  size_t fixed_len;
2556
0
  int preimage_limit;
2557
0
  int ret;
2558
2559
0
  if (preimage->line_nr + current_lno <= img->line_nr) {
2560
    /*
2561
     * The hunk falls within the boundaries of img.
2562
     */
2563
0
    preimage_limit = preimage->line_nr;
2564
0
    if (match_end && (preimage->line_nr + current_lno != img->line_nr)) {
2565
0
      ret = 0;
2566
0
      goto out;
2567
0
    }
2568
0
  } else if (state->ws_error_action == correct_ws_error &&
2569
0
       (ws_rule & WS_BLANK_AT_EOF)) {
2570
    /*
2571
     * This hunk extends beyond the end of img, and we are
2572
     * removing blank lines at the end of the file.  This
2573
     * many lines from the beginning of the preimage must
2574
     * match with img, and the remainder of the preimage
2575
     * must be blank.
2576
     */
2577
0
    preimage_limit = img->line_nr - current_lno;
2578
0
  } else {
2579
    /*
2580
     * The hunk extends beyond the end of the img and
2581
     * we are not removing blanks at the end, so we
2582
     * should reject the hunk at this position.
2583
     */
2584
0
    ret = 0;
2585
0
    goto out;
2586
0
  }
2587
2588
0
  if (match_beginning && current_lno) {
2589
0
    ret = 0;
2590
0
    goto out;
2591
0
  }
2592
2593
  /* Quick hash check */
2594
0
  for (i = 0; i < preimage_limit; i++) {
2595
0
    if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2596
0
        (preimage->line[i].hash != img->line[current_lno + i].hash)) {
2597
0
      ret = 0;
2598
0
      goto out;
2599
0
    }
2600
0
  }
2601
2602
0
  if (preimage_limit == preimage->line_nr) {
2603
    /*
2604
     * Do we have an exact match?  If we were told to match
2605
     * at the end, size must be exactly at current+fragsize,
2606
     * otherwise current+fragsize must be still within the preimage,
2607
     * and either case, the old piece should match the preimage
2608
     * exactly.
2609
     */
2610
0
    if ((match_end
2611
0
         ? (current + preimage->buf.len == img->buf.len)
2612
0
         : (current + preimage->buf.len <= img->buf.len)) &&
2613
0
        !memcmp(img->buf.buf + current, preimage->buf.buf, preimage->buf.len)) {
2614
0
      ret = 1;
2615
0
      goto out;
2616
0
    }
2617
0
  } else {
2618
    /*
2619
     * The preimage extends beyond the end of img, so
2620
     * there cannot be an exact match.
2621
     *
2622
     * There must be one non-blank context line that match
2623
     * a line before the end of img.
2624
     */
2625
0
    const char *buf, *buf_end;
2626
2627
0
    buf = preimage->buf.buf;
2628
0
    buf_end = buf;
2629
0
    for (i = 0; i < preimage_limit; i++)
2630
0
      buf_end += preimage->line[i].len;
2631
2632
0
    for ( ; buf < buf_end; buf++)
2633
0
      if (!isspace(*buf))
2634
0
        break;
2635
0
    if (buf == buf_end) {
2636
0
      ret = 0;
2637
0
      goto out;
2638
0
    }
2639
0
  }
2640
2641
  /*
2642
   * No exact match. If we are ignoring whitespace, run a line-by-line
2643
   * fuzzy matching. We collect all the line length information because
2644
   * we need it to adjust whitespace if we match.
2645
   */
2646
0
  if (state->ws_ignore_action == ignore_ws_change) {
2647
0
    ret = line_by_line_fuzzy_match(img, preimage, postimage,
2648
0
                 current, current_lno, preimage_limit);
2649
0
    goto out;
2650
0
  }
2651
2652
0
  if (state->ws_error_action != correct_ws_error) {
2653
0
    ret = 0;
2654
0
    goto out;
2655
0
  }
2656
2657
  /*
2658
   * The hunk does not apply byte-by-byte, but the hash says
2659
   * it might with whitespace fuzz. We weren't asked to
2660
   * ignore whitespace, we were asked to correct whitespace
2661
   * errors, so let's try matching after whitespace correction.
2662
   *
2663
   * While checking the preimage against the target, whitespace
2664
   * errors in both fixed, we count how large the corresponding
2665
   * postimage needs to be.  The postimage prepared by
2666
   * apply_one_fragment() has whitespace errors fixed on added
2667
   * lines already, but the common lines were propagated as-is,
2668
   * which may become longer when their whitespace errors are
2669
   * fixed.
2670
   */
2671
2672
  /*
2673
   * The preimage may extend beyond the end of the file,
2674
   * but in this loop we will only handle the part of the
2675
   * preimage that falls within the file.
2676
   */
2677
0
  strbuf_grow(&fixed, preimage->buf.len + 1);
2678
0
  orig = preimage->buf.buf;
2679
0
  target = img->buf.buf + current;
2680
0
  for (i = 0; i < preimage_limit; i++) {
2681
0
    size_t oldlen = preimage->line[i].len;
2682
0
    size_t tgtlen = img->line[current_lno + i].len;
2683
0
    size_t fixstart = fixed.len;
2684
0
    struct strbuf tgtfix;
2685
0
    int match;
2686
2687
    /* Try fixing the line in the preimage */
2688
0
    ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2689
2690
    /* Try fixing the line in the target */
2691
0
    strbuf_init(&tgtfix, tgtlen);
2692
0
    ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2693
2694
    /*
2695
     * If they match, either the preimage was based on
2696
     * a version before our tree fixed whitespace breakage,
2697
     * or we are lacking a whitespace-fix patch the tree
2698
     * the preimage was based on already had (i.e. target
2699
     * has whitespace breakage, the preimage doesn't).
2700
     * In either case, we are fixing the whitespace breakages
2701
     * so we might as well take the fix together with their
2702
     * real change.
2703
     */
2704
0
    match = (tgtfix.len == fixed.len - fixstart &&
2705
0
       !memcmp(tgtfix.buf, fixed.buf + fixstart,
2706
0
               fixed.len - fixstart));
2707
2708
0
    strbuf_release(&tgtfix);
2709
0
    if (!match) {
2710
0
      ret = 0;
2711
0
      goto out;
2712
0
    }
2713
2714
0
    orig += oldlen;
2715
0
    target += tgtlen;
2716
0
  }
2717
2718
2719
  /*
2720
   * Now handle the lines in the preimage that falls beyond the
2721
   * end of the file (if any). They will only match if they are
2722
   * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2723
   * false).
2724
   */
2725
0
  for ( ; i < preimage->line_nr; i++) {
2726
0
    size_t fixstart = fixed.len; /* start of the fixed preimage */
2727
0
    size_t oldlen = preimage->line[i].len;
2728
0
    int j;
2729
2730
    /* Try fixing the line in the preimage */
2731
0
    ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2732
2733
0
    for (j = fixstart; j < fixed.len; j++) {
2734
0
      if (!isspace(fixed.buf[j])) {
2735
0
        ret = 0;
2736
0
        goto out;
2737
0
      }
2738
0
    }
2739
2740
2741
0
    orig += oldlen;
2742
0
  }
2743
2744
  /*
2745
   * Yes, the preimage is based on an older version that still
2746
   * has whitespace breakages unfixed, and fixing them makes the
2747
   * hunk match.  Update the context lines in the postimage.
2748
   */
2749
0
  fixed_buf = strbuf_detach(&fixed, &fixed_len);
2750
0
  update_pre_post_images(preimage, postimage,
2751
0
             fixed_buf, fixed_len);
2752
2753
0
  ret = 1;
2754
2755
0
out:
2756
0
  strbuf_release(&fixed);
2757
0
  return ret;
2758
0
}
2759
2760
static int find_pos(struct apply_state *state,
2761
        struct image *img,
2762
        struct image *preimage,
2763
        struct image *postimage,
2764
        int line,
2765
        unsigned ws_rule,
2766
        int match_beginning, int match_end)
2767
0
{
2768
0
  int i;
2769
0
  unsigned long backwards, forwards, current;
2770
0
  int backwards_lno, forwards_lno, current_lno;
2771
2772
  /*
2773
   * When running with --allow-overlap, it is possible that a hunk is
2774
   * seen that pretends to start at the beginning (but no longer does),
2775
   * and that *still* needs to match the end. So trust `match_end` more
2776
   * than `match_beginning`.
2777
   */
2778
0
  if (state->allow_overlap && match_beginning && match_end &&
2779
0
      img->line_nr - preimage->line_nr != 0)
2780
0
    match_beginning = 0;
2781
2782
  /*
2783
   * If match_beginning or match_end is specified, there is no
2784
   * point starting from a wrong line that will never match and
2785
   * wander around and wait for a match at the specified end.
2786
   */
2787
0
  if (match_beginning)
2788
0
    line = 0;
2789
0
  else if (match_end)
2790
0
    line = img->line_nr - preimage->line_nr;
2791
2792
  /*
2793
   * Because the comparison is unsigned, the following test
2794
   * will also take care of a negative line number that can
2795
   * result when match_end and preimage is larger than the target.
2796
   */
2797
0
  if ((size_t) line > img->line_nr)
2798
0
    line = img->line_nr;
2799
2800
0
  current = 0;
2801
0
  for (i = 0; i < line; i++)
2802
0
    current += img->line[i].len;
2803
2804
  /*
2805
   * There's probably some smart way to do this, but I'll leave
2806
   * that to the smart and beautiful people. I'm simple and stupid.
2807
   */
2808
0
  backwards = current;
2809
0
  backwards_lno = line;
2810
0
  forwards = current;
2811
0
  forwards_lno = line;
2812
0
  current_lno = line;
2813
2814
0
  for (i = 0; ; i++) {
2815
0
    if (match_fragment(state, img, preimage, postimage,
2816
0
           current, current_lno, ws_rule,
2817
0
           match_beginning, match_end))
2818
0
      return current_lno;
2819
2820
0
  again:
2821
0
    if (backwards_lno == 0 && forwards_lno == img->line_nr)
2822
0
      break;
2823
2824
0
    if (i & 1) {
2825
0
      if (backwards_lno == 0) {
2826
0
        i++;
2827
0
        goto again;
2828
0
      }
2829
0
      backwards_lno--;
2830
0
      backwards -= img->line[backwards_lno].len;
2831
0
      current = backwards;
2832
0
      current_lno = backwards_lno;
2833
0
    } else {
2834
0
      if (forwards_lno == img->line_nr) {
2835
0
        i++;
2836
0
        goto again;
2837
0
      }
2838
0
      forwards += img->line[forwards_lno].len;
2839
0
      forwards_lno++;
2840
0
      current = forwards;
2841
0
      current_lno = forwards_lno;
2842
0
    }
2843
2844
0
  }
2845
0
  return -1;
2846
0
}
2847
2848
/*
2849
 * The change from "preimage" and "postimage" has been found to
2850
 * apply at applied_pos (counts in line numbers) in "img".
2851
 * Update "img" to remove "preimage" and replace it with "postimage".
2852
 */
2853
static void update_image(struct apply_state *state,
2854
       struct image *img,
2855
       int applied_pos,
2856
       struct image *preimage,
2857
       struct image *postimage)
2858
0
{
2859
  /*
2860
   * remove the copy of preimage at offset in img
2861
   * and replace it with postimage
2862
   */
2863
0
  int i, nr;
2864
0
  size_t remove_count, insert_count, applied_at = 0;
2865
0
  size_t result_alloc;
2866
0
  char *result;
2867
0
  int preimage_limit;
2868
2869
  /*
2870
   * If we are removing blank lines at the end of img,
2871
   * the preimage may extend beyond the end.
2872
   * If that is the case, we must be careful only to
2873
   * remove the part of the preimage that falls within
2874
   * the boundaries of img. Initialize preimage_limit
2875
   * to the number of lines in the preimage that falls
2876
   * within the boundaries.
2877
   */
2878
0
  preimage_limit = preimage->line_nr;
2879
0
  if (preimage_limit > img->line_nr - applied_pos)
2880
0
    preimage_limit = img->line_nr - applied_pos;
2881
2882
0
  for (i = 0; i < applied_pos; i++)
2883
0
    applied_at += img->line[i].len;
2884
2885
0
  remove_count = 0;
2886
0
  for (i = 0; i < preimage_limit; i++)
2887
0
    remove_count += img->line[applied_pos + i].len;
2888
0
  insert_count = postimage->buf.len;
2889
2890
  /* Adjust the contents */
2891
0
  result_alloc = st_add3(st_sub(img->buf.len, remove_count), insert_count, 1);
2892
0
  result = xmalloc(result_alloc);
2893
0
  memcpy(result, img->buf.buf, applied_at);
2894
0
  memcpy(result + applied_at, postimage->buf.buf, postimage->buf.len);
2895
0
  memcpy(result + applied_at + postimage->buf.len,
2896
0
         img->buf.buf + (applied_at + remove_count),
2897
0
         img->buf.len - (applied_at + remove_count));
2898
0
  strbuf_attach(&img->buf, result, postimage->buf.len + img->buf.len - remove_count,
2899
0
          result_alloc);
2900
2901
  /* Adjust the line table */
2902
0
  nr = img->line_nr + postimage->line_nr - preimage_limit;
2903
0
  if (preimage_limit < postimage->line_nr)
2904
    /*
2905
     * NOTE: this knows that we never call image_remove_first_line()
2906
     * on anything other than pre/post image.
2907
     */
2908
0
    REALLOC_ARRAY(img->line, nr);
2909
0
  if (preimage_limit != postimage->line_nr)
2910
0
    MOVE_ARRAY(img->line + applied_pos + postimage->line_nr,
2911
0
         img->line + applied_pos + preimage_limit,
2912
0
         img->line_nr - (applied_pos + preimage_limit));
2913
0
  COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->line_nr);
2914
0
  if (!state->allow_overlap)
2915
0
    for (i = 0; i < postimage->line_nr; i++)
2916
0
      img->line[applied_pos + i].flag |= LINE_PATCHED;
2917
0
  img->line_nr = nr;
2918
0
}
2919
2920
/*
2921
 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2922
 * postimage) for the hunk.  Find lines that match "preimage" in "img" and
2923
 * replace the part of "img" with "postimage" text.
2924
 */
2925
static int apply_one_fragment(struct apply_state *state,
2926
            struct image *img, struct fragment *frag,
2927
            int inaccurate_eof, unsigned ws_rule,
2928
            int nth_fragment)
2929
0
{
2930
0
  int match_beginning, match_end;
2931
0
  const char *patch = frag->patch;
2932
0
  int size = frag->size;
2933
0
  char *old, *oldlines;
2934
0
  struct strbuf newlines;
2935
0
  int new_blank_lines_at_end = 0;
2936
0
  int found_new_blank_lines_at_end = 0;
2937
0
  int hunk_linenr = frag->linenr;
2938
0
  unsigned long leading, trailing;
2939
0
  int pos, applied_pos;
2940
0
  struct image preimage = IMAGE_INIT;
2941
0
  struct image postimage = IMAGE_INIT;
2942
2943
0
  oldlines = xmalloc(size);
2944
0
  strbuf_init(&newlines, size);
2945
2946
0
  old = oldlines;
2947
0
  while (size > 0) {
2948
0
    char first;
2949
0
    int len = linelen(patch, size);
2950
0
    int plen;
2951
0
    int added_blank_line = 0;
2952
0
    int is_blank_context = 0;
2953
0
    size_t start;
2954
2955
0
    if (!len)
2956
0
      break;
2957
2958
    /*
2959
     * "plen" is how much of the line we should use for
2960
     * the actual patch data. Normally we just remove the
2961
     * first character on the line, but if the line is
2962
     * followed by "\ No newline", then we also remove the
2963
     * last one (which is the newline, of course).
2964
     */
2965
0
    plen = len - 1;
2966
0
    if (len < size && patch[len] == '\\')
2967
0
      plen--;
2968
0
    first = *patch;
2969
0
    if (state->apply_in_reverse) {
2970
0
      if (first == '-')
2971
0
        first = '+';
2972
0
      else if (first == '+')
2973
0
        first = '-';
2974
0
    }
2975
2976
0
    switch (first) {
2977
0
    case '\n':
2978
      /* Newer GNU diff, empty context line */
2979
0
      if (plen < 0)
2980
        /* ... followed by '\No newline'; nothing */
2981
0
        break;
2982
0
      *old++ = '\n';
2983
0
      strbuf_addch(&newlines, '\n');
2984
0
      image_add_line(&preimage, "\n", 1, LINE_COMMON);
2985
0
      image_add_line(&postimage, "\n", 1, LINE_COMMON);
2986
0
      is_blank_context = 1;
2987
0
      break;
2988
0
    case ' ':
2989
0
      if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2990
0
          ws_blank_line(patch + 1, plen))
2991
0
        is_blank_context = 1;
2992
      /* fallthrough */
2993
0
    case '-':
2994
0
      memcpy(old, patch + 1, plen);
2995
0
      image_add_line(&preimage, old, plen,
2996
0
              (first == ' ' ? LINE_COMMON : 0));
2997
0
      old += plen;
2998
0
      if (first == '-')
2999
0
        break;
3000
      /* fallthrough */
3001
0
    case '+':
3002
      /* --no-add does not add new lines */
3003
0
      if (first == '+' && state->no_add)
3004
0
        break;
3005
3006
0
      start = newlines.len;
3007
0
      if (first != '+' ||
3008
0
          !state->whitespace_error ||
3009
0
          state->ws_error_action != correct_ws_error) {
3010
0
        strbuf_add(&newlines, patch + 1, plen);
3011
0
      }
3012
0
      else {
3013
0
        ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
3014
0
      }
3015
0
      image_add_line(&postimage, newlines.buf + start, newlines.len - start,
3016
0
              (first == '+' ? 0 : LINE_COMMON));
3017
0
      if (first == '+' &&
3018
0
          (ws_rule & WS_BLANK_AT_EOF) &&
3019
0
          ws_blank_line(patch + 1, plen))
3020
0
        added_blank_line = 1;
3021
0
      break;
3022
0
    case '@': case '\\':
3023
      /* Ignore it, we already handled it */
3024
0
      break;
3025
0
    default:
3026
0
      if (state->apply_verbosity > verbosity_normal)
3027
0
        error(_("invalid start of line: '%c'"), first);
3028
0
      applied_pos = -1;
3029
0
      goto out;
3030
0
    }
3031
0
    if (added_blank_line) {
3032
0
      if (!new_blank_lines_at_end)
3033
0
        found_new_blank_lines_at_end = hunk_linenr;
3034
0
      new_blank_lines_at_end++;
3035
0
    }
3036
0
    else if (is_blank_context)
3037
0
      ;
3038
0
    else
3039
0
      new_blank_lines_at_end = 0;
3040
0
    patch += len;
3041
0
    size -= len;
3042
0
    hunk_linenr++;
3043
0
  }
3044
0
  if (inaccurate_eof &&
3045
0
      old > oldlines && old[-1] == '\n' &&
3046
0
      newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
3047
0
    old--;
3048
0
    strbuf_setlen(&newlines, newlines.len - 1);
3049
0
    preimage.line[preimage.line_nr - 1].len--;
3050
0
    postimage.line[postimage.line_nr - 1].len--;
3051
0
  }
3052
3053
0
  leading = frag->leading;
3054
0
  trailing = frag->trailing;
3055
3056
  /*
3057
   * A hunk to change lines at the beginning would begin with
3058
   * @@ -1,L +N,M @@
3059
   * but we need to be careful.  -U0 that inserts before the second
3060
   * line also has this pattern.
3061
   *
3062
   * And a hunk to add to an empty file would begin with
3063
   * @@ -0,0 +N,M @@
3064
   *
3065
   * In other words, a hunk that is (frag->oldpos <= 1) with or
3066
   * without leading context must match at the beginning.
3067
   */
3068
0
  match_beginning = (!frag->oldpos ||
3069
0
         (frag->oldpos == 1 && !state->unidiff_zero));
3070
3071
  /*
3072
   * A hunk without trailing lines must match at the end.
3073
   * However, we simply cannot tell if a hunk must match end
3074
   * from the lack of trailing lines if the patch was generated
3075
   * with unidiff without any context.
3076
   */
3077
0
  match_end = !state->unidiff_zero && !trailing;
3078
3079
0
  pos = frag->newpos ? (frag->newpos - 1) : 0;
3080
0
  strbuf_add(&preimage.buf, oldlines, old - oldlines);
3081
0
  strbuf_swap(&postimage.buf, &newlines);
3082
3083
0
  for (;;) {
3084
3085
0
    applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3086
0
               ws_rule, match_beginning, match_end);
3087
3088
0
    if (applied_pos >= 0)
3089
0
      break;
3090
3091
    /* Am I at my context limits? */
3092
0
    if ((leading <= state->p_context) && (trailing <= state->p_context))
3093
0
      break;
3094
0
    if (match_beginning || match_end) {
3095
0
      match_beginning = match_end = 0;
3096
0
      continue;
3097
0
    }
3098
3099
    /*
3100
     * Reduce the number of context lines; reduce both
3101
     * leading and trailing if they are equal otherwise
3102
     * just reduce the larger context.
3103
     */
3104
0
    if (leading >= trailing) {
3105
0
      image_remove_first_line(&preimage);
3106
0
      image_remove_first_line(&postimage);
3107
0
      pos--;
3108
0
      leading--;
3109
0
    }
3110
0
    if (trailing > leading) {
3111
0
      image_remove_last_line(&preimage);
3112
0
      image_remove_last_line(&postimage);
3113
0
      trailing--;
3114
0
    }
3115
0
  }
3116
3117
0
  if (applied_pos >= 0) {
3118
0
    if (new_blank_lines_at_end &&
3119
0
        preimage.line_nr + applied_pos >= img->line_nr &&
3120
0
        (ws_rule & WS_BLANK_AT_EOF) &&
3121
0
        state->ws_error_action != nowarn_ws_error) {
3122
0
      record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3123
0
          found_new_blank_lines_at_end);
3124
0
      if (state->ws_error_action == correct_ws_error) {
3125
0
        while (new_blank_lines_at_end--)
3126
0
          image_remove_last_line(&postimage);
3127
0
      }
3128
      /*
3129
       * We would want to prevent write_out_results()
3130
       * from taking place in apply_patch() that follows
3131
       * the callchain led us here, which is:
3132
       * apply_patch->check_patch_list->check_patch->
3133
       * apply_data->apply_fragments->apply_one_fragment
3134
       */
3135
0
      if (state->ws_error_action == die_on_ws_error)
3136
0
        state->apply = 0;
3137
0
    }
3138
3139
0
    if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3140
0
      int offset = applied_pos - pos;
3141
0
      if (state->apply_in_reverse)
3142
0
        offset = 0 - offset;
3143
0
      fprintf_ln(stderr,
3144
0
           Q_("Hunk #%d succeeded at %d (offset %d line).",
3145
0
              "Hunk #%d succeeded at %d (offset %d lines).",
3146
0
              offset),
3147
0
           nth_fragment, applied_pos + 1, offset);
3148
0
    }
3149
3150
    /*
3151
     * Warn if it was necessary to reduce the number
3152
     * of context lines.
3153
     */
3154
0
    if ((leading != frag->leading ||
3155
0
         trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3156
0
      fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3157
0
               " to apply fragment at %d"),
3158
0
           leading, trailing, applied_pos+1);
3159
0
    update_image(state, img, applied_pos, &preimage, &postimage);
3160
0
  } else {
3161
0
    if (state->apply_verbosity > verbosity_normal)
3162
0
      error(_("while searching for:\n%.*s"),
3163
0
            (int)(old - oldlines), oldlines);
3164
0
  }
3165
3166
0
out:
3167
0
  free(oldlines);
3168
0
  strbuf_release(&newlines);
3169
0
  image_clear(&preimage);
3170
0
  image_clear(&postimage);
3171
3172
0
  return (applied_pos < 0);
3173
0
}
3174
3175
static int apply_binary_fragment(struct apply_state *state,
3176
         struct image *img,
3177
         struct patch *patch)
3178
0
{
3179
0
  struct fragment *fragment = patch->fragments;
3180
0
  unsigned long len;
3181
0
  void *dst;
3182
3183
0
  if (!fragment)
3184
0
    return error(_("missing binary patch data for '%s'"),
3185
0
           patch->new_name ?
3186
0
           patch->new_name :
3187
0
           patch->old_name);
3188
3189
  /* Binary patch is irreversible without the optional second hunk */
3190
0
  if (state->apply_in_reverse) {
3191
0
    if (!fragment->next)
3192
0
      return error(_("cannot reverse-apply a binary patch "
3193
0
               "without the reverse hunk to '%s'"),
3194
0
             patch->new_name
3195
0
             ? patch->new_name : patch->old_name);
3196
0
    fragment = fragment->next;
3197
0
  }
3198
0
  switch (fragment->binary_patch_method) {
3199
0
  case BINARY_DELTA_DEFLATED:
3200
0
    dst = patch_delta(img->buf.buf, img->buf.len, fragment->patch,
3201
0
          fragment->size, &len);
3202
0
    if (!dst)
3203
0
      return -1;
3204
0
    image_clear(img);
3205
0
    strbuf_attach(&img->buf, dst, len, len + 1);
3206
0
    return 0;
3207
0
  case BINARY_LITERAL_DEFLATED:
3208
0
    image_clear(img);
3209
0
    strbuf_add(&img->buf, fragment->patch, fragment->size);
3210
0
    return 0;
3211
0
  }
3212
0
  return -1;
3213
0
}
3214
3215
/*
3216
 * Replace "img" with the result of applying the binary patch.
3217
 * The binary patch data itself in patch->fragment is still kept
3218
 * but the preimage prepared by the caller in "img" is freed here
3219
 * or in the helper function apply_binary_fragment() this calls.
3220
 */
3221
static int apply_binary(struct apply_state *state,
3222
      struct image *img,
3223
      struct patch *patch)
3224
0
{
3225
0
  const char *name = patch->old_name ? patch->old_name : patch->new_name;
3226
0
  struct object_id oid;
3227
0
  const unsigned hexsz = the_hash_algo->hexsz;
3228
3229
  /*
3230
   * For safety, we require patch index line to contain
3231
   * full hex textual object ID for old and new, at least for now.
3232
   */
3233
0
  if (strlen(patch->old_oid_prefix) != hexsz ||
3234
0
      strlen(patch->new_oid_prefix) != hexsz ||
3235
0
      get_oid_hex(patch->old_oid_prefix, &oid) ||
3236
0
      get_oid_hex(patch->new_oid_prefix, &oid))
3237
0
    return error(_("cannot apply binary patch to '%s' "
3238
0
             "without full index line"), name);
3239
3240
0
  if (patch->old_name) {
3241
    /*
3242
     * See if the old one matches what the patch
3243
     * applies to.
3244
     */
3245
0
    hash_object_file(the_hash_algo, img->buf.buf, img->buf.len,
3246
0
         OBJ_BLOB, &oid);
3247
0
    if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3248
0
      return error(_("the patch applies to '%s' (%s), "
3249
0
               "which does not match the "
3250
0
               "current contents."),
3251
0
             name, oid_to_hex(&oid));
3252
0
  }
3253
0
  else {
3254
    /* Otherwise, the old one must be empty. */
3255
0
    if (img->buf.len)
3256
0
      return error(_("the patch applies to an empty "
3257
0
               "'%s' but it is not empty"), name);
3258
0
  }
3259
3260
0
  get_oid_hex(patch->new_oid_prefix, &oid);
3261
0
  if (is_null_oid(&oid)) {
3262
0
    image_clear(img);
3263
0
    return 0; /* deletion patch */
3264
0
  }
3265
3266
0
  if (odb_has_object(the_repository->objects, &oid, 0)) {
3267
    /* We already have the postimage */
3268
0
    enum object_type type;
3269
0
    unsigned long size;
3270
0
    char *result;
3271
3272
0
    result = odb_read_object(the_repository->objects, &oid,
3273
0
           &type, &size);
3274
0
    if (!result)
3275
0
      return error(_("the necessary postimage %s for "
3276
0
               "'%s' cannot be read"),
3277
0
             patch->new_oid_prefix, name);
3278
0
    image_clear(img);
3279
0
    strbuf_attach(&img->buf, result, size, size + 1);
3280
0
  } else {
3281
    /*
3282
     * We have verified buf matches the preimage;
3283
     * apply the patch data to it, which is stored
3284
     * in the patch->fragments->{patch,size}.
3285
     */
3286
0
    if (apply_binary_fragment(state, img, patch))
3287
0
      return error(_("binary patch does not apply to '%s'"),
3288
0
             name);
3289
3290
    /* verify that the result matches */
3291
0
    hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, OBJ_BLOB,
3292
0
         &oid);
3293
0
    if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3294
0
      return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3295
0
        name, patch->new_oid_prefix, oid_to_hex(&oid));
3296
0
  }
3297
3298
0
  return 0;
3299
0
}
3300
3301
static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3302
0
{
3303
0
  struct fragment *frag = patch->fragments;
3304
0
  const char *name = patch->old_name ? patch->old_name : patch->new_name;
3305
0
  unsigned ws_rule = patch->ws_rule;
3306
0
  unsigned inaccurate_eof = patch->inaccurate_eof;
3307
0
  int nth = 0;
3308
3309
0
  if (patch->is_binary)
3310
0
    return apply_binary(state, img, patch);
3311
3312
0
  while (frag) {
3313
0
    nth++;
3314
0
    if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3315
0
      error(_("patch failed: %s:%ld"), name, frag->oldpos);
3316
0
      if (!state->apply_with_reject)
3317
0
        return -1;
3318
0
      frag->rejected = 1;
3319
0
    }
3320
0
    frag = frag->next;
3321
0
  }
3322
0
  return 0;
3323
0
}
3324
3325
static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3326
0
{
3327
0
  if (S_ISGITLINK(mode)) {
3328
0
    strbuf_grow(buf, 100);
3329
0
    strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3330
0
  } else {
3331
0
    enum object_type type;
3332
0
    unsigned long sz;
3333
0
    char *result;
3334
3335
0
    result = odb_read_object(the_repository->objects, oid,
3336
0
           &type, &sz);
3337
0
    if (!result)
3338
0
      return -1;
3339
    /* XXX read_sha1_file NUL-terminates */
3340
0
    strbuf_attach(buf, result, sz, sz + 1);
3341
0
  }
3342
0
  return 0;
3343
0
}
3344
3345
static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3346
0
{
3347
0
  if (!ce)
3348
0
    return 0;
3349
0
  return read_blob_object(buf, &ce->oid, ce->ce_mode);
3350
0
}
3351
3352
static struct patch *in_fn_table(struct apply_state *state, const char *name)
3353
0
{
3354
0
  struct string_list_item *item;
3355
3356
0
  if (!name)
3357
0
    return NULL;
3358
3359
0
  item = string_list_lookup(&state->fn_table, name);
3360
0
  if (item)
3361
0
    return (struct patch *)item->util;
3362
3363
0
  return NULL;
3364
0
}
3365
3366
/*
3367
 * item->util in the filename table records the status of the path.
3368
 * Usually it points at a patch (whose result records the contents
3369
 * of it after applying it), but it could be PATH_WAS_DELETED for a
3370
 * path that a previously applied patch has already removed, or
3371
 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3372
 *
3373
 * The latter is needed to deal with a case where two paths A and B
3374
 * are swapped by first renaming A to B and then renaming B to A;
3375
 * moving A to B should not be prevented due to presence of B as we
3376
 * will remove it in a later patch.
3377
 */
3378
0
#define PATH_TO_BE_DELETED ((struct patch *) -2)
3379
0
#define PATH_WAS_DELETED ((struct patch *) -1)
3380
3381
static int to_be_deleted(struct patch *patch)
3382
0
{
3383
0
  return patch == PATH_TO_BE_DELETED;
3384
0
}
3385
3386
static int was_deleted(struct patch *patch)
3387
0
{
3388
0
  return patch == PATH_WAS_DELETED;
3389
0
}
3390
3391
static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3392
0
{
3393
0
  struct string_list_item *item;
3394
3395
  /*
3396
   * Always add new_name unless patch is a deletion
3397
   * This should cover the cases for normal diffs,
3398
   * file creations and copies
3399
   */
3400
0
  if (patch->new_name) {
3401
0
    item = string_list_insert(&state->fn_table, patch->new_name);
3402
0
    item->util = patch;
3403
0
  }
3404
3405
  /*
3406
   * store a failure on rename/deletion cases because
3407
   * later chunks shouldn't patch old names
3408
   */
3409
0
  if ((patch->new_name == NULL) || (patch->is_rename)) {
3410
0
    item = string_list_insert(&state->fn_table, patch->old_name);
3411
0
    item->util = PATH_WAS_DELETED;
3412
0
  }
3413
0
}
3414
3415
static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3416
0
{
3417
  /*
3418
   * store information about incoming file deletion
3419
   */
3420
0
  while (patch) {
3421
0
    if ((patch->new_name == NULL) || (patch->is_rename)) {
3422
0
      struct string_list_item *item;
3423
0
      item = string_list_insert(&state->fn_table, patch->old_name);
3424
0
      item->util = PATH_TO_BE_DELETED;
3425
0
    }
3426
0
    patch = patch->next;
3427
0
  }
3428
0
}
3429
3430
static int checkout_target(struct index_state *istate,
3431
         struct cache_entry *ce, struct stat *st)
3432
0
{
3433
0
  struct checkout costate = CHECKOUT_INIT;
3434
3435
0
  costate.refresh_cache = 1;
3436
0
  costate.istate = istate;
3437
0
  if (checkout_entry(ce, &costate, NULL, NULL) ||
3438
0
      lstat(ce->name, st))
3439
0
    return error(_("cannot checkout %s"), ce->name);
3440
0
  return 0;
3441
0
}
3442
3443
static struct patch *previous_patch(struct apply_state *state,
3444
            struct patch *patch,
3445
            int *gone)
3446
0
{
3447
0
  struct patch *previous;
3448
3449
0
  *gone = 0;
3450
0
  if (patch->is_copy || patch->is_rename)
3451
0
    return NULL; /* "git" patches do not depend on the order */
3452
3453
0
  previous = in_fn_table(state, patch->old_name);
3454
0
  if (!previous)
3455
0
    return NULL;
3456
3457
0
  if (to_be_deleted(previous))
3458
0
    return NULL; /* the deletion hasn't happened yet */
3459
3460
0
  if (was_deleted(previous))
3461
0
    *gone = 1;
3462
3463
0
  return previous;
3464
0
}
3465
3466
static int verify_index_match(struct apply_state *state,
3467
            const struct cache_entry *ce,
3468
            struct stat *st)
3469
0
{
3470
0
  if (S_ISGITLINK(ce->ce_mode)) {
3471
0
    if (!S_ISDIR(st->st_mode))
3472
0
      return -1;
3473
0
    return 0;
3474
0
  }
3475
0
  return ie_match_stat(state->repo->index, ce, st,
3476
0
           CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3477
0
}
3478
3479
0
#define SUBMODULE_PATCH_WITHOUT_INDEX 1
3480
3481
static int load_patch_target(struct apply_state *state,
3482
           struct strbuf *buf,
3483
           const struct cache_entry *ce,
3484
           struct stat *st,
3485
           struct patch *patch,
3486
           const char *name,
3487
           unsigned expected_mode)
3488
0
{
3489
0
  if (state->cached || state->check_index) {
3490
0
    if (read_file_or_gitlink(ce, buf))
3491
0
      return error(_("failed to read %s"), name);
3492
0
  } else if (name) {
3493
0
    if (S_ISGITLINK(expected_mode)) {
3494
0
      if (ce)
3495
0
        return read_file_or_gitlink(ce, buf);
3496
0
      else
3497
0
        return SUBMODULE_PATCH_WITHOUT_INDEX;
3498
0
    } else if (has_symlink_leading_path(name, strlen(name))) {
3499
0
      return error(_("reading from '%s' beyond a symbolic link"), name);
3500
0
    } else {
3501
0
      if (read_old_data(st, patch, name, buf))
3502
0
        return error(_("failed to read %s"), name);
3503
0
    }
3504
0
  }
3505
0
  return 0;
3506
0
}
3507
3508
/*
3509
 * We are about to apply "patch"; populate the "image" with the
3510
 * current version we have, from the working tree or from the index,
3511
 * depending on the situation e.g. --cached/--index.  If we are
3512
 * applying a non-git patch that incrementally updates the tree,
3513
 * we read from the result of a previous diff.
3514
 */
3515
static int load_preimage(struct apply_state *state,
3516
       struct image *image,
3517
       struct patch *patch, struct stat *st,
3518
       const struct cache_entry *ce)
3519
0
{
3520
0
  struct strbuf buf = STRBUF_INIT;
3521
0
  size_t len;
3522
0
  char *img;
3523
0
  struct patch *previous;
3524
0
  int status;
3525
3526
0
  previous = previous_patch(state, patch, &status);
3527
0
  if (status)
3528
0
    return error(_("path %s has been renamed/deleted"),
3529
0
           patch->old_name);
3530
0
  if (previous) {
3531
    /* We have a patched copy in memory; use that. */
3532
0
    strbuf_add(&buf, previous->result, previous->resultsize);
3533
0
  } else {
3534
0
    status = load_patch_target(state, &buf, ce, st, patch,
3535
0
             patch->old_name, patch->old_mode);
3536
0
    if (status < 0)
3537
0
      return status;
3538
0
    else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3539
      /*
3540
       * There is no way to apply subproject
3541
       * patch without looking at the index.
3542
       * NEEDSWORK: shouldn't this be flagged
3543
       * as an error???
3544
       */
3545
0
      free_fragment_list(patch->fragments);
3546
0
      patch->fragments = NULL;
3547
0
    } else if (status) {
3548
0
      return error(_("failed to read %s"), patch->old_name);
3549
0
    }
3550
0
  }
3551
3552
0
  img = strbuf_detach(&buf, &len);
3553
0
  image_prepare(image, img, len, !patch->is_binary);
3554
0
  return 0;
3555
0
}
3556
3557
static int resolve_to(struct image *image, const struct object_id *result_id)
3558
0
{
3559
0
  unsigned long size;
3560
0
  enum object_type type;
3561
0
  char *data;
3562
3563
0
  image_clear(image);
3564
3565
0
  data = odb_read_object(the_repository->objects, result_id, &type, &size);
3566
0
  if (!data || type != OBJ_BLOB)
3567
0
    die("unable to read blob object %s", oid_to_hex(result_id));
3568
0
  strbuf_attach(&image->buf, data, size, size + 1);
3569
3570
0
  return 0;
3571
0
}
3572
3573
static int three_way_merge(struct apply_state *state,
3574
         struct image *image,
3575
         char *path,
3576
         const struct object_id *base,
3577
         const struct object_id *ours,
3578
         const struct object_id *theirs)
3579
0
{
3580
0
  mmfile_t base_file, our_file, their_file;
3581
0
  struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT;
3582
0
  mmbuffer_t result = { NULL };
3583
0
  enum ll_merge_result status;
3584
3585
  /* resolve trivial cases first */
3586
0
  if (oideq(base, ours))
3587
0
    return resolve_to(image, theirs);
3588
0
  else if (oideq(base, theirs) || oideq(ours, theirs))
3589
0
    return resolve_to(image, ours);
3590
3591
0
  read_mmblob(&base_file, the_repository->objects, base);
3592
0
  read_mmblob(&our_file, the_repository->objects, ours);
3593
0
  read_mmblob(&their_file, the_repository->objects, theirs);
3594
0
  merge_opts.variant = state->merge_variant;
3595
0
  status = ll_merge(&result, path,
3596
0
        &base_file, "base",
3597
0
        &our_file, "ours",
3598
0
        &their_file, "theirs",
3599
0
        state->repo->index,
3600
0
        &merge_opts);
3601
0
  if (status == LL_MERGE_BINARY_CONFLICT)
3602
0
    warning("Cannot merge binary files: %s (%s vs. %s)",
3603
0
      path, "ours", "theirs");
3604
0
  free(base_file.ptr);
3605
0
  free(our_file.ptr);
3606
0
  free(their_file.ptr);
3607
0
  if (status < 0 || !result.ptr) {
3608
0
    free(result.ptr);
3609
0
    return -1;
3610
0
  }
3611
0
  image_clear(image);
3612
0
  strbuf_attach(&image->buf, result.ptr, result.size, result.size);
3613
3614
0
  return status;
3615
0
}
3616
3617
/*
3618
 * When directly falling back to add/add three-way merge, we read from
3619
 * the current contents of the new_name.  In no cases other than that
3620
 * this function will be called.
3621
 */
3622
static int load_current(struct apply_state *state,
3623
      struct image *image,
3624
      struct patch *patch)
3625
0
{
3626
0
  struct strbuf buf = STRBUF_INIT;
3627
0
  int status, pos;
3628
0
  size_t len;
3629
0
  char *img;
3630
0
  struct stat st;
3631
0
  struct cache_entry *ce;
3632
0
  char *name = patch->new_name;
3633
0
  unsigned mode = patch->new_mode;
3634
3635
0
  if (!patch->is_new)
3636
0
    BUG("patch to %s is not a creation", patch->old_name);
3637
3638
0
  pos = index_name_pos(state->repo->index, name, strlen(name));
3639
0
  if (pos < 0)
3640
0
    return error(_("%s: does not exist in index"), name);
3641
0
  ce = state->repo->index->cache[pos];
3642
0
  if (lstat(name, &st)) {
3643
0
    if (errno != ENOENT)
3644
0
      return error_errno("%s", name);
3645
0
    if (checkout_target(state->repo->index, ce, &st))
3646
0
      return -1;
3647
0
  }
3648
0
  if (verify_index_match(state, ce, &st))
3649
0
    return error(_("%s: does not match index"), name);
3650
3651
0
  status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3652
0
  if (status < 0)
3653
0
    return status;
3654
0
  else if (status)
3655
0
    return -1;
3656
0
  img = strbuf_detach(&buf, &len);
3657
0
  image_prepare(image, img, len, !patch->is_binary);
3658
0
  return 0;
3659
0
}
3660
3661
static int try_threeway(struct apply_state *state,
3662
      struct image *image,
3663
      struct patch *patch,
3664
      struct stat *st,
3665
      const struct cache_entry *ce)
3666
0
{
3667
0
  struct object_id pre_oid, post_oid, our_oid;
3668
0
  struct strbuf buf = STRBUF_INIT;
3669
0
  size_t len;
3670
0
  int status;
3671
0
  char *img;
3672
0
  struct image tmp_image = IMAGE_INIT;
3673
3674
  /* No point falling back to 3-way merge in these cases */
3675
0
  if (patch->is_delete ||
3676
0
      S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3677
0
      (patch->is_new && !patch->direct_to_threeway) ||
3678
0
      (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3679
0
    return -1;
3680
3681
  /* Preimage the patch was prepared for */
3682
0
  if (patch->is_new)
3683
0
    odb_write_object(the_repository->objects, "", 0, OBJ_BLOB, &pre_oid);
3684
0
  else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3685
0
     read_blob_object(&buf, &pre_oid, patch->old_mode))
3686
0
    return error(_("repository lacks the necessary blob to perform 3-way merge."));
3687
3688
0
  if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3689
0
    fprintf(stderr, _("Performing three-way merge...\n"));
3690
3691
0
  img = strbuf_detach(&buf, &len);
3692
0
  image_prepare(&tmp_image, img, len, 1);
3693
  /* Apply the patch to get the post image */
3694
0
  if (apply_fragments(state, &tmp_image, patch) < 0) {
3695
0
    image_clear(&tmp_image);
3696
0
    return -1;
3697
0
  }
3698
  /* post_oid is theirs */
3699
0
  odb_write_object(the_repository->objects, tmp_image.buf.buf,
3700
0
       tmp_image.buf.len, OBJ_BLOB, &post_oid);
3701
0
  image_clear(&tmp_image);
3702
3703
  /* our_oid is ours */
3704
0
  if (patch->is_new) {
3705
0
    if (load_current(state, &tmp_image, patch))
3706
0
      return error(_("cannot read the current contents of '%s'"),
3707
0
             patch->new_name);
3708
0
  } else {
3709
0
    if (load_preimage(state, &tmp_image, patch, st, ce))
3710
0
      return error(_("cannot read the current contents of '%s'"),
3711
0
             patch->old_name);
3712
0
  }
3713
0
  odb_write_object(the_repository->objects, tmp_image.buf.buf,
3714
0
       tmp_image.buf.len, OBJ_BLOB, &our_oid);
3715
0
  image_clear(&tmp_image);
3716
3717
  /* in-core three-way merge between post and our using pre as base */
3718
0
  status = three_way_merge(state, image, patch->new_name,
3719
0
         &pre_oid, &our_oid, &post_oid);
3720
0
  if (status < 0) {
3721
0
    if (state->apply_verbosity > verbosity_silent)
3722
0
      fprintf(stderr,
3723
0
        _("Failed to perform three-way merge...\n"));
3724
0
    return status;
3725
0
  }
3726
3727
0
  if (status) {
3728
0
    patch->conflicted_threeway = 1;
3729
0
    if (patch->is_new)
3730
0
      oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3731
0
    else
3732
0
      oidcpy(&patch->threeway_stage[0], &pre_oid);
3733
0
    oidcpy(&patch->threeway_stage[1], &our_oid);
3734
0
    oidcpy(&patch->threeway_stage[2], &post_oid);
3735
0
    if (state->apply_verbosity > verbosity_silent)
3736
0
      fprintf(stderr,
3737
0
        _("Applied patch to '%s' with conflicts.\n"),
3738
0
        patch->new_name);
3739
0
  } else {
3740
0
    if (state->apply_verbosity > verbosity_silent)
3741
0
      fprintf(stderr,
3742
0
        _("Applied patch to '%s' cleanly.\n"),
3743
0
        patch->new_name);
3744
0
  }
3745
0
  return 0;
3746
0
}
3747
3748
static int apply_data(struct apply_state *state, struct patch *patch,
3749
          struct stat *st, const struct cache_entry *ce)
3750
0
{
3751
0
  struct image image = IMAGE_INIT;
3752
3753
0
  if (load_preimage(state, &image, patch, st, ce) < 0)
3754
0
    return -1;
3755
3756
0
  if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3757
0
    if (state->apply_verbosity > verbosity_silent &&
3758
0
        state->threeway && !patch->direct_to_threeway)
3759
0
      fprintf(stderr, _("Falling back to direct application...\n"));
3760
3761
    /* Note: with --reject, apply_fragments() returns 0 */
3762
0
    if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3763
0
      image_clear(&image);
3764
0
      return -1;
3765
0
    }
3766
0
  }
3767
0
  patch->result = strbuf_detach(&image.buf, &patch->resultsize);
3768
0
  add_to_fn_table(state, patch);
3769
0
  free(image.line);
3770
3771
0
  if (0 < patch->is_delete && patch->resultsize)
3772
0
    return error(_("removal patch leaves file contents"));
3773
3774
0
  return 0;
3775
0
}
3776
3777
/*
3778
 * If "patch" that we are looking at modifies or deletes what we have,
3779
 * we would want it not to lose any local modification we have, either
3780
 * in the working tree or in the index.
3781
 *
3782
 * This also decides if a non-git patch is a creation patch or a
3783
 * modification to an existing empty file.  We do not check the state
3784
 * of the current tree for a creation patch in this function; the caller
3785
 * check_patch() separately makes sure (and errors out otherwise) that
3786
 * the path the patch creates does not exist in the current tree.
3787
 */
3788
static int check_preimage(struct apply_state *state,
3789
        struct patch *patch,
3790
        struct cache_entry **ce,
3791
        struct stat *st)
3792
0
{
3793
0
  const char *old_name = patch->old_name;
3794
0
  struct patch *previous = NULL;
3795
0
  int stat_ret = 0, status;
3796
0
  unsigned st_mode = 0;
3797
3798
0
  if (!old_name)
3799
0
    return 0;
3800
3801
0
  assert(patch->is_new <= 0);
3802
0
  previous = previous_patch(state, patch, &status);
3803
3804
0
  if (status)
3805
0
    return error(_("path %s has been renamed/deleted"), old_name);
3806
0
  if (previous) {
3807
0
    st_mode = previous->new_mode;
3808
0
  } else if (!state->cached) {
3809
0
    stat_ret = lstat(old_name, st);
3810
0
    if (stat_ret && errno != ENOENT)
3811
0
      return error_errno("%s", old_name);
3812
0
  }
3813
3814
0
  if (state->check_index && !previous) {
3815
0
    int pos = index_name_pos(state->repo->index, old_name,
3816
0
           strlen(old_name));
3817
0
    if (pos < 0) {
3818
0
      if (patch->is_new < 0)
3819
0
        goto is_new;
3820
0
      return error(_("%s: does not exist in index"), old_name);
3821
0
    }
3822
0
    *ce = state->repo->index->cache[pos];
3823
0
    if (stat_ret < 0) {
3824
0
      if (checkout_target(state->repo->index, *ce, st))
3825
0
        return -1;
3826
0
    }
3827
0
    if (!state->cached && verify_index_match(state, *ce, st))
3828
0
      return error(_("%s: does not match index"), old_name);
3829
0
    if (state->cached)
3830
0
      st_mode = (*ce)->ce_mode;
3831
0
  } else if (stat_ret < 0) {
3832
0
    if (patch->is_new < 0)
3833
0
      goto is_new;
3834
0
    return error_errno("%s", old_name);
3835
0
  }
3836
3837
0
  if (!state->cached && !previous) {
3838
0
    if (*ce && !(*ce)->ce_mode)
3839
0
      BUG("ce_mode == 0 for path '%s'", old_name);
3840
3841
0
    if (trust_executable_bit || !S_ISREG(st->st_mode))
3842
0
      st_mode = ce_mode_from_stat(*ce, st->st_mode);
3843
0
    else if (*ce)
3844
0
      st_mode = (*ce)->ce_mode;
3845
0
    else
3846
0
      st_mode = patch->old_mode;
3847
0
  }
3848
3849
0
  if (patch->is_new < 0)
3850
0
    patch->is_new = 0;
3851
0
  if (!patch->old_mode)
3852
0
    patch->old_mode = st_mode;
3853
0
  if ((st_mode ^ patch->old_mode) & S_IFMT)
3854
0
    return error(_("%s: wrong type"), old_name);
3855
0
  if (st_mode != patch->old_mode)
3856
0
    warning(_("%s has type %o, expected %o"),
3857
0
      old_name, st_mode, patch->old_mode);
3858
0
  if (!patch->new_mode && !patch->is_delete)
3859
0
    patch->new_mode = st_mode;
3860
0
  return 0;
3861
3862
0
 is_new:
3863
0
  patch->is_new = 1;
3864
0
  patch->is_delete = 0;
3865
0
  FREE_AND_NULL(patch->old_name);
3866
0
  return 0;
3867
0
}
3868
3869
3870
0
#define EXISTS_IN_INDEX 1
3871
0
#define EXISTS_IN_WORKTREE 2
3872
0
#define EXISTS_IN_INDEX_AS_ITA 3
3873
3874
static int check_to_create(struct apply_state *state,
3875
         const char *new_name,
3876
         int ok_if_exists)
3877
0
{
3878
0
  struct stat nst;
3879
3880
0
  if (state->check_index && (!ok_if_exists || !state->cached)) {
3881
0
    int pos;
3882
3883
0
    pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3884
0
    if (pos >= 0) {
3885
0
      struct cache_entry *ce = state->repo->index->cache[pos];
3886
3887
      /* allow ITA, as they do not yet exist in the index */
3888
0
      if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3889
0
        return EXISTS_IN_INDEX;
3890
3891
      /* ITA entries can never match working tree files */
3892
0
      if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3893
0
        return EXISTS_IN_INDEX_AS_ITA;
3894
0
    }
3895
0
  }
3896
3897
0
  if (state->cached)
3898
0
    return 0;
3899
3900
0
  if (!lstat(new_name, &nst)) {
3901
0
    if (S_ISDIR(nst.st_mode) || ok_if_exists)
3902
0
      return 0;
3903
    /*
3904
     * A leading component of new_name might be a symlink
3905
     * that is going to be removed with this patch, but
3906
     * still pointing at somewhere that has the path.
3907
     * In such a case, path "new_name" does not exist as
3908
     * far as git is concerned.
3909
     */
3910
0
    if (has_symlink_leading_path(new_name, strlen(new_name)))
3911
0
      return 0;
3912
3913
0
    return EXISTS_IN_WORKTREE;
3914
0
  } else if (!is_missing_file_error(errno)) {
3915
0
    return error_errno("%s", new_name);
3916
0
  }
3917
0
  return 0;
3918
0
}
3919
3920
static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3921
0
{
3922
0
  for ( ; patch; patch = patch->next) {
3923
0
    if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3924
0
        (patch->is_rename || patch->is_delete))
3925
      /* the symlink at patch->old_name is removed */
3926
0
      strset_add(&state->removed_symlinks, patch->old_name);
3927
3928
0
    if (patch->new_name && S_ISLNK(patch->new_mode))
3929
      /* the symlink at patch->new_name is created or remains */
3930
0
      strset_add(&state->kept_symlinks, patch->new_name);
3931
0
  }
3932
0
}
3933
3934
static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3935
0
{
3936
0
  do {
3937
0
    while (--name->len && name->buf[name->len] != '/')
3938
0
      ; /* scan backwards */
3939
0
    if (!name->len)
3940
0
      break;
3941
0
    name->buf[name->len] = '\0';
3942
0
    if (strset_contains(&state->kept_symlinks, name->buf))
3943
0
      return 1;
3944
0
    if (strset_contains(&state->removed_symlinks, name->buf))
3945
      /*
3946
       * This cannot be "return 0", because we may
3947
       * see a new one created at a higher level.
3948
       */
3949
0
      continue;
3950
3951
    /* otherwise, check the preimage */
3952
0
    if (state->check_index) {
3953
0
      struct cache_entry *ce;
3954
3955
0
      ce = index_file_exists(state->repo->index, name->buf,
3956
0
                 name->len, ignore_case);
3957
0
      if (ce && S_ISLNK(ce->ce_mode))
3958
0
        return 1;
3959
0
    } else {
3960
0
      struct stat st;
3961
0
      if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3962
0
        return 1;
3963
0
    }
3964
0
  } while (1);
3965
0
  return 0;
3966
0
}
3967
3968
static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3969
0
{
3970
0
  int ret;
3971
0
  struct strbuf name = STRBUF_INIT;
3972
3973
0
  assert(*name_ != '\0');
3974
0
  strbuf_addstr(&name, name_);
3975
0
  ret = path_is_beyond_symlink_1(state, &name);
3976
0
  strbuf_release(&name);
3977
3978
0
  return ret;
3979
0
}
3980
3981
static int check_unsafe_path(struct patch *patch)
3982
0
{
3983
0
  const char *old_name = NULL;
3984
0
  const char *new_name = NULL;
3985
0
  if (patch->is_delete)
3986
0
    old_name = patch->old_name;
3987
0
  else if (!patch->is_new && !patch->is_copy)
3988
0
    old_name = patch->old_name;
3989
0
  if (!patch->is_delete)
3990
0
    new_name = patch->new_name;
3991
3992
0
  if (old_name && !verify_path(old_name, patch->old_mode))
3993
0
    return error(_("invalid path '%s'"), old_name);
3994
0
  if (new_name && !verify_path(new_name, patch->new_mode))
3995
0
    return error(_("invalid path '%s'"), new_name);
3996
0
  return 0;
3997
0
}
3998
3999
/*
4000
 * Check and apply the patch in-core; leave the result in patch->result
4001
 * for the caller to write it out to the final destination.
4002
 */
4003
static int check_patch(struct apply_state *state, struct patch *patch)
4004
0
{
4005
0
  struct stat st;
4006
0
  const char *old_name = patch->old_name;
4007
0
  const char *new_name = patch->new_name;
4008
0
  const char *name = old_name ? old_name : new_name;
4009
0
  struct cache_entry *ce = NULL;
4010
0
  struct patch *tpatch;
4011
0
  int ok_if_exists;
4012
0
  int status;
4013
4014
0
  patch->rejected = 1; /* we will drop this after we succeed */
4015
4016
0
  status = check_preimage(state, patch, &ce, &st);
4017
0
  if (status)
4018
0
    return status;
4019
0
  old_name = patch->old_name;
4020
4021
  /*
4022
   * A type-change diff is always split into a patch to delete
4023
   * old, immediately followed by a patch to create new (see
4024
   * diff.c::run_diff()); in such a case it is Ok that the entry
4025
   * to be deleted by the previous patch is still in the working
4026
   * tree and in the index.
4027
   *
4028
   * A patch to swap-rename between A and B would first rename A
4029
   * to B and then rename B to A.  While applying the first one,
4030
   * the presence of B should not stop A from getting renamed to
4031
   * B; ask to_be_deleted() about the later rename.  Removal of
4032
   * B and rename from A to B is handled the same way by asking
4033
   * was_deleted().
4034
   */
4035
0
  if ((tpatch = in_fn_table(state, new_name)) &&
4036
0
      (was_deleted(tpatch) || to_be_deleted(tpatch)))
4037
0
    ok_if_exists = 1;
4038
0
  else
4039
0
    ok_if_exists = 0;
4040
4041
0
  if (new_name &&
4042
0
      ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
4043
0
    int err = check_to_create(state, new_name, ok_if_exists);
4044
4045
0
    if (err && state->threeway) {
4046
0
      patch->direct_to_threeway = 1;
4047
0
    } else switch (err) {
4048
0
    case 0:
4049
0
      break; /* happy */
4050
0
    case EXISTS_IN_INDEX:
4051
0
      return error(_("%s: already exists in index"), new_name);
4052
0
    case EXISTS_IN_INDEX_AS_ITA:
4053
0
      return error(_("%s: does not match index"), new_name);
4054
0
    case EXISTS_IN_WORKTREE:
4055
0
      return error(_("%s: already exists in working directory"),
4056
0
             new_name);
4057
0
    default:
4058
0
      return err;
4059
0
    }
4060
4061
0
    if (!patch->new_mode) {
4062
0
      if (0 < patch->is_new)
4063
0
        patch->new_mode = S_IFREG | 0644;
4064
0
      else
4065
0
        patch->new_mode = patch->old_mode;
4066
0
    }
4067
0
  }
4068
4069
0
  if (new_name && old_name) {
4070
0
    int same = !strcmp(old_name, new_name);
4071
0
    if (!patch->new_mode)
4072
0
      patch->new_mode = patch->old_mode;
4073
0
    if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4074
0
      if (same)
4075
0
        return error(_("new mode (%o) of %s does not "
4076
0
                 "match old mode (%o)"),
4077
0
          patch->new_mode, new_name,
4078
0
          patch->old_mode);
4079
0
      else
4080
0
        return error(_("new mode (%o) of %s does not "
4081
0
                 "match old mode (%o) of %s"),
4082
0
          patch->new_mode, new_name,
4083
0
          patch->old_mode, old_name);
4084
0
    }
4085
0
  }
4086
4087
0
  if (!state->unsafe_paths && check_unsafe_path(patch))
4088
0
    return -128;
4089
4090
  /*
4091
   * An attempt to read from or delete a path that is beyond a
4092
   * symbolic link will be prevented by load_patch_target() that
4093
   * is called at the beginning of apply_data() so we do not
4094
   * have to worry about a patch marked with "is_delete" bit
4095
   * here.  We however need to make sure that the patch result
4096
   * is not deposited to a path that is beyond a symbolic link
4097
   * here.
4098
   */
4099
0
  if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4100
0
    return error(_("affected file '%s' is beyond a symbolic link"),
4101
0
           patch->new_name);
4102
4103
0
  if (apply_data(state, patch, &st, ce) < 0)
4104
0
    return error(_("%s: patch does not apply"), name);
4105
0
  patch->rejected = 0;
4106
0
  return 0;
4107
0
}
4108
4109
static int check_patch_list(struct apply_state *state, struct patch *patch)
4110
0
{
4111
0
  int err = 0;
4112
4113
0
  prepare_symlink_changes(state, patch);
4114
0
  prepare_fn_table(state, patch);
4115
0
  while (patch) {
4116
0
    int res;
4117
0
    if (state->apply_verbosity > verbosity_normal)
4118
0
      say_patch_name(stderr,
4119
0
               _("Checking patch %s..."), patch);
4120
0
    res = check_patch(state, patch);
4121
0
    if (res == -128)
4122
0
      return -128;
4123
0
    err |= res;
4124
0
    patch = patch->next;
4125
0
  }
4126
0
  return err;
4127
0
}
4128
4129
static int read_apply_cache(struct apply_state *state)
4130
0
{
4131
0
  if (state->index_file)
4132
0
    return read_index_from(state->repo->index, state->index_file,
4133
0
               repo_get_git_dir(the_repository));
4134
0
  else
4135
0
    return repo_read_index(state->repo);
4136
0
}
4137
4138
/* This function tries to read the object name from the current index */
4139
static int get_current_oid(struct apply_state *state, const char *path,
4140
         struct object_id *oid)
4141
0
{
4142
0
  int pos;
4143
4144
0
  if (read_apply_cache(state) < 0)
4145
0
    return -1;
4146
0
  pos = index_name_pos(state->repo->index, path, strlen(path));
4147
0
  if (pos < 0)
4148
0
    return -1;
4149
0
  oidcpy(oid, &state->repo->index->cache[pos]->oid);
4150
0
  return 0;
4151
0
}
4152
4153
static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4154
0
{
4155
  /*
4156
   * A usable gitlink patch has only one fragment (hunk) that looks like:
4157
   * @@ -1 +1 @@
4158
   * -Subproject commit <old sha1>
4159
   * +Subproject commit <new sha1>
4160
   * or
4161
   * @@ -1 +0,0 @@
4162
   * -Subproject commit <old sha1>
4163
   * for a removal patch.
4164
   */
4165
0
  struct fragment *hunk = p->fragments;
4166
0
  static const char heading[] = "-Subproject commit ";
4167
0
  const char *preimage;
4168
4169
0
  if (/* does the patch have only one hunk? */
4170
0
      hunk && !hunk->next &&
4171
      /* is its preimage one line? */
4172
0
      hunk->oldpos == 1 && hunk->oldlines == 1 &&
4173
      /* does preimage begin with the heading? */
4174
0
      (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4175
0
      starts_with(++preimage, heading) &&
4176
      /* does it record full SHA-1? */
4177
0
      !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4178
0
      preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4179
      /* does the abbreviated name on the index line agree with it? */
4180
0
      starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4181
0
    return 0; /* it all looks fine */
4182
4183
  /* we may have full object name on the index line */
4184
0
  return get_oid_hex(p->old_oid_prefix, oid);
4185
0
}
4186
4187
/* Build an index that contains just the files needed for a 3way merge */
4188
static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4189
0
{
4190
0
  struct patch *patch;
4191
0
  struct index_state result = INDEX_STATE_INIT(state->repo);
4192
0
  struct lock_file lock = LOCK_INIT;
4193
0
  int res;
4194
4195
  /* Once we start supporting the reverse patch, it may be
4196
   * worth showing the new sha1 prefix, but until then...
4197
   */
4198
0
  for (patch = list; patch; patch = patch->next) {
4199
0
    struct object_id oid;
4200
0
    struct cache_entry *ce;
4201
0
    const char *name;
4202
4203
0
    name = patch->old_name ? patch->old_name : patch->new_name;
4204
0
    if (0 < patch->is_new)
4205
0
      continue;
4206
4207
0
    if (S_ISGITLINK(patch->old_mode)) {
4208
0
      if (!preimage_oid_in_gitlink_patch(patch, &oid))
4209
0
        ; /* ok, the textual part looks sane */
4210
0
      else
4211
0
        return error(_("sha1 information is lacking or "
4212
0
                 "useless for submodule %s"), name);
4213
0
    } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4214
0
      ; /* ok */
4215
0
    } else if (!patch->lines_added && !patch->lines_deleted) {
4216
      /* mode-only change: update the current */
4217
0
      if (get_current_oid(state, patch->old_name, &oid))
4218
0
        return error(_("mode change for %s, which is not "
4219
0
                 "in current HEAD"), name);
4220
0
    } else
4221
0
      return error(_("sha1 information is lacking or useless "
4222
0
               "(%s)."), name);
4223
4224
0
    ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4225
0
    if (!ce)
4226
0
      return error(_("make_cache_entry failed for path '%s'"),
4227
0
             name);
4228
0
    if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4229
0
      discard_cache_entry(ce);
4230
0
      return error(_("could not add %s to temporary index"),
4231
0
             name);
4232
0
    }
4233
0
  }
4234
4235
0
  hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4236
0
  res = write_locked_index(&result, &lock, COMMIT_LOCK);
4237
0
  discard_index(&result);
4238
4239
0
  if (res)
4240
0
    return error(_("could not write temporary index to %s"),
4241
0
           state->fake_ancestor);
4242
4243
0
  return 0;
4244
0
}
4245
4246
static void stat_patch_list(struct apply_state *state, struct patch *patch)
4247
0
{
4248
0
  int files, adds, dels;
4249
4250
0
  for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4251
0
    files++;
4252
0
    adds += patch->lines_added;
4253
0
    dels += patch->lines_deleted;
4254
0
    show_stats(state, patch);
4255
0
  }
4256
4257
0
  print_stat_summary(stdout, files, adds, dels);
4258
0
}
4259
4260
static void numstat_patch_list(struct apply_state *state,
4261
             struct patch *patch)
4262
0
{
4263
0
  for ( ; patch; patch = patch->next) {
4264
0
    const char *name;
4265
0
    name = patch->new_name ? patch->new_name : patch->old_name;
4266
0
    if (patch->is_binary)
4267
0
      printf("-\t-\t");
4268
0
    else
4269
0
      printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4270
0
    write_name_quoted(name, stdout, state->line_termination);
4271
0
  }
4272
0
}
4273
4274
static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4275
0
{
4276
0
  if (mode)
4277
0
    printf(" %s mode %06o %s\n", newdelete, mode, name);
4278
0
  else
4279
0
    printf(" %s %s\n", newdelete, name);
4280
0
}
4281
4282
static void show_mode_change(struct patch *p, int show_name)
4283
0
{
4284
0
  if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4285
0
    if (show_name)
4286
0
      printf(" mode change %06o => %06o %s\n",
4287
0
             p->old_mode, p->new_mode, p->new_name);
4288
0
    else
4289
0
      printf(" mode change %06o => %06o\n",
4290
0
             p->old_mode, p->new_mode);
4291
0
  }
4292
0
}
4293
4294
static void show_rename_copy(struct patch *p)
4295
0
{
4296
0
  const char *renamecopy = p->is_rename ? "rename" : "copy";
4297
0
  const char *old_name, *new_name;
4298
4299
  /* Find common prefix */
4300
0
  old_name = p->old_name;
4301
0
  new_name = p->new_name;
4302
0
  while (1) {
4303
0
    const char *slash_old, *slash_new;
4304
0
    slash_old = strchr(old_name, '/');
4305
0
    slash_new = strchr(new_name, '/');
4306
0
    if (!slash_old ||
4307
0
        !slash_new ||
4308
0
        slash_old - old_name != slash_new - new_name ||
4309
0
        memcmp(old_name, new_name, slash_new - new_name))
4310
0
      break;
4311
0
    old_name = slash_old + 1;
4312
0
    new_name = slash_new + 1;
4313
0
  }
4314
  /* p->old_name through old_name is the common prefix, and old_name and
4315
   * new_name through the end of names are renames
4316
   */
4317
0
  if (old_name != p->old_name)
4318
0
    printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4319
0
           (int)(old_name - p->old_name), p->old_name,
4320
0
           old_name, new_name, p->score);
4321
0
  else
4322
0
    printf(" %s %s => %s (%d%%)\n", renamecopy,
4323
0
           p->old_name, p->new_name, p->score);
4324
0
  show_mode_change(p, 0);
4325
0
}
4326
4327
static void summary_patch_list(struct patch *patch)
4328
0
{
4329
0
  struct patch *p;
4330
4331
0
  for (p = patch; p; p = p->next) {
4332
0
    if (p->is_new)
4333
0
      show_file_mode_name("create", p->new_mode, p->new_name);
4334
0
    else if (p->is_delete)
4335
0
      show_file_mode_name("delete", p->old_mode, p->old_name);
4336
0
    else {
4337
0
      if (p->is_rename || p->is_copy)
4338
0
        show_rename_copy(p);
4339
0
      else {
4340
0
        if (p->score) {
4341
0
          printf(" rewrite %s (%d%%)\n",
4342
0
                 p->new_name, p->score);
4343
0
          show_mode_change(p, 0);
4344
0
        }
4345
0
        else
4346
0
          show_mode_change(p, 1);
4347
0
      }
4348
0
    }
4349
0
  }
4350
0
}
4351
4352
static void patch_stats(struct apply_state *state, struct patch *patch)
4353
0
{
4354
0
  int lines = patch->lines_added + patch->lines_deleted;
4355
4356
0
  if (lines > state->max_change)
4357
0
    state->max_change = lines;
4358
0
  if (patch->old_name) {
4359
0
    int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4360
0
    if (!len)
4361
0
      len = strlen(patch->old_name);
4362
0
    if (len > state->max_len)
4363
0
      state->max_len = len;
4364
0
  }
4365
0
  if (patch->new_name) {
4366
0
    int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4367
0
    if (!len)
4368
0
      len = strlen(patch->new_name);
4369
0
    if (len > state->max_len)
4370
0
      state->max_len = len;
4371
0
  }
4372
0
}
4373
4374
static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4375
0
{
4376
0
  if (state->update_index && !state->ita_only) {
4377
0
    if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4378
0
      return error(_("unable to remove %s from index"), patch->old_name);
4379
0
  }
4380
0
  if (!state->cached) {
4381
0
    if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4382
0
      remove_path(patch->old_name);
4383
0
    }
4384
0
  }
4385
0
  return 0;
4386
0
}
4387
4388
static int add_index_file(struct apply_state *state,
4389
        const char *path,
4390
        unsigned mode,
4391
        void *buf,
4392
        unsigned long size)
4393
0
{
4394
0
  struct stat st;
4395
0
  struct cache_entry *ce;
4396
0
  int namelen = strlen(path);
4397
4398
0
  ce = make_empty_cache_entry(state->repo->index, namelen);
4399
0
  memcpy(ce->name, path, namelen);
4400
0
  ce->ce_mode = create_ce_mode(mode);
4401
0
  ce->ce_flags = create_ce_flags(0);
4402
0
  ce->ce_namelen = namelen;
4403
0
  if (state->ita_only) {
4404
0
    ce->ce_flags |= CE_INTENT_TO_ADD;
4405
0
    set_object_name_for_intent_to_add_entry(ce);
4406
0
  } else if (S_ISGITLINK(mode)) {
4407
0
    const char *s;
4408
4409
0
    if (!skip_prefix(buf, "Subproject commit ", &s) ||
4410
0
        get_oid_hex(s, &ce->oid)) {
4411
0
      discard_cache_entry(ce);
4412
0
      return error(_("corrupt patch for submodule %s"), path);
4413
0
    }
4414
0
  } else {
4415
0
    if (!state->cached) {
4416
0
      if (lstat(path, &st) < 0) {
4417
0
        discard_cache_entry(ce);
4418
0
        return error_errno(_("unable to stat newly "
4419
0
                 "created file '%s'"),
4420
0
               path);
4421
0
      }
4422
0
      fill_stat_cache_info(state->repo->index, ce, &st);
4423
0
    }
4424
0
    if (odb_write_object(the_repository->objects, buf, size,
4425
0
             OBJ_BLOB, &ce->oid) < 0) {
4426
0
      discard_cache_entry(ce);
4427
0
      return error(_("unable to create backing store "
4428
0
               "for newly created file %s"), path);
4429
0
    }
4430
0
  }
4431
0
  if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4432
0
    discard_cache_entry(ce);
4433
0
    return error(_("unable to add cache entry for %s"), path);
4434
0
  }
4435
4436
0
  return 0;
4437
0
}
4438
4439
/*
4440
 * Returns:
4441
 *  -1 if an unrecoverable error happened
4442
 *   0 if everything went well
4443
 *   1 if a recoverable error happened
4444
 */
4445
static int try_create_file(struct apply_state *state, const char *path,
4446
         unsigned int mode, const char *buf,
4447
         unsigned long size)
4448
0
{
4449
0
  int fd, res;
4450
0
  struct strbuf nbuf = STRBUF_INIT;
4451
4452
0
  if (S_ISGITLINK(mode)) {
4453
0
    struct stat st;
4454
0
    if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4455
0
      return 0;
4456
0
    return !!mkdir(path, 0777);
4457
0
  }
4458
4459
0
  if (has_symlinks && S_ISLNK(mode))
4460
    /* Although buf:size is counted string, it also is NUL
4461
     * terminated.
4462
     */
4463
0
    return !!symlink(buf, path);
4464
4465
0
  fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4466
0
  if (fd < 0)
4467
0
    return 1;
4468
4469
0
  if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4470
0
    size = nbuf.len;
4471
0
    buf  = nbuf.buf;
4472
0
  }
4473
4474
0
  res = write_in_full(fd, buf, size) < 0;
4475
0
  if (res)
4476
0
    error_errno(_("failed to write to '%s'"), path);
4477
0
  strbuf_release(&nbuf);
4478
4479
0
  if (close(fd) < 0 && !res)
4480
0
    return error_errno(_("closing file '%s'"), path);
4481
4482
0
  return res ? -1 : 0;
4483
0
}
4484
4485
/*
4486
 * We optimistically assume that the directories exist,
4487
 * which is true 99% of the time anyway. If they don't,
4488
 * we create them and try again.
4489
 *
4490
 * Returns:
4491
 *   -1 on error
4492
 *   0 otherwise
4493
 */
4494
static int create_one_file(struct apply_state *state,
4495
         char *path,
4496
         unsigned mode,
4497
         const char *buf,
4498
         unsigned long size)
4499
0
{
4500
0
  char *newpath = NULL;
4501
0
  int res;
4502
4503
0
  if (state->cached)
4504
0
    return 0;
4505
4506
  /*
4507
   * We already try to detect whether files are beyond a symlink in our
4508
   * up-front checks. But in the case where symlinks are created by any
4509
   * of the intermediate hunks it can happen that our up-front checks
4510
   * didn't yet see the symlink, but at the point of arriving here there
4511
   * in fact is one. We thus repeat the check for symlinks here.
4512
   *
4513
   * Note that this does not make the up-front check obsolete as the
4514
   * failure mode is different:
4515
   *
4516
   * - The up-front checks cause us to abort before we have written
4517
   *   anything into the working directory. So when we exit this way the
4518
   *   working directory remains clean.
4519
   *
4520
   * - The checks here happen in the middle of the action where we have
4521
   *   already started to apply the patch. The end result will be a dirty
4522
   *   working directory.
4523
   *
4524
   * Ideally, we should update the up-front checks to catch what would
4525
   * happen when we apply the patch before we damage the working tree.
4526
   * We have all the information necessary to do so.  But for now, as a
4527
   * part of embargoed security work, having this check would serve as a
4528
   * reasonable first step.
4529
   */
4530
0
  if (path_is_beyond_symlink(state, path))
4531
0
    return error(_("affected file '%s' is beyond a symbolic link"), path);
4532
4533
0
  res = try_create_file(state, path, mode, buf, size);
4534
0
  if (res < 0)
4535
0
    return -1;
4536
0
  if (!res)
4537
0
    return 0;
4538
4539
0
  if (errno == ENOENT) {
4540
0
    if (safe_create_leading_directories_no_share(path))
4541
0
      return 0;
4542
0
    res = try_create_file(state, path, mode, buf, size);
4543
0
    if (res < 0)
4544
0
      return -1;
4545
0
    if (!res)
4546
0
      return 0;
4547
0
  }
4548
4549
0
  if (errno == EEXIST || errno == EACCES) {
4550
    /* We may be trying to create a file where a directory
4551
     * used to be.
4552
     */
4553
0
    struct stat st;
4554
0
    if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4555
0
      errno = EEXIST;
4556
0
  }
4557
4558
0
  if (errno == EEXIST) {
4559
0
    unsigned int nr = getpid();
4560
4561
0
    for (;;) {
4562
0
      newpath = mkpathdup("%s~%u", path, nr);
4563
0
      res = try_create_file(state, newpath, mode, buf, size);
4564
0
      if (res < 0)
4565
0
        goto out;
4566
0
      if (!res) {
4567
0
        if (!rename(newpath, path))
4568
0
          goto out;
4569
0
        unlink_or_warn(newpath);
4570
0
        break;
4571
0
      }
4572
0
      if (errno != EEXIST)
4573
0
        break;
4574
0
      ++nr;
4575
0
      FREE_AND_NULL(newpath);
4576
0
    }
4577
0
  }
4578
0
  res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4579
0
out:
4580
0
  free(newpath);
4581
0
  return res;
4582
0
}
4583
4584
static int add_conflicted_stages_file(struct apply_state *state,
4585
               struct patch *patch)
4586
0
{
4587
0
  int stage, namelen;
4588
0
  unsigned mode;
4589
0
  struct cache_entry *ce;
4590
4591
0
  if (!state->update_index)
4592
0
    return 0;
4593
0
  namelen = strlen(patch->new_name);
4594
0
  mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4595
4596
0
  remove_file_from_index(state->repo->index, patch->new_name);
4597
0
  for (stage = 1; stage < 4; stage++) {
4598
0
    if (is_null_oid(&patch->threeway_stage[stage - 1]))
4599
0
      continue;
4600
0
    ce = make_empty_cache_entry(state->repo->index, namelen);
4601
0
    memcpy(ce->name, patch->new_name, namelen);
4602
0
    ce->ce_mode = create_ce_mode(mode);
4603
0
    ce->ce_flags = create_ce_flags(stage);
4604
0
    ce->ce_namelen = namelen;
4605
0
    oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4606
0
    if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4607
0
      discard_cache_entry(ce);
4608
0
      return error(_("unable to add cache entry for %s"),
4609
0
             patch->new_name);
4610
0
    }
4611
0
  }
4612
4613
0
  return 0;
4614
0
}
4615
4616
static int create_file(struct apply_state *state, struct patch *patch)
4617
0
{
4618
0
  char *path = patch->new_name;
4619
0
  unsigned mode = patch->new_mode;
4620
0
  unsigned long size = patch->resultsize;
4621
0
  char *buf = patch->result;
4622
4623
0
  if (!mode)
4624
0
    mode = S_IFREG | 0644;
4625
0
  if (create_one_file(state, path, mode, buf, size))
4626
0
    return -1;
4627
4628
0
  if (patch->conflicted_threeway)
4629
0
    return add_conflicted_stages_file(state, patch);
4630
0
  else if (state->check_index || (state->ita_only && patch->is_new > 0))
4631
0
    return add_index_file(state, path, mode, buf, size);
4632
0
  return 0;
4633
0
}
4634
4635
/* phase zero is to remove, phase one is to create */
4636
static int write_out_one_result(struct apply_state *state,
4637
        struct patch *patch,
4638
        int phase)
4639
0
{
4640
0
  if (patch->is_delete > 0) {
4641
0
    if (phase == 0)
4642
0
      return remove_file(state, patch, 1);
4643
0
    return 0;
4644
0
  }
4645
0
  if (patch->is_new > 0 || patch->is_copy) {
4646
0
    if (phase == 1)
4647
0
      return create_file(state, patch);
4648
0
    return 0;
4649
0
  }
4650
  /*
4651
   * Rename or modification boils down to the same
4652
   * thing: remove the old, write the new
4653
   */
4654
0
  if (phase == 0)
4655
0
    return remove_file(state, patch, patch->is_rename);
4656
0
  if (phase == 1)
4657
0
    return create_file(state, patch);
4658
0
  return 0;
4659
0
}
4660
4661
static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4662
0
{
4663
0
  FILE *rej;
4664
0
  char *namebuf;
4665
0
  struct fragment *frag;
4666
0
  int fd, cnt = 0;
4667
0
  struct strbuf sb = STRBUF_INIT;
4668
4669
0
  for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4670
0
    if (!frag->rejected)
4671
0
      continue;
4672
0
    cnt++;
4673
0
  }
4674
4675
0
  if (!cnt) {
4676
0
    if (state->apply_verbosity > verbosity_normal)
4677
0
      say_patch_name(stderr,
4678
0
               _("Applied patch %s cleanly."), patch);
4679
0
    return 0;
4680
0
  }
4681
4682
  /* This should not happen, because a removal patch that leaves
4683
   * contents are marked "rejected" at the patch level.
4684
   */
4685
0
  if (!patch->new_name)
4686
0
    die(_("internal error"));
4687
4688
  /* Say this even without --verbose */
4689
0
  strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4690
0
          "Applying patch %%s with %d rejects...",
4691
0
          cnt),
4692
0
        cnt);
4693
0
  if (state->apply_verbosity > verbosity_silent)
4694
0
    say_patch_name(stderr, sb.buf, patch);
4695
0
  strbuf_release(&sb);
4696
4697
0
  namebuf = xstrfmt("%s.rej", patch->new_name);
4698
4699
0
  fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4700
0
  if (fd < 0) {
4701
0
    if (errno != EEXIST) {
4702
0
      error_errno(_("cannot open %s"), namebuf);
4703
0
      goto error;
4704
0
    }
4705
0
    if (unlink(namebuf)) {
4706
0
      error_errno(_("cannot unlink '%s'"), namebuf);
4707
0
      goto error;
4708
0
    }
4709
0
    fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4710
0
    if (fd < 0) {
4711
0
      error_errno(_("cannot open %s"), namebuf);
4712
0
      goto error;
4713
0
    }
4714
0
  }
4715
0
  rej = fdopen(fd, "w");
4716
0
  if (!rej) {
4717
0
    error_errno(_("cannot open %s"), namebuf);
4718
0
    close(fd);
4719
0
    goto error;
4720
0
  }
4721
4722
  /* Normal git tools never deal with .rej, so do not pretend
4723
   * this is a git patch by saying --git or giving extended
4724
   * headers.  While at it, maybe please "kompare" that wants
4725
   * the trailing TAB and some garbage at the end of line ;-).
4726
   */
4727
0
  fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4728
0
    patch->new_name, patch->new_name);
4729
0
  for (cnt = 1, frag = patch->fragments;
4730
0
       frag;
4731
0
       cnt++, frag = frag->next) {
4732
0
    if (!frag->rejected) {
4733
0
      if (state->apply_verbosity > verbosity_silent)
4734
0
        fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4735
0
      continue;
4736
0
    }
4737
0
    if (state->apply_verbosity > verbosity_silent)
4738
0
      fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4739
0
    fprintf(rej, "%.*s", frag->size, frag->patch);
4740
0
    if (frag->patch[frag->size-1] != '\n')
4741
0
      fputc('\n', rej);
4742
0
  }
4743
0
  fclose(rej);
4744
0
error:
4745
0
  free(namebuf);
4746
0
  return -1;
4747
0
}
4748
4749
/*
4750
 * Returns:
4751
 *  -1 if an error happened
4752
 *   0 if the patch applied cleanly
4753
 *   1 if the patch did not apply cleanly
4754
 */
4755
static int write_out_results(struct apply_state *state, struct patch *list)
4756
0
{
4757
0
  int phase;
4758
0
  int errs = 0;
4759
0
  struct patch *l;
4760
0
  struct string_list cpath = STRING_LIST_INIT_DUP;
4761
4762
0
  for (phase = 0; phase < 2; phase++) {
4763
0
    l = list;
4764
0
    while (l) {
4765
0
      if (l->rejected)
4766
0
        errs = 1;
4767
0
      else {
4768
0
        if (write_out_one_result(state, l, phase)) {
4769
0
          string_list_clear(&cpath, 0);
4770
0
          return -1;
4771
0
        }
4772
0
        if (phase == 1) {
4773
0
          if (write_out_one_reject(state, l))
4774
0
            errs = 1;
4775
0
          if (l->conflicted_threeway) {
4776
0
            string_list_append(&cpath, l->new_name);
4777
0
            errs = 1;
4778
0
          }
4779
0
        }
4780
0
      }
4781
0
      l = l->next;
4782
0
    }
4783
0
  }
4784
4785
0
  if (cpath.nr) {
4786
0
    struct string_list_item *item;
4787
4788
0
    string_list_sort(&cpath);
4789
0
    if (state->apply_verbosity > verbosity_silent) {
4790
0
      for_each_string_list_item(item, &cpath)
4791
0
        fprintf(stderr, "U %s\n", item->string);
4792
0
    }
4793
0
    string_list_clear(&cpath, 0);
4794
4795
    /*
4796
     * rerere relies on the partially merged result being in the working
4797
     * tree with conflict markers, but that isn't written with --cached.
4798
     */
4799
0
    if (!state->cached)
4800
0
      repo_rerere(state->repo, 0);
4801
0
  }
4802
4803
0
  return errs;
4804
0
}
4805
4806
/*
4807
 * Try to apply a patch.
4808
 *
4809
 * Returns:
4810
 *  -128 if a bad error happened (like patch unreadable)
4811
 *  -1 if patch did not apply and user cannot deal with it
4812
 *   0 if the patch applied
4813
 *   1 if the patch did not apply but user might fix it
4814
 */
4815
static int apply_patch(struct apply_state *state,
4816
           int fd,
4817
           const char *filename,
4818
           int options)
4819
0
{
4820
0
  size_t offset;
4821
0
  struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4822
0
  struct patch *list = NULL, **listp = &list;
4823
0
  int skipped_patch = 0;
4824
0
  int res = 0;
4825
0
  int flush_attributes = 0;
4826
4827
0
  state->patch_input_file = filename;
4828
0
  if (read_patch_file(&buf, fd) < 0)
4829
0
    return -128;
4830
0
  offset = 0;
4831
0
  while (offset < buf.len) {
4832
0
    struct patch *patch;
4833
0
    int nr;
4834
4835
0
    CALLOC_ARRAY(patch, 1);
4836
0
    patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4837
0
    patch->recount =  !!(options & APPLY_OPT_RECOUNT);
4838
0
    nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4839
0
    if (nr < 0) {
4840
0
      free_patch(patch);
4841
0
      if (nr == -128) {
4842
0
        res = -128;
4843
0
        goto end;
4844
0
      }
4845
0
      break;
4846
0
    }
4847
0
    if (state->apply_in_reverse)
4848
0
      reverse_patches(patch);
4849
0
    if (use_patch(state, patch)) {
4850
0
      patch_stats(state, patch);
4851
0
      if (!list || !state->apply_in_reverse) {
4852
0
        *listp = patch;
4853
0
        listp = &patch->next;
4854
0
      } else {
4855
0
        patch->next = list;
4856
0
        list = patch;
4857
0
      }
4858
4859
0
      if ((patch->new_name &&
4860
0
           ends_with_path_components(patch->new_name,
4861
0
                   GITATTRIBUTES_FILE)) ||
4862
0
          (patch->old_name &&
4863
0
           ends_with_path_components(patch->old_name,
4864
0
                   GITATTRIBUTES_FILE)))
4865
0
        flush_attributes = 1;
4866
0
    }
4867
0
    else {
4868
0
      if (state->apply_verbosity > verbosity_normal)
4869
0
        say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4870
0
      free_patch(patch);
4871
0
      skipped_patch++;
4872
0
    }
4873
0
    offset += nr;
4874
0
  }
4875
4876
0
  if (!list && !skipped_patch) {
4877
0
    if (!state->allow_empty) {
4878
0
      error(_("No valid patches in input (allow with \"--allow-empty\")"));
4879
0
      res = -128;
4880
0
    }
4881
0
    goto end;
4882
0
  }
4883
4884
0
  if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4885
0
    state->apply = 0;
4886
4887
0
  state->update_index = (state->check_index || state->ita_only) && state->apply;
4888
0
  if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4889
0
    if (state->index_file)
4890
0
      hold_lock_file_for_update(&state->lock_file,
4891
0
              state->index_file,
4892
0
              LOCK_DIE_ON_ERROR);
4893
0
    else
4894
0
      repo_hold_locked_index(state->repo, &state->lock_file,
4895
0
                 LOCK_DIE_ON_ERROR);
4896
0
  }
4897
4898
0
  if ((state->check_index || state->update_index) && read_apply_cache(state) < 0) {
4899
0
    error(_("unable to read index file"));
4900
0
    res = -128;
4901
0
    goto end;
4902
0
  }
4903
4904
0
  if (state->check || state->apply) {
4905
0
    int r = check_patch_list(state, list);
4906
0
    if (r == -128) {
4907
0
      res = -128;
4908
0
      goto end;
4909
0
    }
4910
0
    if (r < 0 && !state->apply_with_reject) {
4911
0
      res = -1;
4912
0
      goto end;
4913
0
    }
4914
0
  }
4915
4916
0
  if (state->apply) {
4917
0
    int write_res = write_out_results(state, list);
4918
0
    if (write_res < 0) {
4919
0
      res = -128;
4920
0
      goto end;
4921
0
    }
4922
0
    if (write_res > 0) {
4923
      /* with --3way, we still need to write the index out */
4924
0
      res = state->apply_with_reject ? -1 : 1;
4925
0
      goto end;
4926
0
    }
4927
0
  }
4928
4929
0
  if (state->fake_ancestor &&
4930
0
      build_fake_ancestor(state, list)) {
4931
0
    res = -128;
4932
0
    goto end;
4933
0
  }
4934
4935
0
  if (state->diffstat && state->apply_verbosity > verbosity_silent)
4936
0
    stat_patch_list(state, list);
4937
4938
0
  if (state->numstat && state->apply_verbosity > verbosity_silent)
4939
0
    numstat_patch_list(state, list);
4940
4941
0
  if (state->summary && state->apply_verbosity > verbosity_silent)
4942
0
    summary_patch_list(list);
4943
4944
0
  if (flush_attributes)
4945
0
    reset_parsed_attributes();
4946
0
end:
4947
0
  free_patch_list(list);
4948
0
  strbuf_release(&buf);
4949
0
  string_list_clear(&state->fn_table, 0);
4950
0
  return res;
4951
0
}
4952
4953
static int apply_option_parse_exclude(const struct option *opt,
4954
              const char *arg, int unset)
4955
0
{
4956
0
  struct apply_state *state = opt->value;
4957
4958
0
  BUG_ON_OPT_NEG(unset);
4959
4960
0
  add_name_limit(state, arg, 1);
4961
0
  return 0;
4962
0
}
4963
4964
static int apply_option_parse_include(const struct option *opt,
4965
              const char *arg, int unset)
4966
0
{
4967
0
  struct apply_state *state = opt->value;
4968
4969
0
  BUG_ON_OPT_NEG(unset);
4970
4971
0
  add_name_limit(state, arg, 0);
4972
0
  state->has_include = 1;
4973
0
  return 0;
4974
0
}
4975
4976
static int apply_option_parse_p(const struct option *opt,
4977
        const char *arg,
4978
        int unset)
4979
0
{
4980
0
  struct apply_state *state = opt->value;
4981
4982
0
  BUG_ON_OPT_NEG(unset);
4983
4984
0
  state->p_value = atoi(arg);
4985
0
  state->p_value_known = 1;
4986
0
  return 0;
4987
0
}
4988
4989
static int apply_option_parse_space_change(const struct option *opt,
4990
             const char *arg, int unset)
4991
0
{
4992
0
  struct apply_state *state = opt->value;
4993
4994
0
  BUG_ON_OPT_ARG(arg);
4995
4996
0
  if (unset)
4997
0
    state->ws_ignore_action = ignore_ws_none;
4998
0
  else
4999
0
    state->ws_ignore_action = ignore_ws_change;
5000
0
  return 0;
5001
0
}
5002
5003
static int apply_option_parse_whitespace(const struct option *opt,
5004
           const char *arg, int unset)
5005
0
{
5006
0
  struct apply_state *state = opt->value;
5007
5008
0
  BUG_ON_OPT_NEG(unset);
5009
5010
0
  state->whitespace_option = arg;
5011
0
  if (parse_whitespace_option(state, arg))
5012
0
    return -1;
5013
0
  return 0;
5014
0
}
5015
5016
static int apply_option_parse_directory(const struct option *opt,
5017
          const char *arg, int unset)
5018
0
{
5019
0
  struct apply_state *state = opt->value;
5020
5021
0
  BUG_ON_OPT_NEG(unset);
5022
5023
0
  strbuf_reset(&state->root);
5024
0
  strbuf_addstr(&state->root, arg);
5025
5026
0
  if (strbuf_normalize_path(&state->root) < 0)
5027
0
    return error(_("unable to normalize directory: '%s'"), arg);
5028
5029
0
  strbuf_complete(&state->root, '/');
5030
0
  return 0;
5031
0
}
5032
5033
int apply_all_patches(struct apply_state *state,
5034
          int argc,
5035
          const char **argv,
5036
          int options)
5037
0
{
5038
0
  int i;
5039
0
  int res;
5040
0
  int errs = 0;
5041
0
  int read_stdin = 1;
5042
5043
0
  for (i = 0; i < argc; i++) {
5044
0
    const char *arg = argv[i];
5045
0
    char *to_free = NULL;
5046
0
    int fd;
5047
5048
0
    if (!strcmp(arg, "-")) {
5049
0
      res = apply_patch(state, 0, "<stdin>", options);
5050
0
      if (res < 0)
5051
0
        goto end;
5052
0
      errs |= res;
5053
0
      read_stdin = 0;
5054
0
      continue;
5055
0
    } else
5056
0
      arg = to_free = prefix_filename(state->prefix, arg);
5057
5058
0
    fd = open(arg, O_RDONLY);
5059
0
    if (fd < 0) {
5060
0
      error(_("can't open patch '%s': %s"), arg, strerror(errno));
5061
0
      res = -128;
5062
0
      free(to_free);
5063
0
      goto end;
5064
0
    }
5065
0
    read_stdin = 0;
5066
0
    set_default_whitespace_mode(state);
5067
0
    res = apply_patch(state, fd, arg, options);
5068
0
    close(fd);
5069
0
    free(to_free);
5070
0
    if (res < 0)
5071
0
      goto end;
5072
0
    errs |= res;
5073
0
  }
5074
0
  set_default_whitespace_mode(state);
5075
0
  if (read_stdin) {
5076
0
    res = apply_patch(state, 0, "<stdin>", options);
5077
0
    if (res < 0)
5078
0
      goto end;
5079
0
    errs |= res;
5080
0
  }
5081
5082
0
  if (state->whitespace_error) {
5083
0
    if (state->squelch_whitespace_errors &&
5084
0
        state->squelch_whitespace_errors < state->whitespace_error) {
5085
0
      int squelched =
5086
0
        state->whitespace_error - state->squelch_whitespace_errors;
5087
0
      warning(Q_("squelched %d whitespace error",
5088
0
           "squelched %d whitespace errors",
5089
0
           squelched),
5090
0
        squelched);
5091
0
    }
5092
0
    if (state->ws_error_action == die_on_ws_error) {
5093
0
      error(Q_("%d line adds whitespace errors.",
5094
0
         "%d lines add whitespace errors.",
5095
0
         state->whitespace_error),
5096
0
            state->whitespace_error);
5097
0
      res = -128;
5098
0
      goto end;
5099
0
    }
5100
0
    if (state->applied_after_fixing_ws && state->apply)
5101
0
      warning(Q_("%d line applied after"
5102
0
           " fixing whitespace errors.",
5103
0
           "%d lines applied after"
5104
0
           " fixing whitespace errors.",
5105
0
           state->applied_after_fixing_ws),
5106
0
        state->applied_after_fixing_ws);
5107
0
    else if (state->whitespace_error)
5108
0
      warning(Q_("%d line adds whitespace errors.",
5109
0
           "%d lines add whitespace errors.",
5110
0
           state->whitespace_error),
5111
0
        state->whitespace_error);
5112
0
  }
5113
5114
0
  if (state->update_index) {
5115
0
    res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5116
0
    if (res) {
5117
0
      error(_("Unable to write new index file"));
5118
0
      res = -128;
5119
0
      goto end;
5120
0
    }
5121
0
  }
5122
5123
0
  res = !!errs;
5124
5125
0
end:
5126
0
  rollback_lock_file(&state->lock_file);
5127
5128
0
  if (state->apply_verbosity <= verbosity_silent) {
5129
0
    set_error_routine(state->saved_error_routine);
5130
0
    set_warn_routine(state->saved_warn_routine);
5131
0
  }
5132
5133
0
  if (res > -1)
5134
0
    return res;
5135
0
  return (res == -1 ? 1 : 128);
5136
0
}
5137
5138
int apply_parse_options(int argc, const char **argv,
5139
      struct apply_state *state,
5140
      int *force_apply, int *options,
5141
      const char * const *apply_usage)
5142
0
{
5143
0
  struct option builtin_apply_options[] = {
5144
0
    OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5145
0
      N_("don't apply changes matching the given path"),
5146
0
      PARSE_OPT_NONEG, apply_option_parse_exclude),
5147
0
    OPT_CALLBACK_F(0, "include", state, N_("path"),
5148
0
      N_("apply changes matching the given path"),
5149
0
      PARSE_OPT_NONEG, apply_option_parse_include),
5150
0
    OPT_CALLBACK('p', NULL, state, N_("num"),
5151
0
      N_("remove <num> leading slashes from traditional diff paths"),
5152
0
      apply_option_parse_p),
5153
0
    OPT_BOOL(0, "no-add", &state->no_add,
5154
0
      N_("ignore additions made by the patch")),
5155
0
    OPT_BOOL(0, "stat", &state->diffstat,
5156
0
      N_("instead of applying the patch, output diffstat for the input")),
5157
0
    OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5158
0
    OPT_NOOP_NOARG(0, "binary"),
5159
0
    OPT_BOOL(0, "numstat", &state->numstat,
5160
0
      N_("show number of added and deleted lines in decimal notation")),
5161
0
    OPT_BOOL(0, "summary", &state->summary,
5162
0
      N_("instead of applying the patch, output a summary for the input")),
5163
0
    OPT_BOOL(0, "check", &state->check,
5164
0
      N_("instead of applying the patch, see if the patch is applicable")),
5165
0
    OPT_BOOL(0, "index", &state->check_index,
5166
0
      N_("make sure the patch is applicable to the current index")),
5167
0
    OPT_BOOL('N', "intent-to-add", &state->ita_only,
5168
0
      N_("mark new files with `git add --intent-to-add`")),
5169
0
    OPT_BOOL(0, "cached", &state->cached,
5170
0
      N_("apply a patch without touching the working tree")),
5171
0
    OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5172
0
         N_("accept a patch that touches outside the working area"),
5173
0
         PARSE_OPT_NOCOMPLETE),
5174
0
    OPT_BOOL(0, "apply", force_apply,
5175
0
      N_("also apply the patch (use with --stat/--summary/--check)")),
5176
0
    OPT_BOOL('3', "3way", &state->threeway,
5177
0
       N_( "attempt three-way merge, fall back on normal patch if that fails")),
5178
0
    OPT_SET_INT_F(0, "ours", &state->merge_variant,
5179
0
      N_("for conflicts, use our version"),
5180
0
      XDL_MERGE_FAVOR_OURS, PARSE_OPT_NONEG),
5181
0
    OPT_SET_INT_F(0, "theirs", &state->merge_variant,
5182
0
      N_("for conflicts, use their version"),
5183
0
      XDL_MERGE_FAVOR_THEIRS, PARSE_OPT_NONEG),
5184
0
    OPT_SET_INT_F(0, "union", &state->merge_variant,
5185
0
      N_("for conflicts, use a union version"),
5186
0
      XDL_MERGE_FAVOR_UNION, PARSE_OPT_NONEG),
5187
0
    OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5188
0
      N_("build a temporary index based on embedded index information")),
5189
    /* Think twice before adding "--nul" synonym to this */
5190
0
    OPT_SET_INT('z', NULL, &state->line_termination,
5191
0
      N_("paths are separated with NUL character"), '\0'),
5192
0
    OPT_UNSIGNED('C', NULL, &state->p_context,
5193
0
           N_("ensure at least <n> lines of context match")),
5194
0
    OPT_CALLBACK(0, "whitespace", state, N_("action"),
5195
0
      N_("detect new or modified lines that have whitespace errors"),
5196
0
      apply_option_parse_whitespace),
5197
0
    OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5198
0
      N_("ignore changes in whitespace when finding context"),
5199
0
      PARSE_OPT_NOARG, apply_option_parse_space_change),
5200
0
    OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5201
0
      N_("ignore changes in whitespace when finding context"),
5202
0
      PARSE_OPT_NOARG, apply_option_parse_space_change),
5203
0
    OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5204
0
      N_("apply the patch in reverse")),
5205
0
    OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5206
0
      N_("don't expect at least one line of context")),
5207
0
    OPT_BOOL(0, "reject", &state->apply_with_reject,
5208
0
      N_("leave the rejected hunks in corresponding *.rej files")),
5209
0
    OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5210
0
      N_("allow overlapping hunks")),
5211
0
    OPT__VERBOSITY(&state->apply_verbosity),
5212
0
    OPT_BIT(0, "inaccurate-eof", options,
5213
0
      N_("tolerate incorrectly detected missing new-line at the end of file"),
5214
0
      APPLY_OPT_INACCURATE_EOF),
5215
0
    OPT_BIT(0, "recount", options,
5216
0
      N_("do not trust the line counts in the hunk headers"),
5217
0
      APPLY_OPT_RECOUNT),
5218
0
    OPT_CALLBACK(0, "directory", state, N_("root"),
5219
0
      N_("prepend <root> to all filenames"),
5220
0
      apply_option_parse_directory),
5221
0
    OPT_BOOL(0, "allow-empty", &state->allow_empty,
5222
0
      N_("don't return error for empty patches")),
5223
0
    OPT_END()
5224
0
  };
5225
5226
0
  argc = parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5227
5228
0
  if (state->merge_variant && !state->threeway)
5229
0
    die(_("--ours, --theirs, and --union require --3way"));
5230
5231
0
  return argc;
5232
0
}