Coverage Report

Created: 2026-10-17 07:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/diff.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2005 Junio C Hamano
3
 */
4
5
#define USE_THE_REPOSITORY_VARIABLE
6
#define DISABLE_SIGN_COMPARE_WARNINGS
7
8
#include "git-compat-util.h"
9
#include "abspath.h"
10
#include "base85.h"
11
#include "config.h"
12
#include "convert.h"
13
#include "environment.h"
14
#include "gettext.h"
15
#include "tempfile.h"
16
#include "revision.h"
17
#include "quote.h"
18
#include "diff.h"
19
#include "diffcore.h"
20
#include "delta.h"
21
#include "hex.h"
22
#include "xdiff-interface.h"
23
#include "color.h"
24
#include "run-command.h"
25
#include "utf8.h"
26
#include "odb.h"
27
#include "userdiff.h"
28
#include "submodule.h"
29
#include "hashmap.h"
30
#include "mem-pool.h"
31
#include "merge-ll.h"
32
#include "string-list.h"
33
#include "strvec.h"
34
#include "tmp-objdir.h"
35
#include "graph.h"
36
#include "oid-array.h"
37
#include "packfile.h"
38
#include "pager.h"
39
#include "parse-options.h"
40
#include "help.h"
41
#include "promisor-remote.h"
42
#include "dir.h"
43
#include "object-file.h"
44
#include "object-name.h"
45
#include "read-cache-ll.h"
46
#include "setup.h"
47
#include "strmap.h"
48
#include "ws.h"
49
50
#ifdef NO_FAST_WORKING_DIRECTORY
51
#define FAST_WORKING_DIRECTORY 0
52
#else
53
0
#define FAST_WORKING_DIRECTORY 1
54
#endif
55
56
static int diff_detect_rename_default;
57
static int diff_indent_heuristic = 1;
58
static int diff_rename_limit_default = 1000;
59
static int diff_suppress_blank_empty;
60
static enum git_colorbool diff_use_color_default = GIT_COLOR_UNKNOWN;
61
static int diff_color_moved_default;
62
static int diff_color_moved_ws_default;
63
static unsigned int diff_context_default = 3;
64
static unsigned int diff_interhunk_context_default;
65
static char *diff_word_regex_cfg;
66
static struct external_diff external_diff_cfg;
67
static char *diff_order_file_cfg;
68
int diff_auto_refresh_index = 1;
69
static int diff_mnemonic_prefix;
70
static int diff_no_prefix;
71
static char *diff_src_prefix;
72
static char *diff_dst_prefix;
73
static int diff_relative;
74
static int diff_stat_name_width;
75
static int diff_stat_graph_width;
76
static int diff_dirstat_permille_default = 30;
77
static struct diff_options default_diff_options;
78
static long diff_algorithm;
79
static unsigned ws_error_highlight_default = WSEH_NEW;
80
81
static char diff_colors[][COLOR_MAXLEN] = {
82
  GIT_COLOR_RESET,
83
  GIT_COLOR_NORMAL, /* CONTEXT */
84
  GIT_COLOR_BOLD,   /* METAINFO */
85
  GIT_COLOR_CYAN,   /* FRAGINFO */
86
  GIT_COLOR_RED,    /* OLD */
87
  GIT_COLOR_GREEN,  /* NEW */
88
  GIT_COLOR_YELLOW, /* COMMIT */
89
  GIT_COLOR_BG_RED, /* WHITESPACE */
90
  GIT_COLOR_NORMAL, /* FUNCINFO */
91
  GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
92
  GIT_COLOR_BOLD_BLUE,  /* OLD_MOVED ALTERNATIVE */
93
  GIT_COLOR_FAINT,  /* OLD_MOVED_DIM */
94
  GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
95
  GIT_COLOR_BOLD_CYAN,  /* NEW_MOVED */
96
  GIT_COLOR_BOLD_YELLOW,  /* NEW_MOVED ALTERNATIVE */
97
  GIT_COLOR_FAINT,  /* NEW_MOVED_DIM */
98
  GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
99
  GIT_COLOR_FAINT,  /* CONTEXT_DIM */
100
  GIT_COLOR_FAINT_RED,  /* OLD_DIM */
101
  GIT_COLOR_FAINT_GREEN,  /* NEW_DIM */
102
  GIT_COLOR_BOLD,   /* CONTEXT_BOLD */
103
  GIT_COLOR_BOLD_RED, /* OLD_BOLD */
104
  GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
105
};
106
107
static const char *color_diff_slots[] = {
108
  [DIFF_CONTEXT]          = "context",
109
  [DIFF_METAINFO]         = "meta",
110
  [DIFF_FRAGINFO]         = "frag",
111
  [DIFF_FILE_OLD]         = "old",
112
  [DIFF_FILE_NEW]         = "new",
113
  [DIFF_COMMIT]         = "commit",
114
  [DIFF_WHITESPACE]       = "whitespace",
115
  [DIFF_FUNCINFO]         = "func",
116
  [DIFF_FILE_OLD_MOVED]       = "oldMoved",
117
  [DIFF_FILE_OLD_MOVED_ALT]     = "oldMovedAlternative",
118
  [DIFF_FILE_OLD_MOVED_DIM]     = "oldMovedDimmed",
119
  [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
120
  [DIFF_FILE_NEW_MOVED]       = "newMoved",
121
  [DIFF_FILE_NEW_MOVED_ALT]     = "newMovedAlternative",
122
  [DIFF_FILE_NEW_MOVED_DIM]     = "newMovedDimmed",
123
  [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
124
  [DIFF_CONTEXT_DIM]        = "contextDimmed",
125
  [DIFF_FILE_OLD_DIM]       = "oldDimmed",
126
  [DIFF_FILE_NEW_DIM]       = "newDimmed",
127
  [DIFF_CONTEXT_BOLD]       = "contextBold",
128
  [DIFF_FILE_OLD_BOLD]        = "oldBold",
129
  [DIFF_FILE_NEW_BOLD]        = "newBold",
130
};
131
132
define_list_config_array_extra(color_diff_slots, {"plain"});
133
134
static int parse_diff_color_slot(const char *var)
135
0
{
136
0
  if (!strcasecmp(var, "plain"))
137
0
    return DIFF_CONTEXT;
138
0
  return LOOKUP_CONFIG(color_diff_slots, var);
139
0
}
140
141
static int parse_dirstat_params(struct diff_options *options, const char *params_string,
142
        struct strbuf *errmsg)
143
0
{
144
0
  char *params_copy = xstrdup(params_string);
145
0
  struct string_list params = STRING_LIST_INIT_NODUP;
146
0
  int ret = 0;
147
0
  int i;
148
149
0
  if (*params_copy)
150
0
    string_list_split_in_place(&params, params_copy, ",", -1);
151
0
  for (i = 0; i < params.nr; i++) {
152
0
    const char *p = params.items[i].string;
153
0
    if (!strcmp(p, "changes")) {
154
0
      options->flags.dirstat_by_line = 0;
155
0
      options->flags.dirstat_by_file = 0;
156
0
    } else if (!strcmp(p, "lines")) {
157
0
      options->flags.dirstat_by_line = 1;
158
0
      options->flags.dirstat_by_file = 0;
159
0
    } else if (!strcmp(p, "files")) {
160
0
      options->flags.dirstat_by_line = 0;
161
0
      options->flags.dirstat_by_file = 1;
162
0
    } else if (!strcmp(p, "noncumulative")) {
163
0
      options->flags.dirstat_cumulative = 0;
164
0
    } else if (!strcmp(p, "cumulative")) {
165
0
      options->flags.dirstat_cumulative = 1;
166
0
    } else if (isdigit(*p)) {
167
0
      char *end;
168
0
      int permille = strtoul(p, &end, 10) * 10;
169
0
      if (*end == '.' && isdigit(*++end)) {
170
        /* only use first digit */
171
0
        permille += *end - '0';
172
        /* .. and ignore any further digits */
173
0
        while (isdigit(*++end))
174
0
          ; /* nothing */
175
0
      }
176
0
      if (!*end)
177
0
        options->dirstat_permille = permille;
178
0
      else {
179
0
        strbuf_addf(errmsg, _("  Failed to parse dirstat cut-off percentage '%s'\n"),
180
0
              p);
181
0
        ret++;
182
0
      }
183
0
    } else {
184
0
      strbuf_addf(errmsg, _("  Unknown dirstat parameter '%s'\n"), p);
185
0
      ret++;
186
0
    }
187
188
0
  }
189
0
  string_list_clear(&params, 0);
190
0
  free(params_copy);
191
0
  return ret;
192
0
}
193
194
static int parse_submodule_params(struct diff_options *options, const char *value)
195
0
{
196
0
  if (!strcmp(value, "log"))
197
0
    options->submodule_format = DIFF_SUBMODULE_LOG;
198
0
  else if (!strcmp(value, "short"))
199
0
    options->submodule_format = DIFF_SUBMODULE_SHORT;
200
0
  else if (!strcmp(value, "diff"))
201
0
    options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
202
  /*
203
   * Please update $__git_diff_submodule_formats in
204
   * git-completion.bash when you add new formats.
205
   */
206
0
  else
207
0
    return -1;
208
0
  return 0;
209
0
}
210
211
int git_config_rename(const char *var, const char *value)
212
0
{
213
0
  if (!value)
214
0
    return DIFF_DETECT_RENAME;
215
0
  if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
216
0
    return  DIFF_DETECT_COPY;
217
0
  return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
218
0
}
219
220
long parse_algorithm_value(const char *value)
221
0
{
222
0
  if (!value)
223
0
    return -1;
224
0
  else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
225
0
    return 0;
226
0
  else if (!strcasecmp(value, "minimal"))
227
0
    return XDF_NEED_MINIMAL;
228
0
  else if (!strcasecmp(value, "patience"))
229
0
    return XDF_PATIENCE_DIFF;
230
0
  else if (!strcasecmp(value, "histogram"))
231
0
    return XDF_HISTOGRAM_DIFF;
232
  /*
233
   * Please update $__git_diff_algorithms in git-completion.bash
234
   * when you add new algorithms.
235
   */
236
0
  return -1;
237
0
}
238
239
static int parse_one_token(const char **arg, const char *token)
240
0
{
241
0
  const char *rest;
242
0
  if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
243
0
    *arg = rest;
244
0
    return 1;
245
0
  }
246
0
  return 0;
247
0
}
248
249
static int parse_ws_error_highlight(const char *arg)
250
0
{
251
0
  const char *orig_arg = arg;
252
0
  unsigned val = 0;
253
254
0
  while (*arg) {
255
0
    if (parse_one_token(&arg, "none"))
256
0
      val = 0;
257
0
    else if (parse_one_token(&arg, "default"))
258
0
      val = WSEH_NEW;
259
0
    else if (parse_one_token(&arg, "all"))
260
0
      val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
261
0
    else if (parse_one_token(&arg, "new"))
262
0
      val |= WSEH_NEW;
263
0
    else if (parse_one_token(&arg, "old"))
264
0
      val |= WSEH_OLD;
265
0
    else if (parse_one_token(&arg, "context"))
266
0
      val |= WSEH_CONTEXT;
267
0
    else {
268
0
      return -1 - (int)(arg - orig_arg);
269
0
    }
270
0
    if (*arg)
271
0
      arg++;
272
0
  }
273
0
  return val;
274
0
}
275
276
/*
277
 * These are to give UI layer defaults.
278
 * The core-level commands such as git-diff-files should
279
 * never be affected by the setting of diff.renames
280
 * the user happens to have in the configuration file.
281
 */
282
void init_diff_ui_defaults(void)
283
0
{
284
0
  diff_detect_rename_default = DIFF_DETECT_RENAME;
285
0
}
286
287
int git_diff_heuristic_config(const char *var, const char *value,
288
            void *cb UNUSED)
289
0
{
290
0
  if (!strcmp(var, "diff.indentheuristic"))
291
0
    diff_indent_heuristic = git_config_bool(var, value);
292
0
  return 0;
293
0
}
294
295
static int parse_color_moved(const char *arg)
296
0
{
297
0
  switch (git_parse_maybe_bool(arg)) {
298
0
  case 0:
299
0
    return COLOR_MOVED_NO;
300
0
  case 1:
301
0
    return COLOR_MOVED_DEFAULT;
302
0
  default:
303
0
    break;
304
0
  }
305
306
0
  if (!strcmp(arg, "no"))
307
0
    return COLOR_MOVED_NO;
308
0
  else if (!strcmp(arg, "plain"))
309
0
    return COLOR_MOVED_PLAIN;
310
0
  else if (!strcmp(arg, "blocks"))
311
0
    return COLOR_MOVED_BLOCKS;
312
0
  else if (!strcmp(arg, "zebra"))
313
0
    return COLOR_MOVED_ZEBRA;
314
0
  else if (!strcmp(arg, "default"))
315
0
    return COLOR_MOVED_DEFAULT;
316
0
  else if (!strcmp(arg, "dimmed-zebra"))
317
0
    return COLOR_MOVED_ZEBRA_DIM;
318
0
  else if (!strcmp(arg, "dimmed_zebra"))
319
0
    return COLOR_MOVED_ZEBRA_DIM;
320
0
  else
321
0
    return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
322
0
}
323
324
static unsigned parse_color_moved_ws(const char *arg)
325
0
{
326
0
  int ret = 0;
327
0
  struct string_list l = STRING_LIST_INIT_DUP;
328
0
  struct string_list_item *i;
329
330
0
  string_list_split_f(&l, arg, ",", -1, STRING_LIST_SPLIT_TRIM);
331
332
0
  for_each_string_list_item(i, &l) {
333
0
    if (!strcmp(i->string, "no"))
334
0
      ret = 0;
335
0
    else if (!strcmp(i->string, "ignore-space-change"))
336
0
      ret |= XDF_IGNORE_WHITESPACE_CHANGE;
337
0
    else if (!strcmp(i->string, "ignore-space-at-eol"))
338
0
      ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
339
0
    else if (!strcmp(i->string, "ignore-all-space"))
340
0
      ret |= XDF_IGNORE_WHITESPACE;
341
0
    else if (!strcmp(i->string, "allow-indentation-change"))
342
0
      ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
343
0
    else {
344
0
      ret |= COLOR_MOVED_WS_ERROR;
345
0
      error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), i->string);
346
0
    }
347
0
  }
348
349
0
  if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
350
0
      (ret & XDF_WHITESPACE_FLAGS)) {
351
0
    error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
352
0
    ret |= COLOR_MOVED_WS_ERROR;
353
0
  }
354
355
0
  string_list_clear(&l, 0);
356
357
0
  return ret;
358
0
}
359
360
int git_diff_ui_config(const char *var, const char *value,
361
           const struct config_context *ctx, void *cb)
362
0
{
363
0
  if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364
0
    diff_use_color_default = git_config_colorbool(var, value);
365
0
    return 0;
366
0
  }
367
0
  if (!strcmp(var, "diff.colormoved")) {
368
0
    int cm = parse_color_moved(value);
369
0
    if (cm < 0)
370
0
      return -1;
371
0
    diff_color_moved_default = cm;
372
0
    return 0;
373
0
  }
374
0
  if (!strcmp(var, "diff.colormovedws")) {
375
0
    unsigned cm;
376
0
    if (!value)
377
0
      return config_error_nonbool(var);
378
0
    cm = parse_color_moved_ws(value);
379
0
    if (cm & COLOR_MOVED_WS_ERROR)
380
0
      return -1;
381
0
    diff_color_moved_ws_default = cm;
382
0
    return 0;
383
0
  }
384
0
  if (!strcmp(var, "diff.context")) {
385
0
    int val = git_config_int(var, value, ctx->kvi);
386
0
    if (val < 0)
387
0
      return -1;
388
0
    diff_context_default = val;
389
0
    return 0;
390
0
  }
391
0
  if (!strcmp(var, "diff.interhunkcontext")) {
392
0
    int val = git_config_int(var, value, ctx->kvi);
393
0
    if (val < 0)
394
0
      return -1;
395
0
    diff_interhunk_context_default = val;
396
0
    return 0;
397
0
  }
398
0
  if (!strcmp(var, "diff.renames")) {
399
0
    diff_detect_rename_default = git_config_rename(var, value);
400
0
    return 0;
401
0
  }
402
0
  if (!strcmp(var, "diff.autorefreshindex")) {
403
0
    diff_auto_refresh_index = git_config_bool(var, value);
404
0
    return 0;
405
0
  }
406
0
  if (!strcmp(var, "diff.mnemonicprefix")) {
407
0
    diff_mnemonic_prefix = git_config_bool(var, value);
408
0
    return 0;
409
0
  }
410
0
  if (!strcmp(var, "diff.noprefix")) {
411
0
    diff_no_prefix = git_config_bool(var, value);
412
0
    return 0;
413
0
  }
414
0
  if (!strcmp(var, "diff.srcprefix")) {
415
0
    FREE_AND_NULL(diff_src_prefix);
416
0
    return git_config_string(&diff_src_prefix, var, value);
417
0
  }
418
0
  if (!strcmp(var, "diff.dstprefix")) {
419
0
    FREE_AND_NULL(diff_dst_prefix);
420
0
    return git_config_string(&diff_dst_prefix, var, value);
421
0
  }
422
0
  if (!strcmp(var, "diff.relative")) {
423
0
    diff_relative = git_config_bool(var, value);
424
0
    return 0;
425
0
  }
426
0
  if (!strcmp(var, "diff.statnamewidth")) {
427
0
    diff_stat_name_width = git_config_int(var, value, ctx->kvi);
428
0
    return 0;
429
0
  }
430
0
  if (!strcmp(var, "diff.statgraphwidth")) {
431
0
    diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
432
0
    return 0;
433
0
  }
434
0
  if (!strcmp(var, "diff.external"))
435
0
    return git_config_string(&external_diff_cfg.cmd, var, value);
436
0
  if (!strcmp(var, "diff.trustexitcode")) {
437
0
    external_diff_cfg.trust_exit_code = git_config_bool(var, value);
438
0
    return 0;
439
0
  }
440
0
  if (!strcmp(var, "diff.wordregex"))
441
0
    return git_config_string(&diff_word_regex_cfg, var, value);
442
0
  if (!strcmp(var, "diff.orderfile")) {
443
0
    FREE_AND_NULL(diff_order_file_cfg);
444
0
    return git_config_pathname(&diff_order_file_cfg, var, value);
445
0
  }
446
447
0
  if (!strcmp(var, "diff.ignoresubmodules")) {
448
0
    if (!value)
449
0
      return config_error_nonbool(var);
450
0
    handle_ignore_submodules_arg(&default_diff_options, value);
451
0
  }
452
453
0
  if (!strcmp(var, "diff.submodule")) {
454
0
    if (!value)
455
0
      return config_error_nonbool(var);
456
0
    if (parse_submodule_params(&default_diff_options, value))
457
0
      warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
458
0
        value);
459
0
    return 0;
460
0
  }
461
462
0
  if (!strcmp(var, "diff.algorithm")) {
463
0
    if (!value)
464
0
      return config_error_nonbool(var);
465
0
    diff_algorithm = parse_algorithm_value(value);
466
0
    if (diff_algorithm < 0)
467
0
      return error(_("unknown value for config '%s': %s"),
468
0
             var, value);
469
0
    return 0;
470
0
  }
471
472
0
  if (git_color_config(var, value, cb) < 0)
473
0
    return -1;
474
475
0
  return git_diff_basic_config(var, value, ctx, cb);
476
0
}
477
478
int git_diff_basic_config(const char *var, const char *value,
479
        const struct config_context *ctx, void *cb)
480
0
{
481
0
  const char *name;
482
483
0
  if (!strcmp(var, "diff.renamelimit")) {
484
0
    diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
485
0
    return 0;
486
0
  }
487
488
0
  if (userdiff_config(var, value) < 0)
489
0
    return -1;
490
491
0
  if (skip_prefix(var, "diff.color.", &name) ||
492
0
      skip_prefix(var, "color.diff.", &name)) {
493
0
    int slot = parse_diff_color_slot(name);
494
0
    if (slot < 0)
495
0
      return 0;
496
0
    if (!value)
497
0
      return config_error_nonbool(var);
498
0
    return color_parse(value, diff_colors[slot]);
499
0
  }
500
501
0
  if (!strcmp(var, "diff.wserrorhighlight")) {
502
0
    int val;
503
0
    if (!value)
504
0
      return config_error_nonbool(var);
505
0
    val = parse_ws_error_highlight(value);
506
0
    if (val < 0)
507
0
      return error(_("unknown value for config '%s': %s"),
508
0
             var, value);
509
0
    ws_error_highlight_default = val;
510
0
    return 0;
511
0
  }
512
513
  /* like GNU diff's --suppress-blank-empty option  */
514
0
  if (!strcmp(var, "diff.suppressblankempty") ||
515
      /* for backwards compatibility */
516
0
      !strcmp(var, "diff.suppress-blank-empty")) {
517
0
    diff_suppress_blank_empty = git_config_bool(var, value);
518
0
    return 0;
519
0
  }
520
521
0
  if (!strcmp(var, "diff.dirstat")) {
522
0
    struct strbuf errmsg = STRBUF_INIT;
523
0
    if (!value)
524
0
      return config_error_nonbool(var);
525
0
    default_diff_options.dirstat_permille = diff_dirstat_permille_default;
526
0
    if (parse_dirstat_params(&default_diff_options, value, &errmsg))
527
0
      warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
528
0
        errmsg.buf);
529
0
    strbuf_release(&errmsg);
530
0
    diff_dirstat_permille_default = default_diff_options.dirstat_permille;
531
0
    return 0;
532
0
  }
533
534
0
  if (git_diff_heuristic_config(var, value, cb) < 0)
535
0
    return -1;
536
537
0
  return git_default_config(var, value, ctx, cb);
538
0
}
539
540
static char *quote_two(const char *one, const char *two)
541
0
{
542
0
  int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
543
0
  int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
544
0
  struct strbuf res = STRBUF_INIT;
545
546
0
  if (need_one + need_two) {
547
0
    strbuf_addch(&res, '"');
548
0
    quote_c_style(one, &res, NULL, CQUOTE_NODQ);
549
0
    quote_c_style(two, &res, NULL, CQUOTE_NODQ);
550
0
    strbuf_addch(&res, '"');
551
0
  } else {
552
0
    strbuf_addstr(&res, one);
553
0
    strbuf_addstr(&res, two);
554
0
  }
555
0
  return strbuf_detach(&res, NULL);
556
0
}
557
558
static const struct external_diff *external_diff(void)
559
0
{
560
0
  static struct external_diff external_diff_env, *external_diff_ptr;
561
0
  static int done_preparing = 0;
562
563
0
  if (done_preparing)
564
0
    return external_diff_ptr;
565
0
  external_diff_env.cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
566
0
  if (git_env_bool("GIT_EXTERNAL_DIFF_TRUST_EXIT_CODE", 0))
567
0
    external_diff_env.trust_exit_code = 1;
568
0
  if (external_diff_env.cmd)
569
0
    external_diff_ptr = &external_diff_env;
570
0
  else if (external_diff_cfg.cmd)
571
0
    external_diff_ptr = &external_diff_cfg;
572
0
  done_preparing = 1;
573
0
  return external_diff_ptr;
574
0
}
575
576
/*
577
 * Keep track of files used for diffing. Sometimes such an entry
578
 * refers to a temporary file, sometimes to an existing file, and
579
 * sometimes to "/dev/null".
580
 */
581
static struct diff_tempfile {
582
  /*
583
   * filename external diff should read from, or NULL if this
584
   * entry is currently not in use:
585
   */
586
  const char *name;
587
588
  char hex[GIT_MAX_HEXSZ + 1];
589
  char mode[10];
590
591
  /*
592
   * If this diff_tempfile instance refers to a temporary file,
593
   * this tempfile object is used to manage its lifetime.
594
   */
595
  struct tempfile *tempfile;
596
} diff_temp[2];
597
598
struct emit_callback {
599
  int color_diff;
600
  unsigned ws_rule;
601
  int blank_at_eof_in_preimage;
602
  int blank_at_eof_in_postimage;
603
  int lno_in_preimage;
604
  int lno_in_postimage;
605
  int last_line_kind;
606
  const char **label_path;
607
  struct diff_words_data *diff_words;
608
  struct diff_options *opt;
609
  struct strbuf *header;
610
};
611
612
/*
613
 * State for the line-range callback wrappers that sit between
614
 * xdi_diff_outf() and fn_out_consume().  xdiff produces a normal,
615
 * unfiltered diff; the wrappers intercept each hunk header and line,
616
 * track post-image position, and forward only lines that fall within
617
 * the requested ranges.  Contiguous in-range lines are collected into
618
 * range hunks and flushed with a synthetic @@ header so that
619
 * fn_out_consume() sees well-formed unified-diff fragments.
620
 *
621
 * Removal lines ('-') cannot be classified by post-image position, so
622
 * they are buffered in pending_rm until the next '+' or ' ' line
623
 * reveals whether they precede an in-range line (flush into range hunk) or
624
 * an out-of-range line (discard).
625
 */
626
struct line_range_callback {
627
  xdiff_emit_line_fn orig_line_fn;
628
  void *orig_cb_data;
629
  const struct range_set *ranges; /* 0-based [start, end) */
630
  unsigned int cur_range;   /* index into the range_set */
631
632
  /* Post/pre-image line counters (1-based, set from hunk headers) */
633
  long lno_post;
634
  long lno_pre;
635
636
  /*
637
   * Function name from most recent xdiff hunk header;
638
   * size matches struct func_line.buf in xdiff/xemit.c.
639
   */
640
  char func[80];
641
  long funclen;
642
643
  /* Range hunk being accumulated for the current range */
644
  struct strbuf rhunk;
645
  long rhunk_old_begin, rhunk_old_count;
646
  long rhunk_new_begin, rhunk_new_count;
647
  int rhunk_active;
648
  int rhunk_has_changes;    /* any '+' or '-' lines? */
649
650
  /* Removal lines not yet known to be in-range */
651
  struct strbuf pending_rm;
652
  int pending_rm_count;
653
  long pending_rm_pre_begin;  /* pre-image line of first pending */
654
655
  int ret;      /* latched error from orig_line_fn */
656
};
657
658
static int count_lines(const char *data, int size)
659
0
{
660
0
  int count, ch, completely_empty = 1, nl_just_seen = 0;
661
0
  count = 0;
662
0
  while (0 < size--) {
663
0
    ch = *data++;
664
0
    if (ch == '\n') {
665
0
      count++;
666
0
      nl_just_seen = 1;
667
0
      completely_empty = 0;
668
0
    }
669
0
    else {
670
0
      nl_just_seen = 0;
671
0
      completely_empty = 0;
672
0
    }
673
0
  }
674
0
  if (completely_empty)
675
0
    return 0;
676
0
  if (!nl_just_seen)
677
0
    count++; /* no trailing newline */
678
0
  return count;
679
0
}
680
681
static int fill_mmfile(struct repository *r, mmfile_t *mf,
682
           struct diff_filespec *one)
683
0
{
684
0
  if (!DIFF_FILE_VALID(one)) {
685
0
    mf->ptr = (char *)""; /* does not matter */
686
0
    mf->size = 0;
687
0
    return 0;
688
0
  }
689
0
  else if (diff_populate_filespec(r, one, NULL))
690
0
    return -1;
691
692
0
  mf->ptr = one->data;
693
0
  mf->size = one->size;
694
0
  return 0;
695
0
}
696
697
/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
698
static unsigned long diff_filespec_size(struct repository *r,
699
          struct diff_filespec *one)
700
0
{
701
0
  struct diff_populate_filespec_options dpf_options = {
702
0
    .check_size_only = 1,
703
0
  };
704
705
0
  if (!DIFF_FILE_VALID(one))
706
0
    return 0;
707
0
  diff_populate_filespec(r, one, &dpf_options);
708
0
  return one->size;
709
0
}
710
711
static int count_trailing_blank(mmfile_t *mf)
712
0
{
713
0
  char *ptr = mf->ptr;
714
0
  long size = mf->size;
715
0
  int cnt = 0;
716
717
0
  if (!size)
718
0
    return cnt;
719
0
  ptr += size - 1; /* pointing at the very end */
720
0
  if (*ptr != '\n')
721
0
    ; /* incomplete line */
722
0
  else
723
0
    ptr--; /* skip the last LF */
724
0
  while (mf->ptr < ptr) {
725
0
    char *prev_eol;
726
0
    for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
727
0
      if (*prev_eol == '\n')
728
0
        break;
729
0
    if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
730
0
      break;
731
0
    cnt++;
732
0
    ptr = prev_eol - 1;
733
0
  }
734
0
  return cnt;
735
0
}
736
737
static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
738
             struct emit_callback *ecbdata)
739
0
{
740
0
  int l1, l2, at;
741
0
  l1 = count_trailing_blank(mf1);
742
0
  l2 = count_trailing_blank(mf2);
743
0
  if (l2 <= l1) {
744
0
    ecbdata->blank_at_eof_in_preimage = 0;
745
0
    ecbdata->blank_at_eof_in_postimage = 0;
746
0
    return;
747
0
  }
748
0
  at = count_lines(mf1->ptr, mf1->size);
749
0
  ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
750
751
0
  at = count_lines(mf2->ptr, mf2->size);
752
0
  ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
753
0
}
754
755
static void emit_line_0(struct diff_options *o,
756
      const char *set_sign, const char *set, unsigned reverse, const char *reset,
757
      int first, const char *line, int len)
758
0
{
759
0
  int has_trailing_newline, has_trailing_carriage_return;
760
0
  int needs_reset = 0; /* at the end of the line */
761
0
  FILE *file = o->file;
762
763
0
  fputs(diff_line_prefix(o), file);
764
765
0
  has_trailing_newline = (len > 0 && line[len-1] == '\n');
766
0
  if (has_trailing_newline)
767
0
    len--;
768
769
0
  has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
770
0
  if (has_trailing_carriage_return)
771
0
    len--;
772
773
0
  if (!len && !first)
774
0
    goto end_of_line;
775
776
0
  if (reverse && want_color(o->use_color)) {
777
0
    fputs(GIT_COLOR_REVERSE, file);
778
0
    needs_reset = 1;
779
0
  }
780
781
0
  if (set_sign) {
782
0
    fputs(set_sign, file);
783
0
    needs_reset = 1;
784
0
  }
785
786
0
  if (first)
787
0
    fputc(first, file);
788
789
0
  if (!len)
790
0
    goto end_of_line;
791
792
0
  if (set) {
793
0
    if (set_sign && set != set_sign)
794
0
      fputs(reset, file);
795
0
    fputs(set, file);
796
0
    needs_reset = 1;
797
0
  }
798
0
  fwrite(line, len, 1, file);
799
0
  needs_reset = 1; /* 'line' may contain color codes. */
800
801
0
end_of_line:
802
0
  if (needs_reset)
803
0
    fputs(reset, file);
804
0
  if (has_trailing_carriage_return)
805
0
    fputc('\r', file);
806
0
  if (has_trailing_newline)
807
0
    fputc('\n', file);
808
0
}
809
810
static void emit_line(struct diff_options *o, const char *set, const char *reset,
811
          const char *line, int len)
812
0
{
813
0
  emit_line_0(o, set, NULL, 0, reset, 0, line, len);
814
0
}
815
816
enum diff_symbol {
817
  DIFF_SYMBOL_BINARY_DIFF_HEADER,
818
  DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
819
  DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
820
  DIFF_SYMBOL_BINARY_DIFF_BODY,
821
  DIFF_SYMBOL_BINARY_DIFF_FOOTER,
822
  DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
823
  DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
824
  DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
825
  DIFF_SYMBOL_STATS_LINE,
826
  DIFF_SYMBOL_WORD_DIFF,
827
  DIFF_SYMBOL_STAT_SEP,
828
  DIFF_SYMBOL_SUMMARY,
829
  DIFF_SYMBOL_SUBMODULE_ADD,
830
  DIFF_SYMBOL_SUBMODULE_DEL,
831
  DIFF_SYMBOL_SUBMODULE_UNTRACKED,
832
  DIFF_SYMBOL_SUBMODULE_MODIFIED,
833
  DIFF_SYMBOL_SUBMODULE_HEADER,
834
  DIFF_SYMBOL_SUBMODULE_ERROR,
835
  DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
836
  DIFF_SYMBOL_REWRITE_DIFF,
837
  DIFF_SYMBOL_BINARY_FILES,
838
  DIFF_SYMBOL_HEADER,
839
  DIFF_SYMBOL_FILEPAIR_PLUS,
840
  DIFF_SYMBOL_FILEPAIR_MINUS,
841
  DIFF_SYMBOL_WORDS_PORCELAIN,
842
  DIFF_SYMBOL_WORDS,
843
  DIFF_SYMBOL_CONTEXT,
844
  DIFF_SYMBOL_CONTEXT_INCOMPLETE,
845
  DIFF_SYMBOL_PLUS,
846
  DIFF_SYMBOL_MINUS,
847
  DIFF_SYMBOL_CONTEXT_FRAGINFO,
848
  DIFF_SYMBOL_CONTEXT_MARKER,
849
  DIFF_SYMBOL_SEPARATOR
850
};
851
852
/*
853
 * Flags for content lines:
854
 * 0..15 are whitespace rules (see ws.h)
855
 * 16..18 are WSEH_NEW | WSEH_CONTEXT | WSEH_OLD
856
 * 19 is marking if the line is blank at EOF
857
 * 20..22 are used for color-moved.
858
 */
859
0
#define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF  (1<<19)
860
0
#define DIFF_SYMBOL_MOVED_LINE      (1<<20)
861
0
#define DIFF_SYMBOL_MOVED_LINE_ALT    (1<<21)
862
0
#define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING  (1<<22)
863
864
0
#define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
865
866
/*
867
 * This struct is used when we need to buffer the output of the diff output.
868
 *
869
 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
870
 * into the pre/post image file. This pointer could be a union with the
871
 * line pointer. By storing an offset into the file instead of the literal line,
872
 * we can decrease the memory footprint for the buffered output. At first we
873
 * may want to only have indirection for the content lines, but we could also
874
 * enhance the state for emitting prefabricated lines, e.g. the similarity
875
 * score line or hunk/file headers would only need to store a number or path
876
 * and then the output can be constructed later on depending on state.
877
 */
878
struct emitted_diff_symbol {
879
  const char *line;
880
  int len;
881
  int flags;
882
  int indent_off;   /* Offset to first non-whitespace character */
883
  int indent_width; /* The visual width of the indentation */
884
  unsigned id;
885
  enum diff_symbol s;
886
};
887
#define EMITTED_DIFF_SYMBOL_INIT { 0 }
888
889
struct emitted_diff_symbols {
890
  struct emitted_diff_symbol *buf;
891
  int nr, alloc;
892
};
893
0
#define EMITTED_DIFF_SYMBOLS_INIT { 0 }
894
895
static void append_emitted_diff_symbol(struct diff_options *o,
896
               struct emitted_diff_symbol *e)
897
0
{
898
0
  struct emitted_diff_symbol *f;
899
900
0
  ALLOC_GROW(o->emitted_symbols->buf,
901
0
       o->emitted_symbols->nr + 1,
902
0
       o->emitted_symbols->alloc);
903
0
  f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
904
905
0
  memcpy(f, e, sizeof(struct emitted_diff_symbol));
906
0
  f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
907
0
}
908
909
static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
910
0
{
911
0
  if (!e)
912
0
    return;
913
0
  free(e->buf);
914
0
  free(e);
915
0
}
916
917
struct moved_entry {
918
  const struct emitted_diff_symbol *es;
919
  struct moved_entry *next_line;
920
  struct moved_entry *next_match;
921
};
922
923
struct moved_block {
924
  struct moved_entry *match;
925
  int wsd; /* The whitespace delta of this block */
926
};
927
928
0
#define INDENT_BLANKLINE INT_MIN
929
930
static void fill_es_indent_data(struct emitted_diff_symbol *es)
931
0
{
932
0
  unsigned int off = 0, i;
933
0
  int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
934
0
  const char *s = es->line;
935
0
  const int len = es->len;
936
937
  /* skip any \v \f \r at start of indentation */
938
0
  while (s[off] == '\f' || s[off] == '\v' ||
939
0
         (off < len - 1 && s[off] == '\r'))
940
0
    off++;
941
942
  /* calculate the visual width of indentation */
943
0
  while(1) {
944
0
    if (s[off] == ' ') {
945
0
      width++;
946
0
      off++;
947
0
    } else if (s[off] == '\t') {
948
0
      width += tab_width - (width % tab_width);
949
0
      while (s[++off] == '\t')
950
0
        width += tab_width;
951
0
    } else {
952
0
      break;
953
0
    }
954
0
  }
955
956
  /* check if this line is blank */
957
0
  for (i = off; i < len; i++)
958
0
    if (!isspace(s[i]))
959
0
        break;
960
961
0
  if (i == len) {
962
0
    es->indent_width = INDENT_BLANKLINE;
963
0
    es->indent_off = len;
964
0
  } else {
965
0
    es->indent_off = off;
966
0
    es->indent_width = width;
967
0
  }
968
0
}
969
970
static int compute_ws_delta(const struct emitted_diff_symbol *a,
971
          const struct emitted_diff_symbol *b)
972
0
{
973
0
  int a_width = a->indent_width,
974
0
      b_width = b->indent_width;
975
976
0
  if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
977
0
    return INDENT_BLANKLINE;
978
979
0
  return a_width - b_width;
980
0
}
981
982
static int cmp_in_block_with_wsd(const struct moved_entry *cur,
983
         const struct emitted_diff_symbol *l,
984
         struct moved_block *pmb)
985
0
{
986
0
  int a_width = cur->es->indent_width, b_width = l->indent_width;
987
0
  int delta;
988
989
  /* The text of each line must match */
990
0
  if (cur->es->id != l->id)
991
0
    return 1;
992
993
  /*
994
   * If 'l' and 'cur' are both blank then we don't need to check the
995
   * indent. We only need to check cur as we know the strings match.
996
   * */
997
0
  if (a_width == INDENT_BLANKLINE)
998
0
    return 0;
999
1000
  /*
1001
   * The indent changes of the block are known and stored in pmb->wsd;
1002
   * however we need to check if the indent changes of the current line
1003
   * match those of the current block.
1004
   */
1005
0
  delta = b_width - a_width;
1006
1007
  /*
1008
   * If the previous lines of this block were all blank then set its
1009
   * whitespace delta.
1010
   */
1011
0
  if (pmb->wsd == INDENT_BLANKLINE)
1012
0
    pmb->wsd = delta;
1013
1014
0
  return delta != pmb->wsd;
1015
0
}
1016
1017
struct interned_diff_symbol {
1018
  struct hashmap_entry ent;
1019
  struct emitted_diff_symbol *es;
1020
};
1021
1022
static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
1023
            const struct hashmap_entry *eptr,
1024
            const struct hashmap_entry *entry_or_key,
1025
            const void *keydata UNUSED)
1026
0
{
1027
0
  const struct diff_options *diffopt = hashmap_cmp_fn_data;
1028
0
  const struct emitted_diff_symbol *a, *b;
1029
0
  unsigned flags = diffopt->color_moved_ws_handling
1030
0
       & XDF_WHITESPACE_FLAGS;
1031
1032
0
  a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
1033
0
  b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
1034
1035
0
  return !xdiff_compare_lines(a->line + a->indent_off,
1036
0
            a->len - a->indent_off,
1037
0
            b->line + b->indent_off,
1038
0
            b->len - b->indent_off, flags);
1039
0
}
1040
1041
static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
1042
        struct interned_diff_symbol *s)
1043
0
{
1044
0
  unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
1045
0
  unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
1046
0
                l->len - l->indent_off, flags);
1047
1048
0
  hashmap_entry_init(&s->ent, hash);
1049
0
  s->es = l;
1050
0
}
1051
1052
struct moved_entry_list {
1053
  struct moved_entry *add, *del;
1054
};
1055
1056
static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
1057
                  struct mem_pool *entry_mem_pool)
1058
0
{
1059
0
  struct moved_entry *prev_line = NULL;
1060
0
  struct mem_pool interned_pool;
1061
0
  struct hashmap interned_map;
1062
0
  struct moved_entry_list *entry_list = NULL;
1063
0
  size_t entry_list_alloc = 0;
1064
0
  unsigned id = 0;
1065
0
  int n;
1066
1067
0
  hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
1068
0
  mem_pool_init(&interned_pool, 1024 * 1024);
1069
1070
0
  for (n = 0; n < o->emitted_symbols->nr; n++) {
1071
0
    struct interned_diff_symbol key;
1072
0
    struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1073
0
    struct interned_diff_symbol *s;
1074
0
    struct moved_entry *entry;
1075
1076
0
    if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
1077
0
      prev_line = NULL;
1078
0
      continue;
1079
0
    }
1080
1081
0
    if (o->color_moved_ws_handling &
1082
0
        COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1083
0
      fill_es_indent_data(l);
1084
1085
0
    prepare_entry(o, l, &key);
1086
0
    s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1087
0
    if (s) {
1088
0
      l->id = s->es->id;
1089
0
    } else {
1090
0
      l->id = id;
1091
0
      ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1092
0
      hashmap_add(&interned_map,
1093
0
            memcpy(mem_pool_alloc(&interned_pool,
1094
0
                sizeof(key)),
1095
0
             &key, sizeof(key)));
1096
0
    }
1097
0
    entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1098
0
    entry->es = l;
1099
0
    entry->next_line = NULL;
1100
0
    if (prev_line && prev_line->es->s == l->s)
1101
0
      prev_line->next_line = entry;
1102
0
    prev_line = entry;
1103
0
    if (l->s == DIFF_SYMBOL_PLUS) {
1104
0
      entry->next_match = entry_list[l->id].add;
1105
0
      entry_list[l->id].add = entry;
1106
0
    } else {
1107
0
      entry->next_match = entry_list[l->id].del;
1108
0
      entry_list[l->id].del = entry;
1109
0
    }
1110
0
  }
1111
1112
0
  hashmap_clear(&interned_map);
1113
0
  mem_pool_discard(&interned_pool, 0);
1114
1115
0
  return entry_list;
1116
0
}
1117
1118
static void pmb_advance_or_null(struct diff_options *o,
1119
        struct emitted_diff_symbol *l,
1120
        struct moved_block *pmb,
1121
        int *pmb_nr)
1122
0
{
1123
0
  int i, j;
1124
1125
0
  for (i = 0, j = 0; i < *pmb_nr; i++) {
1126
0
    int match;
1127
0
    struct moved_entry *prev = pmb[i].match;
1128
0
    struct moved_entry *cur = (prev && prev->next_line) ?
1129
0
        prev->next_line : NULL;
1130
1131
0
    if (o->color_moved_ws_handling &
1132
0
        COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1133
0
      match = cur &&
1134
0
        !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1135
0
    else
1136
0
      match = cur && cur->es->id == l->id;
1137
1138
0
    if (match) {
1139
0
      pmb[j] = pmb[i];
1140
0
      pmb[j++].match = cur;
1141
0
    }
1142
0
  }
1143
0
  *pmb_nr = j;
1144
0
}
1145
1146
static void fill_potential_moved_blocks(struct diff_options *o,
1147
          struct moved_entry *match,
1148
          struct emitted_diff_symbol *l,
1149
          struct moved_block **pmb_p,
1150
          int *pmb_alloc_p, int *pmb_nr_p)
1151
1152
0
{
1153
0
  struct moved_block *pmb = *pmb_p;
1154
0
  int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1155
1156
  /*
1157
   * The current line is the start of a new block.
1158
   * Setup the set of potential blocks.
1159
   */
1160
0
  for (; match; match = match->next_match) {
1161
0
    ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1162
0
    if (o->color_moved_ws_handling &
1163
0
        COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1164
0
      pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1165
0
    else
1166
0
      pmb[pmb_nr].wsd = 0;
1167
0
    pmb[pmb_nr++].match = match;
1168
0
  }
1169
1170
0
  *pmb_p = pmb;
1171
0
  *pmb_alloc_p = pmb_alloc;
1172
0
  *pmb_nr_p = pmb_nr;
1173
0
}
1174
1175
/*
1176
 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1177
 *
1178
 * Otherwise, if the last block has fewer alphanumeric characters than
1179
 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1180
 * that block.
1181
 *
1182
 * The last block consists of the (n - block_length)'th line up to but not
1183
 * including the nth line.
1184
 *
1185
 * Returns 0 if the last block is empty or is unset by this function, non zero
1186
 * otherwise.
1187
 *
1188
 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1189
 * Think of a way to unify them.
1190
 */
1191
#define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1192
0
  (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1193
static int adjust_last_block(struct diff_options *o, int n, int block_length)
1194
0
{
1195
0
  int i, alnum_count = 0;
1196
0
  if (o->color_moved == COLOR_MOVED_PLAIN)
1197
0
    return block_length;
1198
0
  for (i = 1; i < block_length + 1; i++) {
1199
0
    const char *c = o->emitted_symbols->buf[n - i].line;
1200
0
    for (; *c; c++) {
1201
0
      if (!isalnum(*c))
1202
0
        continue;
1203
0
      alnum_count++;
1204
0
      if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1205
0
        return 1;
1206
0
    }
1207
0
  }
1208
0
  for (i = 1; i < block_length + 1; i++)
1209
0
    o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1210
0
  return 0;
1211
0
}
1212
1213
/* Find blocks of moved code, delegate actual coloring decision to helper */
1214
static void mark_color_as_moved(struct diff_options *o,
1215
        struct moved_entry_list *entry_list)
1216
0
{
1217
0
  struct moved_block *pmb = NULL; /* potentially moved blocks */
1218
0
  int pmb_nr = 0, pmb_alloc = 0;
1219
0
  int n, flipped_block = 0, block_length = 0;
1220
0
  enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1221
1222
1223
0
  for (n = 0; n < o->emitted_symbols->nr; n++) {
1224
0
    struct moved_entry *match = NULL;
1225
0
    struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1226
1227
0
    switch (l->s) {
1228
0
    case DIFF_SYMBOL_PLUS:
1229
0
      match = entry_list[l->id].del;
1230
0
      break;
1231
0
    case DIFF_SYMBOL_MINUS:
1232
0
      match = entry_list[l->id].add;
1233
0
      break;
1234
0
    default:
1235
0
      flipped_block = 0;
1236
0
    }
1237
1238
0
    if (pmb_nr && (!match || l->s != moved_symbol)) {
1239
0
      if (!adjust_last_block(o, n, block_length) &&
1240
0
          block_length > 1) {
1241
        /*
1242
         * Rewind in case there is another match
1243
         * starting at the second line of the block
1244
         */
1245
0
        match = NULL;
1246
0
        n -= block_length;
1247
0
      }
1248
0
      pmb_nr = 0;
1249
0
      block_length = 0;
1250
0
      flipped_block = 0;
1251
0
    }
1252
0
    if (!match) {
1253
0
      moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1254
0
      continue;
1255
0
    }
1256
1257
0
    if (o->color_moved == COLOR_MOVED_PLAIN) {
1258
0
      l->flags |= DIFF_SYMBOL_MOVED_LINE;
1259
0
      continue;
1260
0
    }
1261
1262
0
    pmb_advance_or_null(o, l, pmb, &pmb_nr);
1263
1264
0
    if (pmb_nr == 0) {
1265
0
      int contiguous = adjust_last_block(o, n, block_length);
1266
1267
0
      if (!contiguous && block_length > 1)
1268
        /*
1269
         * Rewind in case there is another match
1270
         * starting at the second line of the block
1271
         */
1272
0
        n -= block_length;
1273
0
      else
1274
0
        fill_potential_moved_blocks(o, match, l,
1275
0
                  &pmb, &pmb_alloc,
1276
0
                  &pmb_nr);
1277
1278
0
      if (contiguous && pmb_nr && moved_symbol == l->s)
1279
0
        flipped_block = (flipped_block + 1) % 2;
1280
0
      else
1281
0
        flipped_block = 0;
1282
1283
0
      if (pmb_nr)
1284
0
        moved_symbol = l->s;
1285
0
      else
1286
0
        moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1287
1288
0
      block_length = 0;
1289
0
    }
1290
1291
0
    if (pmb_nr) {
1292
0
      block_length++;
1293
0
      l->flags |= DIFF_SYMBOL_MOVED_LINE;
1294
0
      if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1295
0
        l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1296
0
    }
1297
0
  }
1298
0
  adjust_last_block(o, n, block_length);
1299
1300
0
  free(pmb);
1301
0
}
1302
1303
static void dim_moved_lines(struct diff_options *o)
1304
0
{
1305
0
  int n;
1306
0
  for (n = 0; n < o->emitted_symbols->nr; n++) {
1307
0
    struct emitted_diff_symbol *prev = (n != 0) ?
1308
0
        &o->emitted_symbols->buf[n - 1] : NULL;
1309
0
    struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1310
0
    struct emitted_diff_symbol *next =
1311
0
        (n < o->emitted_symbols->nr - 1) ?
1312
0
        &o->emitted_symbols->buf[n + 1] : NULL;
1313
1314
    /* Not a plus or minus line? */
1315
0
    if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1316
0
      continue;
1317
1318
    /* Not a moved line? */
1319
0
    if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1320
0
      continue;
1321
1322
    /*
1323
     * If prev or next are not a plus or minus line,
1324
     * pretend they don't exist
1325
     */
1326
0
    if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1327
0
          prev->s != DIFF_SYMBOL_MINUS)
1328
0
      prev = NULL;
1329
0
    if (next && next->s != DIFF_SYMBOL_PLUS &&
1330
0
          next->s != DIFF_SYMBOL_MINUS)
1331
0
      next = NULL;
1332
1333
    /* Inside a block? */
1334
0
    if ((prev &&
1335
0
        (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1336
0
        (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1337
0
        (next &&
1338
0
        (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1339
0
        (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1340
0
      l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1341
0
      continue;
1342
0
    }
1343
1344
    /* Check if we are at an interesting bound: */
1345
0
    if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1346
0
        (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1347
0
           (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1348
0
      continue;
1349
0
    if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1350
0
        (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1351
0
           (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1352
0
      continue;
1353
1354
    /*
1355
     * The boundary to prev and next are not interesting,
1356
     * so this line is not interesting as a whole
1357
     */
1358
0
    l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1359
0
  }
1360
0
}
1361
1362
static void emit_line_ws_markup(struct diff_options *o,
1363
        const char *set_sign, const char *set,
1364
        const char *reset,
1365
        int sign_index, const char *line, int len,
1366
        unsigned ws_rule, int blank_at_eof)
1367
0
{
1368
0
  const char *ws = NULL;
1369
0
  int sign = o->output_indicators[sign_index];
1370
1371
0
  if (diff_suppress_blank_empty &&
1372
0
      sign_index == OUTPUT_INDICATOR_CONTEXT &&
1373
0
      len == 1 && line[0] == '\n')
1374
0
    sign = 0;
1375
1376
0
  if (o->ws_error_highlight & ws_rule) {
1377
0
    ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1378
0
    if (!*ws)
1379
0
      ws = NULL;
1380
0
  }
1381
1382
0
  if (!ws && !set_sign) {
1383
0
    emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1384
0
  } else if (!ws) {
1385
0
    emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1386
0
  } else if (blank_at_eof) {
1387
    /* Blank line at EOF - paint '+' as well */
1388
0
    emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1389
0
  } else {
1390
    /* Emit just the prefix, then the rest. */
1391
0
    emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1392
0
          sign, "", 0);
1393
0
    ws_check_emit(line, len, ws_rule,
1394
0
            o->file, set, reset, ws);
1395
0
  }
1396
0
}
1397
1398
static void emit_diff_symbol_from_struct(struct diff_options *o,
1399
           struct emitted_diff_symbol *eds)
1400
0
{
1401
0
  const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1402
1403
0
  enum diff_symbol s = eds->s;
1404
0
  const char *line = eds->line;
1405
0
  int len = eds->len;
1406
0
  unsigned flags = eds->flags;
1407
1408
0
  if (!o->file)
1409
0
    return;
1410
1411
0
  switch (s) {
1412
0
  case DIFF_SYMBOL_SUBMODULE_HEADER:
1413
0
  case DIFF_SYMBOL_SUBMODULE_ERROR:
1414
0
  case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1415
0
  case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1416
0
  case DIFF_SYMBOL_SUMMARY:
1417
0
  case DIFF_SYMBOL_STATS_LINE:
1418
0
  case DIFF_SYMBOL_BINARY_DIFF_BODY:
1419
0
  case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1420
0
    emit_line(o, "", "", line, len);
1421
0
    break;
1422
0
  case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1423
0
    if ((flags & WS_INCOMPLETE_LINE) &&
1424
0
        (flags & o->ws_error_highlight))
1425
0
      set = diff_get_color_opt(o, DIFF_WHITESPACE);
1426
0
    else
1427
0
      set = diff_get_color_opt(o, DIFF_CONTEXT);
1428
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1429
0
    emit_line(o, set, reset, line, len);
1430
0
    break;
1431
0
  case DIFF_SYMBOL_CONTEXT_MARKER:
1432
0
    context = diff_get_color_opt(o, DIFF_CONTEXT);
1433
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1434
0
    emit_line(o, context, reset, line, len);
1435
0
    break;
1436
0
  case DIFF_SYMBOL_SEPARATOR:
1437
0
    fprintf(o->file, "%s%c",
1438
0
      diff_line_prefix(o),
1439
0
      o->line_termination);
1440
0
    break;
1441
0
  case DIFF_SYMBOL_CONTEXT:
1442
0
    set = diff_get_color_opt(o, DIFF_CONTEXT);
1443
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1444
0
    set_sign = NULL;
1445
0
    if (o->flags.dual_color_diffed_diffs) {
1446
0
      char c = !len ? 0 : line[0];
1447
1448
0
      if (c == '+')
1449
0
        set = diff_get_color_opt(o, DIFF_FILE_NEW);
1450
0
      else if (c == '@')
1451
0
        set = diff_get_color_opt(o, DIFF_FRAGINFO);
1452
0
      else if (c == '-')
1453
0
        set = diff_get_color_opt(o, DIFF_FILE_OLD);
1454
0
    }
1455
0
    emit_line_ws_markup(o, set_sign, set, reset,
1456
0
            OUTPUT_INDICATOR_CONTEXT, line, len,
1457
0
            flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1458
0
    break;
1459
0
  case DIFF_SYMBOL_PLUS:
1460
0
    switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1461
0
         DIFF_SYMBOL_MOVED_LINE_ALT |
1462
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1463
0
    case DIFF_SYMBOL_MOVED_LINE |
1464
0
         DIFF_SYMBOL_MOVED_LINE_ALT |
1465
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1466
0
      set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1467
0
      break;
1468
0
    case DIFF_SYMBOL_MOVED_LINE |
1469
0
         DIFF_SYMBOL_MOVED_LINE_ALT:
1470
0
      set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1471
0
      break;
1472
0
    case DIFF_SYMBOL_MOVED_LINE |
1473
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1474
0
      set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1475
0
      break;
1476
0
    case DIFF_SYMBOL_MOVED_LINE:
1477
0
      set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1478
0
      break;
1479
0
    default:
1480
0
      set = diff_get_color_opt(o, DIFF_FILE_NEW);
1481
0
    }
1482
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1483
0
    if (!o->flags.dual_color_diffed_diffs)
1484
0
      set_sign = NULL;
1485
0
    else {
1486
0
      char c = !len ? 0 : line[0];
1487
1488
0
      set_sign = set;
1489
0
      if (c == '-')
1490
0
        set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1491
0
      else if (c == '@')
1492
0
        set = diff_get_color_opt(o, DIFF_FRAGINFO);
1493
0
      else if (c == '+')
1494
0
        set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1495
0
      else
1496
0
        set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1497
0
      flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1498
0
    }
1499
0
    emit_line_ws_markup(o, set_sign, set, reset,
1500
0
            OUTPUT_INDICATOR_NEW, line, len,
1501
0
            flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1502
0
            flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1503
0
    break;
1504
0
  case DIFF_SYMBOL_MINUS:
1505
0
    switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1506
0
         DIFF_SYMBOL_MOVED_LINE_ALT |
1507
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1508
0
    case DIFF_SYMBOL_MOVED_LINE |
1509
0
         DIFF_SYMBOL_MOVED_LINE_ALT |
1510
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1511
0
      set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1512
0
      break;
1513
0
    case DIFF_SYMBOL_MOVED_LINE |
1514
0
         DIFF_SYMBOL_MOVED_LINE_ALT:
1515
0
      set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1516
0
      break;
1517
0
    case DIFF_SYMBOL_MOVED_LINE |
1518
0
         DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1519
0
      set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1520
0
      break;
1521
0
    case DIFF_SYMBOL_MOVED_LINE:
1522
0
      set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1523
0
      break;
1524
0
    default:
1525
0
      set = diff_get_color_opt(o, DIFF_FILE_OLD);
1526
0
    }
1527
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1528
0
    if (!o->flags.dual_color_diffed_diffs)
1529
0
      set_sign = NULL;
1530
0
    else {
1531
0
      char c = !len ? 0 : line[0];
1532
1533
0
      set_sign = set;
1534
0
      if (c == '+')
1535
0
        set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1536
0
      else if (c == '@')
1537
0
        set = diff_get_color_opt(o, DIFF_FRAGINFO);
1538
0
      else if (c == '-')
1539
0
        set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1540
0
      else
1541
0
        set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1542
0
    }
1543
0
    emit_line_ws_markup(o, set_sign, set, reset,
1544
0
            OUTPUT_INDICATOR_OLD, line, len,
1545
0
            flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1546
0
    break;
1547
0
  case DIFF_SYMBOL_WORDS_PORCELAIN:
1548
0
    context = diff_get_color_opt(o, DIFF_CONTEXT);
1549
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1550
0
    emit_line(o, context, reset, line, len);
1551
0
    fputs("~\n", o->file);
1552
0
    break;
1553
0
  case DIFF_SYMBOL_WORDS:
1554
0
    context = diff_get_color_opt(o, DIFF_CONTEXT);
1555
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1556
1557
    /* Skip the prefix character */
1558
0
    line++; len--;
1559
0
    emit_line(o, context, reset, line, len);
1560
0
    break;
1561
0
  case DIFF_SYMBOL_FILEPAIR_PLUS:
1562
0
    meta = diff_get_color_opt(o, DIFF_METAINFO);
1563
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1564
0
    fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1565
0
      line, reset,
1566
0
      strchr(line, ' ') ? "\t" : "");
1567
0
    break;
1568
0
  case DIFF_SYMBOL_FILEPAIR_MINUS:
1569
0
    meta = diff_get_color_opt(o, DIFF_METAINFO);
1570
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1571
0
    fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1572
0
      line, reset,
1573
0
      strchr(line, ' ') ? "\t" : "");
1574
0
    break;
1575
0
  case DIFF_SYMBOL_BINARY_FILES:
1576
0
  case DIFF_SYMBOL_HEADER:
1577
0
    fprintf(o->file, "%s", line);
1578
0
    break;
1579
0
  case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1580
0
    fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1581
0
    break;
1582
0
  case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1583
0
    fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1584
0
    break;
1585
0
  case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1586
0
    fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1587
0
    break;
1588
0
  case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1589
0
    fputs(diff_line_prefix(o), o->file);
1590
0
    fputc('\n', o->file);
1591
0
    break;
1592
0
  case DIFF_SYMBOL_REWRITE_DIFF:
1593
0
    fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1594
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1595
0
    emit_line(o, fraginfo, reset, line, len);
1596
0
    break;
1597
0
  case DIFF_SYMBOL_SUBMODULE_ADD:
1598
0
    set = diff_get_color_opt(o, DIFF_FILE_NEW);
1599
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1600
0
    emit_line(o, set, reset, line, len);
1601
0
    break;
1602
0
  case DIFF_SYMBOL_SUBMODULE_DEL:
1603
0
    set = diff_get_color_opt(o, DIFF_FILE_OLD);
1604
0
    reset = diff_get_color_opt(o, DIFF_RESET);
1605
0
    emit_line(o, set, reset, line, len);
1606
0
    break;
1607
0
  case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1608
0
    fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1609
0
      diff_line_prefix(o), line);
1610
0
    break;
1611
0
  case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1612
0
    fprintf(o->file, "%sSubmodule %s contains modified content\n",
1613
0
      diff_line_prefix(o), line);
1614
0
    break;
1615
0
  case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1616
0
    emit_line(o, "", "", " 0 files changed\n",
1617
0
        strlen(" 0 files changed\n"));
1618
0
    break;
1619
0
  case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1620
0
    emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1621
0
    break;
1622
0
  case DIFF_SYMBOL_WORD_DIFF:
1623
0
    fprintf(o->file, "%.*s", len, line);
1624
0
    break;
1625
0
  case DIFF_SYMBOL_STAT_SEP:
1626
0
    fputs(o->stat_sep, o->file);
1627
0
    break;
1628
0
  default:
1629
0
    BUG("unknown diff symbol");
1630
0
  }
1631
0
}
1632
1633
static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1634
           const char *line, int len, unsigned flags)
1635
0
{
1636
0
  struct emitted_diff_symbol e = {
1637
0
    .line = line, .len = len, .flags = flags, .s = s
1638
0
  };
1639
1640
0
  if (o->emitted_symbols)
1641
0
    append_emitted_diff_symbol(o, &e);
1642
0
  else
1643
0
    emit_diff_symbol_from_struct(o, &e);
1644
0
}
1645
1646
void diff_emit_submodule_del(struct diff_options *o, const char *line)
1647
0
{
1648
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1649
0
}
1650
1651
void diff_emit_submodule_add(struct diff_options *o, const char *line)
1652
0
{
1653
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1654
0
}
1655
1656
void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1657
0
{
1658
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1659
0
       path, strlen(path), 0);
1660
0
}
1661
1662
void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1663
0
{
1664
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1665
0
       path, strlen(path), 0);
1666
0
}
1667
1668
void diff_emit_submodule_header(struct diff_options *o, const char *header)
1669
0
{
1670
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1671
0
       header, strlen(header), 0);
1672
0
}
1673
1674
void diff_emit_submodule_error(struct diff_options *o, const char *err)
1675
0
{
1676
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1677
0
}
1678
1679
void diff_emit_submodule_pipethrough(struct diff_options *o,
1680
             const char *line, int len)
1681
0
{
1682
0
  emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1683
0
}
1684
1685
static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1686
0
{
1687
0
  if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1688
0
        ecbdata->blank_at_eof_in_preimage &&
1689
0
        ecbdata->blank_at_eof_in_postimage &&
1690
0
        ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1691
0
        ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1692
0
    return 0;
1693
0
  return ws_blank_line(line, len);
1694
0
}
1695
1696
static void emit_add_line(struct emit_callback *ecbdata,
1697
        const char *line, int len)
1698
0
{
1699
0
  unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1700
0
  if (new_blank_line_at_eof(ecbdata, line, len))
1701
0
    flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1702
1703
0
  emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1704
0
}
1705
1706
static void emit_del_line(struct emit_callback *ecbdata,
1707
        const char *line, int len)
1708
0
{
1709
0
  unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1710
0
  emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1711
0
}
1712
1713
static void emit_context_line(struct emit_callback *ecbdata,
1714
            const char *line, int len)
1715
0
{
1716
0
  unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1717
0
  emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1718
0
}
1719
1720
static void emit_incomplete_line_marker(struct emit_callback *ecbdata,
1721
          const char *line, int len)
1722
0
{
1723
0
  int last_line_kind = ecbdata->last_line_kind;
1724
0
  unsigned flags = (last_line_kind == '+'
1725
0
        ? WSEH_NEW
1726
0
        : last_line_kind == '-'
1727
0
        ? WSEH_OLD
1728
0
        : WSEH_CONTEXT) | ecbdata->ws_rule;
1729
0
  emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1730
0
       line, len, flags);
1731
0
}
1732
1733
static void emit_hunk_header(struct emit_callback *ecbdata,
1734
           const char *line, int len)
1735
0
{
1736
0
  const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1737
0
  const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1738
0
  const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1739
0
  const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1740
0
  const char *reverse = want_color(ecbdata->color_diff) ? GIT_COLOR_REVERSE : "";
1741
0
  static const char atat[2] = { '@', '@' };
1742
0
  const char *cp, *ep;
1743
0
  struct strbuf msgbuf = STRBUF_INIT;
1744
0
  int org_len = len;
1745
0
  int i = 1;
1746
1747
  /*
1748
   * As a hunk header must begin with "@@ -<old>, +<new> @@",
1749
   * it always is at least 10 bytes long.
1750
   */
1751
0
  if (len < 10 ||
1752
0
      memcmp(line, atat, 2) ||
1753
0
      !(ep = memmem(line + 2, len - 2, atat, 2))) {
1754
0
    emit_diff_symbol(ecbdata->opt,
1755
0
         DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1756
0
    return;
1757
0
  }
1758
0
  ep += 2; /* skip over @@ */
1759
1760
  /* The hunk header in fraginfo color */
1761
0
  if (ecbdata->opt->flags.dual_color_diffed_diffs)
1762
0
    strbuf_addstr(&msgbuf, reverse);
1763
0
  strbuf_addstr(&msgbuf, frag);
1764
0
  if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1765
0
    strbuf_add(&msgbuf, atat, sizeof(atat));
1766
0
  else
1767
0
    strbuf_add(&msgbuf, line, ep - line);
1768
0
  strbuf_addstr(&msgbuf, reset);
1769
1770
  /*
1771
   * trailing "\r\n"
1772
   */
1773
0
  for ( ; i < 3; i++)
1774
0
    if (line[len - i] == '\r' || line[len - i] == '\n')
1775
0
      len--;
1776
1777
  /* blank before the func header */
1778
0
  for (cp = ep; ep - line < len; ep++)
1779
0
    if (*ep != ' ' && *ep != '\t')
1780
0
      break;
1781
0
  if (ep != cp) {
1782
0
    strbuf_addstr(&msgbuf, context);
1783
0
    strbuf_add(&msgbuf, cp, ep - cp);
1784
0
    strbuf_addstr(&msgbuf, reset);
1785
0
  }
1786
1787
0
  if (ep < line + len) {
1788
0
    strbuf_addstr(&msgbuf, func);
1789
0
    strbuf_add(&msgbuf, ep, line + len - ep);
1790
0
    strbuf_addstr(&msgbuf, reset);
1791
0
  }
1792
1793
0
  strbuf_add(&msgbuf, line + len, org_len - len);
1794
0
  strbuf_complete_line(&msgbuf);
1795
0
  emit_diff_symbol(ecbdata->opt,
1796
0
       DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1797
0
  strbuf_release(&msgbuf);
1798
0
}
1799
1800
static struct diff_tempfile *claim_diff_tempfile(void)
1801
0
{
1802
0
  int i;
1803
0
  for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1804
0
    if (!diff_temp[i].name)
1805
0
      return diff_temp + i;
1806
0
  BUG("diff is failing to clean up its tempfiles");
1807
0
}
1808
1809
static void remove_tempfile(void)
1810
0
{
1811
0
  int i;
1812
0
  for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1813
0
    if (is_tempfile_active(diff_temp[i].tempfile))
1814
0
      delete_tempfile(&diff_temp[i].tempfile);
1815
0
    diff_temp[i].name = NULL;
1816
0
  }
1817
0
}
1818
1819
static void add_line_count(struct strbuf *out, int count)
1820
0
{
1821
0
  switch (count) {
1822
0
  case 0:
1823
0
    strbuf_addstr(out, "0,0");
1824
0
    break;
1825
0
  case 1:
1826
0
    strbuf_addstr(out, "1");
1827
0
    break;
1828
0
  default:
1829
0
    strbuf_addf(out, "1,%d", count);
1830
0
    break;
1831
0
  }
1832
0
}
1833
1834
static void emit_rewrite_lines(struct emit_callback *ecbdata,
1835
             int prefix, const char *data, int size)
1836
0
{
1837
0
  const char *endp = NULL;
1838
1839
0
  while (0 < size) {
1840
0
    int len, plen;
1841
0
    char *pdata = NULL;
1842
1843
0
    endp = memchr(data, '\n', size);
1844
1845
0
    if (endp) {
1846
0
      len = endp - data + 1;
1847
0
      plen = len;
1848
0
    } else {
1849
0
      len = size;
1850
0
      plen = len + 1;
1851
0
      pdata = xmalloc(plen + 2);
1852
0
      memcpy(pdata, data, len);
1853
0
      pdata[len] = '\n';
1854
0
      pdata[len + 1] = '\0';
1855
0
    }
1856
0
    if (prefix != '+') {
1857
0
      ecbdata->lno_in_preimage++;
1858
0
      emit_del_line(ecbdata, pdata ? pdata : data, plen);
1859
0
    } else {
1860
0
      ecbdata->lno_in_postimage++;
1861
0
      emit_add_line(ecbdata, pdata ? pdata : data, plen);
1862
0
    }
1863
0
    free(pdata);
1864
0
    size -= len;
1865
0
    data += len;
1866
0
  }
1867
0
  if (!endp) {
1868
0
    static const char nneof[] = "\\ No newline at end of file\n";
1869
0
    ecbdata->last_line_kind = prefix;
1870
0
    emit_incomplete_line_marker(ecbdata, nneof, sizeof(nneof) - 1);
1871
0
  }
1872
0
}
1873
1874
static void emit_rewrite_diff(const char *name_a,
1875
            const char *name_b,
1876
            struct diff_filespec *one,
1877
            struct diff_filespec *two,
1878
            struct userdiff_driver *textconv_one,
1879
            struct userdiff_driver *textconv_two,
1880
            struct diff_options *o)
1881
0
{
1882
0
  int lc_a, lc_b;
1883
0
  static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1884
0
  const char *a_prefix, *b_prefix;
1885
0
  char *data_one, *data_two;
1886
0
  size_t size_one, size_two;
1887
0
  unsigned ws_rule;
1888
0
  struct emit_callback ecbdata;
1889
0
  struct strbuf out = STRBUF_INIT;
1890
1891
0
  if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1892
0
    a_prefix = o->b_prefix;
1893
0
    b_prefix = o->a_prefix;
1894
0
  } else {
1895
0
    a_prefix = o->a_prefix;
1896
0
    b_prefix = o->b_prefix;
1897
0
  }
1898
1899
0
  name_a += (*name_a == '/');
1900
0
  name_b += (*name_b == '/');
1901
1902
0
  strbuf_reset(&a_name);
1903
0
  strbuf_reset(&b_name);
1904
0
  quote_two_c_style(&a_name, a_prefix, name_a, 0);
1905
0
  quote_two_c_style(&b_name, b_prefix, name_b, 0);
1906
1907
0
  size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1908
0
  size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1909
1910
0
  ws_rule = whitespace_rule(o->repo->index, name_b);
1911
1912
  /* symlink being an incomplete line is not a news */
1913
0
  if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
1914
0
    ws_rule &= ~WS_INCOMPLETE_LINE;
1915
1916
0
  memset(&ecbdata, 0, sizeof(ecbdata));
1917
0
  ecbdata.color_diff = o->use_color;
1918
0
  ecbdata.ws_rule = ws_rule;
1919
0
  ecbdata.opt = o;
1920
0
  if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1921
0
    mmfile_t mf1, mf2;
1922
0
    mf1.ptr = (char *)data_one;
1923
0
    mf2.ptr = (char *)data_two;
1924
0
    mf1.size = size_one;
1925
0
    mf2.size = size_two;
1926
0
    check_blank_at_eof(&mf1, &mf2, &ecbdata);
1927
0
  }
1928
0
  ecbdata.lno_in_preimage = 1;
1929
0
  ecbdata.lno_in_postimage = 1;
1930
1931
0
  lc_a = count_lines(data_one, size_one);
1932
0
  lc_b = count_lines(data_two, size_two);
1933
1934
0
  emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1935
0
       a_name.buf, a_name.len, 0);
1936
0
  emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1937
0
       b_name.buf, b_name.len, 0);
1938
1939
0
  strbuf_addstr(&out, "@@ -");
1940
0
  if (!o->irreversible_delete)
1941
0
    add_line_count(&out, lc_a);
1942
0
  else
1943
0
    strbuf_addstr(&out, "?,?");
1944
0
  strbuf_addstr(&out, " +");
1945
0
  add_line_count(&out, lc_b);
1946
0
  strbuf_addstr(&out, " @@\n");
1947
0
  emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1948
0
  strbuf_release(&out);
1949
1950
0
  if (lc_a && !o->irreversible_delete)
1951
0
    emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1952
0
  if (lc_b)
1953
0
    emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1954
0
  if (textconv_one)
1955
0
    free((char *)data_one);
1956
0
  if (textconv_two)
1957
0
    free((char *)data_two);
1958
0
}
1959
1960
struct diff_words_buffer {
1961
  mmfile_t text;
1962
  unsigned long alloc;
1963
  struct diff_words_orig {
1964
    const char *begin, *end;
1965
  } *orig;
1966
  int orig_nr, orig_alloc;
1967
};
1968
1969
static void diff_words_append(char *line, unsigned long len,
1970
    struct diff_words_buffer *buffer)
1971
0
{
1972
0
  ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1973
0
  line++;
1974
0
  len--;
1975
0
  memcpy(buffer->text.ptr + buffer->text.size, line, len);
1976
0
  buffer->text.size += len;
1977
0
  buffer->text.ptr[buffer->text.size] = '\0';
1978
0
}
1979
1980
struct diff_words_style_elem {
1981
  const char *prefix;
1982
  const char *suffix;
1983
  const char *color; /* NULL; filled in by the setup code if
1984
          * color is enabled */
1985
};
1986
1987
struct diff_words_style {
1988
  enum diff_words_type type;
1989
  struct diff_words_style_elem new_word, old_word, ctx;
1990
  const char *newline;
1991
};
1992
1993
static struct diff_words_style diff_words_styles[] = {
1994
  { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1995
  { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1996
  { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1997
};
1998
1999
struct diff_words_data {
2000
  struct diff_words_buffer minus, plus;
2001
  const char *current_plus;
2002
  int last_minus;
2003
  struct diff_options *opt;
2004
  regex_t *word_regex;
2005
  enum diff_words_type type;
2006
  struct diff_words_style *style;
2007
};
2008
2009
static int fn_out_diff_words_write_helper(struct diff_options *o,
2010
            struct diff_words_style_elem *st_el,
2011
            const char *newline,
2012
            size_t count, const char *buf)
2013
0
{
2014
0
  int print = 0;
2015
0
  struct strbuf sb = STRBUF_INIT;
2016
2017
0
  while (count) {
2018
0
    const char *p = memchr(buf, '\n', count);
2019
0
    if (print)
2020
0
      strbuf_addstr(&sb, diff_line_prefix(o));
2021
2022
0
    if (p != buf) {
2023
0
      const char *reset = st_el->color && *st_el->color ?
2024
0
              GIT_COLOR_RESET : NULL;
2025
0
      if (st_el->color && *st_el->color)
2026
0
        strbuf_addstr(&sb, st_el->color);
2027
0
      strbuf_addstr(&sb, st_el->prefix);
2028
0
      strbuf_add(&sb, buf, p ? p - buf : count);
2029
0
      strbuf_addstr(&sb, st_el->suffix);
2030
0
      if (reset)
2031
0
        strbuf_addstr(&sb, reset);
2032
0
    }
2033
0
    if (!p)
2034
0
      goto out;
2035
2036
0
    strbuf_addstr(&sb, newline);
2037
0
    count -= p + 1 - buf;
2038
0
    buf = p + 1;
2039
0
    print = 1;
2040
0
    if (count) {
2041
0
      emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
2042
0
           sb.buf, sb.len, 0);
2043
0
      strbuf_reset(&sb);
2044
0
    }
2045
0
  }
2046
2047
0
out:
2048
0
  if (sb.len)
2049
0
    emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
2050
0
         sb.buf, sb.len, 0);
2051
0
  strbuf_release(&sb);
2052
0
  return 0;
2053
0
}
2054
2055
/*
2056
 * '--color-words' algorithm can be described as:
2057
 *
2058
 *   1. collect the minus/plus lines of a diff hunk, divided into
2059
 *      minus-lines and plus-lines;
2060
 *
2061
 *   2. break both minus-lines and plus-lines into words and
2062
 *      place them into two mmfile_t with one word for each line;
2063
 *
2064
 *   3. use xdiff to run diff on the two mmfile_t to get the words level diff;
2065
 *
2066
 * And for the common parts of the both file, we output the plus side text.
2067
 * diff_words->current_plus is used to trace the current position of the plus file
2068
 * which printed. diff_words->last_minus is used to trace the last minus word
2069
 * printed.
2070
 *
2071
 * For '--graph' to work with '--color-words', we need to output the graph prefix
2072
 * on each line of color words output. Generally, there are two conditions on
2073
 * which we should output the prefix.
2074
 *
2075
 *   1. diff_words->last_minus == 0 &&
2076
 *      diff_words->current_plus == diff_words->plus.text.ptr
2077
 *
2078
 *      that is: the plus text must start as a new line, and if there is no minus
2079
 *      word printed, a graph prefix must be printed.
2080
 *
2081
 *   2. diff_words->current_plus > diff_words->plus.text.ptr &&
2082
 *      *(diff_words->current_plus - 1) == '\n'
2083
 *
2084
 *      that is: a graph prefix must be printed following a '\n'
2085
 */
2086
static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
2087
0
{
2088
0
  if ((diff_words->last_minus == 0 &&
2089
0
    diff_words->current_plus == diff_words->plus.text.ptr) ||
2090
0
    (diff_words->current_plus > diff_words->plus.text.ptr &&
2091
0
    *(diff_words->current_plus - 1) == '\n')) {
2092
0
    return 1;
2093
0
  } else {
2094
0
    return 0;
2095
0
  }
2096
0
}
2097
2098
static void fn_out_diff_words_aux(void *priv,
2099
          long minus_first, long minus_len,
2100
          long plus_first, long plus_len,
2101
          const char *func UNUSED, long funclen UNUSED)
2102
0
{
2103
0
  struct diff_words_data *diff_words = priv;
2104
0
  struct diff_words_style *style = diff_words->style;
2105
0
  const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2106
0
  struct diff_options *opt = diff_words->opt;
2107
0
  const char *line_prefix;
2108
2109
0
  assert(opt);
2110
0
  line_prefix = diff_line_prefix(opt);
2111
2112
  /* POSIX requires that first be decremented by one if len == 0... */
2113
0
  if (minus_len) {
2114
0
    minus_begin = diff_words->minus.orig[minus_first].begin;
2115
0
    minus_end =
2116
0
      diff_words->minus.orig[minus_first + minus_len - 1].end;
2117
0
  } else
2118
0
    minus_begin = minus_end =
2119
0
      diff_words->minus.orig[minus_first].end;
2120
2121
0
  if (plus_len) {
2122
0
    plus_begin = diff_words->plus.orig[plus_first].begin;
2123
0
    plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2124
0
  } else
2125
0
    plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2126
2127
0
  if (color_words_output_graph_prefix(diff_words)) {
2128
0
    fputs(line_prefix, diff_words->opt->file);
2129
0
  }
2130
0
  if (diff_words->current_plus != plus_begin) {
2131
0
    fn_out_diff_words_write_helper(diff_words->opt,
2132
0
        &style->ctx, style->newline,
2133
0
        plus_begin - diff_words->current_plus,
2134
0
        diff_words->current_plus);
2135
0
  }
2136
0
  if (minus_begin != minus_end) {
2137
0
    fn_out_diff_words_write_helper(diff_words->opt,
2138
0
        &style->old_word, style->newline,
2139
0
        minus_end - minus_begin, minus_begin);
2140
0
  }
2141
0
  if (plus_begin != plus_end) {
2142
0
    fn_out_diff_words_write_helper(diff_words->opt,
2143
0
        &style->new_word, style->newline,
2144
0
        plus_end - plus_begin, plus_begin);
2145
0
  }
2146
2147
0
  diff_words->current_plus = plus_end;
2148
0
  diff_words->last_minus = minus_first;
2149
0
}
2150
2151
/* This function starts looking at *begin, and returns 0 iff a word was found. */
2152
static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2153
    int *begin, int *end)
2154
0
{
2155
0
  while (word_regex && *begin < buffer->size) {
2156
0
    regmatch_t match[1];
2157
0
    if (!regexec_buf(word_regex, buffer->ptr + *begin,
2158
0
         buffer->size - *begin, 1, match, 0)) {
2159
0
      char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2160
0
          '\n', match[0].rm_eo - match[0].rm_so);
2161
0
      *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2162
0
      *begin += match[0].rm_so;
2163
0
      if (*begin == *end)
2164
0
        (*begin)++;
2165
0
      else
2166
0
        return *begin > *end;
2167
0
    } else {
2168
0
      return -1;
2169
0
    }
2170
0
  }
2171
2172
  /* find the next word */
2173
0
  while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2174
0
    (*begin)++;
2175
0
  if (*begin >= buffer->size)
2176
0
    return -1;
2177
2178
  /* find the end of the word */
2179
0
  *end = *begin + 1;
2180
0
  while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2181
0
    (*end)++;
2182
2183
0
  return 0;
2184
0
}
2185
2186
/*
2187
 * This function splits the words in buffer->text, stores the list with
2188
 * newline separator into out, and saves the offsets of the original words
2189
 * in buffer->orig.
2190
 */
2191
static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2192
    regex_t *word_regex)
2193
0
{
2194
0
  int i, j;
2195
0
  long alloc = 0;
2196
2197
0
  out->size = 0;
2198
0
  out->ptr = NULL;
2199
2200
  /* fake an empty "0th" word */
2201
0
  ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2202
0
  buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2203
0
  buffer->orig_nr = 1;
2204
2205
0
  for (i = 0; i < buffer->text.size; i++) {
2206
0
    if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2207
0
      return;
2208
2209
    /* store original boundaries */
2210
0
    ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2211
0
        buffer->orig_alloc);
2212
0
    buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2213
0
    buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2214
0
    buffer->orig_nr++;
2215
2216
    /* store one word */
2217
0
    ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2218
0
    memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2219
0
    out->ptr[out->size + j - i] = '\n';
2220
0
    out->size += j - i + 1;
2221
2222
0
    i = j - 1;
2223
0
  }
2224
0
}
2225
2226
/* this executes the word diff on the accumulated buffers */
2227
static void diff_words_show(struct diff_words_data *diff_words)
2228
0
{
2229
0
  xpparam_t xpp;
2230
0
  xdemitconf_t xecfg;
2231
0
  mmfile_t minus, plus;
2232
0
  struct diff_words_style *style = diff_words->style;
2233
2234
0
  struct diff_options *opt = diff_words->opt;
2235
0
  const char *line_prefix;
2236
2237
0
  assert(opt);
2238
0
  line_prefix = diff_line_prefix(opt);
2239
2240
  /* special case: only removal */
2241
0
  if (!diff_words->plus.text.size) {
2242
0
    emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2243
0
         line_prefix, strlen(line_prefix), 0);
2244
0
    fn_out_diff_words_write_helper(diff_words->opt,
2245
0
      &style->old_word, style->newline,
2246
0
      diff_words->minus.text.size,
2247
0
      diff_words->minus.text.ptr);
2248
0
    diff_words->minus.text.size = 0;
2249
0
    return;
2250
0
  }
2251
2252
0
  diff_words->current_plus = diff_words->plus.text.ptr;
2253
0
  diff_words->last_minus = 0;
2254
2255
0
  memset(&xpp, 0, sizeof(xpp));
2256
0
  memset(&xecfg, 0, sizeof(xecfg));
2257
0
  diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2258
0
  diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2259
0
  xpp.flags = 0;
2260
  /* as only the hunk header will be parsed, we need a 0-context */
2261
0
  xecfg.ctxlen = 0;
2262
0
  if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2263
0
        diff_words, &xpp, &xecfg))
2264
0
    die("unable to generate word diff");
2265
0
  free(minus.ptr);
2266
0
  free(plus.ptr);
2267
0
  if (diff_words->current_plus != diff_words->plus.text.ptr +
2268
0
      diff_words->plus.text.size) {
2269
0
    if (color_words_output_graph_prefix(diff_words))
2270
0
      emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2271
0
           line_prefix, strlen(line_prefix), 0);
2272
0
    fn_out_diff_words_write_helper(diff_words->opt,
2273
0
      &style->ctx, style->newline,
2274
0
      diff_words->plus.text.ptr + diff_words->plus.text.size
2275
0
      - diff_words->current_plus, diff_words->current_plus);
2276
0
  }
2277
0
  diff_words->minus.text.size = diff_words->plus.text.size = 0;
2278
0
}
2279
2280
/* In "color-words" mode, show word-diff of words accumulated in the buffer */
2281
static void diff_words_flush(struct emit_callback *ecbdata)
2282
0
{
2283
0
  struct diff_options *wo = ecbdata->diff_words->opt;
2284
2285
0
  if (ecbdata->diff_words->minus.text.size ||
2286
0
      ecbdata->diff_words->plus.text.size)
2287
0
    diff_words_show(ecbdata->diff_words);
2288
2289
0
  if (wo->emitted_symbols) {
2290
0
    struct diff_options *o = ecbdata->opt;
2291
0
    struct emitted_diff_symbols *wol = wo->emitted_symbols;
2292
0
    int i;
2293
2294
    /*
2295
     * NEEDSWORK:
2296
     * Instead of appending each, concat all words to a line?
2297
     */
2298
0
    for (i = 0; i < wol->nr; i++)
2299
0
      append_emitted_diff_symbol(o, &wol->buf[i]);
2300
2301
0
    for (i = 0; i < wol->nr; i++)
2302
0
      free((void *)wol->buf[i].line);
2303
2304
0
    wol->nr = 0;
2305
0
  }
2306
0
}
2307
2308
static void diff_filespec_load_driver(struct diff_filespec *one,
2309
              struct index_state *istate)
2310
0
{
2311
  /* Use already-loaded driver */
2312
0
  if (one->driver)
2313
0
    return;
2314
2315
0
  if (S_ISREG(one->mode))
2316
0
    one->driver = userdiff_find_by_path(istate, one->path);
2317
2318
  /* Fallback to default settings */
2319
0
  if (!one->driver)
2320
0
    one->driver = userdiff_find_by_name("default");
2321
0
}
2322
2323
static const char *userdiff_word_regex(struct diff_filespec *one,
2324
               struct index_state *istate)
2325
0
{
2326
0
  diff_filespec_load_driver(one, istate);
2327
0
  return one->driver->word_regex;
2328
0
}
2329
2330
static void init_diff_words_data(struct emit_callback *ecbdata,
2331
         struct diff_options *orig_opts,
2332
         struct diff_filespec *one,
2333
         struct diff_filespec *two)
2334
0
{
2335
0
  int i;
2336
0
  struct diff_options *o = xmalloc(sizeof(struct diff_options));
2337
0
  memcpy(o, orig_opts, sizeof(struct diff_options));
2338
2339
0
  CALLOC_ARRAY(ecbdata->diff_words, 1);
2340
0
  ecbdata->diff_words->type = o->word_diff;
2341
0
  ecbdata->diff_words->opt = o;
2342
2343
0
  if (orig_opts->emitted_symbols)
2344
0
    CALLOC_ARRAY(o->emitted_symbols, 1);
2345
2346
0
  if (!o->word_regex)
2347
0
    o->word_regex = userdiff_word_regex(one, o->repo->index);
2348
0
  if (!o->word_regex)
2349
0
    o->word_regex = userdiff_word_regex(two, o->repo->index);
2350
0
  if (!o->word_regex)
2351
0
    o->word_regex = diff_word_regex_cfg;
2352
0
  if (o->word_regex) {
2353
0
    ecbdata->diff_words->word_regex = (regex_t *)
2354
0
      xmalloc(sizeof(regex_t));
2355
0
    if (regcomp(ecbdata->diff_words->word_regex,
2356
0
          o->word_regex,
2357
0
          REG_EXTENDED | REG_NEWLINE))
2358
0
      die("invalid regular expression: %s",
2359
0
          o->word_regex);
2360
0
  }
2361
0
  for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2362
0
    if (o->word_diff == diff_words_styles[i].type) {
2363
0
      ecbdata->diff_words->style =
2364
0
        &diff_words_styles[i];
2365
0
      break;
2366
0
    }
2367
0
  }
2368
0
  if (want_color(o->use_color)) {
2369
0
    struct diff_words_style *st = ecbdata->diff_words->style;
2370
0
    st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2371
0
    st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2372
0
    st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2373
0
  }
2374
0
}
2375
2376
static void free_diff_words_data(struct emit_callback *ecbdata)
2377
0
{
2378
0
  if (ecbdata->diff_words) {
2379
0
    diff_words_flush(ecbdata);
2380
0
    free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2381
0
    free (ecbdata->diff_words->opt);
2382
0
    free (ecbdata->diff_words->minus.text.ptr);
2383
0
    free (ecbdata->diff_words->minus.orig);
2384
0
    free (ecbdata->diff_words->plus.text.ptr);
2385
0
    free (ecbdata->diff_words->plus.orig);
2386
0
    if (ecbdata->diff_words->word_regex) {
2387
0
      regfree(ecbdata->diff_words->word_regex);
2388
0
      free(ecbdata->diff_words->word_regex);
2389
0
    }
2390
0
    FREE_AND_NULL(ecbdata->diff_words);
2391
0
  }
2392
0
}
2393
2394
const char *diff_get_color(enum git_colorbool diff_use_color, enum color_diff ix)
2395
0
{
2396
0
  if (want_color(diff_use_color))
2397
0
    return diff_colors[ix];
2398
0
  return "";
2399
0
}
2400
2401
const char *diff_line_prefix(struct diff_options *opt)
2402
0
{
2403
0
  return opt->output_prefix ?
2404
0
    opt->output_prefix(opt, opt->output_prefix_data) :
2405
0
    "";
2406
0
}
2407
2408
static unsigned long sane_truncate_line(char *line, unsigned long len)
2409
0
{
2410
0
  const char *cp;
2411
0
  unsigned long allot;
2412
0
  size_t l = len;
2413
2414
0
  cp = line;
2415
0
  allot = l;
2416
0
  while (0 < l) {
2417
0
    (void) utf8_width(&cp, &l);
2418
0
    if (!cp)
2419
0
      break; /* truncated in the middle? */
2420
0
  }
2421
0
  return allot - l;
2422
0
}
2423
2424
static void find_lno(const char *line, struct emit_callback *ecbdata)
2425
0
{
2426
0
  const char *p;
2427
0
  ecbdata->lno_in_preimage = 0;
2428
0
  ecbdata->lno_in_postimage = 0;
2429
0
  p = strchr(line, '-');
2430
0
  if (!p)
2431
0
    return; /* cannot happen */
2432
0
  ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2433
0
  p = strchr(p, '+');
2434
0
  if (!p)
2435
0
    return; /* cannot happen */
2436
0
  ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2437
0
}
2438
2439
static int fn_out_consume(void *priv, char *line, unsigned long len)
2440
0
{
2441
0
  struct emit_callback *ecbdata = priv;
2442
0
  struct diff_options *o = ecbdata->opt;
2443
2444
0
  o->found_changes = 1;
2445
2446
0
  if (ecbdata->header) {
2447
0
    emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2448
0
         ecbdata->header->buf, ecbdata->header->len, 0);
2449
0
    strbuf_reset(ecbdata->header);
2450
0
    ecbdata->header = NULL;
2451
0
  }
2452
2453
0
  if (ecbdata->label_path[0]) {
2454
0
    emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2455
0
         ecbdata->label_path[0],
2456
0
         strlen(ecbdata->label_path[0]), 0);
2457
0
    emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2458
0
         ecbdata->label_path[1],
2459
0
         strlen(ecbdata->label_path[1]), 0);
2460
0
    ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2461
0
  }
2462
2463
0
  if (line[0] == '@') {
2464
0
    if (ecbdata->diff_words)
2465
0
      diff_words_flush(ecbdata);
2466
0
    len = sane_truncate_line(line, len);
2467
0
    find_lno(line, ecbdata);
2468
0
    emit_hunk_header(ecbdata, line, len);
2469
0
    return 0;
2470
0
  }
2471
2472
0
  if (ecbdata->diff_words) {
2473
0
    enum diff_symbol s =
2474
0
      ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2475
0
      DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2476
0
    if (line[0] == '-') {
2477
0
      diff_words_append(line, len,
2478
0
            &ecbdata->diff_words->minus);
2479
0
      return 0;
2480
0
    } else if (line[0] == '+') {
2481
0
      diff_words_append(line, len,
2482
0
            &ecbdata->diff_words->plus);
2483
0
      return 0;
2484
0
    } else if (starts_with(line, "\\ ")) {
2485
      /*
2486
       * Eat the "no newline at eof" marker as if we
2487
       * saw a "+" or "-" line with nothing on it,
2488
       * and return without diff_words_flush() to
2489
       * defer processing. If this is the end of
2490
       * preimage, more "+" lines may come after it.
2491
       */
2492
0
      return 0;
2493
0
    }
2494
0
    diff_words_flush(ecbdata);
2495
0
    emit_diff_symbol(o, s, line, len, 0);
2496
0
    return 0;
2497
0
  }
2498
2499
0
  switch (line[0]) {
2500
0
  case '+':
2501
0
    ecbdata->lno_in_postimage++;
2502
0
    emit_add_line(ecbdata, line + 1, len - 1);
2503
0
    break;
2504
0
  case '-':
2505
0
    ecbdata->lno_in_preimage++;
2506
0
    emit_del_line(ecbdata, line + 1, len - 1);
2507
0
    break;
2508
0
  case ' ':
2509
0
    ecbdata->lno_in_postimage++;
2510
0
    ecbdata->lno_in_preimage++;
2511
0
    emit_context_line(ecbdata, line + 1, len - 1);
2512
0
    break;
2513
0
  case '\\':
2514
    /* incomplete line at the end */
2515
0
    switch (ecbdata->last_line_kind) {
2516
0
    case '+':
2517
0
    case '-':
2518
0
    case ' ':
2519
0
      break;
2520
0
    default:
2521
0
      BUG("fn_out_consume: '\\No newline' after unknown line (%c)",
2522
0
          ecbdata->last_line_kind);
2523
0
    }
2524
0
    ecbdata->lno_in_preimage++;
2525
0
    emit_incomplete_line_marker(ecbdata, line, len);
2526
0
    break;
2527
0
  default:
2528
0
    BUG("fn_out_consume: unknown line '%s'", line);
2529
0
  }
2530
0
  ecbdata->last_line_kind = line[0];
2531
0
  return 0;
2532
0
}
2533
2534
static int quick_consume(void *priv, char *line UNUSED, unsigned long len UNUSED)
2535
0
{
2536
0
  struct emit_callback *ecbdata = priv;
2537
0
  struct diff_options *o = ecbdata->opt;
2538
2539
0
  o->found_changes = 1;
2540
0
  return 1;
2541
0
}
2542
2543
static void discard_pending_rm(struct line_range_callback *s)
2544
0
{
2545
0
  strbuf_reset(&s->pending_rm);
2546
0
  s->pending_rm_count = 0;
2547
0
}
2548
2549
static void flush_rhunk(struct line_range_callback *s)
2550
0
{
2551
0
  struct strbuf hdr = STRBUF_INIT;
2552
0
  const char *p, *end;
2553
2554
0
  if (!s->rhunk_active || s->ret)
2555
0
    return;
2556
2557
  /* Drain any pending removal lines into the range hunk */
2558
0
  if (s->pending_rm_count) {
2559
0
    strbuf_addbuf(&s->rhunk, &s->pending_rm);
2560
0
    s->rhunk_old_count += s->pending_rm_count;
2561
0
    s->rhunk_has_changes = 1;
2562
0
    discard_pending_rm(s);
2563
0
  }
2564
2565
  /*
2566
   * Suppress context-only hunks: they contain no actual changes
2567
   * and would just be noise.  This can happen when the inflated
2568
   * ctxlen causes xdiff to emit context covering a range that
2569
   * has no changes in this commit.
2570
   */
2571
0
  if (!s->rhunk_has_changes) {
2572
0
    s->rhunk_active = 0;
2573
0
    strbuf_reset(&s->rhunk);
2574
0
    return;
2575
0
  }
2576
2577
0
  strbuf_addf(&hdr, "@@ -%ld,%ld +%ld,%ld @@",
2578
0
        s->rhunk_old_begin, s->rhunk_old_count,
2579
0
        s->rhunk_new_begin, s->rhunk_new_count);
2580
0
  if (s->funclen > 0) {
2581
0
    strbuf_addch(&hdr, ' ');
2582
0
    strbuf_add(&hdr, s->func, s->funclen);
2583
0
  }
2584
0
  strbuf_addch(&hdr, '\n');
2585
2586
0
  s->ret = s->orig_line_fn(s->orig_cb_data, hdr.buf, hdr.len);
2587
0
  strbuf_release(&hdr);
2588
2589
  /*
2590
   * Replay buffered lines one at a time through fn_out_consume.
2591
   * The cast discards const because xdiff_emit_line_fn takes
2592
   * char *, though fn_out_consume does not modify the buffer.
2593
   */
2594
0
  p = s->rhunk.buf;
2595
0
  end = p + s->rhunk.len;
2596
0
  while (!s->ret && p < end) {
2597
0
    const char *eol = memchr(p, '\n', end - p);
2598
0
    unsigned long line_len = eol ? (unsigned long)(eol - p + 1)
2599
0
               : (unsigned long)(end - p);
2600
0
    s->ret = s->orig_line_fn(s->orig_cb_data, (char *)p, line_len);
2601
0
    p += line_len;
2602
0
  }
2603
2604
0
  s->rhunk_active = 0;
2605
0
  strbuf_reset(&s->rhunk);
2606
0
}
2607
2608
static void line_range_hunk_fn(void *data,
2609
             long old_begin, long old_nr UNUSED,
2610
             long new_begin, long new_nr UNUSED,
2611
             const char *func, long funclen)
2612
0
{
2613
0
  struct line_range_callback *s = data;
2614
2615
  /*
2616
   * When count > 0, begin is 1-based.  When count == 0, begin is
2617
   * adjusted down by 1 by xdl_emit_hunk_hdr(), but no lines of
2618
   * that type will arrive, so the value is unused.
2619
   *
2620
   * Any pending removal lines from the previous xdiff hunk are
2621
   * intentionally left in pending_rm: the line callback will
2622
   * flush or discard them when the next content line reveals
2623
   * whether the removals precede in-range content.
2624
   */
2625
0
  s->lno_post = new_begin;
2626
0
  s->lno_pre = old_begin;
2627
2628
0
  if (funclen > 0) {
2629
0
    if (funclen > (long)sizeof(s->func))
2630
0
      funclen = sizeof(s->func);
2631
0
    memcpy(s->func, func, funclen);
2632
0
  }
2633
0
  s->funclen = funclen;
2634
0
}
2635
2636
static int line_range_line_fn(void *priv, char *line, unsigned long len)
2637
0
{
2638
0
  struct line_range_callback *s = priv;
2639
0
  const struct range *cur;
2640
0
  long lno_0, cur_pre;
2641
2642
0
  if (s->ret)
2643
0
    return s->ret;
2644
2645
0
  if (line[0] == '-') {
2646
0
    if (!s->pending_rm_count)
2647
0
      s->pending_rm_pre_begin = s->lno_pre;
2648
0
    s->lno_pre++;
2649
0
    strbuf_add(&s->pending_rm, line, len);
2650
0
    s->pending_rm_count++;
2651
0
    return s->ret;
2652
0
  }
2653
2654
0
  if (line[0] == '\\') {
2655
0
    if (s->pending_rm_count)
2656
0
      strbuf_add(&s->pending_rm, line, len);
2657
0
    else if (s->rhunk_active)
2658
0
      strbuf_add(&s->rhunk, line, len);
2659
    /* otherwise outside tracked range; drop silently */
2660
0
    return s->ret;
2661
0
  }
2662
2663
0
  if (line[0] != '+' && line[0] != ' ')
2664
0
    BUG("unexpected diff line type '%c'", line[0]);
2665
2666
0
  lno_0 = s->lno_post - 1;
2667
0
  cur_pre = s->lno_pre; /* save before advancing for context lines */
2668
0
  s->lno_post++;
2669
0
  if (line[0] == ' ')
2670
0
    s->lno_pre++;
2671
2672
  /* Advance past ranges we've passed */
2673
0
  while (s->cur_range < s->ranges->nr &&
2674
0
         lno_0 >= s->ranges->ranges[s->cur_range].end) {
2675
0
    if (s->rhunk_active)
2676
0
      flush_rhunk(s);
2677
0
    discard_pending_rm(s);
2678
0
    s->cur_range++;
2679
0
  }
2680
2681
  /* Past all ranges */
2682
0
  if (s->cur_range >= s->ranges->nr) {
2683
0
    discard_pending_rm(s);
2684
0
    return s->ret;
2685
0
  }
2686
2687
0
  cur = &s->ranges->ranges[s->cur_range];
2688
2689
  /* Before current range */
2690
0
  if (lno_0 < cur->start) {
2691
0
    discard_pending_rm(s);
2692
0
    return s->ret;
2693
0
  }
2694
2695
  /* In range so start a new range hunk if needed */
2696
0
  if (!s->rhunk_active) {
2697
0
    s->rhunk_active = 1;
2698
0
    s->rhunk_has_changes = 0;
2699
0
    s->rhunk_new_begin = lno_0 + 1;
2700
0
    s->rhunk_old_begin = s->pending_rm_count
2701
0
      ? s->pending_rm_pre_begin : cur_pre;
2702
0
    s->rhunk_old_count = 0;
2703
0
    s->rhunk_new_count = 0;
2704
0
    strbuf_reset(&s->rhunk);
2705
0
  }
2706
2707
  /* Flush pending removals into range hunk */
2708
0
  if (s->pending_rm_count) {
2709
0
    strbuf_addbuf(&s->rhunk, &s->pending_rm);
2710
0
    s->rhunk_old_count += s->pending_rm_count;
2711
0
    s->rhunk_has_changes = 1;
2712
0
    discard_pending_rm(s);
2713
0
  }
2714
2715
0
  strbuf_add(&s->rhunk, line, len);
2716
0
  s->rhunk_new_count++;
2717
0
  if (line[0] == '+')
2718
0
    s->rhunk_has_changes = 1;
2719
0
  else
2720
0
    s->rhunk_old_count++;
2721
2722
0
  return s->ret;
2723
0
}
2724
2725
static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2726
0
{
2727
0
  const char *old_name = a;
2728
0
  const char *new_name = b;
2729
0
  int pfx_length, sfx_length;
2730
0
  int pfx_adjust_for_slash;
2731
0
  int len_a = strlen(a);
2732
0
  int len_b = strlen(b);
2733
0
  int a_midlen, b_midlen;
2734
0
  int qlen_a = quote_c_style(a, NULL, NULL, 0);
2735
0
  int qlen_b = quote_c_style(b, NULL, NULL, 0);
2736
2737
0
  if (qlen_a || qlen_b) {
2738
0
    quote_c_style(a, name, NULL, 0);
2739
0
    strbuf_addstr(name, " => ");
2740
0
    quote_c_style(b, name, NULL, 0);
2741
0
    return;
2742
0
  }
2743
2744
  /* Find common prefix */
2745
0
  pfx_length = 0;
2746
0
  while (*old_name && *new_name && *old_name == *new_name) {
2747
0
    if (*old_name == '/')
2748
0
      pfx_length = old_name - a + 1;
2749
0
    old_name++;
2750
0
    new_name++;
2751
0
  }
2752
2753
  /* Find common suffix */
2754
0
  old_name = a + len_a;
2755
0
  new_name = b + len_b;
2756
0
  sfx_length = 0;
2757
  /*
2758
   * If there is a common prefix, it must end in a slash.  In
2759
   * that case we let this loop run 1 into the prefix to see the
2760
   * same slash.
2761
   *
2762
   * If there is no common prefix, we cannot do this as it would
2763
   * underrun the input strings.
2764
   */
2765
0
  pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2766
0
  while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2767
0
         b + pfx_length - pfx_adjust_for_slash <= new_name &&
2768
0
         *old_name == *new_name) {
2769
0
    if (*old_name == '/')
2770
0
      sfx_length = len_a - (old_name - a);
2771
0
    old_name--;
2772
0
    new_name--;
2773
0
  }
2774
2775
  /*
2776
   * pfx{mid-a => mid-b}sfx
2777
   * {pfx-a => pfx-b}sfx
2778
   * pfx{sfx-a => sfx-b}
2779
   * name-a => name-b
2780
   */
2781
0
  a_midlen = len_a - pfx_length - sfx_length;
2782
0
  b_midlen = len_b - pfx_length - sfx_length;
2783
0
  if (a_midlen < 0)
2784
0
    a_midlen = 0;
2785
0
  if (b_midlen < 0)
2786
0
    b_midlen = 0;
2787
2788
0
  strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2789
0
  if (pfx_length + sfx_length) {
2790
0
    strbuf_add(name, a, pfx_length);
2791
0
    strbuf_addch(name, '{');
2792
0
  }
2793
0
  strbuf_add(name, a + pfx_length, a_midlen);
2794
0
  strbuf_addstr(name, " => ");
2795
0
  strbuf_add(name, b + pfx_length, b_midlen);
2796
0
  if (pfx_length + sfx_length) {
2797
0
    strbuf_addch(name, '}');
2798
0
    strbuf_add(name, a + len_a - sfx_length, sfx_length);
2799
0
  }
2800
0
}
2801
2802
static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2803
            const char *name_a,
2804
            const char *name_b)
2805
0
{
2806
0
  struct diffstat_file *x;
2807
0
  CALLOC_ARRAY(x, 1);
2808
0
  ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2809
0
  diffstat->files[diffstat->nr++] = x;
2810
0
  if (name_b) {
2811
0
    x->from_name = xstrdup(name_a);
2812
0
    x->name = xstrdup(name_b);
2813
0
    x->is_renamed = 1;
2814
0
  }
2815
0
  else {
2816
0
    x->from_name = NULL;
2817
0
    x->name = xstrdup(name_a);
2818
0
  }
2819
0
  return x;
2820
0
}
2821
2822
static int diffstat_consume(void *priv, char *line, unsigned long len)
2823
0
{
2824
0
  struct diffstat_t *diffstat = priv;
2825
0
  struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2826
2827
0
  if (!len)
2828
0
    BUG("xdiff fed us an empty line");
2829
2830
0
  if (line[0] == '+')
2831
0
    x->added++;
2832
0
  else if (line[0] == '-')
2833
0
    x->deleted++;
2834
0
  return 0;
2835
0
}
2836
2837
const char mime_boundary_leader[] = "------------";
2838
2839
static int scale_linear(int it, int width, int max_change)
2840
0
{
2841
0
  if (!it)
2842
0
    return 0;
2843
  /*
2844
   * make sure that at least one '-' or '+' is printed if
2845
   * there is any change to this path. The easiest way is to
2846
   * scale linearly as if the allotted width is one column shorter
2847
   * than it is, and then add 1 to the result.
2848
   */
2849
0
  return 1 + (it * (width - 1) / max_change);
2850
0
}
2851
2852
static void show_graph(struct strbuf *out, char ch, int cnt,
2853
           const char *set, const char *reset)
2854
0
{
2855
0
  if (cnt <= 0)
2856
0
    return;
2857
0
  strbuf_addstr(out, set);
2858
0
  strbuf_addchars(out, ch, cnt);
2859
0
  strbuf_addstr(out, reset);
2860
0
}
2861
2862
static void fill_print_name(struct diffstat_file *file)
2863
0
{
2864
0
  struct strbuf pname = STRBUF_INIT;
2865
2866
0
  if (file->print_name)
2867
0
    return;
2868
2869
0
  if (file->is_renamed)
2870
0
    pprint_rename(&pname, file->from_name, file->name);
2871
0
  else
2872
0
    quote_c_style(file->name, &pname, NULL, 0);
2873
2874
0
  if (file->comments)
2875
0
    strbuf_addf(&pname, " (%s)", file->comments);
2876
2877
0
  file->print_name = strbuf_detach(&pname, NULL);
2878
0
}
2879
2880
static void print_stat_summary_inserts_deletes(struct diff_options *options,
2881
    int files, int insertions, int deletions)
2882
0
{
2883
0
  struct strbuf sb = STRBUF_INIT;
2884
2885
0
  if (!files) {
2886
0
    assert(insertions == 0 && deletions == 0);
2887
0
    emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2888
0
         NULL, 0, 0);
2889
0
    return;
2890
0
  }
2891
2892
0
  strbuf_addf(&sb,
2893
0
        (files == 1) ? " %d file changed" : " %d files changed",
2894
0
        files);
2895
2896
  /*
2897
   * For binary diff, the caller may want to print "x files
2898
   * changed" with insertions == 0 && deletions == 0.
2899
   *
2900
   * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2901
   * is probably less confusing (i.e skip over "2 files changed
2902
   * but nothing about added/removed lines? Is this a bug in Git?").
2903
   */
2904
0
  if (insertions || deletions == 0) {
2905
0
    strbuf_addf(&sb,
2906
0
          (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2907
0
          insertions);
2908
0
  }
2909
2910
0
  if (deletions || insertions == 0) {
2911
0
    strbuf_addf(&sb,
2912
0
          (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2913
0
          deletions);
2914
0
  }
2915
0
  strbuf_addch(&sb, '\n');
2916
0
  emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2917
0
       sb.buf, sb.len, 0);
2918
0
  strbuf_release(&sb);
2919
0
}
2920
2921
void print_stat_summary(FILE *fp, int files,
2922
      int insertions, int deletions)
2923
0
{
2924
0
  struct diff_options o;
2925
0
  memset(&o, 0, sizeof(o));
2926
0
  o.file = fp;
2927
2928
0
  print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2929
0
}
2930
2931
/*
2932
 * Like utf8_width(), but guaranteed safe for use in loops that subtract
2933
 * per-character widths:
2934
 *
2935
 *   - utf8_width() sets *start to NULL on invalid UTF-8 and returns 0;
2936
 *     we restore the pointer and advance by one byte, returning width 1
2937
 *     (matching the strlen()-based fallback in utf8_strwidth()).
2938
 *
2939
 *   - utf8_width() returns -1 for control characters; we return 0
2940
 *     (matching utf8_strnwidth() which skips them).
2941
 */
2942
static int utf8_ish_width(const char **start)
2943
0
{
2944
0
  const char *old = *start;
2945
0
  int w = utf8_width(start, NULL);
2946
0
  if (!*start) {
2947
0
    *start = old + 1;
2948
0
    return 1;
2949
0
  }
2950
0
  return (w < 0) ? 0 : w;
2951
0
}
2952
2953
static void show_stats(struct diffstat_t *data, struct diff_options *options)
2954
0
{
2955
0
  int i, len, add, del, adds = 0, dels = 0;
2956
0
  uintmax_t max_change = 0, max_len = 0;
2957
0
  int total_files = data->nr, count;
2958
0
  int width, name_width, graph_width, number_width = 0, bin_width = 0;
2959
0
  const char *reset, *add_c, *del_c;
2960
0
  int extra_shown = 0;
2961
0
  const char *line_prefix = diff_line_prefix(options);
2962
0
  struct strbuf out = STRBUF_INIT;
2963
2964
0
  if (data->nr == 0)
2965
0
    return;
2966
2967
0
  count = options->stat_count ? options->stat_count : data->nr;
2968
2969
0
  reset = diff_get_color_opt(options, DIFF_RESET);
2970
0
  add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2971
0
  del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2972
2973
  /*
2974
   * Find the longest filename and max number of changes
2975
   */
2976
0
  for (i = 0; (i < count) && (i < data->nr); i++) {
2977
0
    struct diffstat_file *file = data->files[i];
2978
0
    uintmax_t change = file->added + file->deleted;
2979
2980
0
    if (!file->is_interesting && (change == 0)) {
2981
0
      count++; /* not shown == room for one more */
2982
0
      continue;
2983
0
    }
2984
0
    fill_print_name(file);
2985
0
    len = utf8_strwidth(file->print_name);
2986
0
    if (max_len < len)
2987
0
      max_len = len;
2988
2989
0
    if (file->is_unmerged) {
2990
      /* "Unmerged" is 8 characters */
2991
0
      bin_width = bin_width < 8 ? 8 : bin_width;
2992
0
      continue;
2993
0
    }
2994
0
    if (file->is_binary) {
2995
      /* "Bin XXX -> YYY bytes" */
2996
0
      int w = 14 + decimal_width(file->added)
2997
0
        + decimal_width(file->deleted);
2998
0
      bin_width = bin_width < w ? w : bin_width;
2999
      /* Display change counts aligned with "Bin" */
3000
0
      number_width = 3;
3001
0
      continue;
3002
0
    }
3003
3004
0
    if (max_change < change)
3005
0
      max_change = change;
3006
0
  }
3007
0
  count = i; /* where we can stop scanning in data->files[] */
3008
3009
  /*
3010
   * We have width = stat_width or term_columns() columns total minus the
3011
   * length of line_prefix skipping ANSI escape codes to get the display
3012
   * width (e.g., skip ANSI-colored strings in "log --graph --stat").
3013
   * We want a maximum of min(max_len, stat_name_width) for the name part.
3014
   * We want a maximum of min(max_change, stat_graph_width) for the +- part.
3015
   * We also need 1 for " " and 4 + decimal_width(max_change)
3016
   * for " | NNNN " and one the empty column at the end, altogether
3017
   * 6 + decimal_width(max_change).
3018
   *
3019
   * If there's not enough space, we will use the smaller of
3020
   * stat_name_width (if set) and 5/8*width for the filename,
3021
   * and the rest for constant elements + graph part, but no more
3022
   * than stat_graph_width for the graph part.
3023
   * (5/8 gives 50 for filename and 30 for the constant parts + graph
3024
   * for the standard terminal size).
3025
   *
3026
   * In other words: stat_width limits the maximum width, and
3027
   * stat_name_width fixes the maximum width of the filename,
3028
   * and is also used to divide available columns if there
3029
   * aren't enough.
3030
   *
3031
   * Binary files are displayed with "Bin XXX -> YYY bytes"
3032
   * instead of the change count and graph. This part is treated
3033
   * similarly to the graph part, except that it is not
3034
   * "scaled". If total width is too small to accommodate the
3035
   * guaranteed minimum width of the filename part and the
3036
   * separators and this message, this message will "overflow"
3037
   * making the line longer than the maximum width.
3038
   */
3039
0
  if (options->stat_width == -1)
3040
0
    width = term_columns() - utf8_strnwidth(line_prefix, strlen(line_prefix), 1);
3041
0
  else
3042
0
    width = options->stat_width ? options->stat_width : 80;
3043
0
  number_width = decimal_width(max_change) > number_width ?
3044
0
    decimal_width(max_change) : number_width;
3045
3046
0
  if (options->stat_name_width == -1)
3047
0
    options->stat_name_width = diff_stat_name_width;
3048
0
  if (options->stat_graph_width == -1)
3049
0
    options->stat_graph_width = diff_stat_graph_width;
3050
3051
  /*
3052
   * Guarantee 3/8*16 == 6 for the graph part
3053
   * and 5/8*16 == 10 for the filename part
3054
   */
3055
0
  if (width < 16 + 6 + number_width)
3056
0
    width = 16 + 6 + number_width;
3057
3058
  /*
3059
   * First assign sizes that are wanted, ignoring available width.
3060
   * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
3061
   * starting from "XXX" should fit in graph_width.
3062
   */
3063
0
  graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
3064
0
  if (options->stat_graph_width &&
3065
0
      options->stat_graph_width < graph_width)
3066
0
    graph_width = options->stat_graph_width;
3067
3068
0
  name_width = (options->stat_name_width > 0 &&
3069
0
          options->stat_name_width < max_len) ?
3070
0
    options->stat_name_width : max_len;
3071
3072
  /*
3073
   * Adjust adjustable widths not to exceed maximum width
3074
   */
3075
0
  if (name_width + number_width + 6 + graph_width > width) {
3076
0
    if (graph_width > width * 3/8 - number_width - 6) {
3077
0
      graph_width = width * 3/8 - number_width - 6;
3078
0
      if (graph_width < 6)
3079
0
        graph_width = 6;
3080
0
    }
3081
3082
0
    if (options->stat_graph_width &&
3083
0
        graph_width > options->stat_graph_width)
3084
0
      graph_width = options->stat_graph_width;
3085
0
    if (name_width > width - number_width - 6 - graph_width)
3086
0
      name_width = width - number_width - 6 - graph_width;
3087
0
    else
3088
0
      graph_width = width - number_width - 6 - name_width;
3089
0
  }
3090
3091
  /*
3092
   * From here name_width is the width of the name area,
3093
   * and graph_width is the width of the graph area.
3094
   * max_change is used to scale graph properly.
3095
   */
3096
0
  for (i = 0; i < count; i++) {
3097
0
    const char *prefix = "";
3098
0
    struct diffstat_file *file = data->files[i];
3099
0
    char *name = file->print_name;
3100
0
    uintmax_t added = file->added;
3101
0
    uintmax_t deleted = file->deleted;
3102
0
    int name_len, padding;
3103
3104
0
    if (!file->is_interesting && (added + deleted == 0))
3105
0
      continue;
3106
3107
    /*
3108
     * "scale" the filename
3109
     */
3110
0
    len = name_width;
3111
0
    name_len = utf8_strwidth(name);
3112
0
    if (name_width < name_len) {
3113
0
      char *slash;
3114
0
      prefix = "...";
3115
0
      len -= 3;
3116
0
      if (len < 0)
3117
0
        len = 0;
3118
3119
0
      while (name_len > len && *name)
3120
0
        name_len -= utf8_ish_width((const char**)&name);
3121
3122
0
      slash = strchr(name, '/');
3123
0
      if (slash)
3124
0
        name = slash;
3125
0
    }
3126
0
    padding = len - utf8_strwidth(name);
3127
0
    if (padding < 0)
3128
0
      padding = 0;
3129
3130
0
    if (file->is_binary) {
3131
0
      strbuf_addf(&out, " %s%s%*s | %*s",
3132
0
            prefix, name, padding, "",
3133
0
            number_width, "Bin");
3134
0
      if (!added && !deleted) {
3135
0
        strbuf_addch(&out, '\n');
3136
0
        emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3137
0
             out.buf, out.len, 0);
3138
0
        strbuf_reset(&out);
3139
0
        continue;
3140
0
      }
3141
0
      strbuf_addf(&out, " %s%"PRIuMAX"%s",
3142
0
        del_c, deleted, reset);
3143
0
      strbuf_addstr(&out, " -> ");
3144
0
      strbuf_addf(&out, "%s%"PRIuMAX"%s",
3145
0
        add_c, added, reset);
3146
0
      strbuf_addstr(&out, " bytes\n");
3147
0
      emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3148
0
           out.buf, out.len, 0);
3149
0
      strbuf_reset(&out);
3150
0
      continue;
3151
0
    }
3152
0
    else if (file->is_unmerged) {
3153
0
      strbuf_addf(&out, " %s%s%*s | %*s",
3154
0
            prefix, name, padding, "",
3155
0
            number_width, "Unmerged\n");
3156
0
      emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3157
0
           out.buf, out.len, 0);
3158
0
      strbuf_reset(&out);
3159
0
      continue;
3160
0
    }
3161
3162
    /*
3163
     * scale the add/delete
3164
     */
3165
0
    add = added;
3166
0
    del = deleted;
3167
3168
0
    if (graph_width <= max_change) {
3169
0
      int total = scale_linear(add + del, graph_width, max_change);
3170
0
      if (total < 2 && add && del)
3171
        /* width >= 2 due to the sanity check */
3172
0
        total = 2;
3173
0
      if (add < del) {
3174
0
        add = scale_linear(add, graph_width, max_change);
3175
0
        del = total - add;
3176
0
      } else {
3177
0
        del = scale_linear(del, graph_width, max_change);
3178
0
        add = total - del;
3179
0
      }
3180
0
    }
3181
0
    strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
3182
0
          prefix, name, padding, "",
3183
0
          number_width, added + deleted,
3184
0
          added + deleted ? " " : "");
3185
0
    show_graph(&out, '+', add, add_c, reset);
3186
0
    show_graph(&out, '-', del, del_c, reset);
3187
0
    strbuf_addch(&out, '\n');
3188
0
    emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
3189
0
         out.buf, out.len, 0);
3190
0
    strbuf_reset(&out);
3191
0
  }
3192
3193
0
  for (i = 0; i < data->nr; i++) {
3194
0
    struct diffstat_file *file = data->files[i];
3195
0
    uintmax_t added = file->added;
3196
0
    uintmax_t deleted = file->deleted;
3197
3198
0
    if (file->is_unmerged ||
3199
0
        (!file->is_interesting && (added + deleted == 0))) {
3200
0
      total_files--;
3201
0
      continue;
3202
0
    }
3203
3204
0
    if (!file->is_binary) {
3205
0
      adds += added;
3206
0
      dels += deleted;
3207
0
    }
3208
0
    if (i < count)
3209
0
      continue;
3210
0
    if (!extra_shown)
3211
0
      emit_diff_symbol(options,
3212
0
           DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
3213
0
           NULL, 0, 0);
3214
0
    extra_shown = 1;
3215
0
  }
3216
3217
0
  print_stat_summary_inserts_deletes(options, total_files, adds, dels);
3218
0
  strbuf_release(&out);
3219
0
}
3220
3221
static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
3222
0
{
3223
0
  int i, adds = 0, dels = 0, total_files = data->nr;
3224
3225
0
  if (data->nr == 0)
3226
0
    return;
3227
3228
0
  for (i = 0; i < data->nr; i++) {
3229
0
    int added = data->files[i]->added;
3230
0
    int deleted = data->files[i]->deleted;
3231
3232
0
    if (data->files[i]->is_unmerged ||
3233
0
        (!data->files[i]->is_interesting && (added + deleted == 0))) {
3234
0
      total_files--;
3235
0
    } else if (!data->files[i]->is_binary) { /* don't count bytes */
3236
0
      adds += added;
3237
0
      dels += deleted;
3238
0
    }
3239
0
  }
3240
0
  print_stat_summary_inserts_deletes(options, total_files, adds, dels);
3241
0
}
3242
3243
static void show_numstat(struct diffstat_t *data, struct diff_options *options)
3244
0
{
3245
0
  int i;
3246
3247
0
  if (data->nr == 0)
3248
0
    return;
3249
3250
0
  for (i = 0; i < data->nr; i++) {
3251
0
    struct diffstat_file *file = data->files[i];
3252
3253
0
    fprintf(options->file, "%s", diff_line_prefix(options));
3254
3255
0
    if (file->is_binary)
3256
0
      fprintf(options->file, "-\t-\t");
3257
0
    else
3258
0
      fprintf(options->file,
3259
0
        "%"PRIuMAX"\t%"PRIuMAX"\t",
3260
0
        file->added, file->deleted);
3261
0
    if (options->line_termination) {
3262
0
      fill_print_name(file);
3263
0
      if (!file->is_renamed)
3264
0
        write_name_quoted(file->name, options->file,
3265
0
              options->line_termination);
3266
0
      else {
3267
0
        fputs(file->print_name, options->file);
3268
0
        putc(options->line_termination, options->file);
3269
0
      }
3270
0
    } else {
3271
0
      if (file->is_renamed) {
3272
0
        putc('\0', options->file);
3273
0
        write_name_quoted(file->from_name, options->file, '\0');
3274
0
      }
3275
0
      write_name_quoted(file->name, options->file, '\0');
3276
0
    }
3277
0
  }
3278
0
}
3279
3280
struct dirstat_file {
3281
  const char *name;
3282
  unsigned long changed;
3283
};
3284
3285
struct dirstat_dir {
3286
  struct dirstat_file *files;
3287
  int alloc, nr, permille, cumulative;
3288
};
3289
3290
static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
3291
    unsigned long changed, const char *base, int baselen)
3292
0
{
3293
0
  unsigned long sum_changes = 0;
3294
0
  unsigned int sources = 0;
3295
0
  const char *line_prefix = diff_line_prefix(opt);
3296
3297
0
  while (dir->nr) {
3298
0
    struct dirstat_file *f = dir->files;
3299
0
    int namelen = strlen(f->name);
3300
0
    unsigned long changes;
3301
0
    const char *slash;
3302
3303
0
    if (namelen < baselen)
3304
0
      break;
3305
0
    if (memcmp(f->name, base, baselen))
3306
0
      break;
3307
0
    slash = strchr(f->name + baselen, '/');
3308
0
    if (slash) {
3309
0
      int newbaselen = slash + 1 - f->name;
3310
0
      changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3311
0
      sources++;
3312
0
    } else {
3313
0
      changes = f->changed;
3314
0
      dir->files++;
3315
0
      dir->nr--;
3316
0
      sources += 2;
3317
0
    }
3318
0
    sum_changes += changes;
3319
0
  }
3320
3321
  /*
3322
   * We don't report dirstat's for
3323
   *  - the top level
3324
   *  - or cases where everything came from a single directory
3325
   *    under this directory (sources == 1).
3326
   */
3327
0
  if (baselen && sources != 1) {
3328
0
    if (sum_changes) {
3329
0
      int permille = sum_changes * 1000 / changed;
3330
0
      if (permille >= dir->permille) {
3331
0
        fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3332
0
          permille / 10, permille % 10, baselen, base);
3333
0
        if (!dir->cumulative)
3334
0
          return 0;
3335
0
      }
3336
0
    }
3337
0
  }
3338
0
  return sum_changes;
3339
0
}
3340
3341
static int dirstat_compare(const void *_a, const void *_b)
3342
0
{
3343
0
  const struct dirstat_file *a = _a;
3344
0
  const struct dirstat_file *b = _b;
3345
0
  return strcmp(a->name, b->name);
3346
0
}
3347
3348
static void conclude_dirstat(struct diff_options *options,
3349
           struct dirstat_dir *dir,
3350
           unsigned long changed)
3351
0
{
3352
0
  struct dirstat_file *to_free = dir->files;
3353
3354
0
  if (!changed) {
3355
    /* This can happen even with many files, if everything was renames */
3356
0
    ;
3357
0
  } else {
3358
    /* Show all directories with more than x% of the changes */
3359
0
    QSORT(dir->files, dir->nr, dirstat_compare);
3360
0
    gather_dirstat(options, dir, changed, "", 0);
3361
0
  }
3362
3363
0
  free(to_free);
3364
0
}
3365
3366
static void show_dirstat(struct diff_options *options)
3367
0
{
3368
0
  int i;
3369
0
  unsigned long changed;
3370
0
  struct dirstat_dir dir;
3371
0
  struct diff_queue_struct *q = &diff_queued_diff;
3372
3373
0
  dir.files = NULL;
3374
0
  dir.alloc = 0;
3375
0
  dir.nr = 0;
3376
0
  dir.permille = options->dirstat_permille;
3377
0
  dir.cumulative = options->flags.dirstat_cumulative;
3378
3379
0
  changed = 0;
3380
0
  for (i = 0; i < q->nr; i++) {
3381
0
    struct diff_filepair *p = q->queue[i];
3382
0
    const char *name;
3383
0
    unsigned long copied, added, damage;
3384
0
    struct diff_populate_filespec_options dpf_options = {
3385
0
      .check_size_only = 1,
3386
0
    };
3387
3388
0
    name = p->two->path ? p->two->path : p->one->path;
3389
3390
0
    if (p->one->oid_valid && p->two->oid_valid &&
3391
0
        oideq(&p->one->oid, &p->two->oid)) {
3392
      /*
3393
       * The SHA1 has not changed, so pre-/post-content is
3394
       * identical. We can therefore skip looking at the
3395
       * file contents altogether.
3396
       */
3397
0
      damage = 0;
3398
0
      goto found_damage;
3399
0
    }
3400
3401
0
    if (options->flags.dirstat_by_file) {
3402
      /*
3403
       * In --dirstat-by-file mode, we don't really need to
3404
       * look at the actual file contents at all.
3405
       * The fact that the SHA1 changed is enough for us to
3406
       * add this file to the list of results
3407
       * (with each file contributing equal damage).
3408
       */
3409
0
      damage = 1;
3410
0
      goto found_damage;
3411
0
    }
3412
3413
0
    if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3414
0
      diff_populate_filespec(options->repo, p->one, NULL);
3415
0
      diff_populate_filespec(options->repo, p->two, NULL);
3416
0
      diffcore_count_changes(options->repo,
3417
0
                 p->one, p->two, NULL, NULL,
3418
0
                 &copied, &added);
3419
0
      diff_free_filespec_data(p->one);
3420
0
      diff_free_filespec_data(p->two);
3421
0
    } else if (DIFF_FILE_VALID(p->one)) {
3422
0
      diff_populate_filespec(options->repo, p->one, &dpf_options);
3423
0
      copied = added = 0;
3424
0
      diff_free_filespec_data(p->one);
3425
0
    } else if (DIFF_FILE_VALID(p->two)) {
3426
0
      diff_populate_filespec(options->repo, p->two, &dpf_options);
3427
0
      copied = 0;
3428
0
      added = p->two->size;
3429
0
      diff_free_filespec_data(p->two);
3430
0
    } else
3431
0
      continue;
3432
3433
    /*
3434
     * Original minus copied is the removed material,
3435
     * added is the new material.  They are both damages
3436
     * made to the preimage.
3437
     * If the resulting damage is zero, we know that
3438
     * diffcore_count_changes() considers the two entries to
3439
     * be identical, but since the oid changed, we
3440
     * know that there must have been _some_ kind of change,
3441
     * so we force all entries to have damage > 0.
3442
     */
3443
0
    damage = (p->one->size - copied) + added;
3444
0
    if (!damage)
3445
0
      damage = 1;
3446
3447
0
found_damage:
3448
0
    ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3449
0
    dir.files[dir.nr].name = name;
3450
0
    dir.files[dir.nr].changed = damage;
3451
0
    changed += damage;
3452
0
    dir.nr++;
3453
0
  }
3454
3455
0
  conclude_dirstat(options, &dir, changed);
3456
0
}
3457
3458
static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3459
0
{
3460
0
  int i;
3461
0
  unsigned long changed;
3462
0
  struct dirstat_dir dir;
3463
3464
0
  if (data->nr == 0)
3465
0
    return;
3466
3467
0
  dir.files = NULL;
3468
0
  dir.alloc = 0;
3469
0
  dir.nr = 0;
3470
0
  dir.permille = options->dirstat_permille;
3471
0
  dir.cumulative = options->flags.dirstat_cumulative;
3472
3473
0
  changed = 0;
3474
0
  for (i = 0; i < data->nr; i++) {
3475
0
    struct diffstat_file *file = data->files[i];
3476
0
    unsigned long damage = file->added + file->deleted;
3477
0
    if (file->is_binary)
3478
      /*
3479
       * binary files counts bytes, not lines. Must find some
3480
       * way to normalize binary bytes vs. textual lines.
3481
       * The following heuristic assumes that there are 64
3482
       * bytes per "line".
3483
       * This is stupid and ugly, but very cheap...
3484
       */
3485
0
      damage = DIV_ROUND_UP(damage, 64);
3486
0
    ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3487
0
    dir.files[dir.nr].name = file->name;
3488
0
    dir.files[dir.nr].changed = damage;
3489
0
    changed += damage;
3490
0
    dir.nr++;
3491
0
  }
3492
3493
0
  conclude_dirstat(options, &dir, changed);
3494
0
}
3495
3496
static void free_diffstat_file(struct diffstat_file *f)
3497
0
{
3498
0
  free(f->print_name);
3499
0
  free(f->name);
3500
0
  free(f->from_name);
3501
0
  free(f);
3502
0
}
3503
3504
void free_diffstat_info(struct diffstat_t *diffstat)
3505
0
{
3506
0
  int i;
3507
0
  for (i = 0; i < diffstat->nr; i++)
3508
0
    free_diffstat_file(diffstat->files[i]);
3509
0
  free(diffstat->files);
3510
0
}
3511
3512
struct checkdiff_t {
3513
  const char *filename;
3514
  int lineno;
3515
  int conflict_marker_size;
3516
  struct diff_options *o;
3517
  unsigned ws_rule;
3518
  unsigned status;
3519
  int last_line_kind;
3520
};
3521
3522
static void checkdiff_consume_hunk(void *priv,
3523
           long ob UNUSED, long on UNUSED,
3524
           long nb, long nn UNUSED,
3525
           const char *func UNUSED, long funclen UNUSED)
3526
3527
0
{
3528
0
  struct checkdiff_t *data = priv;
3529
0
  data->lineno = nb - 1;
3530
0
}
3531
3532
static int checkdiff_consume(void *priv, char *line, unsigned long len)
3533
0
{
3534
0
  struct checkdiff_t *data = priv;
3535
0
  int last_line_kind;
3536
0
  int marker_size = data->conflict_marker_size;
3537
0
  const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3538
0
  const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3539
0
  const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3540
0
  char *err;
3541
0
  const char *line_prefix;
3542
3543
0
  assert(data->o);
3544
0
  line_prefix = diff_line_prefix(data->o);
3545
3546
0
  last_line_kind = data->last_line_kind;
3547
0
  data->last_line_kind = line[0];
3548
0
  if (line[0] == '+') {
3549
0
    unsigned bad;
3550
0
    data->lineno++;
3551
0
    if (is_conflict_marker_line(line + 1, len - 1, marker_size)) {
3552
0
      data->status |= 1;
3553
0
      fprintf(data->o->file,
3554
0
        "%s%s:%d: leftover conflict marker\n",
3555
0
        line_prefix, data->filename, data->lineno);
3556
0
    }
3557
0
    bad = ws_check(line + 1, len - 1, data->ws_rule);
3558
0
    if (!bad)
3559
0
      return 0;
3560
0
    data->status |= bad;
3561
0
    err = whitespace_error_string(bad);
3562
0
    fprintf(data->o->file, "%s%s:%d: %s.\n",
3563
0
      line_prefix, data->filename, data->lineno, err);
3564
0
    free(err);
3565
0
    emit_line(data->o, set, reset, line, 1);
3566
0
    ws_check_emit(line + 1, len - 1, data->ws_rule,
3567
0
            data->o->file, set, reset, ws);
3568
0
  } else if (line[0] == ' ') {
3569
0
    data->lineno++;
3570
0
  } else if (line[0] == '\\') {
3571
    /* no newline at the end of the line */
3572
0
    if ((data->ws_rule & WS_INCOMPLETE_LINE) &&
3573
0
        (last_line_kind == '+')) {
3574
0
      unsigned bad = WS_INCOMPLETE_LINE;
3575
0
      data->status |= bad;
3576
0
      err = whitespace_error_string(bad);
3577
0
      fprintf(data->o->file, "%s%s:%d: %s.\n",
3578
0
        line_prefix, data->filename, data->lineno, err);
3579
0
      free(err);
3580
0
    }
3581
0
  }
3582
0
  return 0;
3583
0
}
3584
3585
static unsigned char *deflate_it(char *data,
3586
         unsigned long size,
3587
         unsigned long *result_size)
3588
0
{
3589
0
  size_t bound;
3590
0
  unsigned char *deflated;
3591
0
  git_zstream stream;
3592
0
  struct repo_config_values *cfg = repo_config_values(the_repository);
3593
3594
0
  git_deflate_init(&stream, cfg->zlib_compression_level);
3595
0
  bound = git_deflate_bound(&stream, size);
3596
0
  deflated = xmalloc(bound);
3597
0
  stream.next_out = deflated;
3598
0
  stream.avail_out = bound;
3599
3600
0
  stream.next_in = (unsigned char *)data;
3601
0
  stream.avail_in = size;
3602
0
  while (git_deflate(&stream, Z_FINISH) == Z_OK)
3603
0
    ; /* nothing */
3604
0
  git_deflate_end(&stream);
3605
0
  *result_size = stream.total_out;
3606
0
  return deflated;
3607
0
}
3608
3609
static void emit_binary_diff_body(struct diff_options *o,
3610
          mmfile_t *one, mmfile_t *two)
3611
0
{
3612
0
  void *cp;
3613
0
  void *delta;
3614
0
  void *deflated;
3615
0
  void *data;
3616
0
  unsigned long orig_size;
3617
0
  unsigned long delta_size;
3618
0
  unsigned long deflate_size;
3619
0
  unsigned long data_size;
3620
3621
  /* We could do deflated delta, or we could do just deflated two,
3622
   * whichever is smaller.
3623
   */
3624
0
  delta = NULL;
3625
0
  deflated = deflate_it(two->ptr, two->size, &deflate_size);
3626
0
  if (one->size && two->size) {
3627
0
    size_t delta_size_st = 0;
3628
0
    delta = diff_delta(one->ptr, one->size,
3629
0
           two->ptr, two->size,
3630
0
           &delta_size_st, deflate_size);
3631
0
    delta_size = cast_size_t_to_ulong(delta_size_st);
3632
0
    if (delta) {
3633
0
      void *to_free = delta;
3634
0
      orig_size = delta_size;
3635
0
      delta = deflate_it(delta, delta_size, &delta_size);
3636
0
      free(to_free);
3637
0
    }
3638
0
  }
3639
3640
0
  if (delta && delta_size < deflate_size) {
3641
0
    char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3642
0
    emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3643
0
         s, strlen(s), 0);
3644
0
    free(s);
3645
0
    free(deflated);
3646
0
    data = delta;
3647
0
    data_size = delta_size;
3648
0
  } else {
3649
0
    char *s = xstrfmt("%"PRIuMAX, (uintmax_t)two->size);
3650
0
    emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3651
0
         s, strlen(s), 0);
3652
0
    free(s);
3653
0
    free(delta);
3654
0
    data = deflated;
3655
0
    data_size = deflate_size;
3656
0
  }
3657
3658
  /* emit data encoded in base85 */
3659
0
  cp = data;
3660
0
  while (data_size) {
3661
0
    int len;
3662
0
    int bytes = (52 < data_size) ? 52 : data_size;
3663
0
    char line[71];
3664
0
    data_size -= bytes;
3665
0
    if (bytes <= 26)
3666
0
      line[0] = bytes + 'A' - 1;
3667
0
    else
3668
0
      line[0] = bytes - 26 + 'a' - 1;
3669
0
    encode_85(line + 1, cp, bytes);
3670
0
    cp = (char *) cp + bytes;
3671
3672
0
    len = strlen(line);
3673
0
    line[len++] = '\n';
3674
0
    line[len] = '\0';
3675
3676
0
    emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3677
0
         line, len, 0);
3678
0
  }
3679
0
  emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3680
0
  free(data);
3681
0
}
3682
3683
static void emit_binary_diff(struct diff_options *o,
3684
           mmfile_t *one, mmfile_t *two)
3685
0
{
3686
0
  emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3687
0
  emit_binary_diff_body(o, one, two);
3688
0
  emit_binary_diff_body(o, two, one);
3689
0
}
3690
3691
int diff_filespec_is_binary(struct repository *r,
3692
          struct diff_filespec *one)
3693
0
{
3694
0
  struct diff_populate_filespec_options dpf_options = {
3695
0
    .check_binary = 1,
3696
0
  };
3697
3698
0
  if (one->is_binary == -1) {
3699
0
    diff_filespec_load_driver(one, r->index);
3700
0
    if (one->driver->binary != -1)
3701
0
      one->is_binary = one->driver->binary;
3702
0
    else {
3703
0
      if (!one->data && DIFF_FILE_VALID(one))
3704
0
        diff_populate_filespec(r, one, &dpf_options);
3705
0
      if (one->is_binary == -1 && one->data)
3706
0
        one->is_binary = buffer_is_binary(one->data,
3707
0
            one->size);
3708
0
      if (one->is_binary == -1)
3709
0
        one->is_binary = 0;
3710
0
    }
3711
0
  }
3712
0
  return one->is_binary;
3713
0
}
3714
3715
static const struct userdiff_funcname *
3716
diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3717
0
{
3718
0
  diff_filespec_load_driver(one, o->repo->index);
3719
0
  return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3720
0
}
3721
3722
void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3723
0
{
3724
0
  if (!options->a_prefix)
3725
0
    options->a_prefix = a;
3726
0
  if (!options->b_prefix)
3727
0
    options->b_prefix = b;
3728
0
}
3729
3730
void diff_set_noprefix(struct diff_options *options)
3731
0
{
3732
0
  options->a_prefix = options->b_prefix = "";
3733
0
}
3734
3735
void diff_set_default_prefix(struct diff_options *options)
3736
0
{
3737
0
  options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3738
0
  options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3739
0
}
3740
3741
struct userdiff_driver *get_textconv(struct repository *r,
3742
             struct diff_filespec *one)
3743
0
{
3744
0
  if (!DIFF_FILE_VALID(one))
3745
0
    return NULL;
3746
3747
0
  diff_filespec_load_driver(one, r->index);
3748
0
  return userdiff_get_textconv(r, one->driver);
3749
0
}
3750
3751
static struct string_list *additional_headers(struct diff_options *o,
3752
                const char *path)
3753
0
{
3754
0
  if (!o->additional_path_headers)
3755
0
    return NULL;
3756
0
  return strmap_get(o->additional_path_headers, path);
3757
0
}
3758
3759
static void add_formatted_header(struct strbuf *msg,
3760
          const char *header,
3761
          const char *line_prefix,
3762
          const char *meta,
3763
          const char *reset)
3764
0
{
3765
0
  const char *next, *newline;
3766
3767
0
  for (next = header; *next; next = newline) {
3768
0
    newline = strchrnul(next, '\n');
3769
0
    strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3770
0
          (int)(newline - next), next, reset);
3771
0
    if (*newline)
3772
0
      newline++;
3773
0
  }
3774
0
}
3775
3776
static void add_formatted_headers(struct strbuf *msg,
3777
          struct string_list *more_headers,
3778
          const char *line_prefix,
3779
          const char *meta,
3780
          const char *reset)
3781
0
{
3782
0
  int i;
3783
3784
0
  for (i = 0; i < more_headers->nr; i++)
3785
0
    add_formatted_header(msg, more_headers->items[i].string,
3786
0
             line_prefix, meta, reset);
3787
0
}
3788
3789
static int diff_filepair_is_phoney(struct diff_filespec *one,
3790
           struct diff_filespec *two)
3791
0
{
3792
  /*
3793
   * This function specifically looks for pairs injected by
3794
   * create_filepairs_for_header_only_notifications().  Such
3795
   * pairs are "phoney" in that they do not represent any
3796
   * content or even mode difference, but were inserted because
3797
   * diff_queued_diff previously had no pair associated with
3798
   * that path but we needed some pair to avoid losing the
3799
   * "remerge CONFLICT" header associated with the path.
3800
   */
3801
0
  return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3802
0
}
3803
3804
static int set_diff_algorithm(struct diff_options *opts,
3805
            const char *alg)
3806
0
{
3807
0
  long value = parse_algorithm_value(alg);
3808
3809
0
  if (value < 0)
3810
0
    return -1;
3811
3812
  /* clear out previous settings */
3813
0
  opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3814
0
  opts->xdl_opts |= value;
3815
3816
0
  return 0;
3817
0
}
3818
3819
static void builtin_diff(const char *name_a,
3820
       const char *name_b,
3821
       struct diff_filespec *one,
3822
       struct diff_filespec *two,
3823
       const char *xfrm_msg,
3824
       int must_show_header,
3825
       struct diff_options *o,
3826
       int complete_rewrite,
3827
       const struct range_set *line_ranges)
3828
0
{
3829
0
  mmfile_t mf1, mf2;
3830
0
  const char *lbl[2];
3831
0
  char *a_one, *b_two;
3832
0
  const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3833
0
  const char *reset = diff_get_color_opt(o, DIFF_RESET);
3834
0
  const char *a_prefix, *b_prefix;
3835
0
  struct userdiff_driver *textconv_one = NULL;
3836
0
  struct userdiff_driver *textconv_two = NULL;
3837
0
  struct strbuf header = STRBUF_INIT;
3838
0
  const char *line_prefix = diff_line_prefix(o);
3839
3840
0
  diff_set_mnemonic_prefix(o, "a/", "b/");
3841
0
  if (o->flags.reverse_diff) {
3842
0
    a_prefix = o->b_prefix;
3843
0
    b_prefix = o->a_prefix;
3844
0
  } else {
3845
0
    a_prefix = o->a_prefix;
3846
0
    b_prefix = o->b_prefix;
3847
0
  }
3848
3849
0
  if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3850
0
      (!one->mode || S_ISGITLINK(one->mode)) &&
3851
0
      (!two->mode || S_ISGITLINK(two->mode)) &&
3852
0
      (!diff_filepair_is_phoney(one, two))) {
3853
0
    show_submodule_diff_summary(o, one->path ? one->path : two->path,
3854
0
        &one->oid, &two->oid,
3855
0
        two->dirty_submodule);
3856
0
    o->found_changes = 1;
3857
0
    return;
3858
0
  } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3859
0
       (!one->mode || S_ISGITLINK(one->mode)) &&
3860
0
       (!two->mode || S_ISGITLINK(two->mode)) &&
3861
0
       (!diff_filepair_is_phoney(one, two))) {
3862
0
    show_submodule_inline_diff(o, one->path ? one->path : two->path,
3863
0
        &one->oid, &two->oid,
3864
0
        two->dirty_submodule);
3865
0
    o->found_changes = 1;
3866
0
    return;
3867
0
  }
3868
3869
0
  if (o->flags.allow_textconv) {
3870
0
    textconv_one = get_textconv(o->repo, one);
3871
0
    textconv_two = get_textconv(o->repo, two);
3872
0
  }
3873
3874
  /* Never use a non-valid filename anywhere if at all possible */
3875
0
  name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3876
0
  name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3877
3878
0
  a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3879
0
  b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3880
0
  lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3881
0
  lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3882
0
  if (diff_filepair_is_phoney(one, two)) {
3883
    /*
3884
     * We should only reach this point for pairs generated from
3885
     * create_filepairs_for_header_only_notifications().  For
3886
     * these, we want to avoid the "/dev/null" special casing
3887
     * above, because we do not want such pairs shown as either
3888
     * "new file" or "deleted file" below.
3889
     */
3890
0
    lbl[0] = a_one;
3891
0
    lbl[1] = b_two;
3892
0
  }
3893
0
  strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3894
0
  if (lbl[0][0] == '/') {
3895
    /* /dev/null */
3896
0
    strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3897
0
    if (xfrm_msg)
3898
0
      strbuf_addstr(&header, xfrm_msg);
3899
0
    o->found_changes = 1;
3900
0
    must_show_header = 1;
3901
0
  }
3902
0
  else if (lbl[1][0] == '/') {
3903
0
    strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3904
0
    if (xfrm_msg)
3905
0
      strbuf_addstr(&header, xfrm_msg);
3906
0
    o->found_changes = 1;
3907
0
    must_show_header = 1;
3908
0
  }
3909
0
  else {
3910
0
    if (one->mode != two->mode) {
3911
0
      strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3912
0
      strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3913
0
      o->found_changes = 1;
3914
0
      must_show_header = 1;
3915
0
    }
3916
0
    if (xfrm_msg)
3917
0
      strbuf_addstr(&header, xfrm_msg);
3918
3919
    /*
3920
     * we do not run diff between different kind
3921
     * of objects.
3922
     */
3923
0
    if ((one->mode ^ two->mode) & S_IFMT)
3924
0
      goto free_ab_and_return;
3925
0
    if (complete_rewrite &&
3926
0
        (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3927
0
        (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3928
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3929
0
           header.buf, header.len, 0);
3930
0
      strbuf_reset(&header);
3931
0
      emit_rewrite_diff(name_a, name_b, one, two,
3932
0
            textconv_one, textconv_two, o);
3933
0
      o->found_changes = 1;
3934
0
      goto free_ab_and_return;
3935
0
    }
3936
0
  }
3937
3938
0
  if (o->irreversible_delete && lbl[1][0] == '/') {
3939
0
    emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3940
0
         header.len, 0);
3941
0
    strbuf_reset(&header);
3942
0
    goto free_ab_and_return;
3943
0
  } else if (!o->flags.text &&
3944
0
       ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3945
0
         (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3946
0
    struct strbuf sb = STRBUF_INIT;
3947
0
    if (!one->data && !two->data &&
3948
0
        S_ISREG(one->mode) && S_ISREG(two->mode) &&
3949
0
        !o->flags.binary) {
3950
0
      if (oideq(&one->oid, &two->oid)) {
3951
0
        if (must_show_header)
3952
0
          emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3953
0
               header.buf, header.len,
3954
0
               0);
3955
0
        goto free_ab_and_return;
3956
0
      }
3957
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3958
0
           header.buf, header.len, 0);
3959
0
      strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3960
0
            diff_line_prefix(o), lbl[0], lbl[1]);
3961
0
      emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3962
0
           sb.buf, sb.len, 0);
3963
0
      strbuf_release(&sb);
3964
0
      o->found_changes = 1;
3965
0
      goto free_ab_and_return;
3966
0
    }
3967
0
    if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3968
0
        fill_mmfile(o->repo, &mf2, two) < 0)
3969
0
      die("unable to read files to diff");
3970
    /* Quite common confusing case */
3971
0
    if (mf1.size == mf2.size &&
3972
0
        !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3973
0
      if (must_show_header)
3974
0
        emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3975
0
             header.buf, header.len, 0);
3976
0
      goto free_ab_and_return;
3977
0
    }
3978
0
    emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3979
0
    strbuf_reset(&header);
3980
0
    if (o->flags.binary)
3981
0
      emit_binary_diff(o, &mf1, &mf2);
3982
0
    else {
3983
0
      strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3984
0
            diff_line_prefix(o), lbl[0], lbl[1]);
3985
0
      emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3986
0
           sb.buf, sb.len, 0);
3987
0
      strbuf_release(&sb);
3988
0
    }
3989
0
    o->found_changes = 1;
3990
0
  } else {
3991
    /* Crazy xdl interfaces.. */
3992
0
    const char *diffopts;
3993
0
    const char *v;
3994
0
    xpparam_t xpp;
3995
0
    xdemitconf_t xecfg;
3996
0
    struct emit_callback ecbdata;
3997
0
    unsigned ws_rule;
3998
0
    const struct userdiff_funcname *pe;
3999
4000
0
    if (must_show_header) {
4001
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
4002
0
           header.buf, header.len, 0);
4003
0
      strbuf_reset(&header);
4004
0
    }
4005
4006
0
    mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
4007
0
    mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
4008
4009
0
    ws_rule = whitespace_rule(o->repo->index, name_b);
4010
4011
    /* symlink being an incomplete line is not a news */
4012
0
    if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4013
0
      ws_rule &= ~WS_INCOMPLETE_LINE;
4014
4015
0
    pe = diff_funcname_pattern(o, one);
4016
0
    if (!pe)
4017
0
      pe = diff_funcname_pattern(o, two);
4018
4019
0
    memset(&xpp, 0, sizeof(xpp));
4020
0
    memset(&xecfg, 0, sizeof(xecfg));
4021
0
    memset(&ecbdata, 0, sizeof(ecbdata));
4022
0
    if (o->flags.suppress_diff_headers)
4023
0
      lbl[0] = NULL;
4024
0
    ecbdata.label_path = lbl;
4025
0
    ecbdata.color_diff = o->use_color;
4026
0
    ecbdata.ws_rule = ws_rule;
4027
0
    if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
4028
0
      check_blank_at_eof(&mf1, &mf2, &ecbdata);
4029
0
    ecbdata.opt = o;
4030
0
    if (header.len && !o->flags.suppress_diff_headers)
4031
0
      ecbdata.header = &header;
4032
0
    xpp.flags = o->xdl_opts;
4033
0
    xpp.ignore_regex = o->ignore_regex;
4034
0
    xpp.ignore_regex_nr = o->ignore_regex_nr;
4035
0
    xpp.anchors = o->anchors;
4036
0
    xpp.anchors_nr = o->anchors_nr;
4037
0
    xecfg.ctxlen = o->context;
4038
0
    xecfg.interhunkctxlen = o->interhunkcontext;
4039
0
    xecfg.flags = XDL_EMIT_FUNCNAMES;
4040
0
    if (o->flags.funccontext)
4041
0
      xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
4042
0
    if (pe)
4043
0
      xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
4044
4045
0
    diffopts = getenv("GIT_DIFF_OPTS");
4046
0
    if (!diffopts)
4047
0
      ;
4048
0
    else if (skip_prefix(diffopts, "--unified=", &v))
4049
0
      xecfg.ctxlen = strtoul(v, NULL, 10);
4050
0
    else if (skip_prefix(diffopts, "-u", &v))
4051
0
      xecfg.ctxlen = strtoul(v, NULL, 10);
4052
4053
0
    if (o->word_diff)
4054
0
      init_diff_words_data(&ecbdata, o, one, two);
4055
0
    if (!o->file) {
4056
      /*
4057
       * Unlike the normal output case, we need to ignore the
4058
       * return value from xdi_diff_outf() here, because
4059
       * xdi_diff_outf() takes non-zero return from its
4060
       * callback function as a sign of error and returns
4061
       * early (which is why we return non-zero from our
4062
       * callback, quick_consume()).  Unfortunately,
4063
       * xdi_diff_outf() signals an error by returning
4064
       * non-zero.
4065
       */
4066
0
      xdi_diff_outf(&mf1, &mf2, NULL, quick_consume,
4067
0
              &ecbdata, &xpp, &xecfg);
4068
0
    } else if (line_ranges) {
4069
0
      struct line_range_callback lr_state;
4070
0
      unsigned int i;
4071
0
      long max_span = 0;
4072
4073
0
      memset(&lr_state, 0, sizeof(lr_state));
4074
0
      lr_state.orig_line_fn = fn_out_consume;
4075
0
      lr_state.orig_cb_data = &ecbdata;
4076
0
      lr_state.ranges = line_ranges;
4077
0
      strbuf_init(&lr_state.rhunk, 0);
4078
0
      strbuf_init(&lr_state.pending_rm, 0);
4079
4080
      /*
4081
       * Inflate ctxlen so that all changes within
4082
       * any single range are merged into one xdiff
4083
       * hunk and the inter-change context is emitted.
4084
       * The callback clips back to range boundaries.
4085
       *
4086
       * The optimal ctxlen depends on where changes
4087
       * fall within the range, which is only known
4088
       * after xdiff runs; the max range span is the
4089
       * upper bound that guarantees correctness in a
4090
       * single pass.
4091
       */
4092
0
      for (i = 0; i < line_ranges->nr; i++) {
4093
0
        long span = line_ranges->ranges[i].end -
4094
0
              line_ranges->ranges[i].start;
4095
0
        if (span > max_span)
4096
0
          max_span = span;
4097
0
      }
4098
0
      if (max_span > xecfg.ctxlen)
4099
0
        xecfg.ctxlen = max_span;
4100
4101
0
      if (xdi_diff_outf(&mf1, &mf2,
4102
0
            line_range_hunk_fn,
4103
0
            line_range_line_fn,
4104
0
            &lr_state, &xpp, &xecfg))
4105
0
        die("unable to generate diff for %s",
4106
0
            one->path);
4107
4108
0
      flush_rhunk(&lr_state);
4109
0
      if (lr_state.ret)
4110
0
        die("unable to generate diff for %s",
4111
0
            one->path);
4112
0
      strbuf_release(&lr_state.rhunk);
4113
0
      strbuf_release(&lr_state.pending_rm);
4114
0
    } else if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
4115
0
           &ecbdata, &xpp, &xecfg))
4116
0
      die("unable to generate diff for %s", one->path);
4117
0
    if (o->word_diff)
4118
0
      free_diff_words_data(&ecbdata);
4119
0
    if (textconv_one)
4120
0
      free(mf1.ptr);
4121
0
    if (textconv_two)
4122
0
      free(mf2.ptr);
4123
0
    xdiff_clear_find_func(&xecfg);
4124
0
  }
4125
4126
0
 free_ab_and_return:
4127
0
  strbuf_release(&header);
4128
0
  diff_free_filespec_data(one);
4129
0
  diff_free_filespec_data(two);
4130
0
  free(a_one);
4131
0
  free(b_two);
4132
0
  return;
4133
0
}
4134
4135
static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
4136
0
{
4137
0
  if (!is_renamed) {
4138
0
    if (p->status == DIFF_STATUS_ADDED) {
4139
0
      if (S_ISLNK(p->two->mode))
4140
0
        return "new +l";
4141
0
      else if ((p->two->mode & 0777) == 0755)
4142
0
        return "new +x";
4143
0
      else
4144
0
        return "new";
4145
0
    } else if (p->status == DIFF_STATUS_DELETED)
4146
0
      return "gone";
4147
0
  }
4148
0
  if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
4149
0
    return "mode -l";
4150
0
  else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
4151
0
    return "mode +l";
4152
0
  else if ((p->one->mode & 0777) == 0644 &&
4153
0
     (p->two->mode & 0777) == 0755)
4154
0
    return "mode +x";
4155
0
  else if ((p->one->mode & 0777) == 0755 &&
4156
0
     (p->two->mode & 0777) == 0644)
4157
0
    return "mode -x";
4158
0
  return NULL;
4159
0
}
4160
4161
static void builtin_diffstat(const char *name_a, const char *name_b,
4162
           struct diff_filespec *one,
4163
           struct diff_filespec *two,
4164
           struct diffstat_t *diffstat,
4165
           struct diff_options *o,
4166
           struct diff_filepair *p)
4167
0
{
4168
0
  mmfile_t mf1, mf2;
4169
0
  struct diffstat_file *data;
4170
0
  int may_differ;
4171
0
  int complete_rewrite = 0;
4172
4173
0
  if (!DIFF_PAIR_UNMERGED(p)) {
4174
0
    if (p->status == DIFF_STATUS_MODIFIED && p->score)
4175
0
      complete_rewrite = 1;
4176
0
  }
4177
4178
0
  data = diffstat_add(diffstat, name_a, name_b);
4179
0
  data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
4180
0
  if (o->flags.stat_with_summary)
4181
0
    data->comments = get_compact_summary(p, data->is_renamed);
4182
4183
0
  if (!one || !two) {
4184
0
    data->is_unmerged = 1;
4185
0
    return;
4186
0
  }
4187
4188
  /* saves some reads if true, not a guarantee of diff outcome */
4189
0
  may_differ = !(one->oid_valid && two->oid_valid &&
4190
0
      oideq(&one->oid, &two->oid));
4191
4192
0
  if (diff_filespec_is_binary(o->repo, one) ||
4193
0
      diff_filespec_is_binary(o->repo, two)) {
4194
0
    data->is_binary = 1;
4195
0
    if (!may_differ) {
4196
0
      data->added = 0;
4197
0
      data->deleted = 0;
4198
0
    } else {
4199
0
      data->added = diff_filespec_size(o->repo, two);
4200
0
      data->deleted = diff_filespec_size(o->repo, one);
4201
0
    }
4202
0
  }
4203
4204
0
  else if (complete_rewrite) {
4205
0
    diff_populate_filespec(o->repo, one, NULL);
4206
0
    diff_populate_filespec(o->repo, two, NULL);
4207
0
    data->deleted = count_lines(one->data, one->size);
4208
0
    data->added = count_lines(two->data, two->size);
4209
0
  }
4210
4211
0
  else if (may_differ) {
4212
    /* Crazy xdl interfaces.. */
4213
0
    xpparam_t xpp;
4214
0
    xdemitconf_t xecfg;
4215
4216
0
    if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4217
0
        fill_mmfile(o->repo, &mf2, two) < 0)
4218
0
      die("unable to read files to diff");
4219
4220
0
    memset(&xpp, 0, sizeof(xpp));
4221
0
    memset(&xecfg, 0, sizeof(xecfg));
4222
0
    xpp.flags = o->xdl_opts;
4223
0
    xpp.ignore_regex = o->ignore_regex;
4224
0
    xpp.ignore_regex_nr = o->ignore_regex_nr;
4225
0
    xpp.anchors = o->anchors;
4226
0
    xpp.anchors_nr = o->anchors_nr;
4227
0
    xecfg.ctxlen = o->context;
4228
0
    xecfg.interhunkctxlen = o->interhunkcontext;
4229
0
    xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
4230
0
    if (xdi_diff_outf(&mf1, &mf2, NULL,
4231
0
          diffstat_consume, diffstat, &xpp, &xecfg))
4232
0
      die("unable to generate diffstat for %s", one->path);
4233
4234
0
    if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
4235
0
      struct diffstat_file *file =
4236
0
        diffstat->files[diffstat->nr - 1];
4237
      /*
4238
       * Omit diffstats of modified files where nothing changed.
4239
       * Even if may_differ, this might be the case due to
4240
       * ignoring whitespace changes, etc.
4241
       *
4242
       * But note that we special-case additions, deletions,
4243
       * renames, and mode changes as adding an empty file,
4244
       * for example is still of interest.
4245
       */
4246
0
      if ((p->status == DIFF_STATUS_MODIFIED)
4247
0
        && !file->added
4248
0
        && !file->deleted
4249
0
        && one->mode == two->mode) {
4250
0
        free_diffstat_file(file);
4251
0
        diffstat->nr--;
4252
0
      }
4253
0
    }
4254
0
  }
4255
4256
0
  diff_free_filespec_data(one);
4257
0
  diff_free_filespec_data(two);
4258
0
}
4259
4260
static void builtin_checkdiff(const char *name_a, const char *name_b,
4261
            const char *attr_path,
4262
            struct diff_filespec *one,
4263
            struct diff_filespec *two,
4264
            struct diff_options *o)
4265
0
{
4266
0
  mmfile_t mf1, mf2;
4267
0
  struct checkdiff_t data;
4268
4269
0
  if (!two)
4270
0
    return;
4271
4272
0
  memset(&data, 0, sizeof(data));
4273
0
  data.filename = name_b ? name_b : name_a;
4274
0
  data.lineno = 0;
4275
0
  data.o = o;
4276
0
  data.ws_rule = whitespace_rule(o->repo->index, attr_path);
4277
0
  data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
4278
4279
  /* symlink being an incomplete line is not a news */
4280
0
  if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4281
0
    data.ws_rule &= ~WS_INCOMPLETE_LINE;
4282
4283
0
  if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4284
0
      fill_mmfile(o->repo, &mf2, two) < 0)
4285
0
    die("unable to read files to diff");
4286
4287
  /*
4288
   * All the other codepaths check both sides, but not checking
4289
   * the "old" side here is deliberate.  We are checking the newly
4290
   * introduced changes, and as long as the "new" side is text, we
4291
   * can and should check what it introduces.
4292
   */
4293
0
  if (diff_filespec_is_binary(o->repo, two))
4294
0
    goto free_and_return;
4295
0
  else {
4296
    /* Crazy xdl interfaces.. */
4297
0
    xpparam_t xpp;
4298
0
    xdemitconf_t xecfg;
4299
4300
0
    memset(&xpp, 0, sizeof(xpp));
4301
0
    memset(&xecfg, 0, sizeof(xecfg));
4302
0
    xecfg.ctxlen = 1; /* at least one context line */
4303
0
    xpp.flags = 0;
4304
0
    if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
4305
0
          checkdiff_consume, &data,
4306
0
          &xpp, &xecfg))
4307
0
      die("unable to generate checkdiff for %s", one->path);
4308
4309
0
    if (data.ws_rule & WS_BLANK_AT_EOF) {
4310
0
      struct emit_callback ecbdata;
4311
0
      int blank_at_eof;
4312
4313
0
      ecbdata.ws_rule = data.ws_rule;
4314
0
      check_blank_at_eof(&mf1, &mf2, &ecbdata);
4315
0
      blank_at_eof = ecbdata.blank_at_eof_in_postimage;
4316
4317
0
      if (blank_at_eof) {
4318
0
        static char *err;
4319
0
        if (!err)
4320
0
          err = whitespace_error_string(WS_BLANK_AT_EOF);
4321
0
        fprintf(o->file, "%s:%d: %s.\n",
4322
0
          data.filename, blank_at_eof, err);
4323
0
        data.status = 1; /* report errors */
4324
0
      }
4325
0
    }
4326
0
  }
4327
0
 free_and_return:
4328
0
  diff_free_filespec_data(one);
4329
0
  diff_free_filespec_data(two);
4330
0
  if (data.status)
4331
0
    o->flags.check_failed = 1;
4332
0
}
4333
4334
struct diff_filespec *alloc_filespec(const char *path)
4335
0
{
4336
0
  struct diff_filespec *spec;
4337
4338
0
  FLEXPTR_ALLOC_STR(spec, path, path);
4339
0
  spec->count = 1;
4340
0
  spec->is_binary = -1;
4341
0
  return spec;
4342
0
}
4343
4344
void free_filespec(struct diff_filespec *spec)
4345
0
{
4346
0
  if (!--spec->count) {
4347
0
    diff_free_filespec_data(spec);
4348
0
    free(spec);
4349
0
  }
4350
0
}
4351
4352
void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
4353
       int oid_valid, unsigned short mode)
4354
0
{
4355
0
  if (mode) {
4356
0
    spec->mode = canon_mode(mode);
4357
0
    oidcpy(&spec->oid, oid);
4358
0
    spec->oid_valid = oid_valid;
4359
0
  }
4360
0
}
4361
4362
/*
4363
 * Given a name and sha1 pair, if the index tells us the file in
4364
 * the work tree has that object contents, return true, so that
4365
 * prepare_temp_file() does not have to inflate and extract.
4366
 */
4367
static int reuse_worktree_file(struct index_state *istate,
4368
             const char *name,
4369
             const struct object_id *oid,
4370
             int want_file)
4371
0
{
4372
0
  const struct cache_entry *ce;
4373
0
  struct stat st;
4374
0
  int pos, len;
4375
4376
  /*
4377
   * We do not read the cache ourselves here, because the
4378
   * benchmark with my previous version that always reads cache
4379
   * shows that it makes things worse for diff-tree comparing
4380
   * two linux-2.6 kernel trees in an already checked out work
4381
   * tree.  This is because most diff-tree comparisons deal with
4382
   * only a small number of files, while reading the cache is
4383
   * expensive for a large project, and its cost outweighs the
4384
   * savings we get by not inflating the object to a temporary
4385
   * file.  Practically, this code only helps when we are used
4386
   * by diff-cache --cached, which does read the cache before
4387
   * calling us.
4388
   */
4389
0
  if (!istate->cache)
4390
0
    return 0;
4391
4392
  /* We want to avoid the working directory if our caller
4393
   * doesn't need the data in a normal file, this system
4394
   * is rather slow with its stat/open/mmap/close syscalls,
4395
   * and the object is contained in a pack file.  The pack
4396
   * is probably already open and will be faster to obtain
4397
   * the data through than the working directory.  Loose
4398
   * objects however would tend to be slower as they need
4399
   * to be individually opened and inflated.
4400
   */
4401
0
  if (!FAST_WORKING_DIRECTORY && !want_file &&
4402
0
      has_object_pack(istate->repo, oid))
4403
0
    return 0;
4404
4405
  /*
4406
   * Similarly, if we'd have to convert the file contents anyway, that
4407
   * makes the optimization not worthwhile.
4408
   */
4409
0
  if (!want_file && would_convert_to_git(istate, name))
4410
0
    return 0;
4411
4412
  /*
4413
   * If this path does not match our sparse-checkout definition,
4414
   * then the file will not be in the working directory.
4415
   */
4416
0
  if (!path_in_sparse_checkout(name, istate))
4417
0
    return 0;
4418
4419
0
  len = strlen(name);
4420
0
  pos = index_name_pos(istate, name, len);
4421
0
  if (pos < 0)
4422
0
    return 0;
4423
0
  ce = istate->cache[pos];
4424
4425
  /*
4426
   * This is not the sha1 we are looking for, or
4427
   * unreusable because it is not a regular file.
4428
   */
4429
0
  if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4430
0
    return 0;
4431
4432
  /*
4433
   * If ce is marked as "assume unchanged", there is no
4434
   * guarantee that work tree matches what we are looking for.
4435
   */
4436
0
  if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4437
0
    return 0;
4438
4439
  /*
4440
   * If ce matches the file in the work tree, we can reuse it.
4441
   */
4442
0
  if (ce_uptodate(ce) ||
4443
0
      (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4444
0
    return 1;
4445
4446
0
  return 0;
4447
0
}
4448
4449
static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4450
0
{
4451
0
  struct strbuf buf = STRBUF_INIT;
4452
0
  const char *dirty = "";
4453
4454
  /* Are we looking at the work tree? */
4455
0
  if (s->dirty_submodule)
4456
0
    dirty = "-dirty";
4457
4458
0
  strbuf_addf(&buf, "Subproject commit %s%s\n",
4459
0
        oid_to_hex(&s->oid), dirty);
4460
0
  s->size = buf.len;
4461
0
  if (size_only) {
4462
0
    s->data = NULL;
4463
0
    strbuf_release(&buf);
4464
0
  } else {
4465
0
    s->data = strbuf_detach(&buf, NULL);
4466
0
    s->should_free = 1;
4467
0
  }
4468
0
  return 0;
4469
0
}
4470
4471
/*
4472
 * While doing rename detection and pickaxe operation, we may need to
4473
 * grab the data for the blob (or file) for our own in-core comparison.
4474
 * diff_filespec has data and size fields for this purpose.
4475
 */
4476
int diff_populate_filespec(struct repository *r,
4477
         struct diff_filespec *s,
4478
         const struct diff_populate_filespec_options *options)
4479
0
{
4480
0
  int size_only = options ? options->check_size_only : 0;
4481
0
  int check_binary = options ? options->check_binary : 0;
4482
0
  int err = 0;
4483
0
  int conv_flags = global_conv_flags_eol;
4484
  /*
4485
   * demote FAIL to WARN to allow inspecting the situation
4486
   * instead of refusing.
4487
   */
4488
0
  if (conv_flags & CONV_EOL_RNDTRP_DIE)
4489
0
    conv_flags = CONV_EOL_RNDTRP_WARN;
4490
4491
0
  if (!DIFF_FILE_VALID(s))
4492
0
    die("internal error: asking to populate invalid file.");
4493
0
  if (S_ISDIR(s->mode))
4494
0
    return -1;
4495
4496
0
  if (s->data)
4497
0
    return 0;
4498
4499
0
  if (size_only && 0 < s->size)
4500
0
    return 0;
4501
4502
0
  if (S_ISGITLINK(s->mode))
4503
0
    return diff_populate_gitlink(s, size_only);
4504
4505
0
  if (!s->oid_valid ||
4506
0
      reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4507
0
    struct strbuf buf = STRBUF_INIT;
4508
0
    struct stat st;
4509
0
    int fd;
4510
4511
0
    if (lstat(s->path, &st) < 0) {
4512
0
    err_empty:
4513
0
      err = -1;
4514
0
    empty:
4515
0
      s->data = (char *)"";
4516
0
      s->size = 0;
4517
0
      return err;
4518
0
    }
4519
0
    s->size = xsize_t(st.st_size);
4520
0
    if (!s->size)
4521
0
      goto empty;
4522
0
    if (S_ISLNK(st.st_mode)) {
4523
0
      struct strbuf sb = STRBUF_INIT;
4524
4525
0
      if (strbuf_readlink(&sb, s->path, s->size))
4526
0
        goto err_empty;
4527
0
      s->size = sb.len;
4528
0
      s->data = strbuf_detach(&sb, NULL);
4529
0
      s->should_free = 1;
4530
0
      return 0;
4531
0
    }
4532
4533
    /*
4534
     * Even if the caller would be happy with getting
4535
     * only the size, we cannot return early at this
4536
     * point if the path requires us to run the content
4537
     * conversion.
4538
     */
4539
0
    if (size_only && !would_convert_to_git(r->index, s->path))
4540
0
      return 0;
4541
4542
    /*
4543
     * Note: this check uses xsize_t(st.st_size) that may
4544
     * not be the true size of the blob after it goes
4545
     * through convert_to_git().  This may not strictly be
4546
     * correct, but the whole point of big_file_threshold
4547
     * and is_binary check being that we want to avoid
4548
     * opening the file and inspecting the contents, this
4549
     * is probably fine.
4550
     */
4551
0
    if (check_binary &&
4552
0
        s->size > repo_settings_get_big_file_threshold(the_repository) &&
4553
0
        s->is_binary == -1) {
4554
0
      s->is_binary = 1;
4555
0
      return 0;
4556
0
    }
4557
0
    fd = open(s->path, O_RDONLY);
4558
0
    if (fd < 0)
4559
0
      goto err_empty;
4560
0
    s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4561
0
    close(fd);
4562
0
    s->should_munmap = 1;
4563
4564
    /*
4565
     * Convert from working tree format to canonical git format
4566
     */
4567
0
    if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4568
0
      size_t size = 0;
4569
0
      munmap(s->data, s->size);
4570
0
      s->should_munmap = 0;
4571
0
      s->data = strbuf_detach(&buf, &size);
4572
0
      s->size = size;
4573
0
      s->should_free = 1;
4574
0
    }
4575
0
  }
4576
0
  else {
4577
0
    size_t size_st = 0;
4578
0
    struct object_info info = {
4579
0
      .sizep = &size_st
4580
0
    };
4581
4582
0
    if (!(size_only || check_binary))
4583
      /*
4584
       * Set contentp, since there is no chance that merely
4585
       * the size is sufficient.
4586
       */
4587
0
      info.contentp = &s->data;
4588
4589
0
    if (options && options->missing_object_cb) {
4590
0
      if (!odb_read_object_info_extended(r->objects, &s->oid, &info,
4591
0
                 OBJECT_INFO_LOOKUP_REPLACE |
4592
0
                 OBJECT_INFO_SKIP_FETCH_OBJECT))
4593
0
        goto object_read;
4594
0
      options->missing_object_cb(options->missing_object_data);
4595
0
    }
4596
0
    if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4597
0
              OBJECT_INFO_LOOKUP_REPLACE))
4598
0
      die("unable to read %s", oid_to_hex(&s->oid));
4599
4600
0
object_read:
4601
0
    s->size = cast_size_t_to_ulong(size_st);
4602
0
    if (size_only || check_binary) {
4603
0
      if (size_only)
4604
0
        return 0;
4605
0
      if (s->size > repo_settings_get_big_file_threshold(the_repository) &&
4606
0
          s->is_binary == -1) {
4607
0
        s->is_binary = 1;
4608
0
        return 0;
4609
0
      }
4610
0
    }
4611
0
    if (!info.contentp) {
4612
0
      info.contentp = &s->data;
4613
0
      if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4614
0
                OBJECT_INFO_LOOKUP_REPLACE))
4615
0
        die("unable to read %s", oid_to_hex(&s->oid));
4616
0
      s->size = cast_size_t_to_ulong(size_st);
4617
0
    }
4618
0
    s->should_free = 1;
4619
0
  }
4620
0
  return 0;
4621
0
}
4622
4623
void diff_free_filespec_blob(struct diff_filespec *s)
4624
0
{
4625
0
  if (s->should_free)
4626
0
    free(s->data);
4627
0
  else if (s->should_munmap)
4628
0
    munmap(s->data, s->size);
4629
4630
0
  if (s->should_free || s->should_munmap) {
4631
0
    s->should_free = s->should_munmap = 0;
4632
0
    s->data = NULL;
4633
0
  }
4634
0
}
4635
4636
void diff_free_filespec_data(struct diff_filespec *s)
4637
0
{
4638
0
  if (!s)
4639
0
    return;
4640
4641
0
  diff_free_filespec_blob(s);
4642
0
  FREE_AND_NULL(s->cnt_data);
4643
0
}
4644
4645
static void prep_temp_blob(struct index_state *istate,
4646
         const char *path, struct diff_tempfile *temp,
4647
         void *blob,
4648
         unsigned long size,
4649
         const struct object_id *oid,
4650
         int mode)
4651
0
{
4652
0
  struct strbuf buf = STRBUF_INIT;
4653
0
  char *path_dup = xstrdup(path);
4654
0
  const char *base = basename(path_dup);
4655
0
  struct checkout_metadata meta;
4656
4657
0
  init_checkout_metadata(&meta, NULL, NULL, oid);
4658
4659
0
  temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4660
0
  if (!temp->tempfile)
4661
0
    die_errno("unable to create temp-file");
4662
0
  if (convert_to_working_tree(istate, path,
4663
0
      (const char *)blob, (size_t)size, &buf, &meta)) {
4664
0
    blob = buf.buf;
4665
0
    size = buf.len;
4666
0
  }
4667
0
  if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4668
0
      close_tempfile_gently(temp->tempfile))
4669
0
    die_errno("unable to write temp-file");
4670
0
  temp->name = get_tempfile_path(temp->tempfile);
4671
0
  oid_to_hex_r(temp->hex, oid);
4672
0
  xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4673
0
  strbuf_release(&buf);
4674
0
  free(path_dup);
4675
0
}
4676
4677
static struct diff_tempfile *prepare_temp_file(struct repository *r,
4678
                 struct diff_filespec *one)
4679
0
{
4680
0
  struct diff_tempfile *temp = claim_diff_tempfile();
4681
4682
0
  if (!DIFF_FILE_VALID(one)) {
4683
0
  not_a_valid_file:
4684
    /* A '-' entry produces this for file-2, and
4685
     * a '+' entry produces this for file-1.
4686
     */
4687
0
    temp->name = "/dev/null";
4688
0
    xsnprintf(temp->hex, sizeof(temp->hex), ".");
4689
0
    xsnprintf(temp->mode, sizeof(temp->mode), ".");
4690
0
    return temp;
4691
0
  }
4692
4693
0
  if (!S_ISGITLINK(one->mode) &&
4694
0
      (!one->oid_valid ||
4695
0
       reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4696
0
    struct stat st;
4697
0
    if (lstat(one->path, &st) < 0) {
4698
0
      if (errno == ENOENT)
4699
0
        goto not_a_valid_file;
4700
0
      die_errno("stat(%s)", one->path);
4701
0
    }
4702
0
    if (S_ISLNK(st.st_mode)) {
4703
0
      struct strbuf sb = STRBUF_INIT;
4704
0
      if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4705
0
        die_errno("readlink(%s)", one->path);
4706
0
      prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4707
0
               (one->oid_valid ?
4708
0
          &one->oid : null_oid(the_hash_algo)),
4709
0
               (one->oid_valid ?
4710
0
          one->mode : S_IFLNK));
4711
0
      strbuf_release(&sb);
4712
0
    }
4713
0
    else {
4714
      /* we can borrow from the file in the work tree */
4715
0
      temp->name = one->path;
4716
0
      if (!one->oid_valid)
4717
0
        oid_to_hex_r(temp->hex, null_oid(the_hash_algo));
4718
0
      else
4719
0
        oid_to_hex_r(temp->hex, &one->oid);
4720
      /* Even though we may sometimes borrow the
4721
       * contents from the work tree, we always want
4722
       * one->mode.  mode is trustworthy even when
4723
       * !(one->oid_valid), as long as
4724
       * DIFF_FILE_VALID(one).
4725
       */
4726
0
      xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4727
0
    }
4728
0
    return temp;
4729
0
  }
4730
0
  else {
4731
0
    if (diff_populate_filespec(r, one, NULL))
4732
0
      die("cannot read data blob for %s", one->path);
4733
0
    prep_temp_blob(r->index, one->path, temp,
4734
0
             one->data, one->size,
4735
0
             &one->oid, one->mode);
4736
0
  }
4737
0
  return temp;
4738
0
}
4739
4740
static void add_external_diff_name(struct repository *r,
4741
           struct strvec *argv,
4742
           struct diff_filespec *df)
4743
0
{
4744
0
  struct diff_tempfile *temp = prepare_temp_file(r, df);
4745
0
  strvec_push(argv, temp->name);
4746
0
  strvec_push(argv, temp->hex);
4747
0
  strvec_push(argv, temp->mode);
4748
0
}
4749
4750
/* An external diff command takes:
4751
 *
4752
 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4753
 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
4754
 *
4755
 */
4756
static void run_external_diff(const struct external_diff *pgm,
4757
            const char *name,
4758
            const char *other,
4759
            struct diff_filespec *one,
4760
            struct diff_filespec *two,
4761
            const char *xfrm_msg,
4762
            struct diff_options *o)
4763
0
{
4764
0
  struct child_process cmd = CHILD_PROCESS_INIT;
4765
0
  struct diff_queue_struct *q = &diff_queued_diff;
4766
0
  int rc;
4767
4768
  /*
4769
   * Trivial equality is handled by diff_unmodified_pair() before
4770
   * we get here.  If we don't need to show the diff and the
4771
   * external diff program lacks the ability to tell us whether
4772
   * it's empty then we consider it non-empty without even asking.
4773
   */
4774
0
  if (!pgm->trust_exit_code && !o->file) {
4775
0
    o->found_changes = 1;
4776
0
    return;
4777
0
  }
4778
4779
0
  strvec_push(&cmd.args, pgm->cmd);
4780
0
  strvec_push(&cmd.args, name);
4781
4782
0
  if (one && two) {
4783
0
    add_external_diff_name(o->repo, &cmd.args, one);
4784
0
    add_external_diff_name(o->repo, &cmd.args, two);
4785
0
    if (other) {
4786
0
      strvec_push(&cmd.args, other);
4787
0
      if (xfrm_msg)
4788
0
        strvec_push(&cmd.args, xfrm_msg);
4789
0
    }
4790
0
  }
4791
4792
0
  strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4793
0
         ++o->diff_path_counter);
4794
0
  strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4795
4796
0
  diff_free_filespec_data(one);
4797
0
  diff_free_filespec_data(two);
4798
0
  cmd.use_shell = 1;
4799
0
  if (!o->file)
4800
0
    cmd.no_stdout = 1;
4801
0
  else if (o->file != stdout)
4802
0
    cmd.out = xdup(fileno(o->file));
4803
0
  rc = run_command(&cmd);
4804
0
  if (!pgm->trust_exit_code && rc == 0)
4805
0
    o->found_changes = 1;
4806
0
  else if (pgm->trust_exit_code && rc == 0)
4807
0
    ; /* nothing */
4808
0
  else if (pgm->trust_exit_code && rc == 1)
4809
0
    o->found_changes = 1;
4810
0
  else
4811
0
    die(_("external diff died, stopping at %s"), name);
4812
4813
0
  remove_tempfile();
4814
0
}
4815
4816
static int similarity_index(struct diff_filepair *p)
4817
0
{
4818
0
  return p->score * 100 / MAX_SCORE;
4819
0
}
4820
4821
static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4822
0
{
4823
0
  if (startup_info->have_repository)
4824
0
    return repo_find_unique_abbrev(the_repository, oid, abbrev);
4825
0
  else {
4826
0
    char *hex = oid_to_hex(oid);
4827
0
    if (abbrev < 0)
4828
0
      abbrev = FALLBACK_DEFAULT_ABBREV;
4829
0
    if (abbrev > the_hash_algo->hexsz)
4830
0
      BUG("oid abbreviation out of range: %d", abbrev);
4831
0
    if (abbrev)
4832
0
      hex[abbrev] = '\0';
4833
0
    return hex;
4834
0
  }
4835
0
}
4836
4837
static void fill_metainfo(struct strbuf *msg,
4838
        const char *name,
4839
        const char *other,
4840
        struct diff_filespec *one,
4841
        struct diff_filespec *two,
4842
        struct diff_options *o,
4843
        struct diff_filepair *p,
4844
        int *must_show_header,
4845
        enum git_colorbool use_color)
4846
0
{
4847
0
  const char *set = diff_get_color(use_color, DIFF_METAINFO);
4848
0
  const char *reset = diff_get_color(use_color, DIFF_RESET);
4849
0
  const char *line_prefix = diff_line_prefix(o);
4850
0
  struct string_list *more_headers = NULL;
4851
4852
0
  *must_show_header = 1;
4853
0
  strbuf_init(msg, PATH_MAX * 2 + 300);
4854
0
  switch (p->status) {
4855
0
  case DIFF_STATUS_COPIED:
4856
0
    strbuf_addf(msg, "%s%ssimilarity index %d%%",
4857
0
          line_prefix, set, similarity_index(p));
4858
0
    strbuf_addf(msg, "%s\n%s%scopy from ",
4859
0
          reset,  line_prefix, set);
4860
0
    quote_c_style(name, msg, NULL, 0);
4861
0
    strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4862
0
    quote_c_style(other, msg, NULL, 0);
4863
0
    strbuf_addf(msg, "%s\n", reset);
4864
0
    break;
4865
0
  case DIFF_STATUS_RENAMED:
4866
0
    strbuf_addf(msg, "%s%ssimilarity index %d%%",
4867
0
          line_prefix, set, similarity_index(p));
4868
0
    strbuf_addf(msg, "%s\n%s%srename from ",
4869
0
          reset, line_prefix, set);
4870
0
    quote_c_style(name, msg, NULL, 0);
4871
0
    strbuf_addf(msg, "%s\n%s%srename to ",
4872
0
          reset, line_prefix, set);
4873
0
    quote_c_style(other, msg, NULL, 0);
4874
0
    strbuf_addf(msg, "%s\n", reset);
4875
0
    break;
4876
0
  case DIFF_STATUS_MODIFIED:
4877
0
    if (p->score) {
4878
0
      strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4879
0
            line_prefix,
4880
0
            set, similarity_index(p), reset);
4881
0
      break;
4882
0
    }
4883
    /* fallthru */
4884
0
  default:
4885
0
    *must_show_header = 0;
4886
0
  }
4887
0
  if ((more_headers = additional_headers(o, name))) {
4888
0
    add_formatted_headers(msg, more_headers,
4889
0
              line_prefix, set, reset);
4890
0
    *must_show_header = 1;
4891
0
  }
4892
0
  if (one && two && !oideq(&one->oid, &two->oid)) {
4893
0
    const unsigned hexsz = the_hash_algo->hexsz;
4894
0
    int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4895
4896
0
    if (o->flags.full_index)
4897
0
      abbrev = hexsz;
4898
4899
0
    if (o->flags.binary) {
4900
0
      mmfile_t mf;
4901
0
      if ((!fill_mmfile(o->repo, &mf, one) &&
4902
0
           diff_filespec_is_binary(o->repo, one)) ||
4903
0
          (!fill_mmfile(o->repo, &mf, two) &&
4904
0
           diff_filespec_is_binary(o->repo, two)))
4905
0
        abbrev = hexsz;
4906
0
    }
4907
0
    strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4908
0
          diff_abbrev_oid(&one->oid, abbrev),
4909
0
          diff_abbrev_oid(&two->oid, abbrev));
4910
0
    if (one->mode == two->mode)
4911
0
      strbuf_addf(msg, " %06o", one->mode);
4912
0
    strbuf_addf(msg, "%s\n", reset);
4913
0
  }
4914
0
}
4915
4916
static void run_diff_cmd(const struct external_diff *pgm,
4917
       const char *name,
4918
       const char *other,
4919
       const char *attr_path,
4920
       struct diff_filespec *one,
4921
       struct diff_filespec *two,
4922
       struct strbuf *msg,
4923
       struct diff_options *o,
4924
       struct diff_filepair *p)
4925
0
{
4926
0
  const char *xfrm_msg = NULL;
4927
0
  int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4928
0
  int must_show_header = 0;
4929
0
  struct userdiff_driver *drv = NULL;
4930
4931
0
  if (o->flags.allow_external || !o->ignore_driver_algorithm)
4932
0
    drv = userdiff_find_by_path(o->repo->index, attr_path);
4933
4934
0
  if (o->flags.allow_external && drv && drv->external.cmd)
4935
0
    pgm = &drv->external;
4936
4937
0
  if (msg) {
4938
    /*
4939
     * don't use colors when the header is intended for an
4940
     * external diff driver
4941
     */
4942
0
    fill_metainfo(msg, name, other, one, two, o, p,
4943
0
            &must_show_header,
4944
0
            pgm ? GIT_COLOR_NEVER : o->use_color);
4945
0
    xfrm_msg = msg->len ? msg->buf : NULL;
4946
0
  }
4947
4948
0
  if (pgm) {
4949
0
    run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4950
0
    return;
4951
0
  }
4952
0
  if (one && two) {
4953
0
    if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4954
0
      set_diff_algorithm(o, drv->algorithm);
4955
4956
0
    builtin_diff(name, other ? other : name,
4957
0
           one, two, xfrm_msg, must_show_header,
4958
0
           o, complete_rewrite, p->line_ranges);
4959
0
    if (p->status == DIFF_STATUS_COPIED ||
4960
0
        p->status == DIFF_STATUS_RENAMED)
4961
0
      o->found_changes = 1;
4962
0
  } else {
4963
0
    if (o->file)
4964
0
      fprintf(o->file, "* Unmerged path %s\n", name);
4965
0
    o->found_changes = 1;
4966
0
  }
4967
0
}
4968
4969
static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4970
0
{
4971
0
  if (DIFF_FILE_VALID(one)) {
4972
0
    if (!one->oid_valid) {
4973
0
      struct stat st;
4974
0
      if (one->is_stdin) {
4975
0
        oidclr(&one->oid, the_repository->hash_algo);
4976
0
        return;
4977
0
      }
4978
0
      if (lstat(one->path, &st) < 0)
4979
0
        die_errno("stat '%s'", one->path);
4980
0
      if (index_path(istate, &one->oid, one->path, &st, 0))
4981
0
        die("cannot hash %s", one->path);
4982
0
    }
4983
0
  }
4984
0
  else
4985
0
    oidclr(&one->oid, the_repository->hash_algo);
4986
0
}
4987
4988
static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4989
0
{
4990
  /* Strip the prefix but do not molest /dev/null and absolute paths */
4991
0
  if (*namep && !is_absolute_path(*namep)) {
4992
0
    *namep += prefix_length;
4993
0
    if (**namep == '/')
4994
0
      ++*namep;
4995
0
  }
4996
0
  if (*otherp && !is_absolute_path(*otherp)) {
4997
0
    *otherp += prefix_length;
4998
0
    if (**otherp == '/')
4999
0
      ++*otherp;
5000
0
  }
5001
0
}
5002
5003
static void run_diff(struct diff_filepair *p, struct diff_options *o)
5004
0
{
5005
0
  const struct external_diff *pgm = external_diff();
5006
0
  struct strbuf msg;
5007
0
  struct diff_filespec *one = p->one;
5008
0
  struct diff_filespec *two = p->two;
5009
0
  const char *name;
5010
0
  const char *other;
5011
0
  const char *attr_path;
5012
5013
0
  name  = one->path;
5014
0
  other = (strcmp(name, two->path) ? two->path : NULL);
5015
0
  attr_path = name;
5016
0
  if (o->prefix_length)
5017
0
    strip_prefix(o->prefix_length, &name, &other);
5018
5019
0
  if (!o->flags.allow_external)
5020
0
    pgm = NULL;
5021
5022
0
  if (DIFF_PAIR_UNMERGED(p)) {
5023
0
    run_diff_cmd(pgm, name, NULL, attr_path,
5024
0
           NULL, NULL, NULL, o, p);
5025
0
    return;
5026
0
  }
5027
5028
0
  diff_fill_oid_info(one, o->repo->index);
5029
0
  diff_fill_oid_info(two, o->repo->index);
5030
5031
0
  if (!pgm &&
5032
0
      DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
5033
0
      (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
5034
    /*
5035
     * a filepair that changes between file and symlink
5036
     * needs to be split into deletion and creation.
5037
     */
5038
0
    struct diff_filespec *null = alloc_filespec(two->path);
5039
0
    run_diff_cmd(NULL, name, other, attr_path,
5040
0
           one, null, &msg,
5041
0
           o, p);
5042
0
    free(null);
5043
0
    strbuf_release(&msg);
5044
5045
0
    null = alloc_filespec(one->path);
5046
0
    run_diff_cmd(NULL, name, other, attr_path,
5047
0
           null, two, &msg, o, p);
5048
0
    free(null);
5049
0
  }
5050
0
  else
5051
0
    run_diff_cmd(pgm, name, other, attr_path,
5052
0
           one, two, &msg, o, p);
5053
5054
0
  strbuf_release(&msg);
5055
0
}
5056
5057
static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
5058
       struct diffstat_t *diffstat)
5059
0
{
5060
0
  const char *name;
5061
0
  const char *other;
5062
5063
0
  if (!o->ignore_driver_algorithm) {
5064
0
    struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
5065
0
                    p->one->path);
5066
5067
0
    if (drv && drv->algorithm)
5068
0
      set_diff_algorithm(o, drv->algorithm);
5069
0
  }
5070
5071
0
  if (DIFF_PAIR_UNMERGED(p)) {
5072
    /* unmerged */
5073
0
    builtin_diffstat(p->one->path, NULL, NULL, NULL,
5074
0
         diffstat, o, p);
5075
0
    return;
5076
0
  }
5077
5078
0
  name = p->one->path;
5079
0
  other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5080
5081
0
  if (o->prefix_length)
5082
0
    strip_prefix(o->prefix_length, &name, &other);
5083
5084
0
  diff_fill_oid_info(p->one, o->repo->index);
5085
0
  diff_fill_oid_info(p->two, o->repo->index);
5086
5087
0
  builtin_diffstat(name, other, p->one, p->two,
5088
0
       diffstat, o, p);
5089
0
}
5090
5091
static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
5092
0
{
5093
0
  const char *name;
5094
0
  const char *other;
5095
0
  const char *attr_path;
5096
5097
0
  if (DIFF_PAIR_UNMERGED(p)) {
5098
    /* unmerged */
5099
0
    return;
5100
0
  }
5101
5102
0
  name = p->one->path;
5103
0
  other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5104
0
  attr_path = other ? other : name;
5105
5106
0
  if (o->prefix_length)
5107
0
    strip_prefix(o->prefix_length, &name, &other);
5108
5109
0
  diff_fill_oid_info(p->one, o->repo->index);
5110
0
  diff_fill_oid_info(p->two, o->repo->index);
5111
5112
0
  builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
5113
0
}
5114
5115
void repo_diff_setup(struct repository *r, struct diff_options *options)
5116
0
{
5117
0
  memcpy(options, &default_diff_options, sizeof(*options));
5118
5119
0
  options->file = stdout;
5120
0
  options->repo = r;
5121
5122
0
  options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
5123
0
  options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
5124
0
  options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
5125
0
  options->abbrev = DEFAULT_ABBREV;
5126
0
  options->line_termination = '\n';
5127
0
  options->break_opt = -1;
5128
0
  options->rename_limit = -1;
5129
0
  options->dirstat_permille = diff_dirstat_permille_default;
5130
0
  options->context = diff_context_default;
5131
0
  options->interhunkcontext = diff_interhunk_context_default;
5132
0
  options->ws_error_highlight = ws_error_highlight_default;
5133
0
  options->flags.rename_empty = 1;
5134
0
  options->flags.relative_name = diff_relative;
5135
0
  options->objfind = NULL;
5136
5137
  /* pathchange left =NULL by default */
5138
0
  options->change = diff_change;
5139
0
  options->add_remove = diff_addremove;
5140
0
  options->use_color = diff_use_color_default;
5141
0
  options->detect_rename = diff_detect_rename_default;
5142
0
  options->xdl_opts |= diff_algorithm;
5143
0
  if (diff_indent_heuristic)
5144
0
    DIFF_XDL_SET(options, INDENT_HEURISTIC);
5145
5146
0
  options->orderfile = xstrdup_or_null(diff_order_file_cfg);
5147
5148
0
  if (!options->flags.ignore_submodule_set)
5149
0
    options->flags.ignore_untracked_in_submodules = 1;
5150
5151
0
  if (diff_no_prefix) {
5152
0
    diff_set_noprefix(options);
5153
0
  } else if (!diff_mnemonic_prefix) {
5154
0
    diff_set_default_prefix(options);
5155
0
  }
5156
5157
0
  options->color_moved = diff_color_moved_default;
5158
0
  options->color_moved_ws_handling = diff_color_moved_ws_default;
5159
0
}
5160
5161
static const char diff_status_letters[] = {
5162
  DIFF_STATUS_ADDED,
5163
  DIFF_STATUS_COPIED,
5164
  DIFF_STATUS_DELETED,
5165
  DIFF_STATUS_MODIFIED,
5166
  DIFF_STATUS_RENAMED,
5167
  DIFF_STATUS_TYPE_CHANGED,
5168
  DIFF_STATUS_UNKNOWN,
5169
  DIFF_STATUS_UNMERGED,
5170
  DIFF_STATUS_FILTER_AON,
5171
  DIFF_STATUS_FILTER_BROKEN,
5172
  '\0',
5173
};
5174
5175
static unsigned int filter_bit['Z' + 1];
5176
5177
static void prepare_filter_bits(void)
5178
0
{
5179
0
  int i;
5180
5181
0
  if (!filter_bit[DIFF_STATUS_ADDED]) {
5182
0
    for (i = 0; diff_status_letters[i]; i++)
5183
0
      filter_bit[(int) diff_status_letters[i]] = (1 << i);
5184
0
  }
5185
0
}
5186
5187
static unsigned filter_bit_tst(char status, const struct diff_options *opt)
5188
0
{
5189
0
  return opt->filter & filter_bit[(int) status];
5190
0
}
5191
5192
unsigned diff_filter_bit(char status)
5193
0
{
5194
0
  prepare_filter_bits();
5195
0
  return filter_bit[(int) status];
5196
0
}
5197
5198
int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
5199
0
{
5200
0
  unsigned forbidden_magic;
5201
5202
0
  if (ps->nr != 1) {
5203
0
    if (die_on_error)
5204
0
      die(_("--follow requires exactly one pathspec"));
5205
0
    return 0;
5206
0
  }
5207
5208
0
  forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
5209
0
             PATHSPEC_LITERAL);
5210
0
  if (forbidden_magic) {
5211
0
    if (die_on_error) {
5212
0
      struct strbuf sb = STRBUF_INIT;
5213
0
      pathspec_magic_names(forbidden_magic, &sb);
5214
0
      die(_("pathspec magic not supported by --follow: %s"),
5215
0
          sb.buf);
5216
0
    }
5217
0
    return 0;
5218
0
  }
5219
5220
0
  return 1;
5221
0
}
5222
5223
void diff_setup_done(struct diff_options *options)
5224
0
{
5225
0
  unsigned check_mask = DIFF_FORMAT_NAME |
5226
0
            DIFF_FORMAT_NAME_STATUS |
5227
0
            DIFF_FORMAT_CHECKDIFF |
5228
0
            DIFF_FORMAT_NO_OUTPUT;
5229
  /*
5230
   * This must be signed because we're comparing against a potentially
5231
   * negative value.
5232
   */
5233
0
  const int hexsz = the_hash_algo->hexsz;
5234
5235
0
  if (options->set_default)
5236
0
    options->set_default(options);
5237
5238
0
  if (HAS_MULTI_BITS(options->output_format & check_mask))
5239
0
    die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
5240
0
      "--name-only", "--name-status", "--check", "-s");
5241
5242
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
5243
0
    die(_("options '%s', '%s', and '%s' cannot be used together"),
5244
0
      "-G", "-S", "--find-object");
5245
5246
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
5247
0
    die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
5248
0
      "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
5249
5250
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
5251
0
    die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
5252
0
      "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
5253
5254
  /*
5255
   * Most of the time we can say "there are changes"
5256
   * only by checking if there are changed paths, but
5257
   * --ignore-whitespace* options force us to look
5258
   * inside contents.
5259
   */
5260
5261
0
  if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
5262
0
      options->ignore_regex_nr)
5263
0
    options->flags.diff_from_contents = 1;
5264
0
  else
5265
0
    options->flags.diff_from_contents = 0;
5266
5267
0
  if (options->flags.find_copies_harder)
5268
0
    options->detect_rename = DIFF_DETECT_COPY;
5269
5270
0
  if (!options->flags.relative_name)
5271
0
    options->prefix = NULL;
5272
0
  if (options->prefix)
5273
0
    options->prefix_length = strlen(options->prefix);
5274
0
  else
5275
0
    options->prefix_length = 0;
5276
5277
  /*
5278
   * --name-only, --name-status, --checkdiff, and -s
5279
   * turn other output format off.
5280
   */
5281
0
  if (options->output_format & (DIFF_FORMAT_NAME |
5282
0
              DIFF_FORMAT_NAME_STATUS |
5283
0
              DIFF_FORMAT_CHECKDIFF |
5284
0
              DIFF_FORMAT_NO_OUTPUT))
5285
0
    options->output_format &= ~(DIFF_FORMAT_RAW |
5286
0
              DIFF_FORMAT_NUMSTAT |
5287
0
              DIFF_FORMAT_DIFFSTAT |
5288
0
              DIFF_FORMAT_SHORTSTAT |
5289
0
              DIFF_FORMAT_DIRSTAT |
5290
0
              DIFF_FORMAT_SUMMARY |
5291
0
              DIFF_FORMAT_PATCH);
5292
5293
  /*
5294
   * These cases always need recursive; we do not drop caller-supplied
5295
   * recursive bits for other formats here.
5296
   */
5297
0
  if (options->output_format & (DIFF_FORMAT_PATCH |
5298
0
              DIFF_FORMAT_NUMSTAT |
5299
0
              DIFF_FORMAT_DIFFSTAT |
5300
0
              DIFF_FORMAT_SHORTSTAT |
5301
0
              DIFF_FORMAT_DIRSTAT |
5302
0
              DIFF_FORMAT_SUMMARY |
5303
0
              DIFF_FORMAT_CHECKDIFF))
5304
0
    options->flags.recursive = 1;
5305
  /*
5306
   * Also pickaxe would not work very well if you do not say recursive
5307
   */
5308
0
  if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5309
0
    options->flags.recursive = 1;
5310
  /*
5311
   * When patches are generated, submodules diffed against the work tree
5312
   * must be checked for dirtiness too so it can be shown in the output
5313
   */
5314
0
  if (options->output_format & DIFF_FORMAT_PATCH)
5315
0
    options->flags.dirty_submodules = 1;
5316
5317
0
  if (options->detect_rename && options->rename_limit < 0)
5318
0
    options->rename_limit = diff_rename_limit_default;
5319
0
  if (hexsz < options->abbrev)
5320
0
    options->abbrev = hexsz; /* full */
5321
5322
  /*
5323
   * It does not make sense to show the first hit we happened
5324
   * to have found.  It does not make sense not to return with
5325
   * exit code in such a case either.
5326
   */
5327
0
  if (options->flags.quick) {
5328
0
    options->output_format = DIFF_FORMAT_NO_OUTPUT;
5329
0
    options->flags.exit_with_status = 1;
5330
0
    options->detect_rename = 0;
5331
0
    options->flags.find_copies_harder = 0;
5332
0
  }
5333
5334
  /*
5335
   * External diffs could declare non-identical contents equal
5336
   * (think diff --ignore-space-change).
5337
   */
5338
0
  if (options->flags.allow_external && options->flags.exit_with_status)
5339
0
    options->flags.diff_from_contents = 1;
5340
5341
0
  options->diff_path_counter = 0;
5342
5343
0
  if (options->flags.follow_renames)
5344
0
    diff_check_follow_pathspec(&options->pathspec, 1);
5345
5346
0
  if (options->flags.allow_external && external_diff())
5347
0
    options->color_moved = 0;
5348
5349
0
  if (options->filter_not) {
5350
0
    if (!options->filter)
5351
0
      options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
5352
0
    options->filter &= ~options->filter_not;
5353
0
  }
5354
5355
0
  if (options->pathspec.has_wildcard && options->max_depth_valid)
5356
0
    die("max-depth cannot be used with wildcard pathspecs");
5357
0
}
5358
5359
int parse_long_opt(const char *opt, const char **argv,
5360
       const char **optarg)
5361
0
{
5362
0
  const char *arg = argv[0];
5363
0
  if (!skip_prefix(arg, "--", &arg))
5364
0
    return 0;
5365
0
  if (!skip_prefix(arg, opt, &arg))
5366
0
    return 0;
5367
0
  if (*arg == '=') { /* stuck form: --option=value */
5368
0
    *optarg = arg + 1;
5369
0
    return 1;
5370
0
  }
5371
0
  if (*arg != '\0')
5372
0
    return 0;
5373
  /* separate form: --option value */
5374
0
  if (!argv[1])
5375
0
    die("Option '--%s' requires a value", opt);
5376
0
  *optarg = argv[1];
5377
0
  return 2;
5378
0
}
5379
5380
static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5381
0
{
5382
0
  struct diff_options *options = opt->value;
5383
0
  int width = options->stat_width;
5384
0
  int name_width = options->stat_name_width;
5385
0
  int graph_width = options->stat_graph_width;
5386
0
  int count = options->stat_count;
5387
0
  char *end;
5388
5389
0
  BUG_ON_OPT_NEG(unset);
5390
5391
0
  if (!strcmp(opt->long_name, "stat")) {
5392
0
    if (value) {
5393
0
      width = strtoul(value, &end, 10);
5394
0
      if (*end == ',')
5395
0
        name_width = strtoul(end+1, &end, 10);
5396
0
      if (*end == ',')
5397
0
        count = strtoul(end+1, &end, 10);
5398
0
      if (*end)
5399
0
        return error(_("invalid --stat value: %s"), value);
5400
0
    }
5401
0
  } else if (!strcmp(opt->long_name, "stat-width")) {
5402
0
    width = strtoul(value, &end, 10);
5403
0
    if (*end)
5404
0
      return error(_("%s expects a numerical value"),
5405
0
             opt->long_name);
5406
0
  } else if (!strcmp(opt->long_name, "stat-name-width")) {
5407
0
    name_width = strtoul(value, &end, 10);
5408
0
    if (*end)
5409
0
      return error(_("%s expects a numerical value"),
5410
0
             opt->long_name);
5411
0
  } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5412
0
    graph_width = strtoul(value, &end, 10);
5413
0
    if (*end)
5414
0
      return error(_("%s expects a numerical value"),
5415
0
             opt->long_name);
5416
0
  } else if (!strcmp(opt->long_name, "stat-count")) {
5417
0
    count = strtoul(value, &end, 10);
5418
0
    if (*end)
5419
0
      return error(_("%s expects a numerical value"),
5420
0
             opt->long_name);
5421
0
  } else
5422
0
    BUG("%s should not get here", opt->long_name);
5423
5424
0
  options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5425
0
  options->output_format |= DIFF_FORMAT_DIFFSTAT;
5426
0
  options->stat_name_width = name_width;
5427
0
  options->stat_graph_width = graph_width;
5428
0
  options->stat_width = width;
5429
0
  options->stat_count = count;
5430
0
  return 0;
5431
0
}
5432
5433
static int parse_dirstat_opt(struct diff_options *options, const char *params)
5434
0
{
5435
0
  struct strbuf errmsg = STRBUF_INIT;
5436
0
  if (parse_dirstat_params(options, params, &errmsg))
5437
0
    die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5438
0
        errmsg.buf);
5439
0
  strbuf_release(&errmsg);
5440
  /*
5441
   * The caller knows a dirstat-related option is given from the command
5442
   * line; allow it to say "return this_function();"
5443
   */
5444
0
  options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5445
0
  options->output_format |= DIFF_FORMAT_DIRSTAT;
5446
0
  return 1;
5447
0
}
5448
5449
static int diff_opt_diff_filter(const struct option *option,
5450
        const char *optarg, int unset)
5451
0
{
5452
0
  struct diff_options *opt = option->value;
5453
0
  int i, optch;
5454
5455
0
  BUG_ON_OPT_NEG(unset);
5456
0
  prepare_filter_bits();
5457
5458
0
  for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5459
0
    unsigned int bit;
5460
0
    int negate;
5461
5462
0
    if ('a' <= optch && optch <= 'z') {
5463
0
      negate = 1;
5464
0
      optch = toupper(optch);
5465
0
    } else {
5466
0
      negate = 0;
5467
0
    }
5468
5469
0
    bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5470
0
    if (!bit)
5471
0
      return error(_("unknown change class '%c' in --diff-filter=%s"),
5472
0
             optarg[i], optarg);
5473
0
    if (negate)
5474
0
      opt->filter_not |= bit;
5475
0
    else
5476
0
      opt->filter |= bit;
5477
0
  }
5478
0
  return 0;
5479
0
}
5480
5481
static void enable_patch_output(int *fmt)
5482
0
{
5483
0
  *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5484
0
  *fmt |= DIFF_FORMAT_PATCH;
5485
0
}
5486
5487
static int diff_opt_ws_error_highlight(const struct option *option,
5488
               const char *arg, int unset)
5489
0
{
5490
0
  struct diff_options *opt = option->value;
5491
0
  int val = parse_ws_error_highlight(arg);
5492
5493
0
  BUG_ON_OPT_NEG(unset);
5494
0
  if (val < 0)
5495
0
    return error(_("unknown value after ws-error-highlight=%.*s"),
5496
0
           -1 - val, arg);
5497
0
  opt->ws_error_highlight = val;
5498
0
  return 0;
5499
0
}
5500
5501
static int diff_opt_find_object(const struct option *option,
5502
        const char *arg, int unset)
5503
0
{
5504
0
  struct diff_options *opt = option->value;
5505
0
  struct object_id oid;
5506
5507
0
  BUG_ON_OPT_NEG(unset);
5508
0
  if (!startup_info->have_repository)
5509
0
    return error(_("--find-object requires a git repository"));
5510
0
  if (repo_get_oid(the_repository, arg, &oid))
5511
0
    return error(_("unable to resolve '%s'"), arg);
5512
5513
0
  if (!opt->objfind)
5514
0
    CALLOC_ARRAY(opt->objfind, 1);
5515
5516
0
  opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5517
0
  opt->flags.recursive = 1;
5518
0
  opt->flags.tree_in_recursive = 1;
5519
0
  oidset_insert(opt->objfind, &oid);
5520
0
  return 0;
5521
0
}
5522
5523
static int diff_opt_anchored(const struct option *opt,
5524
           const char *arg, int unset)
5525
0
{
5526
0
  struct diff_options *options = opt->value;
5527
5528
0
  BUG_ON_OPT_NEG(unset);
5529
0
  options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5530
0
  ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5531
0
       options->anchors_alloc);
5532
0
  options->anchors[options->anchors_nr++] = xstrdup(arg);
5533
0
  return 0;
5534
0
}
5535
5536
static int diff_opt_binary(const struct option *opt,
5537
         const char *arg, int unset)
5538
0
{
5539
0
  struct diff_options *options = opt->value;
5540
5541
0
  BUG_ON_OPT_NEG(unset);
5542
0
  BUG_ON_OPT_ARG(arg);
5543
0
  enable_patch_output(&options->output_format);
5544
0
  options->flags.binary = 1;
5545
0
  return 0;
5546
0
}
5547
5548
static int diff_opt_break_rewrites(const struct option *opt,
5549
           const char *arg, int unset)
5550
0
{
5551
0
  int *break_opt = opt->value;
5552
0
  int opt1, opt2;
5553
5554
0
  BUG_ON_OPT_NEG(unset);
5555
0
  if (!arg)
5556
0
    arg = "";
5557
0
  opt1 = parse_rename_score(&arg);
5558
0
  if (*arg == 0)
5559
0
    opt2 = 0;
5560
0
  else if (*arg != '/')
5561
0
    return error(_("%s expects <n>/<m> form"), opt->long_name);
5562
0
  else {
5563
0
    arg++;
5564
0
    opt2 = parse_rename_score(&arg);
5565
0
  }
5566
0
  if (*arg != 0)
5567
0
    return error(_("%s expects <n>/<m> form"), opt->long_name);
5568
0
  *break_opt = opt1 | (opt2 << 16);
5569
0
  return 0;
5570
0
}
5571
5572
static int diff_opt_char(const struct option *opt,
5573
       const char *arg, int unset)
5574
0
{
5575
0
  char *value = opt->value;
5576
5577
0
  BUG_ON_OPT_NEG(unset);
5578
0
  if (arg[1])
5579
0
    return error(_("%s expects a character, got '%s'"),
5580
0
           opt->long_name, arg);
5581
0
  *value = arg[0];
5582
0
  return 0;
5583
0
}
5584
5585
static int diff_opt_color_moved(const struct option *opt,
5586
        const char *arg, int unset)
5587
0
{
5588
0
  struct diff_options *options = opt->value;
5589
5590
0
  if (unset) {
5591
0
    options->color_moved = COLOR_MOVED_NO;
5592
0
  } else if (!arg) {
5593
0
    if (diff_color_moved_default)
5594
0
      options->color_moved = diff_color_moved_default;
5595
0
    if (options->color_moved == COLOR_MOVED_NO)
5596
0
      options->color_moved = COLOR_MOVED_DEFAULT;
5597
0
  } else {
5598
0
    int cm = parse_color_moved(arg);
5599
0
    if (cm < 0)
5600
0
      return error(_("bad --color-moved argument: %s"), arg);
5601
0
    options->color_moved = cm;
5602
0
  }
5603
0
  return 0;
5604
0
}
5605
5606
static int diff_opt_color_moved_ws(const struct option *opt,
5607
           const char *arg, int unset)
5608
0
{
5609
0
  struct diff_options *options = opt->value;
5610
0
  unsigned cm;
5611
5612
0
  if (unset) {
5613
0
    options->color_moved_ws_handling = 0;
5614
0
    return 0;
5615
0
  }
5616
5617
0
  cm = parse_color_moved_ws(arg);
5618
0
  if (cm & COLOR_MOVED_WS_ERROR)
5619
0
    return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5620
0
  options->color_moved_ws_handling = cm;
5621
0
  return 0;
5622
0
}
5623
5624
static int diff_opt_color_words(const struct option *opt,
5625
        const char *arg, int unset)
5626
0
{
5627
0
  struct diff_options *options = opt->value;
5628
5629
0
  BUG_ON_OPT_NEG(unset);
5630
0
  options->use_color = GIT_COLOR_ALWAYS;
5631
0
  options->word_diff = DIFF_WORDS_COLOR;
5632
0
  options->word_regex = arg;
5633
0
  return 0;
5634
0
}
5635
5636
static int diff_opt_compact_summary(const struct option *opt,
5637
            const char *arg, int unset)
5638
0
{
5639
0
  struct diff_options *options = opt->value;
5640
5641
0
  BUG_ON_OPT_ARG(arg);
5642
0
  if (unset) {
5643
0
    options->flags.stat_with_summary = 0;
5644
0
  } else {
5645
0
    options->flags.stat_with_summary = 1;
5646
0
    options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5647
0
    options->output_format |= DIFF_FORMAT_DIFFSTAT;
5648
0
  }
5649
0
  return 0;
5650
0
}
5651
5652
static int diff_opt_diff_algorithm(const struct option *opt,
5653
           const char *arg, int unset)
5654
0
{
5655
0
  struct diff_options *options = opt->value;
5656
5657
0
  BUG_ON_OPT_NEG(unset);
5658
5659
0
  if (set_diff_algorithm(options, arg))
5660
0
    return error(_("option diff-algorithm accepts \"myers\", "
5661
0
             "\"minimal\", \"patience\" and \"histogram\""));
5662
5663
0
  options->ignore_driver_algorithm = 1;
5664
5665
0
  return 0;
5666
0
}
5667
5668
static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5669
           const char *arg, int unset)
5670
0
{
5671
0
  struct diff_options *options = opt->value;
5672
5673
0
  BUG_ON_OPT_NEG(unset);
5674
0
  BUG_ON_OPT_ARG(arg);
5675
5676
0
  if (set_diff_algorithm(options, opt->long_name))
5677
0
    BUG("available diff algorithms include \"myers\", "
5678
0
             "\"minimal\", \"patience\" and \"histogram\"");
5679
5680
0
  options->ignore_driver_algorithm = 1;
5681
5682
0
  return 0;
5683
0
}
5684
5685
static int diff_opt_dirstat(const struct option *opt,
5686
          const char *arg, int unset)
5687
0
{
5688
0
  struct diff_options *options = opt->value;
5689
5690
0
  BUG_ON_OPT_NEG(unset);
5691
0
  if (!strcmp(opt->long_name, "cumulative")) {
5692
0
    if (arg)
5693
0
      BUG("how come --cumulative take a value?");
5694
0
    arg = "cumulative";
5695
0
  } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5696
0
    parse_dirstat_opt(options, "files");
5697
0
  parse_dirstat_opt(options, arg ? arg : "");
5698
0
  return 0;
5699
0
}
5700
5701
static int diff_opt_find_copies(const struct option *opt,
5702
        const char *arg, int unset)
5703
0
{
5704
0
  struct diff_options *options = opt->value;
5705
5706
0
  BUG_ON_OPT_NEG(unset);
5707
0
  if (!arg)
5708
0
    arg = "";
5709
0
  options->rename_score = parse_rename_score(&arg);
5710
0
  if (*arg != 0)
5711
0
    return error(_("invalid argument to %s"), opt->long_name);
5712
5713
0
  if (options->detect_rename == DIFF_DETECT_COPY)
5714
0
    options->flags.find_copies_harder = 1;
5715
0
  else
5716
0
    options->detect_rename = DIFF_DETECT_COPY;
5717
5718
0
  return 0;
5719
0
}
5720
5721
static int diff_opt_find_renames(const struct option *opt,
5722
         const char *arg, int unset)
5723
0
{
5724
0
  struct diff_options *options = opt->value;
5725
5726
0
  BUG_ON_OPT_NEG(unset);
5727
0
  if (!arg)
5728
0
    arg = "";
5729
0
  options->rename_score = parse_rename_score(&arg);
5730
0
  if (*arg != 0)
5731
0
    return error(_("invalid argument to %s"), opt->long_name);
5732
5733
0
  options->detect_rename = DIFF_DETECT_RENAME;
5734
0
  return 0;
5735
0
}
5736
5737
static int diff_opt_follow(const struct option *opt,
5738
         const char *arg, int unset)
5739
0
{
5740
0
  struct diff_options *options = opt->value;
5741
5742
0
  BUG_ON_OPT_ARG(arg);
5743
0
  if (unset) {
5744
0
    options->flags.follow_renames = 0;
5745
0
    options->flags.default_follow_renames = 0;
5746
0
  } else {
5747
0
    options->flags.follow_renames = 1;
5748
0
  }
5749
0
  return 0;
5750
0
}
5751
5752
static int diff_opt_ignore_submodules(const struct option *opt,
5753
              const char *arg, int unset)
5754
0
{
5755
0
  struct diff_options *options = opt->value;
5756
5757
0
  BUG_ON_OPT_NEG(unset);
5758
0
  if (!arg)
5759
0
    arg = "all";
5760
0
  options->flags.override_submodule_config = 1;
5761
0
  handle_ignore_submodules_arg(options, arg);
5762
0
  return 0;
5763
0
}
5764
5765
static int diff_opt_line_prefix(const struct option *opt,
5766
        const char *optarg, int unset)
5767
0
{
5768
0
  struct diff_options *options = opt->value;
5769
5770
0
  BUG_ON_OPT_NEG(unset);
5771
0
  options->line_prefix = optarg;
5772
0
  graph_setup_line_prefix(options);
5773
0
  return 0;
5774
0
}
5775
5776
static int diff_opt_no_prefix(const struct option *opt,
5777
            const char *optarg, int unset)
5778
0
{
5779
0
  struct diff_options *options = opt->value;
5780
5781
0
  BUG_ON_OPT_NEG(unset);
5782
0
  BUG_ON_OPT_ARG(optarg);
5783
0
  diff_set_noprefix(options);
5784
0
  return 0;
5785
0
}
5786
5787
static int diff_opt_default_prefix(const struct option *opt,
5788
           const char *optarg, int unset)
5789
0
{
5790
0
  struct diff_options *options = opt->value;
5791
5792
0
  BUG_ON_OPT_NEG(unset);
5793
0
  BUG_ON_OPT_ARG(optarg);
5794
0
  FREE_AND_NULL(diff_src_prefix);
5795
0
  FREE_AND_NULL(diff_dst_prefix);
5796
0
  diff_set_default_prefix(options);
5797
0
  return 0;
5798
0
}
5799
5800
static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5801
               const struct option *opt,
5802
               const char *arg, int unset)
5803
0
{
5804
0
  struct diff_options *options = opt->value;
5805
0
  char *path;
5806
5807
0
  BUG_ON_OPT_NEG(unset);
5808
0
  path = prefix_filename(ctx->prefix, arg);
5809
0
  options->file = xfopen(path, "w");
5810
0
  options->close_file = 1;
5811
0
  if (options->use_color != GIT_COLOR_ALWAYS)
5812
0
    options->use_color = GIT_COLOR_NEVER;
5813
0
  free(path);
5814
0
  return 0;
5815
0
}
5816
5817
static int diff_opt_patience(const struct option *opt,
5818
           const char *arg, int unset)
5819
0
{
5820
0
  struct diff_options *options = opt->value;
5821
0
  int i;
5822
5823
0
  BUG_ON_OPT_NEG(unset);
5824
0
  BUG_ON_OPT_ARG(arg);
5825
  /*
5826
   * Both --patience and --anchored use PATIENCE_DIFF
5827
   * internally, so remove any anchors previously
5828
   * specified.
5829
   */
5830
0
  for (i = 0; i < options->anchors_nr; i++)
5831
0
    free(options->anchors[i]);
5832
0
  options->anchors_nr = 0;
5833
0
  options->ignore_driver_algorithm = 1;
5834
5835
0
  return set_diff_algorithm(options, "patience");
5836
0
}
5837
5838
static int diff_opt_ignore_regex(const struct option *opt,
5839
         const char *arg, int unset)
5840
0
{
5841
0
  struct diff_options *options = opt->value;
5842
0
  regex_t *regex;
5843
5844
0
  BUG_ON_OPT_NEG(unset);
5845
5846
0
  regex = xmalloc(sizeof(*regex));
5847
0
  if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5848
0
    free(regex);
5849
0
    return error(_("invalid regex given to -I: '%s'"), arg);
5850
0
  }
5851
5852
0
  ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5853
0
       options->ignore_regex_alloc);
5854
0
  options->ignore_regex[options->ignore_regex_nr++] = regex;
5855
0
  return 0;
5856
0
}
5857
5858
static int diff_opt_pickaxe_regex(const struct option *opt,
5859
          const char *arg, int unset)
5860
0
{
5861
0
  struct diff_options *options = opt->value;
5862
5863
0
  BUG_ON_OPT_NEG(unset);
5864
0
  options->pickaxe = arg;
5865
0
  options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5866
0
  if (arg && !*arg)
5867
0
    return error(_("-G requires a non-empty argument"));
5868
0
  return 0;
5869
0
}
5870
5871
static int diff_opt_pickaxe_string(const struct option *opt,
5872
           const char *arg, int unset)
5873
0
{
5874
0
  struct diff_options *options = opt->value;
5875
5876
0
  BUG_ON_OPT_NEG(unset);
5877
0
  options->pickaxe = arg;
5878
0
  options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5879
0
  if (arg && !*arg)
5880
0
    return error(_("-S requires a non-empty argument"));
5881
0
  return 0;
5882
0
}
5883
5884
static int diff_opt_relative(const struct option *opt,
5885
           const char *arg, int unset)
5886
0
{
5887
0
  struct diff_options *options = opt->value;
5888
5889
0
  options->flags.relative_name = !unset;
5890
0
  if (arg)
5891
0
    options->prefix = arg;
5892
0
  return 0;
5893
0
}
5894
5895
static int diff_opt_submodule(const struct option *opt,
5896
            const char *arg, int unset)
5897
0
{
5898
0
  struct diff_options *options = opt->value;
5899
5900
0
  BUG_ON_OPT_NEG(unset);
5901
0
  if (!arg)
5902
0
    arg = "log";
5903
0
  if (parse_submodule_params(options, arg))
5904
0
    return error(_("failed to parse --submodule option parameter: '%s'"),
5905
0
           arg);
5906
0
  return 0;
5907
0
}
5908
5909
static int diff_opt_textconv(const struct option *opt,
5910
           const char *arg, int unset)
5911
0
{
5912
0
  struct diff_options *options = opt->value;
5913
5914
0
  BUG_ON_OPT_ARG(arg);
5915
0
  if (unset) {
5916
0
    options->flags.allow_textconv = 0;
5917
0
  } else {
5918
0
    options->flags.allow_textconv = 1;
5919
0
    options->flags.textconv_set_via_cmdline = 1;
5920
0
  }
5921
0
  return 0;
5922
0
}
5923
5924
static int diff_opt_unified(const struct option *opt,
5925
          const char *arg, int unset)
5926
0
{
5927
0
  struct diff_options *options = opt->value;
5928
0
  char *s;
5929
5930
0
  BUG_ON_OPT_NEG(unset);
5931
5932
0
  if (arg) {
5933
0
    long val = strtol(arg, &s, 10);
5934
0
    if (*s)
5935
0
      return error(_("%s expects a numerical value"), "--unified");
5936
0
    if (val < 0)
5937
0
      return error(_("%s expects a non-negative integer"), "--unified");
5938
0
    options->context = val;
5939
0
  }
5940
0
  enable_patch_output(&options->output_format);
5941
5942
0
  return 0;
5943
0
}
5944
5945
static int diff_opt_word_diff(const struct option *opt,
5946
            const char *arg, int unset)
5947
0
{
5948
0
  struct diff_options *options = opt->value;
5949
5950
0
  BUG_ON_OPT_NEG(unset);
5951
0
  if (arg) {
5952
0
    if (!strcmp(arg, "plain"))
5953
0
      options->word_diff = DIFF_WORDS_PLAIN;
5954
0
    else if (!strcmp(arg, "color")) {
5955
0
      options->use_color = GIT_COLOR_ALWAYS;
5956
0
      options->word_diff = DIFF_WORDS_COLOR;
5957
0
    }
5958
0
    else if (!strcmp(arg, "porcelain"))
5959
0
      options->word_diff = DIFF_WORDS_PORCELAIN;
5960
0
    else if (!strcmp(arg, "none"))
5961
0
      options->word_diff = DIFF_WORDS_NONE;
5962
0
    else
5963
0
      return error(_("bad --word-diff argument: %s"), arg);
5964
0
  } else {
5965
0
    if (options->word_diff == DIFF_WORDS_NONE)
5966
0
      options->word_diff = DIFF_WORDS_PLAIN;
5967
0
  }
5968
0
  return 0;
5969
0
}
5970
5971
static int diff_opt_word_diff_regex(const struct option *opt,
5972
            const char *arg, int unset)
5973
0
{
5974
0
  struct diff_options *options = opt->value;
5975
5976
0
  BUG_ON_OPT_NEG(unset);
5977
0
  if (options->word_diff == DIFF_WORDS_NONE)
5978
0
    options->word_diff = DIFF_WORDS_PLAIN;
5979
0
  options->word_regex = arg;
5980
0
  return 0;
5981
0
}
5982
5983
static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5984
0
{
5985
0
  struct diff_options *options = opt->value;
5986
5987
0
  BUG_ON_OPT_NEG(unset);
5988
0
  if (!strcmp(opt->long_name, "skip-to"))
5989
0
    options->skip_instead_of_rotate = 1;
5990
0
  else
5991
0
    options->skip_instead_of_rotate = 0;
5992
0
  options->rotate_to = arg;
5993
0
  return 0;
5994
0
}
5995
5996
static int diff_opt_max_depth(const struct option *opt,
5997
            const char *arg, int unset)
5998
0
{
5999
0
  struct diff_options *options = opt->value;
6000
6001
0
  BUG_ON_OPT_NEG(unset);
6002
6003
0
  if (!git_parse_int(arg, &options->max_depth))
6004
0
    return error(_("invalid value for '%s': '%s'"),
6005
0
           "--max-depth", arg);
6006
6007
0
  options->flags.recursive = 1;
6008
0
  options->max_depth_valid = options->max_depth >= 0;
6009
6010
0
  return 0;
6011
0
}
6012
6013
/*
6014
 * Consider adding new flags to __git_diff_common_options
6015
 * in contrib/completion/git-completion.bash
6016
 */
6017
struct option *add_diff_options(const struct option *opts,
6018
        struct diff_options *options)
6019
0
{
6020
0
  struct option parseopts[] = {
6021
0
    OPT_GROUP(N_("Diff output format options")),
6022
0
    OPT_BITOP('p', "patch", &options->output_format,
6023
0
        N_("generate patch"),
6024
0
        DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6025
0
    OPT_SET_INT('s', "no-patch", &options->output_format,
6026
0
          N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
6027
0
    OPT_BITOP('u', NULL, &options->output_format,
6028
0
        N_("generate patch"),
6029
0
        DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6030
0
    OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
6031
0
             N_("generate diffs with <n> lines context"),
6032
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
6033
0
    OPT_BOOL('W', "function-context", &options->flags.funccontext,
6034
0
       N_("generate diffs with <n> lines context")),
6035
0
    OPT_BITOP(0, "raw", &options->output_format,
6036
0
        N_("generate the diff in raw format"),
6037
0
        DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
6038
0
    OPT_BITOP(0, "patch-with-raw", &options->output_format,
6039
0
        N_("synonym for '-p --raw'"),
6040
0
        DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
6041
0
        DIFF_FORMAT_NO_OUTPUT),
6042
0
    OPT_BITOP(0, "patch-with-stat", &options->output_format,
6043
0
        N_("synonym for '-p --stat'"),
6044
0
        DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
6045
0
        DIFF_FORMAT_NO_OUTPUT),
6046
0
    OPT_BITOP(0, "numstat", &options->output_format,
6047
0
        N_("machine friendly --stat"),
6048
0
        DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
6049
0
    OPT_BITOP(0, "shortstat", &options->output_format,
6050
0
        N_("output only the last line of --stat"),
6051
0
        DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
6052
0
    OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
6053
0
             N_("output the distribution of relative amount of changes for each sub-directory"),
6054
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6055
0
             diff_opt_dirstat),
6056
0
    OPT_CALLBACK_F(0, "cumulative", options, NULL,
6057
0
             N_("synonym for --dirstat=cumulative"),
6058
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6059
0
             diff_opt_dirstat),
6060
0
    OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
6061
0
             N_("synonym for --dirstat=files,<param1>,<param2>..."),
6062
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6063
0
             diff_opt_dirstat),
6064
0
    OPT_BIT_F(0, "check", &options->output_format,
6065
0
        N_("warn if changes introduce conflict markers or whitespace errors"),
6066
0
        DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
6067
0
    OPT_BITOP(0, "summary", &options->output_format,
6068
0
        N_("condensed summary such as creations, renames and mode changes"),
6069
0
        DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
6070
0
    OPT_BIT_F(0, "name-only", &options->output_format,
6071
0
        N_("show only names of changed files"),
6072
0
        DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
6073
0
    OPT_BIT_F(0, "name-status", &options->output_format,
6074
0
        N_("show only names and status of changed files"),
6075
0
        DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
6076
0
    OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
6077
0
             N_("generate diffstat"),
6078
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
6079
0
    OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
6080
0
             N_("generate diffstat with a given width"),
6081
0
             PARSE_OPT_NONEG, diff_opt_stat),
6082
0
    OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
6083
0
             N_("generate diffstat with a given name width"),
6084
0
             PARSE_OPT_NONEG, diff_opt_stat),
6085
0
    OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
6086
0
             N_("generate diffstat with a given graph width"),
6087
0
             PARSE_OPT_NONEG, diff_opt_stat),
6088
0
    OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
6089
0
             N_("generate diffstat with limited lines"),
6090
0
             PARSE_OPT_NONEG, diff_opt_stat),
6091
0
    OPT_CALLBACK_F(0, "compact-summary", options, NULL,
6092
0
             N_("generate compact summary in diffstat"),
6093
0
             PARSE_OPT_NOARG, diff_opt_compact_summary),
6094
0
    OPT_CALLBACK_F(0, "binary", options, NULL,
6095
0
             N_("output a binary diff that can be applied"),
6096
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
6097
0
    OPT_BOOL(0, "full-index", &options->flags.full_index,
6098
0
       N_("show full pre- and post-image object names on the \"index\" lines")),
6099
0
    OPT_COLOR_FLAG(0, "color", &options->use_color,
6100
0
             N_("show colored diff")),
6101
0
    OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
6102
0
             N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
6103
0
             PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
6104
0
    OPT_SET_INT('z', NULL, &options->line_termination,
6105
0
          N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
6106
0
          0),
6107
0
    OPT__ABBREV(&options->abbrev),
6108
0
    OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
6109
0
           N_("show the given source prefix instead of \"a/\""),
6110
0
           PARSE_OPT_NONEG),
6111
0
    OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
6112
0
           N_("show the given destination prefix instead of \"b/\""),
6113
0
           PARSE_OPT_NONEG),
6114
0
    OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
6115
0
             N_("prepend an additional prefix to every line of output"),
6116
0
             PARSE_OPT_NONEG, diff_opt_line_prefix),
6117
0
    OPT_CALLBACK_F(0, "no-prefix", options, NULL,
6118
0
             N_("do not show any source or destination prefix"),
6119
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
6120
0
    OPT_CALLBACK_F(0, "default-prefix", options, NULL,
6121
0
             N_("use default prefixes a/ and b/"),
6122
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
6123
0
    OPT_UNSIGNED(0, "inter-hunk-context", &options->interhunkcontext,
6124
0
           N_("show context between diff hunks up to the specified number of lines")),
6125
0
    OPT_CALLBACK_F(0, "output-indicator-new",
6126
0
             &options->output_indicators[OUTPUT_INDICATOR_NEW],
6127
0
             N_("<char>"),
6128
0
             N_("specify the character to indicate a new line instead of '+'"),
6129
0
             PARSE_OPT_NONEG, diff_opt_char),
6130
0
    OPT_CALLBACK_F(0, "output-indicator-old",
6131
0
             &options->output_indicators[OUTPUT_INDICATOR_OLD],
6132
0
             N_("<char>"),
6133
0
             N_("specify the character to indicate an old line instead of '-'"),
6134
0
             PARSE_OPT_NONEG, diff_opt_char),
6135
0
    OPT_CALLBACK_F(0, "output-indicator-context",
6136
0
             &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
6137
0
             N_("<char>"),
6138
0
             N_("specify the character to indicate a context instead of ' '"),
6139
0
             PARSE_OPT_NONEG, diff_opt_char),
6140
6141
0
    OPT_GROUP(N_("Diff rename options")),
6142
0
    OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
6143
0
             N_("break complete rewrite changes into pairs of delete and create"),
6144
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6145
0
             diff_opt_break_rewrites),
6146
0
    OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
6147
0
             N_("detect renames"),
6148
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6149
0
             diff_opt_find_renames),
6150
0
    OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
6151
0
            N_("omit the preimage for deletes"),
6152
0
            1, PARSE_OPT_NONEG),
6153
0
    OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
6154
0
             N_("detect copies"),
6155
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6156
0
             diff_opt_find_copies),
6157
0
    OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
6158
0
       N_("use unmodified files as source to find copies")),
6159
0
    OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
6160
0
            N_("disable rename detection"),
6161
0
            0, PARSE_OPT_NONEG),
6162
0
    OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
6163
0
       N_("use empty blobs as rename source")),
6164
0
    OPT_CALLBACK_F(0, "follow", options, NULL,
6165
0
             N_("continue listing the history of a file beyond renames"),
6166
0
             PARSE_OPT_NOARG, diff_opt_follow),
6167
0
    OPT_INTEGER('l', NULL, &options->rename_limit,
6168
0
          N_("limit to cheap rename/copy detection if the number of rename/copy targets exceeds this value")),
6169
6170
0
    OPT_GROUP(N_("Diff algorithm options")),
6171
0
    OPT_CALLBACK_F(0, "minimal", options, NULL,
6172
0
             N_("produce the smallest possible diff"),
6173
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6174
0
             diff_opt_diff_algorithm_no_arg),
6175
0
    OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
6176
0
        N_("ignore whitespace when comparing lines"),
6177
0
        XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
6178
0
    OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
6179
0
        N_("ignore changes in amount of whitespace"),
6180
0
        XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
6181
0
    OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
6182
0
        N_("ignore changes in whitespace at EOL"),
6183
0
        XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
6184
0
    OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
6185
0
        N_("ignore carrier-return at the end of line"),
6186
0
        XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
6187
0
    OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
6188
0
        N_("ignore changes whose lines are all blank"),
6189
0
        XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
6190
0
    OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
6191
0
             N_("ignore changes whose all lines match <regex>"),
6192
0
             0, diff_opt_ignore_regex),
6193
0
    OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
6194
0
      N_("heuristic to shift diff hunk boundaries for easy reading"),
6195
0
      XDF_INDENT_HEURISTIC),
6196
0
    OPT_CALLBACK_F(0, "patience", options, NULL,
6197
0
             N_("generate diff using the \"patience diff\" algorithm"),
6198
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6199
0
             diff_opt_patience),
6200
0
    OPT_CALLBACK_F(0, "histogram", options, NULL,
6201
0
             N_("generate diff using the \"histogram diff\" algorithm"),
6202
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6203
0
             diff_opt_diff_algorithm_no_arg),
6204
0
    OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
6205
0
             N_("choose a diff algorithm"),
6206
0
             PARSE_OPT_NONEG, diff_opt_diff_algorithm),
6207
0
    OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
6208
0
             N_("generate diff using the \"anchored diff\" algorithm"),
6209
0
             PARSE_OPT_NONEG, diff_opt_anchored),
6210
0
    OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
6211
0
             N_("show word diff, using <mode> to delimit changed words"),
6212
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
6213
0
    OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
6214
0
             N_("use <regex> to decide what a word is"),
6215
0
             PARSE_OPT_NONEG, diff_opt_word_diff_regex),
6216
0
    OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
6217
0
             N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
6218
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
6219
0
    OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
6220
0
             N_("moved lines of code are colored differently"),
6221
0
             PARSE_OPT_OPTARG, diff_opt_color_moved),
6222
0
    OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
6223
0
             N_("how white spaces are ignored in --color-moved"),
6224
0
             0, diff_opt_color_moved_ws),
6225
6226
0
    OPT_GROUP(N_("Other diff options")),
6227
0
    OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
6228
0
             N_("when run from subdir, exclude changes outside and show relative paths"),
6229
0
             PARSE_OPT_OPTARG,
6230
0
             diff_opt_relative),
6231
0
    OPT_BOOL('a', "text", &options->flags.text,
6232
0
       N_("treat all files as text")),
6233
0
    OPT_BOOL('R', NULL, &options->flags.reverse_diff,
6234
0
       N_("swap two inputs, reverse the diff")),
6235
0
    OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
6236
0
       N_("exit with 1 if there were differences, 0 otherwise")),
6237
0
    OPT_BOOL(0, "quiet", &options->flags.quick,
6238
0
       N_("disable all output of the program")),
6239
0
    OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
6240
0
       N_("allow an external diff helper to be executed")),
6241
0
    OPT_CALLBACK_F(0, "textconv", options, NULL,
6242
0
             N_("run external text conversion filters when comparing binary files"),
6243
0
             PARSE_OPT_NOARG, diff_opt_textconv),
6244
0
    OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
6245
0
             N_("ignore changes to submodules in the diff generation"),
6246
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6247
0
             diff_opt_ignore_submodules),
6248
0
    OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
6249
0
             N_("specify how differences in submodules are shown"),
6250
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6251
0
             diff_opt_submodule),
6252
0
    OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
6253
0
            N_("hide 'git add -N' entries from the index"),
6254
0
            1, PARSE_OPT_NONEG),
6255
0
    OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
6256
0
            N_("treat 'git add -N' entries as real in the index"),
6257
0
            0, PARSE_OPT_NONEG),
6258
0
    OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
6259
0
             N_("look for differences that change the number of occurrences of the specified string"),
6260
0
             0, diff_opt_pickaxe_string),
6261
0
    OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
6262
0
             N_("look for differences that change the number of occurrences of the specified regex"),
6263
0
             0, diff_opt_pickaxe_regex),
6264
0
    OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
6265
0
        N_("show all changes in the changeset with -S or -G"),
6266
0
        DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
6267
0
    OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
6268
0
        N_("treat <string> in -S as extended POSIX regular expression"),
6269
0
        DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
6270
0
    OPT_FILENAME('O', NULL, &options->orderfile,
6271
0
           N_("control the order in which files appear in the output")),
6272
0
    OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
6273
0
             N_("show the change in the specified path first"),
6274
0
             PARSE_OPT_NONEG, diff_opt_rotate_to),
6275
0
    OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
6276
0
             N_("skip the output to the specified path"),
6277
0
             PARSE_OPT_NONEG, diff_opt_rotate_to),
6278
0
    OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
6279
0
             N_("look for differences that change the number of occurrences of the specified object"),
6280
0
             PARSE_OPT_NONEG, diff_opt_find_object),
6281
0
    OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
6282
0
             N_("select files by diff type"),
6283
0
             PARSE_OPT_NONEG, diff_opt_diff_filter),
6284
0
    OPT_CALLBACK_F(0, "max-depth", options, N_("<depth>"),
6285
0
             N_("maximum tree depth to recurse"),
6286
0
             PARSE_OPT_NONEG, diff_opt_max_depth),
6287
6288
0
    {
6289
0
      .type = OPTION_CALLBACK,
6290
0
      .long_name = "output",
6291
0
      .value = options,
6292
0
      .argh = N_("<file>"),
6293
0
      .help = N_("output to a specific file"),
6294
0
      .flags = PARSE_OPT_NONEG,
6295
0
      .ll_callback = diff_opt_output,
6296
0
    },
6297
0
    OPT_END()
6298
0
  };
6299
6300
0
  return parse_options_concat(opts, parseopts);
6301
0
}
6302
6303
int diff_opt_parse(struct diff_options *options,
6304
       const char **av, int ac, const char *prefix)
6305
0
{
6306
0
  struct option no_options[] = { OPT_END() };
6307
0
  struct option *parseopts = add_diff_options(no_options, options);
6308
6309
0
  if (!prefix)
6310
0
    prefix = "";
6311
6312
0
  ac = parse_options(ac, av, prefix, parseopts, NULL,
6313
0
         PARSE_OPT_KEEP_DASHDASH |
6314
0
         PARSE_OPT_KEEP_UNKNOWN_OPT |
6315
0
         PARSE_OPT_NO_INTERNAL_HELP |
6316
0
         PARSE_OPT_ONE_SHOT |
6317
0
         PARSE_OPT_STOP_AT_NON_OPTION);
6318
0
  free(parseopts);
6319
6320
0
  return ac;
6321
0
}
6322
6323
int parse_rename_score(const char **cp_p)
6324
0
{
6325
0
  unsigned long num, scale;
6326
0
  int ch, dot;
6327
0
  const char *cp = *cp_p;
6328
6329
0
  num = 0;
6330
0
  scale = 1;
6331
0
  dot = 0;
6332
0
  for (;;) {
6333
0
    ch = *cp;
6334
0
    if ( !dot && ch == '.' ) {
6335
0
      scale = 1;
6336
0
      dot = 1;
6337
0
    } else if ( ch == '%' ) {
6338
0
      scale = dot ? scale*100 : 100;
6339
0
      cp++; /* % is always at the end */
6340
0
      break;
6341
0
    } else if ( ch >= '0' && ch <= '9' ) {
6342
0
      if ( scale < 100000 ) {
6343
0
        scale *= 10;
6344
0
        num = (num*10) + (ch-'0');
6345
0
      }
6346
0
    } else {
6347
0
      break;
6348
0
    }
6349
0
    cp++;
6350
0
  }
6351
0
  *cp_p = cp;
6352
6353
  /* user says num divided by scale and we say internally that
6354
   * is MAX_SCORE * num / scale.
6355
   */
6356
0
  return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6357
0
}
6358
6359
struct diff_queue_struct diff_queued_diff;
6360
6361
void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
6362
0
{
6363
0
  ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6364
0
  queue->queue[queue->nr++] = dp;
6365
0
}
6366
6367
struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
6368
         struct diff_filespec *one,
6369
         struct diff_filespec *two)
6370
0
{
6371
0
  struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6372
0
  dp->one = one;
6373
0
  dp->two = two;
6374
0
  if (queue)
6375
0
    diff_q(queue, dp);
6376
0
  return dp;
6377
0
}
6378
6379
void diff_free_filepair(struct diff_filepair *p)
6380
0
{
6381
0
  free_filespec(p->one);
6382
0
  free_filespec(p->two);
6383
0
  free(p);
6384
0
}
6385
6386
void diff_queue_init(struct diff_queue_struct *q)
6387
0
{
6388
0
  struct diff_queue_struct blank = DIFF_QUEUE_INIT;
6389
0
  memcpy(q, &blank, sizeof(*q));
6390
0
}
6391
6392
void diff_queue_clear(struct diff_queue_struct *q)
6393
0
{
6394
0
  for (int i = 0; i < q->nr; i++)
6395
0
    diff_free_filepair(q->queue[i]);
6396
0
  free(q->queue);
6397
0
  diff_queue_init(q);
6398
0
}
6399
6400
const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6401
0
{
6402
0
  int abblen;
6403
0
  const char *abbrev;
6404
6405
  /* Do we want all 40 hex characters? */
6406
0
  if (len == the_hash_algo->hexsz)
6407
0
    return oid_to_hex(oid);
6408
6409
  /* An abbreviated value is fine, possibly followed by an ellipsis. */
6410
0
  abbrev = diff_abbrev_oid(oid, len);
6411
6412
0
  if (!print_sha1_ellipsis())
6413
0
    return abbrev;
6414
6415
0
  abblen = strlen(abbrev);
6416
6417
  /*
6418
   * In well-behaved cases, where the abbreviated result is the
6419
   * same as the requested length, append three dots after the
6420
   * abbreviation (hence the whole logic is limited to the case
6421
   * where abblen < 37); when the actual abbreviated result is a
6422
   * bit longer than the requested length, we reduce the number
6423
   * of dots so that they match the well-behaved ones.  However,
6424
   * if the actual abbreviation is longer than the requested
6425
   * length by more than three, we give up on aligning, and add
6426
   * three dots anyway, to indicate that the output is not the
6427
   * full object name.  Yes, this may be suboptimal, but this
6428
   * appears only in "diff --raw --abbrev" output and it is not
6429
   * worth the effort to change it now.  Note that this would
6430
   * likely to work fine when the automatic sizing of default
6431
   * abbreviation length is used--we would be fed -1 in "len" in
6432
   * that case, and will end up always appending three-dots, but
6433
   * the automatic sizing is supposed to give abblen that ensures
6434
   * uniqueness across all objects (statistically speaking).
6435
   */
6436
0
  if (abblen < the_hash_algo->hexsz - 3) {
6437
0
    static char hex[GIT_MAX_HEXSZ + 1];
6438
0
    if (len < abblen && abblen <= len + 2)
6439
0
      xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6440
0
    else
6441
0
      xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6442
0
    return hex;
6443
0
  }
6444
6445
0
  return oid_to_hex(oid);
6446
0
}
6447
6448
static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6449
0
{
6450
0
  int line_termination = opt->line_termination;
6451
0
  int inter_name_termination = line_termination ? '\t' : '\0';
6452
6453
0
  fprintf(opt->file, "%s", diff_line_prefix(opt));
6454
0
  if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6455
0
    fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6456
0
      diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6457
0
    fprintf(opt->file, "%s ",
6458
0
      diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6459
0
  }
6460
0
  if (p->score) {
6461
0
    fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6462
0
      inter_name_termination);
6463
0
  } else {
6464
0
    fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6465
0
  }
6466
6467
0
  if (p->status == DIFF_STATUS_COPIED ||
6468
0
      p->status == DIFF_STATUS_RENAMED) {
6469
0
    const char *name_a, *name_b;
6470
0
    name_a = p->one->path;
6471
0
    name_b = p->two->path;
6472
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6473
0
    write_name_quoted(name_a, opt->file, inter_name_termination);
6474
0
    write_name_quoted(name_b, opt->file, line_termination);
6475
0
  } else {
6476
0
    const char *name_a, *name_b;
6477
0
    name_a = p->one->mode ? p->one->path : p->two->path;
6478
0
    name_b = NULL;
6479
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6480
0
    write_name_quoted(name_a, opt->file, line_termination);
6481
0
  }
6482
0
}
6483
6484
int diff_unmodified_pair(struct diff_filepair *p)
6485
0
{
6486
  /* This function is written stricter than necessary to support
6487
   * the currently implemented transformers, but the idea is to
6488
   * let transformers to produce diff_filepairs any way they want,
6489
   * and filter and clean them up here before producing the output.
6490
   */
6491
0
  struct diff_filespec *one = p->one, *two = p->two;
6492
6493
0
  if (DIFF_PAIR_UNMERGED(p))
6494
0
    return 0; /* unmerged is interesting */
6495
6496
  /* deletion, addition, mode or type change
6497
   * and rename are all interesting.
6498
   */
6499
0
  if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6500
0
      DIFF_PAIR_MODE_CHANGED(p) ||
6501
0
      strcmp(one->path, two->path))
6502
0
    return 0;
6503
6504
  /* both are valid and point at the same path.  that is, we are
6505
   * dealing with a change.
6506
   */
6507
0
  if (one->oid_valid && two->oid_valid &&
6508
0
      oideq(&one->oid, &two->oid) &&
6509
0
      !one->dirty_submodule && !two->dirty_submodule)
6510
0
    return 1; /* no change */
6511
0
  if (!one->oid_valid && !two->oid_valid)
6512
0
    return 1; /* both look at the same file on the filesystem. */
6513
0
  return 0;
6514
0
}
6515
6516
static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6517
0
{
6518
0
  int include_conflict_headers =
6519
0
      (additional_headers(o, p->one->path) &&
6520
0
       !o->pickaxe_opts &&
6521
0
       (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6522
6523
  /*
6524
   * Check if we can return early without showing a diff.  Note that
6525
   * diff_filepair only stores {oid, path, mode, is_valid}
6526
   * information for each path, and thus diff_unmodified_pair() only
6527
   * considers those bits of info.  However, we do not want pairs
6528
   * created by create_filepairs_for_header_only_notifications()
6529
   * (which always look like unmodified pairs) to be ignored, so
6530
   * return early if both p is unmodified AND we don't want to
6531
   * include_conflict_headers.
6532
   */
6533
0
  if (diff_unmodified_pair(p) && !include_conflict_headers)
6534
0
    return;
6535
6536
  /* Actually, we can also return early to avoid showing tree diffs */
6537
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6538
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6539
0
    return;
6540
6541
0
  run_diff(p, o);
6542
0
}
6543
6544
/* return 1 if any change is found; otherwise, return 0 */
6545
static int diff_flush_patch_quietly(struct diff_filepair *p, struct diff_options *o)
6546
0
{
6547
0
  FILE *saved_file = o->file;
6548
0
  int saved_found_changes = o->found_changes;
6549
0
  int ret;
6550
6551
0
  o->file = NULL;
6552
0
  o->found_changes = 0;
6553
0
  diff_flush_patch(p, o);
6554
0
  ret = o->found_changes;
6555
0
  o->file = saved_file;
6556
0
  o->found_changes |= saved_found_changes;
6557
0
  return ret;
6558
0
}
6559
6560
static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6561
          struct diffstat_t *diffstat)
6562
0
{
6563
0
  if (diff_unmodified_pair(p))
6564
0
    return;
6565
6566
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6567
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6568
0
    return; /* no useful stat for tree diffs */
6569
6570
0
  run_diffstat(p, o, diffstat);
6571
0
}
6572
6573
static void diff_flush_checkdiff(struct diff_filepair *p,
6574
    struct diff_options *o)
6575
0
{
6576
0
  if (diff_unmodified_pair(p))
6577
0
    return;
6578
6579
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6580
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6581
0
    return; /* nothing to check in tree diffs */
6582
6583
0
  run_checkdiff(p, o);
6584
0
}
6585
6586
int diff_queue_is_empty(struct diff_options *o)
6587
0
{
6588
0
  struct diff_queue_struct *q = &diff_queued_diff;
6589
0
  int i;
6590
0
  int include_conflict_headers =
6591
0
      (o->additional_path_headers &&
6592
0
       strmap_get_size(o->additional_path_headers) &&
6593
0
       !o->pickaxe_opts &&
6594
0
       (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6595
6596
0
  if (include_conflict_headers)
6597
0
    return 0;
6598
6599
0
  for (i = 0; i < q->nr; i++)
6600
0
    if (!diff_unmodified_pair(q->queue[i]))
6601
0
      return 0;
6602
0
  return 1;
6603
0
}
6604
6605
#if DIFF_DEBUG
6606
void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6607
{
6608
  fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6609
    x, one ? one : "",
6610
    s->path,
6611
    DIFF_FILE_VALID(s) ? "valid" : "invalid",
6612
    s->mode,
6613
    s->oid_valid ? oid_to_hex(&s->oid) : "");
6614
  fprintf(stderr, "queue[%d] %s size %lu\n",
6615
    x, one ? one : "",
6616
    s->size);
6617
}
6618
6619
void diff_debug_filepair(const struct diff_filepair *p, int i)
6620
{
6621
  diff_debug_filespec(p->one, i, "one");
6622
  diff_debug_filespec(p->two, i, "two");
6623
  fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6624
    p->score, p->status ? p->status : '?',
6625
    p->one->rename_used, p->broken_pair);
6626
}
6627
6628
void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6629
{
6630
  int i;
6631
  if (msg)
6632
    fprintf(stderr, "%s\n", msg);
6633
  fprintf(stderr, "q->nr = %d\n", q->nr);
6634
  for (i = 0; i < q->nr; i++) {
6635
    struct diff_filepair *p = q->queue[i];
6636
    diff_debug_filepair(p, i);
6637
  }
6638
}
6639
#endif
6640
6641
static void diff_resolve_rename_copy(void)
6642
0
{
6643
0
  int i;
6644
0
  struct diff_filepair *p;
6645
0
  struct diff_queue_struct *q = &diff_queued_diff;
6646
6647
0
  diff_debug_queue("resolve-rename-copy", q);
6648
6649
0
  for (i = 0; i < q->nr; i++) {
6650
0
    p = q->queue[i];
6651
0
    p->status = 0; /* undecided */
6652
0
    if (DIFF_PAIR_UNMERGED(p))
6653
0
      p->status = DIFF_STATUS_UNMERGED;
6654
0
    else if (!DIFF_FILE_VALID(p->one))
6655
0
      p->status = DIFF_STATUS_ADDED;
6656
0
    else if (!DIFF_FILE_VALID(p->two))
6657
0
      p->status = DIFF_STATUS_DELETED;
6658
0
    else if (DIFF_PAIR_TYPE_CHANGED(p))
6659
0
      p->status = DIFF_STATUS_TYPE_CHANGED;
6660
6661
    /* from this point on, we are dealing with a pair
6662
     * whose both sides are valid and of the same type, i.e.
6663
     * either in-place edit or rename/copy edit.
6664
     */
6665
0
    else if (DIFF_PAIR_RENAME(p)) {
6666
      /*
6667
       * A rename might have re-connected a broken
6668
       * pair up, causing the pathnames to be the
6669
       * same again. If so, that's not a rename at
6670
       * all, just a modification..
6671
       *
6672
       * Otherwise, see if this source was used for
6673
       * multiple renames, in which case we decrement
6674
       * the count, and call it a copy.
6675
       */
6676
0
      if (!strcmp(p->one->path, p->two->path))
6677
0
        p->status = DIFF_STATUS_MODIFIED;
6678
0
      else if (--p->one->rename_used > 0)
6679
0
        p->status = DIFF_STATUS_COPIED;
6680
0
      else
6681
0
        p->status = DIFF_STATUS_RENAMED;
6682
0
    }
6683
0
    else if (!oideq(&p->one->oid, &p->two->oid) ||
6684
0
       p->one->mode != p->two->mode ||
6685
0
       p->one->dirty_submodule ||
6686
0
       p->two->dirty_submodule ||
6687
0
       is_null_oid(&p->one->oid))
6688
0
      p->status = DIFF_STATUS_MODIFIED;
6689
0
    else {
6690
      /* This is a "no-change" entry and should not
6691
       * happen anymore, but prepare for broken callers.
6692
       */
6693
0
      error("feeding unmodified %s to diffcore",
6694
0
            p->one->path);
6695
0
      p->status = DIFF_STATUS_UNKNOWN;
6696
0
    }
6697
0
  }
6698
0
  diff_debug_queue("resolve-rename-copy done", q);
6699
0
}
6700
6701
static int check_pair_status(struct diff_filepair *p)
6702
0
{
6703
0
  switch (p->status) {
6704
0
  case DIFF_STATUS_UNKNOWN:
6705
0
    return 0;
6706
0
  case 0:
6707
0
    die("internal error in diff-resolve-rename-copy");
6708
0
  default:
6709
0
    return 1;
6710
0
  }
6711
0
}
6712
6713
static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6714
0
{
6715
0
  int fmt = opt->output_format;
6716
6717
0
  if (fmt & DIFF_FORMAT_CHECKDIFF)
6718
0
    diff_flush_checkdiff(p, opt);
6719
0
  else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6720
0
    diff_flush_raw(p, opt);
6721
0
  else if (fmt & DIFF_FORMAT_NAME) {
6722
0
    const char *name_a, *name_b;
6723
0
    name_a = p->two->path;
6724
0
    name_b = NULL;
6725
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6726
0
    fprintf(opt->file, "%s", diff_line_prefix(opt));
6727
0
    write_name_quoted(name_a, opt->file, opt->line_termination);
6728
0
  }
6729
6730
0
  opt->found_changes = 1;
6731
0
}
6732
6733
static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6734
0
{
6735
0
  struct strbuf sb = STRBUF_INIT;
6736
0
  if (fs->mode)
6737
0
    strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6738
0
  else
6739
0
    strbuf_addf(&sb, " %s ", newdelete);
6740
6741
0
  quote_c_style(fs->path, &sb, NULL, 0);
6742
0
  strbuf_addch(&sb, '\n');
6743
0
  emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6744
0
       sb.buf, sb.len, 0);
6745
0
  strbuf_release(&sb);
6746
0
}
6747
6748
static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6749
    int show_name)
6750
0
{
6751
0
  if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6752
0
    struct strbuf sb = STRBUF_INIT;
6753
0
    strbuf_addf(&sb, " mode change %06o => %06o",
6754
0
          p->one->mode, p->two->mode);
6755
0
    if (show_name) {
6756
0
      strbuf_addch(&sb, ' ');
6757
0
      quote_c_style(p->two->path, &sb, NULL, 0);
6758
0
    }
6759
0
    strbuf_addch(&sb, '\n');
6760
0
    emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6761
0
         sb.buf, sb.len, 0);
6762
0
    strbuf_release(&sb);
6763
0
  }
6764
0
}
6765
6766
static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6767
    struct diff_filepair *p)
6768
0
{
6769
0
  struct strbuf sb = STRBUF_INIT;
6770
0
  struct strbuf names = STRBUF_INIT;
6771
6772
0
  pprint_rename(&names, p->one->path, p->two->path);
6773
0
  strbuf_addf(&sb, " %s %s (%d%%)\n",
6774
0
        renamecopy, names.buf, similarity_index(p));
6775
0
  strbuf_release(&names);
6776
0
  emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6777
0
         sb.buf, sb.len, 0);
6778
0
  show_mode_change(opt, p, 0);
6779
0
  strbuf_release(&sb);
6780
0
}
6781
6782
static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6783
0
{
6784
0
  switch(p->status) {
6785
0
  case DIFF_STATUS_DELETED:
6786
0
    show_file_mode_name(opt, "delete", p->one);
6787
0
    break;
6788
0
  case DIFF_STATUS_ADDED:
6789
0
    show_file_mode_name(opt, "create", p->two);
6790
0
    break;
6791
0
  case DIFF_STATUS_COPIED:
6792
0
    show_rename_copy(opt, "copy", p);
6793
0
    break;
6794
0
  case DIFF_STATUS_RENAMED:
6795
0
    show_rename_copy(opt, "rename", p);
6796
0
    break;
6797
0
  default:
6798
0
    if (p->score) {
6799
0
      struct strbuf sb = STRBUF_INIT;
6800
0
      strbuf_addstr(&sb, " rewrite ");
6801
0
      quote_c_style(p->two->path, &sb, NULL, 0);
6802
0
      strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6803
0
      emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6804
0
           sb.buf, sb.len, 0);
6805
0
      strbuf_release(&sb);
6806
0
    }
6807
0
    show_mode_change(opt, p, !p->score);
6808
0
    break;
6809
0
  }
6810
0
}
6811
6812
struct patch_id_t {
6813
  struct git_hash_ctx *ctx;
6814
  int patchlen;
6815
};
6816
6817
static int remove_space(char *line, int len)
6818
0
{
6819
0
  int i;
6820
0
  char *dst = line;
6821
0
  unsigned char c;
6822
6823
0
  for (i = 0; i < len; i++)
6824
0
    if (!isspace((c = line[i])))
6825
0
      *dst++ = c;
6826
6827
0
  return dst - line;
6828
0
}
6829
6830
void flush_one_hunk(struct object_id *result, struct git_hash_ctx *ctx)
6831
0
{
6832
0
  unsigned char hash[GIT_MAX_RAWSZ];
6833
0
  unsigned short carry = 0;
6834
0
  int i;
6835
6836
0
  git_hash_final(hash, ctx);
6837
0
  git_hash_init(ctx, the_hash_algo);
6838
  /* 20-byte sum, with carry */
6839
0
  for (i = 0; i < the_hash_algo->rawsz; ++i) {
6840
0
    carry += result->hash[i] + hash[i];
6841
0
    result->hash[i] = carry;
6842
0
    carry >>= 8;
6843
0
  }
6844
0
}
6845
6846
static int patch_id_consume(void *priv, char *line, unsigned long len)
6847
0
{
6848
0
  struct patch_id_t *data = priv;
6849
0
  int new_len;
6850
6851
0
  if (len > 12 && starts_with(line, "\\ "))
6852
0
    return 0;
6853
0
  new_len = remove_space(line, len);
6854
6855
0
  git_hash_update(data->ctx, line, new_len);
6856
0
  data->patchlen += new_len;
6857
0
  return 0;
6858
0
}
6859
6860
static void patch_id_add_string(struct git_hash_ctx *ctx, const char *str)
6861
0
{
6862
0
  git_hash_update(ctx, str, strlen(str));
6863
0
}
6864
6865
static void patch_id_add_mode(struct git_hash_ctx *ctx, unsigned mode)
6866
0
{
6867
  /* large enough for 2^32 in octal */
6868
0
  char buf[12];
6869
0
  int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6870
0
  git_hash_update(ctx, buf, len);
6871
0
}
6872
6873
/* returns 0 upon success, and writes result into oid */
6874
static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6875
0
{
6876
0
  struct diff_queue_struct *q = &diff_queued_diff;
6877
0
  int i;
6878
0
  struct git_hash_ctx ctx;
6879
0
  struct patch_id_t data;
6880
6881
0
  git_hash_init(&ctx, the_hash_algo);
6882
0
  memset(&data, 0, sizeof(struct patch_id_t));
6883
0
  data.ctx = &ctx;
6884
0
  oidclr(oid, the_repository->hash_algo);
6885
6886
0
  for (i = 0; i < q->nr; i++) {
6887
0
    xpparam_t xpp;
6888
0
    xdemitconf_t xecfg;
6889
0
    mmfile_t mf1, mf2;
6890
0
    struct diff_filepair *p = q->queue[i];
6891
0
    int len1, len2;
6892
6893
0
    memset(&xpp, 0, sizeof(xpp));
6894
0
    memset(&xecfg, 0, sizeof(xecfg));
6895
0
    if (p->status == 0)
6896
0
      return error("internal diff status error");
6897
0
    if (p->status == DIFF_STATUS_UNKNOWN)
6898
0
      continue;
6899
0
    if (diff_unmodified_pair(p))
6900
0
      continue;
6901
0
    if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6902
0
        (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6903
0
      continue;
6904
0
    if (DIFF_PAIR_UNMERGED(p))
6905
0
      continue;
6906
6907
0
    diff_fill_oid_info(p->one, options->repo->index);
6908
0
    diff_fill_oid_info(p->two, options->repo->index);
6909
6910
0
    len1 = remove_space(p->one->path, strlen(p->one->path));
6911
0
    len2 = remove_space(p->two->path, strlen(p->two->path));
6912
0
    patch_id_add_string(&ctx, "diff--git");
6913
0
    patch_id_add_string(&ctx, "a/");
6914
0
    git_hash_update(&ctx, p->one->path, len1);
6915
0
    patch_id_add_string(&ctx, "b/");
6916
0
    git_hash_update(&ctx, p->two->path, len2);
6917
6918
0
    if (p->one->mode == 0) {
6919
0
      patch_id_add_string(&ctx, "newfilemode");
6920
0
      patch_id_add_mode(&ctx, p->two->mode);
6921
0
    } else if (p->two->mode == 0) {
6922
0
      patch_id_add_string(&ctx, "deletedfilemode");
6923
0
      patch_id_add_mode(&ctx, p->one->mode);
6924
0
    } else if (p->one->mode != p->two->mode) {
6925
0
      patch_id_add_string(&ctx, "oldmode");
6926
0
      patch_id_add_mode(&ctx, p->one->mode);
6927
0
      patch_id_add_string(&ctx, "newmode");
6928
0
      patch_id_add_mode(&ctx, p->two->mode);
6929
0
    }
6930
6931
0
    if (diff_header_only) {
6932
      /* don't do anything since we're only populating header info */
6933
0
    } else if (diff_filespec_is_binary(options->repo, p->one) ||
6934
0
        diff_filespec_is_binary(options->repo, p->two)) {
6935
0
      git_hash_update(&ctx, oid_to_hex(&p->one->oid),
6936
0
          the_hash_algo->hexsz);
6937
0
      git_hash_update(&ctx, oid_to_hex(&p->two->oid),
6938
0
          the_hash_algo->hexsz);
6939
0
    } else {
6940
0
      if (p->one->mode == 0) {
6941
0
        patch_id_add_string(&ctx, "---/dev/null");
6942
0
        patch_id_add_string(&ctx, "+++b/");
6943
0
        git_hash_update(&ctx, p->two->path, len2);
6944
0
      } else if (p->two->mode == 0) {
6945
0
        patch_id_add_string(&ctx, "---a/");
6946
0
        git_hash_update(&ctx, p->one->path, len1);
6947
0
        patch_id_add_string(&ctx, "+++/dev/null");
6948
0
      } else {
6949
0
        patch_id_add_string(&ctx, "---a/");
6950
0
        git_hash_update(&ctx, p->one->path, len1);
6951
0
        patch_id_add_string(&ctx, "+++b/");
6952
0
        git_hash_update(&ctx, p->two->path, len2);
6953
0
      }
6954
6955
0
      if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6956
0
          fill_mmfile(options->repo, &mf2, p->two) < 0)
6957
0
        return error("unable to read files to diff");
6958
0
      xpp.flags = 0;
6959
0
      xecfg.ctxlen = 3;
6960
0
      xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6961
0
      if (xdi_diff_outf(&mf1, &mf2, NULL,
6962
0
            patch_id_consume, &data, &xpp, &xecfg))
6963
0
        return error("unable to generate patch-id diff for %s",
6964
0
               p->one->path);
6965
0
    }
6966
0
    flush_one_hunk(oid, &ctx);
6967
0
  }
6968
6969
0
  git_hash_discard(&ctx);
6970
0
  return 0;
6971
0
}
6972
6973
int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6974
0
{
6975
0
  struct diff_queue_struct *q = &diff_queued_diff;
6976
0
  int result = diff_get_patch_id(options, oid, diff_header_only);
6977
6978
0
  diff_queue_clear(q);
6979
6980
0
  return result;
6981
0
}
6982
6983
static int is_summary_empty(const struct diff_queue_struct *q)
6984
0
{
6985
0
  int i;
6986
6987
0
  for (i = 0; i < q->nr; i++) {
6988
0
    const struct diff_filepair *p = q->queue[i];
6989
6990
0
    switch (p->status) {
6991
0
    case DIFF_STATUS_DELETED:
6992
0
    case DIFF_STATUS_ADDED:
6993
0
    case DIFF_STATUS_COPIED:
6994
0
    case DIFF_STATUS_RENAMED:
6995
0
      return 0;
6996
0
    default:
6997
0
      if (p->score)
6998
0
        return 0;
6999
0
      if (p->one->mode && p->two->mode &&
7000
0
          p->one->mode != p->two->mode)
7001
0
        return 0;
7002
0
      break;
7003
0
    }
7004
0
  }
7005
0
  return 1;
7006
0
}
7007
7008
static const char rename_limit_warning[] =
7009
N_("exhaustive rename detection was skipped due to too many files.");
7010
7011
static const char degrade_cc_to_c_warning[] =
7012
N_("only found copies from modified paths due to too many files.");
7013
7014
static const char rename_limit_advice[] =
7015
N_("you may want to set your %s variable to at least "
7016
   "%d and retry the command.");
7017
7018
void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
7019
0
{
7020
0
  fflush(stdout);
7021
0
  if (degraded_cc)
7022
0
    warning(_(degrade_cc_to_c_warning));
7023
0
  else if (needed)
7024
0
    warning(_(rename_limit_warning));
7025
0
  else
7026
0
    return;
7027
0
  if (0 < needed)
7028
0
    warning(_(rename_limit_advice), varname, needed);
7029
0
}
7030
7031
static void create_filepairs_for_header_only_notifications(struct diff_options *o)
7032
0
{
7033
0
  struct strset present;
7034
0
  struct diff_queue_struct *q = &diff_queued_diff;
7035
0
  struct hashmap_iter iter;
7036
0
  struct strmap_entry *e;
7037
0
  int i;
7038
7039
0
  strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
7040
7041
  /*
7042
   * Find out which paths exist in diff_queued_diff, preferring
7043
   * one->path for any pair that has multiple paths.
7044
   */
7045
0
  for (i = 0; i < q->nr; i++) {
7046
0
    struct diff_filepair *p = q->queue[i];
7047
0
    char *path = p->one->path ? p->one->path : p->two->path;
7048
7049
0
    if (strmap_contains(o->additional_path_headers, path))
7050
0
      strset_add(&present, path);
7051
0
  }
7052
7053
  /*
7054
   * Loop over paths in additional_path_headers; for each NOT already
7055
   * in diff_queued_diff, create a synthetic filepair and insert that
7056
   * into diff_queued_diff.
7057
   */
7058
0
  strmap_for_each_entry(o->additional_path_headers, &iter, e) {
7059
0
    if (!strset_contains(&present, e->key)) {
7060
0
      struct diff_filespec *one, *two;
7061
0
      struct diff_filepair *p;
7062
7063
0
      one = alloc_filespec(e->key);
7064
0
      two = alloc_filespec(e->key);
7065
0
      fill_filespec(one, null_oid(the_hash_algo), 0, 0);
7066
0
      fill_filespec(two, null_oid(the_hash_algo), 0, 0);
7067
0
      p = diff_queue(q, one, two);
7068
0
      p->status = DIFF_STATUS_MODIFIED;
7069
0
    }
7070
0
  }
7071
7072
  /* Re-sort the filepairs */
7073
0
  diffcore_fix_diff_index();
7074
7075
  /* Cleanup */
7076
0
  strset_clear(&present);
7077
0
}
7078
7079
static void diff_flush_patch_all_file_pairs(struct diff_options *o)
7080
0
{
7081
0
  int i;
7082
0
  static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
7083
0
  struct diff_queue_struct *q = &diff_queued_diff;
7084
7085
0
  if (WSEH_NEW & WS_RULE_MASK)
7086
0
    BUG("WS rules bit mask overlaps with diff symbol flags");
7087
7088
0
  if (o->color_moved && want_color(o->use_color))
7089
0
    o->emitted_symbols = &esm;
7090
7091
0
  if (o->additional_path_headers)
7092
0
    create_filepairs_for_header_only_notifications(o);
7093
7094
0
  for (i = 0; i < q->nr; i++) {
7095
0
    struct diff_filepair *p = q->queue[i];
7096
0
    if (check_pair_status(p))
7097
0
      diff_flush_patch(p, o);
7098
0
  }
7099
7100
0
  if (o->emitted_symbols) {
7101
0
    struct mem_pool entry_pool;
7102
0
    struct moved_entry_list *entry_list;
7103
7104
0
    mem_pool_init(&entry_pool, 1024 * 1024);
7105
0
    entry_list = add_lines_to_move_detection(o, &entry_pool);
7106
0
    mark_color_as_moved(o, entry_list);
7107
0
    if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
7108
0
      dim_moved_lines(o);
7109
7110
0
    mem_pool_discard(&entry_pool, 0);
7111
0
    free(entry_list);
7112
7113
0
    for (i = 0; i < esm.nr; i++)
7114
0
      emit_diff_symbol_from_struct(o, &esm.buf[i]);
7115
7116
0
    for (i = 0; i < esm.nr; i++)
7117
0
      free((void *)esm.buf[i].line);
7118
0
    esm.nr = 0;
7119
7120
0
    o->emitted_symbols = NULL;
7121
0
  }
7122
0
}
7123
7124
static void diff_free_file(struct diff_options *options)
7125
0
{
7126
0
  if (options->close_file && options->file) {
7127
0
    fclose(options->file);
7128
0
    options->file = NULL;
7129
0
  }
7130
0
}
7131
7132
static void diff_free_ignore_regex(struct diff_options *options)
7133
0
{
7134
0
  int i;
7135
7136
0
  for (i = 0; i < options->ignore_regex_nr; i++) {
7137
0
    regfree(options->ignore_regex[i]);
7138
0
    free(options->ignore_regex[i]);
7139
0
  }
7140
7141
0
  FREE_AND_NULL(options->ignore_regex);
7142
0
  options->ignore_regex_nr = 0;
7143
0
}
7144
7145
void diff_free(struct diff_options *options)
7146
0
{
7147
0
  if (options->no_free)
7148
0
    return;
7149
7150
0
  if (options->objfind) {
7151
0
    oidset_clear(options->objfind);
7152
0
    FREE_AND_NULL(options->objfind);
7153
0
  }
7154
7155
0
  FREE_AND_NULL(options->orderfile);
7156
0
  for (size_t i = 0; i < options->anchors_nr; i++)
7157
0
    free(options->anchors[i]);
7158
0
  FREE_AND_NULL(options->anchors);
7159
0
  options->anchors_nr = options->anchors_alloc = 0;
7160
7161
0
  diff_free_file(options);
7162
0
  diff_free_ignore_regex(options);
7163
0
  clear_pathspec(&options->pathspec);
7164
0
}
7165
7166
void diff_flush(struct diff_options *options)
7167
0
{
7168
0
  struct diff_queue_struct *q = &diff_queued_diff;
7169
0
  int i, output_format = options->output_format;
7170
0
  int separator = 0;
7171
0
  int dirstat_by_line = 0;
7172
7173
  /*
7174
   * Order: raw, stat, summary, patch
7175
   * or:    name/name-status/checkdiff (other bits clear)
7176
   */
7177
0
  if (!q->nr && !options->additional_path_headers)
7178
0
    goto free_queue;
7179
7180
0
  if (output_format & (DIFF_FORMAT_RAW |
7181
0
           DIFF_FORMAT_NAME |
7182
0
           DIFF_FORMAT_NAME_STATUS |
7183
0
           DIFF_FORMAT_CHECKDIFF)) {
7184
0
    for (i = 0; i < q->nr; i++) {
7185
0
      struct diff_filepair *p = q->queue[i];
7186
7187
0
      if (!check_pair_status(p))
7188
0
        continue;
7189
7190
0
      if (options->flags.diff_from_contents &&
7191
0
          !diff_flush_patch_quietly(p, options))
7192
0
        continue;
7193
7194
0
      flush_one_pair(p, options);
7195
0
    }
7196
0
    separator++;
7197
0
  }
7198
7199
0
  if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
7200
0
    dirstat_by_line = 1;
7201
7202
0
  if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
7203
0
      dirstat_by_line) {
7204
0
    struct diffstat_t diffstat;
7205
7206
0
    compute_diffstat(options, &diffstat, q);
7207
0
    if (output_format & DIFF_FORMAT_NUMSTAT)
7208
0
      show_numstat(&diffstat, options);
7209
0
    if (output_format & DIFF_FORMAT_DIFFSTAT)
7210
0
      show_stats(&diffstat, options);
7211
0
    if (output_format & DIFF_FORMAT_SHORTSTAT)
7212
0
      show_shortstats(&diffstat, options);
7213
0
    if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
7214
0
      show_dirstat_by_line(&diffstat, options);
7215
0
    free_diffstat_info(&diffstat);
7216
0
    separator++;
7217
0
  }
7218
0
  if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
7219
0
    show_dirstat(options);
7220
7221
0
  if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7222
0
    for (i = 0; i < q->nr; i++) {
7223
0
      diff_summary(options, q->queue[i]);
7224
0
    }
7225
0
    separator++;
7226
0
  }
7227
7228
0
  if (output_format & DIFF_FORMAT_PATCH) {
7229
0
    if (separator) {
7230
0
      emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
7231
0
      if (options->stat_sep)
7232
        /* attach patch instead of inline */
7233
0
        emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
7234
0
             NULL, 0, 0);
7235
0
    }
7236
7237
0
    diff_flush_patch_all_file_pairs(options);
7238
0
  }
7239
7240
0
  if (output_format & DIFF_FORMAT_CALLBACK)
7241
0
    options->format_callback(q, options, options->format_callback_data);
7242
7243
0
  if (output_format & DIFF_FORMAT_NO_OUTPUT &&
7244
0
      options->flags.exit_with_status &&
7245
0
      options->flags.diff_from_contents) {
7246
0
    for (i = 0; i < q->nr; i++) {
7247
0
      struct diff_filepair *p = q->queue[i];
7248
0
      if (check_pair_status(p))
7249
0
        diff_flush_patch_quietly(p, options);
7250
0
      if (options->found_changes)
7251
0
        break;
7252
0
    }
7253
0
  }
7254
7255
0
free_queue:
7256
0
  diff_queue_clear(q);
7257
0
  diff_free(options);
7258
7259
  /*
7260
   * Report the content-level differences with HAS_CHANGES;
7261
   * diff_addremove/diff_change does not set the bit when
7262
   * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
7263
   */
7264
0
  if (options->flags.diff_from_contents) {
7265
0
    if (options->found_changes)
7266
0
      options->flags.has_changes = 1;
7267
0
    else
7268
0
      options->flags.has_changes = 0;
7269
0
  }
7270
0
}
7271
7272
static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
7273
0
{
7274
0
  return (((p->status == DIFF_STATUS_MODIFIED) &&
7275
0
     ((p->score &&
7276
0
       filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
7277
0
      (!p->score &&
7278
0
       filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
7279
0
    ((p->status != DIFF_STATUS_MODIFIED) &&
7280
0
     filter_bit_tst(p->status, options)));
7281
0
}
7282
7283
static void diffcore_apply_filter(struct diff_options *options)
7284
0
{
7285
0
  int i;
7286
0
  struct diff_queue_struct *q = &diff_queued_diff;
7287
0
  struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7288
7289
0
  if (!options->filter)
7290
0
    return;
7291
7292
0
  if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
7293
0
    int found;
7294
0
    for (i = found = 0; !found && i < q->nr; i++) {
7295
0
      if (match_filter(options, q->queue[i]))
7296
0
        found++;
7297
0
    }
7298
0
    if (found)
7299
0
      return;
7300
7301
    /* otherwise we will clear the whole queue
7302
     * by copying the empty outq at the end of this
7303
     * function, but first clear the current entries
7304
     * in the queue.
7305
     */
7306
0
    for (i = 0; i < q->nr; i++)
7307
0
      diff_free_filepair(q->queue[i]);
7308
0
  }
7309
0
  else {
7310
    /* Only the matching ones */
7311
0
    for (i = 0; i < q->nr; i++) {
7312
0
      struct diff_filepair *p = q->queue[i];
7313
0
      if (match_filter(options, p))
7314
0
        diff_q(&outq, p);
7315
0
      else
7316
0
        diff_free_filepair(p);
7317
0
    }
7318
0
  }
7319
0
  free(q->queue);
7320
0
  *q = outq;
7321
0
}
7322
7323
/* Check whether two filespecs with the same mode and size are identical */
7324
static int diff_filespec_is_identical(struct repository *r,
7325
              struct diff_filespec *one,
7326
              struct diff_filespec *two)
7327
0
{
7328
0
  if (S_ISGITLINK(one->mode))
7329
0
    return 0;
7330
0
  if (diff_populate_filespec(r, one, NULL))
7331
0
    return 0;
7332
0
  if (diff_populate_filespec(r, two, NULL))
7333
0
    return 0;
7334
0
  return !memcmp(one->data, two->data, one->size);
7335
0
}
7336
7337
static int diff_filespec_check_stat_unmatch(struct repository *r,
7338
              struct diff_filepair *p)
7339
0
{
7340
0
  struct diff_populate_filespec_options dpf_options = {
7341
0
    .check_size_only = 1,
7342
0
    .missing_object_cb = diff_queued_diff_prefetch,
7343
0
    .missing_object_data = r,
7344
0
  };
7345
7346
0
  if (p->done_skip_stat_unmatch)
7347
0
    return p->skip_stat_unmatch_result;
7348
7349
0
  p->done_skip_stat_unmatch = 1;
7350
0
  p->skip_stat_unmatch_result = 0;
7351
  /*
7352
   * 1. Entries that come from stat info dirtiness
7353
   *    always have both sides (iow, not create/delete),
7354
   *    one side of the object name is unknown, with
7355
   *    the same mode and size.  Keep the ones that
7356
   *    do not match these criteria.  They have real
7357
   *    differences.
7358
   *
7359
   * 2. At this point, the file is known to be modified,
7360
   *    with the same mode and size, and the object
7361
   *    name of one side is unknown.  Need to inspect
7362
   *    the identical contents.
7363
   */
7364
0
  if (!DIFF_FILE_VALID(p->one) || /* (1) */
7365
0
      !DIFF_FILE_VALID(p->two) ||
7366
0
      (p->one->oid_valid && p->two->oid_valid) ||
7367
0
      (p->one->mode != p->two->mode) ||
7368
0
      diff_populate_filespec(r, p->one, &dpf_options) ||
7369
0
      diff_populate_filespec(r, p->two, &dpf_options) ||
7370
0
      (p->one->size != p->two->size) ||
7371
0
      !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
7372
0
    p->skip_stat_unmatch_result = 1;
7373
0
  return p->skip_stat_unmatch_result;
7374
0
}
7375
7376
static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
7377
0
{
7378
0
  int i;
7379
0
  struct diff_queue_struct *q = &diff_queued_diff;
7380
0
  struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7381
7382
0
  for (i = 0; i < q->nr; i++) {
7383
0
    struct diff_filepair *p = q->queue[i];
7384
7385
0
    if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
7386
0
      diff_q(&outq, p);
7387
0
    else {
7388
      /*
7389
       * The caller can subtract 1 from skip_stat_unmatch
7390
       * to determine how many paths were dirty only
7391
       * due to stat info mismatch.
7392
       */
7393
0
      if (!diffopt->flags.no_index)
7394
0
        diffopt->skip_stat_unmatch++;
7395
0
      diff_free_filepair(p);
7396
0
      q->queue[i] = NULL;
7397
0
    }
7398
0
  }
7399
0
  free(q->queue);
7400
0
  *q = outq;
7401
0
}
7402
7403
static int diffnamecmp(const void *a_, const void *b_)
7404
0
{
7405
0
  const struct diff_filepair *a = *((const struct diff_filepair **)a_);
7406
0
  const struct diff_filepair *b = *((const struct diff_filepair **)b_);
7407
0
  const char *name_a, *name_b;
7408
7409
0
  name_a = a->one ? a->one->path : a->two->path;
7410
0
  name_b = b->one ? b->one->path : b->two->path;
7411
0
  return strcmp(name_a, name_b);
7412
0
}
7413
7414
void diffcore_fix_diff_index(void)
7415
0
{
7416
0
  struct diff_queue_struct *q = &diff_queued_diff;
7417
0
  QSORT(q->queue, q->nr, diffnamecmp);
7418
0
}
7419
7420
void diff_add_if_missing(struct repository *r,
7421
       struct oid_array *to_fetch,
7422
       const struct diff_filespec *filespec)
7423
0
{
7424
0
  if (filespec && filespec->oid_valid &&
7425
0
      !S_ISGITLINK(filespec->mode) &&
7426
0
      odb_read_object_info_extended(r->objects, &filespec->oid, NULL,
7427
0
            OBJECT_INFO_FOR_PREFETCH))
7428
0
    oid_array_append(to_fetch, &filespec->oid);
7429
0
}
7430
7431
void diff_queued_diff_prefetch(void *repository)
7432
0
{
7433
0
  struct repository *repo = repository;
7434
0
  int i;
7435
0
  struct diff_queue_struct *q = &diff_queued_diff;
7436
0
  struct oid_array to_fetch = OID_ARRAY_INIT;
7437
7438
0
  for (i = 0; i < q->nr; i++) {
7439
0
    struct diff_filepair *p = q->queue[i];
7440
7441
0
    if (!p)
7442
0
      continue;
7443
7444
0
    diff_add_if_missing(repo, &to_fetch, p->one);
7445
0
    diff_add_if_missing(repo, &to_fetch, p->two);
7446
0
  }
7447
7448
  /*
7449
   * NEEDSWORK: Consider deduplicating the OIDs sent.
7450
   */
7451
0
  promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7452
7453
0
  oid_array_clear(&to_fetch);
7454
0
}
7455
7456
void init_diffstat_widths(struct diff_options *options)
7457
0
{
7458
0
  options->stat_width = -1;        /* use full terminal width */
7459
0
  options->stat_name_width = -1;   /* respect diff.statNameWidth config */
7460
0
  options->stat_graph_width = -1;  /* respect diff.statGraphWidth config */
7461
0
}
7462
7463
void diffcore_std(struct diff_options *options)
7464
0
{
7465
0
  int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7466
0
    DIFF_FORMAT_NUMSTAT |
7467
0
    DIFF_FORMAT_PATCH |
7468
0
    DIFF_FORMAT_SHORTSTAT |
7469
0
    DIFF_FORMAT_DIRSTAT;
7470
7471
  /*
7472
   * Check if the user requested a blob-data-requiring diff output and/or
7473
   * break-rewrite detection (which requires blob data). If yes, prefetch
7474
   * the diff pairs.
7475
   *
7476
   * If no prefetching occurs, diffcore_rename() will prefetch if it
7477
   * decides that it needs inexact rename detection.
7478
   */
7479
0
  if (repo_has_promisor_remote(options->repo) &&
7480
0
      (options->output_format & output_formats_to_prefetch ||
7481
0
       options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7482
0
    diff_queued_diff_prefetch(options->repo);
7483
7484
  /* NOTE please keep the following in sync with diff_tree_combined() */
7485
0
  if (options->skip_stat_unmatch)
7486
0
    diffcore_skip_stat_unmatch(options);
7487
0
  if (!options->found_follow) {
7488
    /* See try_to_follow_renames() in tree-diff.c */
7489
0
    if (options->break_opt != -1)
7490
0
      diffcore_break(options->repo,
7491
0
               options->break_opt);
7492
0
    if (options->detect_rename)
7493
0
      diffcore_rename(options);
7494
0
    if (options->break_opt != -1)
7495
0
      diffcore_merge_broken();
7496
0
  }
7497
0
  if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7498
0
    diffcore_pickaxe(options);
7499
0
  if (options->orderfile)
7500
0
    diffcore_order(options->orderfile);
7501
0
  if (options->rotate_to)
7502
0
    diffcore_rotate(options);
7503
0
  if (!options->found_follow && !options->skip_resolving_statuses)
7504
    /* See try_to_follow_renames() in tree-diff.c */
7505
0
    diff_resolve_rename_copy();
7506
0
  diffcore_apply_filter(options);
7507
7508
0
  if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7509
0
    options->flags.has_changes = 1;
7510
0
  else
7511
0
    options->flags.has_changes = 0;
7512
7513
0
  options->found_follow = 0;
7514
0
}
7515
7516
int diff_result_code(struct rev_info *revs)
7517
0
{
7518
0
  struct diff_options *opt = &revs->diffopt;
7519
0
  int result = 0;
7520
7521
0
  if (revs->remerge_diff) {
7522
0
    tmp_objdir_destroy(revs->remerge_objdir);
7523
0
    revs->remerge_objdir = NULL;
7524
0
  }
7525
7526
0
  diff_warn_rename_limit("diff.renameLimit",
7527
0
             opt->needed_rename_limit,
7528
0
             opt->degraded_cc_to_c);
7529
7530
0
  if (opt->flags.exit_with_status &&
7531
0
      opt->flags.has_changes)
7532
0
    result |= 01;
7533
0
  if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7534
0
      opt->flags.check_failed)
7535
0
    result |= 02;
7536
0
  return result;
7537
0
}
7538
7539
int diff_can_quit_early(struct diff_options *opt)
7540
0
{
7541
0
  return (opt->flags.quick &&
7542
0
    !opt->filter &&
7543
0
    opt->flags.has_changes);
7544
0
}
7545
7546
/*
7547
 * Shall changes to this submodule be ignored?
7548
 *
7549
 * Submodule changes can be configured to be ignored separately for each path,
7550
 * but that configuration can be overridden from the command line.
7551
 */
7552
static int is_submodule_ignored(const char *path, struct diff_options *options)
7553
0
{
7554
0
  int ignored = 0;
7555
0
  struct diff_flags orig_flags = options->flags;
7556
0
  if (!options->flags.override_submodule_config)
7557
0
    set_diffopt_flags_from_submodule_config(options, path);
7558
0
  if (options->flags.ignore_submodules)
7559
0
    ignored = 1;
7560
0
  options->flags = orig_flags;
7561
0
  return ignored;
7562
0
}
7563
7564
void compute_diffstat(struct diff_options *options,
7565
          struct diffstat_t *diffstat,
7566
          struct diff_queue_struct *q)
7567
0
{
7568
0
  int i;
7569
7570
0
  memset(diffstat, 0, sizeof(struct diffstat_t));
7571
0
  for (i = 0; i < q->nr; i++) {
7572
0
    struct diff_filepair *p = q->queue[i];
7573
0
    if (check_pair_status(p))
7574
0
      diff_flush_stat(p, options, diffstat);
7575
0
  }
7576
0
  options->found_changes = !!diffstat->nr;
7577
0
}
7578
7579
struct diff_filepair *diff_queue_addremove(struct diff_queue_struct *queue,
7580
             struct diff_options *options,
7581
             int addremove, unsigned mode,
7582
             const struct object_id *oid,
7583
             int oid_valid,
7584
             const char *concatpath,
7585
             unsigned dirty_submodule)
7586
0
{
7587
0
  struct diff_filespec *one, *two;
7588
0
  struct diff_filepair *pair;
7589
7590
0
  if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7591
0
    return NULL;
7592
7593
  /* This may look odd, but it is a preparation for
7594
   * feeding "there are unchanged files which should
7595
   * not produce diffs, but when you are doing copy
7596
   * detection you would need them, so here they are"
7597
   * entries to the diff-core.  They will be prefixed
7598
   * with something like '=' or '*' (I haven't decided
7599
   * which but should not make any difference).
7600
   * Feeding the same new and old to diff_change()
7601
   * also has the same effect.
7602
   * Before the final output happens, they are pruned after
7603
   * merged into rename/copy pairs as appropriate.
7604
   */
7605
0
  if (options->flags.reverse_diff)
7606
0
    addremove = (addremove == '+' ? '-' :
7607
0
           addremove == '-' ? '+' : addremove);
7608
7609
0
  if (options->prefix &&
7610
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7611
0
    return NULL;
7612
7613
0
  one = alloc_filespec(concatpath);
7614
0
  two = alloc_filespec(concatpath);
7615
7616
0
  if (addremove != '+')
7617
0
    fill_filespec(one, oid, oid_valid, mode);
7618
0
  if (addremove != '-') {
7619
0
    fill_filespec(two, oid, oid_valid, mode);
7620
0
    two->dirty_submodule = dirty_submodule;
7621
0
  }
7622
7623
0
  pair = diff_queue(queue, one, two);
7624
0
  if (!options->flags.diff_from_contents)
7625
0
    options->flags.has_changes = 1;
7626
7627
0
  return pair;
7628
0
}
7629
7630
struct diff_filepair *diff_queue_change(struct diff_queue_struct *queue,
7631
          struct diff_options *options,
7632
          unsigned old_mode, unsigned new_mode,
7633
          const struct object_id *old_oid,
7634
          const struct object_id *new_oid,
7635
          int old_oid_valid, int new_oid_valid,
7636
          const char *concatpath,
7637
          unsigned old_dirty_submodule,
7638
          unsigned new_dirty_submodule)
7639
0
{
7640
0
  struct diff_filespec *one, *two;
7641
0
  struct diff_filepair *p;
7642
7643
0
  if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7644
0
      is_submodule_ignored(concatpath, options))
7645
0
    return NULL;
7646
7647
0
  if (options->flags.reverse_diff) {
7648
0
    SWAP(old_mode, new_mode);
7649
0
    SWAP(old_oid, new_oid);
7650
0
    SWAP(old_oid_valid, new_oid_valid);
7651
0
    SWAP(old_dirty_submodule, new_dirty_submodule);
7652
0
  }
7653
7654
0
  if (options->prefix &&
7655
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7656
0
    return NULL;
7657
7658
0
  one = alloc_filespec(concatpath);
7659
0
  two = alloc_filespec(concatpath);
7660
0
  fill_filespec(one, old_oid, old_oid_valid, old_mode);
7661
0
  fill_filespec(two, new_oid, new_oid_valid, new_mode);
7662
0
  one->dirty_submodule = old_dirty_submodule;
7663
0
  two->dirty_submodule = new_dirty_submodule;
7664
0
  p = diff_queue(queue, one, two);
7665
7666
0
  if (options->flags.diff_from_contents)
7667
0
    return p;
7668
7669
0
  if (options->flags.quick && options->skip_stat_unmatch &&
7670
0
      !diff_filespec_check_stat_unmatch(options->repo, p)) {
7671
0
    diff_free_filespec_data(p->one);
7672
0
    diff_free_filespec_data(p->two);
7673
0
    return p;
7674
0
  }
7675
7676
0
  options->flags.has_changes = 1;
7677
7678
0
  return p;
7679
0
}
7680
7681
void diff_addremove(struct diff_options *options, int addremove, unsigned mode,
7682
        const struct object_id *oid, int oid_valid,
7683
        const char *concatpath, unsigned dirty_submodule)
7684
0
{
7685
0
  diff_queue_addremove(&diff_queued_diff, options, addremove, mode, oid,
7686
0
           oid_valid, concatpath, dirty_submodule);
7687
0
}
7688
7689
void diff_change(struct diff_options *options,
7690
     unsigned old_mode, unsigned new_mode,
7691
     const struct object_id *old_oid,
7692
     const struct object_id *new_oid,
7693
     int old_oid_valid, int new_oid_valid,
7694
     const char *concatpath,
7695
     unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7696
0
{
7697
0
  diff_queue_change(&diff_queued_diff, options, old_mode, new_mode,
7698
0
        old_oid, new_oid, old_oid_valid, new_oid_valid,
7699
0
        concatpath, old_dirty_submodule, new_dirty_submodule);
7700
0
}
7701
7702
void diff_same(struct diff_options *options,
7703
         unsigned mode,
7704
         const struct object_id *oid,
7705
         const char *concatpath)
7706
0
{
7707
0
  struct diff_filespec *one;
7708
7709
0
  if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7710
0
    return;
7711
7712
0
  if (options->prefix &&
7713
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7714
0
    return;
7715
7716
0
  one = alloc_filespec(concatpath);
7717
0
  fill_filespec(one, oid, 1, mode);
7718
0
  one->count++;
7719
0
  diff_queue(&diff_queued_diff, one, one);
7720
0
}
7721
7722
struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7723
0
{
7724
0
  struct diff_filepair *pair;
7725
0
  struct diff_filespec *one, *two;
7726
7727
0
  if (options->prefix &&
7728
0
      strncmp(path, options->prefix, options->prefix_length))
7729
0
    return NULL;
7730
7731
0
  one = alloc_filespec(path);
7732
0
  two = alloc_filespec(path);
7733
0
  pair = diff_queue(&diff_queued_diff, one, two);
7734
0
  pair->is_unmerged = 1;
7735
0
  return pair;
7736
0
}
7737
7738
static char *run_textconv(struct repository *r,
7739
        const char *pgm,
7740
        struct diff_filespec *spec,
7741
        size_t *outsize)
7742
0
{
7743
0
  struct diff_tempfile *temp;
7744
0
  struct child_process child = CHILD_PROCESS_INIT;
7745
0
  struct strbuf buf = STRBUF_INIT;
7746
0
  int err = 0;
7747
7748
0
  temp = prepare_temp_file(r, spec);
7749
0
  strvec_push(&child.args, pgm);
7750
0
  strvec_push(&child.args, temp->name);
7751
7752
0
  child.use_shell = 1;
7753
0
  child.out = -1;
7754
0
  if (start_command(&child)) {
7755
0
    remove_tempfile();
7756
0
    return NULL;
7757
0
  }
7758
7759
0
  if (strbuf_read(&buf, child.out, 0) < 0)
7760
0
    err = error("error reading from textconv command '%s'", pgm);
7761
0
  close(child.out);
7762
7763
0
  if (finish_command(&child) || err) {
7764
0
    strbuf_release(&buf);
7765
0
    remove_tempfile();
7766
0
    return NULL;
7767
0
  }
7768
0
  remove_tempfile();
7769
7770
0
  return strbuf_detach(&buf, outsize);
7771
0
}
7772
7773
size_t fill_textconv(struct repository *r,
7774
         struct userdiff_driver *driver,
7775
         struct diff_filespec *df,
7776
         char **outbuf)
7777
0
{
7778
0
  size_t size;
7779
7780
0
  if (!driver) {
7781
0
    if (!DIFF_FILE_VALID(df)) {
7782
0
      *outbuf = (char *) "";
7783
0
      return 0;
7784
0
    }
7785
0
    if (diff_populate_filespec(r, df, NULL))
7786
0
      die("unable to read files to diff");
7787
0
    *outbuf = df->data;
7788
0
    return df->size;
7789
0
  }
7790
7791
0
  if (!driver->textconv)
7792
0
    BUG("fill_textconv called with non-textconv driver");
7793
7794
0
  if (driver->textconv_cache && df->oid_valid) {
7795
0
    *outbuf = notes_cache_get(driver->textconv_cache,
7796
0
            &df->oid,
7797
0
            &size);
7798
0
    if (*outbuf)
7799
0
      return size;
7800
0
  }
7801
7802
0
  *outbuf = run_textconv(r, driver->textconv, df, &size);
7803
0
  if (!*outbuf)
7804
0
    die("unable to read files to diff");
7805
7806
0
  if (driver->textconv_cache && df->oid_valid) {
7807
    /* ignore errors, as we might be in a readonly repository */
7808
0
    notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7809
0
        size);
7810
    /*
7811
     * we could save up changes and flush them all at the end,
7812
     * but we would need an extra call after all diffing is done.
7813
     * Since generating a cache entry is the slow path anyway,
7814
     * this extra overhead probably isn't a big deal.
7815
     */
7816
0
    notes_cache_write(driver->textconv_cache);
7817
0
  }
7818
7819
0
  return size;
7820
0
}
7821
7822
int textconv_object(struct repository *r,
7823
        const char *path,
7824
        unsigned mode,
7825
        const struct object_id *oid,
7826
        int oid_valid,
7827
        char **buf,
7828
        unsigned long *buf_size)
7829
0
{
7830
0
  struct diff_filespec *df;
7831
0
  struct userdiff_driver *textconv;
7832
7833
0
  df = alloc_filespec(path);
7834
0
  fill_filespec(df, oid, oid_valid, mode);
7835
0
  textconv = get_textconv(r, df);
7836
0
  if (!textconv) {
7837
0
    free_filespec(df);
7838
0
    return 0;
7839
0
  }
7840
7841
0
  *buf_size = fill_textconv(r, textconv, df, buf);
7842
0
  free_filespec(df);
7843
0
  return 1;
7844
0
}
7845
7846
void setup_diff_pager(struct diff_options *opt)
7847
0
{
7848
  /*
7849
   * If the user asked for our exit code, then either they want --quiet
7850
   * or --exit-code. We should definitely not bother with a pager in the
7851
   * former case, as we will generate no output. Since we still properly
7852
   * report our exit code even when a pager is run, we _could_ run a
7853
   * pager with --exit-code. But since we have not done so historically,
7854
   * and because it is easy to find people oneline advising "git diff
7855
   * --exit-code" in hooks and other scripts, we do not do so.
7856
   */
7857
0
  if (!opt->flags.exit_with_status &&
7858
0
      check_pager_config(the_repository, "diff") != 0)
7859
0
    setup_pager(the_repository);
7860
0
}