Coverage Report

Created: 2026-11-12 06:03

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_line(char *line, int len, void *output_data)
3610
0
{
3611
0
  struct diff_options *o = output_data;
3612
0
  emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY, line, len, 0);
3613
0
}
3614
3615
static void emit_binary_diff_body(struct diff_options *o,
3616
          mmfile_t *one, mmfile_t *two)
3617
0
{
3618
0
  void *delta;
3619
0
  void *deflated;
3620
0
  void *data;
3621
0
  unsigned long orig_size;
3622
0
  unsigned long delta_size;
3623
0
  unsigned long deflate_size;
3624
0
  unsigned long data_size;
3625
3626
  /* We could do deflated delta, or we could do just deflated two,
3627
   * whichever is smaller.
3628
   */
3629
0
  delta = NULL;
3630
0
  deflated = deflate_it(two->ptr, two->size, &deflate_size);
3631
0
  if (one->size && two->size) {
3632
0
    size_t delta_size_st = 0;
3633
0
    delta = diff_delta(one->ptr, one->size,
3634
0
           two->ptr, two->size,
3635
0
           &delta_size_st, deflate_size);
3636
0
    delta_size = cast_size_t_to_ulong(delta_size_st);
3637
0
    if (delta) {
3638
0
      void *to_free = delta;
3639
0
      orig_size = delta_size;
3640
0
      delta = deflate_it(delta, delta_size, &delta_size);
3641
0
      free(to_free);
3642
0
    }
3643
0
  }
3644
3645
0
  if (delta && delta_size < deflate_size) {
3646
0
    char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3647
0
    emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3648
0
         s, strlen(s), 0);
3649
0
    free(s);
3650
0
    free(deflated);
3651
0
    data = delta;
3652
0
    data_size = delta_size;
3653
0
  } else {
3654
0
    char *s = xstrfmt("%"PRIuMAX, (uintmax_t)two->size);
3655
0
    emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3656
0
         s, strlen(s), 0);
3657
0
    free(s);
3658
0
    free(delta);
3659
0
    data = deflated;
3660
0
    data_size = deflate_size;
3661
0
  }
3662
3663
  /* emit data encoded in base85 */
3664
0
  chunk_and_encode85(data, data_size, emit_binary_diff_line, o);
3665
0
  emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3666
0
  free(data);
3667
0
}
3668
3669
static void emit_binary_diff(struct diff_options *o,
3670
           mmfile_t *one, mmfile_t *two)
3671
0
{
3672
0
  emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3673
0
  emit_binary_diff_body(o, one, two);
3674
0
  emit_binary_diff_body(o, two, one);
3675
0
}
3676
3677
int diff_filespec_is_binary(struct repository *r,
3678
          struct diff_filespec *one)
3679
0
{
3680
0
  struct diff_populate_filespec_options dpf_options = {
3681
0
    .check_binary = 1,
3682
0
  };
3683
3684
0
  if (one->is_binary == -1) {
3685
0
    diff_filespec_load_driver(one, r->index);
3686
0
    if (one->driver->binary != -1)
3687
0
      one->is_binary = one->driver->binary;
3688
0
    else {
3689
0
      if (!one->data && DIFF_FILE_VALID(one))
3690
0
        diff_populate_filespec(r, one, &dpf_options);
3691
0
      if (one->is_binary == -1 && one->data)
3692
0
        one->is_binary = buffer_is_binary(one->data,
3693
0
            one->size);
3694
0
      if (one->is_binary == -1)
3695
0
        one->is_binary = 0;
3696
0
    }
3697
0
  }
3698
0
  return one->is_binary;
3699
0
}
3700
3701
static const struct userdiff_funcname *
3702
diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3703
0
{
3704
0
  diff_filespec_load_driver(one, o->repo->index);
3705
0
  return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3706
0
}
3707
3708
void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3709
0
{
3710
0
  if (!options->a_prefix)
3711
0
    options->a_prefix = a;
3712
0
  if (!options->b_prefix)
3713
0
    options->b_prefix = b;
3714
0
}
3715
3716
void diff_set_noprefix(struct diff_options *options)
3717
0
{
3718
0
  options->a_prefix = options->b_prefix = "";
3719
0
}
3720
3721
void diff_set_default_prefix(struct diff_options *options)
3722
0
{
3723
0
  options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3724
0
  options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3725
0
}
3726
3727
struct userdiff_driver *get_textconv(struct repository *r,
3728
             struct diff_filespec *one)
3729
0
{
3730
0
  if (!DIFF_FILE_VALID(one))
3731
0
    return NULL;
3732
3733
0
  diff_filespec_load_driver(one, r->index);
3734
0
  return userdiff_get_textconv(r, one->driver);
3735
0
}
3736
3737
static struct string_list *additional_headers(struct diff_options *o,
3738
                const char *path)
3739
0
{
3740
0
  if (!o->additional_path_headers)
3741
0
    return NULL;
3742
0
  return strmap_get(o->additional_path_headers, path);
3743
0
}
3744
3745
static void add_formatted_header(struct strbuf *msg,
3746
          const char *header,
3747
          const char *line_prefix,
3748
          const char *meta,
3749
          const char *reset)
3750
0
{
3751
0
  const char *next, *newline;
3752
3753
0
  for (next = header; *next; next = newline) {
3754
0
    newline = strchrnul(next, '\n');
3755
0
    strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3756
0
          (int)(newline - next), next, reset);
3757
0
    if (*newline)
3758
0
      newline++;
3759
0
  }
3760
0
}
3761
3762
static void add_formatted_headers(struct strbuf *msg,
3763
          struct string_list *more_headers,
3764
          const char *line_prefix,
3765
          const char *meta,
3766
          const char *reset)
3767
0
{
3768
0
  int i;
3769
3770
0
  for (i = 0; i < more_headers->nr; i++)
3771
0
    add_formatted_header(msg, more_headers->items[i].string,
3772
0
             line_prefix, meta, reset);
3773
0
}
3774
3775
static int diff_filepair_is_phoney(struct diff_filespec *one,
3776
           struct diff_filespec *two)
3777
0
{
3778
  /*
3779
   * This function specifically looks for pairs injected by
3780
   * create_filepairs_for_header_only_notifications().  Such
3781
   * pairs are "phoney" in that they do not represent any
3782
   * content or even mode difference, but were inserted because
3783
   * diff_queued_diff previously had no pair associated with
3784
   * that path but we needed some pair to avoid losing the
3785
   * "remerge CONFLICT" header associated with the path.
3786
   */
3787
0
  return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3788
0
}
3789
3790
static int set_diff_algorithm(struct diff_options *opts,
3791
            const char *alg)
3792
0
{
3793
0
  long value = parse_algorithm_value(alg);
3794
3795
0
  if (value < 0)
3796
0
    return -1;
3797
3798
  /* clear out previous settings */
3799
0
  opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3800
0
  opts->xdl_opts |= value;
3801
3802
0
  return 0;
3803
0
}
3804
3805
static void builtin_diff(const char *name_a,
3806
       const char *name_b,
3807
       struct diff_filespec *one,
3808
       struct diff_filespec *two,
3809
       const char *xfrm_msg,
3810
       int must_show_header,
3811
       struct diff_options *o,
3812
       int complete_rewrite,
3813
       const struct range_set *line_ranges)
3814
0
{
3815
0
  mmfile_t mf1, mf2;
3816
0
  const char *lbl[2];
3817
0
  char *a_one, *b_two;
3818
0
  const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3819
0
  const char *reset = diff_get_color_opt(o, DIFF_RESET);
3820
0
  const char *a_prefix, *b_prefix;
3821
0
  struct userdiff_driver *textconv_one = NULL;
3822
0
  struct userdiff_driver *textconv_two = NULL;
3823
0
  struct strbuf header = STRBUF_INIT;
3824
0
  const char *line_prefix = diff_line_prefix(o);
3825
3826
0
  diff_set_mnemonic_prefix(o, "a/", "b/");
3827
0
  if (o->flags.reverse_diff) {
3828
0
    a_prefix = o->b_prefix;
3829
0
    b_prefix = o->a_prefix;
3830
0
  } else {
3831
0
    a_prefix = o->a_prefix;
3832
0
    b_prefix = o->b_prefix;
3833
0
  }
3834
3835
0
  if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3836
0
      (!one->mode || S_ISGITLINK(one->mode)) &&
3837
0
      (!two->mode || S_ISGITLINK(two->mode)) &&
3838
0
      (!diff_filepair_is_phoney(one, two))) {
3839
0
    show_submodule_diff_summary(o, one->path ? one->path : two->path,
3840
0
        &one->oid, &two->oid,
3841
0
        two->dirty_submodule);
3842
0
    o->found_changes = 1;
3843
0
    return;
3844
0
  } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3845
0
       (!one->mode || S_ISGITLINK(one->mode)) &&
3846
0
       (!two->mode || S_ISGITLINK(two->mode)) &&
3847
0
       (!diff_filepair_is_phoney(one, two))) {
3848
0
    show_submodule_inline_diff(o, one->path ? one->path : two->path,
3849
0
        &one->oid, &two->oid,
3850
0
        two->dirty_submodule);
3851
0
    o->found_changes = 1;
3852
0
    return;
3853
0
  }
3854
3855
0
  if (o->flags.allow_textconv) {
3856
0
    textconv_one = get_textconv(o->repo, one);
3857
0
    textconv_two = get_textconv(o->repo, two);
3858
0
  }
3859
3860
  /* Never use a non-valid filename anywhere if at all possible */
3861
0
  name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3862
0
  name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3863
3864
0
  a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3865
0
  b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3866
0
  lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3867
0
  lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3868
0
  if (diff_filepair_is_phoney(one, two)) {
3869
    /*
3870
     * We should only reach this point for pairs generated from
3871
     * create_filepairs_for_header_only_notifications().  For
3872
     * these, we want to avoid the "/dev/null" special casing
3873
     * above, because we do not want such pairs shown as either
3874
     * "new file" or "deleted file" below.
3875
     */
3876
0
    lbl[0] = a_one;
3877
0
    lbl[1] = b_two;
3878
0
  }
3879
0
  strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3880
0
  if (lbl[0][0] == '/') {
3881
    /* /dev/null */
3882
0
    strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3883
0
    if (xfrm_msg)
3884
0
      strbuf_addstr(&header, xfrm_msg);
3885
0
    o->found_changes = 1;
3886
0
    must_show_header = 1;
3887
0
  }
3888
0
  else if (lbl[1][0] == '/') {
3889
0
    strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3890
0
    if (xfrm_msg)
3891
0
      strbuf_addstr(&header, xfrm_msg);
3892
0
    o->found_changes = 1;
3893
0
    must_show_header = 1;
3894
0
  }
3895
0
  else {
3896
0
    if (one->mode != two->mode) {
3897
0
      strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3898
0
      strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3899
0
      o->found_changes = 1;
3900
0
      must_show_header = 1;
3901
0
    }
3902
0
    if (xfrm_msg)
3903
0
      strbuf_addstr(&header, xfrm_msg);
3904
3905
    /*
3906
     * we do not run diff between different kind
3907
     * of objects.
3908
     */
3909
0
    if ((one->mode ^ two->mode) & S_IFMT)
3910
0
      goto free_ab_and_return;
3911
0
    if (complete_rewrite &&
3912
0
        (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3913
0
        (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3914
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3915
0
           header.buf, header.len, 0);
3916
0
      strbuf_reset(&header);
3917
0
      emit_rewrite_diff(name_a, name_b, one, two,
3918
0
            textconv_one, textconv_two, o);
3919
0
      o->found_changes = 1;
3920
0
      goto free_ab_and_return;
3921
0
    }
3922
0
  }
3923
3924
0
  if (o->irreversible_delete && lbl[1][0] == '/') {
3925
0
    emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3926
0
         header.len, 0);
3927
0
    strbuf_reset(&header);
3928
0
    goto free_ab_and_return;
3929
0
  } else if (!o->flags.text &&
3930
0
       ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3931
0
         (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3932
0
    struct strbuf sb = STRBUF_INIT;
3933
0
    if (!one->data && !two->data &&
3934
0
        S_ISREG(one->mode) && S_ISREG(two->mode) &&
3935
0
        !o->flags.binary) {
3936
0
      if (oideq(&one->oid, &two->oid)) {
3937
0
        if (must_show_header)
3938
0
          emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3939
0
               header.buf, header.len,
3940
0
               0);
3941
0
        goto free_ab_and_return;
3942
0
      }
3943
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3944
0
           header.buf, header.len, 0);
3945
0
      strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3946
0
            diff_line_prefix(o), lbl[0], lbl[1]);
3947
0
      emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3948
0
           sb.buf, sb.len, 0);
3949
0
      strbuf_release(&sb);
3950
0
      o->found_changes = 1;
3951
0
      goto free_ab_and_return;
3952
0
    }
3953
0
    if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3954
0
        fill_mmfile(o->repo, &mf2, two) < 0)
3955
0
      die("unable to read files to diff");
3956
    /* Quite common confusing case */
3957
0
    if (mf1.size == mf2.size &&
3958
0
        !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3959
0
      if (must_show_header)
3960
0
        emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3961
0
             header.buf, header.len, 0);
3962
0
      goto free_ab_and_return;
3963
0
    }
3964
0
    emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3965
0
    strbuf_reset(&header);
3966
0
    if (o->flags.binary)
3967
0
      emit_binary_diff(o, &mf1, &mf2);
3968
0
    else {
3969
0
      strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3970
0
            diff_line_prefix(o), lbl[0], lbl[1]);
3971
0
      emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3972
0
           sb.buf, sb.len, 0);
3973
0
      strbuf_release(&sb);
3974
0
    }
3975
0
    o->found_changes = 1;
3976
0
  } else {
3977
    /* Crazy xdl interfaces.. */
3978
0
    const char *diffopts;
3979
0
    const char *v;
3980
0
    xpparam_t xpp;
3981
0
    xdemitconf_t xecfg;
3982
0
    struct emit_callback ecbdata;
3983
0
    unsigned ws_rule;
3984
0
    const struct userdiff_funcname *pe;
3985
3986
0
    if (must_show_header) {
3987
0
      emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3988
0
           header.buf, header.len, 0);
3989
0
      strbuf_reset(&header);
3990
0
    }
3991
3992
0
    mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3993
0
    mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3994
3995
0
    ws_rule = whitespace_rule(o->repo->index, name_b);
3996
3997
    /* symlink being an incomplete line is not a news */
3998
0
    if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
3999
0
      ws_rule &= ~WS_INCOMPLETE_LINE;
4000
4001
0
    pe = diff_funcname_pattern(o, one);
4002
0
    if (!pe)
4003
0
      pe = diff_funcname_pattern(o, two);
4004
4005
0
    memset(&xpp, 0, sizeof(xpp));
4006
0
    memset(&xecfg, 0, sizeof(xecfg));
4007
0
    memset(&ecbdata, 0, sizeof(ecbdata));
4008
0
    if (o->flags.suppress_diff_headers)
4009
0
      lbl[0] = NULL;
4010
0
    ecbdata.label_path = lbl;
4011
0
    ecbdata.color_diff = o->use_color;
4012
0
    ecbdata.ws_rule = ws_rule;
4013
0
    if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
4014
0
      check_blank_at_eof(&mf1, &mf2, &ecbdata);
4015
0
    ecbdata.opt = o;
4016
0
    if (header.len && !o->flags.suppress_diff_headers)
4017
0
      ecbdata.header = &header;
4018
0
    xpp.flags = o->xdl_opts;
4019
0
    xpp.ignore_regex = o->ignore_regex;
4020
0
    xpp.ignore_regex_nr = o->ignore_regex_nr;
4021
0
    xpp.anchors = o->anchors;
4022
0
    xpp.anchors_nr = o->anchors_nr;
4023
0
    xecfg.ctxlen = o->context;
4024
0
    xecfg.interhunkctxlen = o->interhunkcontext;
4025
0
    xecfg.flags = XDL_EMIT_FUNCNAMES;
4026
0
    if (o->flags.funccontext)
4027
0
      xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
4028
0
    if (pe)
4029
0
      xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
4030
4031
0
    diffopts = getenv("GIT_DIFF_OPTS");
4032
0
    if (!diffopts)
4033
0
      ;
4034
0
    else if (skip_prefix(diffopts, "--unified=", &v))
4035
0
      xecfg.ctxlen = strtoul(v, NULL, 10);
4036
0
    else if (skip_prefix(diffopts, "-u", &v))
4037
0
      xecfg.ctxlen = strtoul(v, NULL, 10);
4038
4039
0
    if (o->word_diff)
4040
0
      init_diff_words_data(&ecbdata, o, one, two);
4041
0
    if (!o->file) {
4042
      /*
4043
       * Unlike the normal output case, we need to ignore the
4044
       * return value from xdi_diff_outf() here, because
4045
       * xdi_diff_outf() takes non-zero return from its
4046
       * callback function as a sign of error and returns
4047
       * early (which is why we return non-zero from our
4048
       * callback, quick_consume()).  Unfortunately,
4049
       * xdi_diff_outf() signals an error by returning
4050
       * non-zero.
4051
       */
4052
0
      xdi_diff_outf(&mf1, &mf2, NULL, quick_consume,
4053
0
              &ecbdata, &xpp, &xecfg);
4054
0
    } else if (line_ranges) {
4055
0
      struct line_range_callback lr_state;
4056
0
      unsigned int i;
4057
0
      long max_span = 0;
4058
4059
0
      memset(&lr_state, 0, sizeof(lr_state));
4060
0
      lr_state.orig_line_fn = fn_out_consume;
4061
0
      lr_state.orig_cb_data = &ecbdata;
4062
0
      lr_state.ranges = line_ranges;
4063
0
      strbuf_init(&lr_state.rhunk, 0);
4064
0
      strbuf_init(&lr_state.pending_rm, 0);
4065
4066
      /*
4067
       * Inflate ctxlen so that all changes within
4068
       * any single range are merged into one xdiff
4069
       * hunk and the inter-change context is emitted.
4070
       * The callback clips back to range boundaries.
4071
       *
4072
       * The optimal ctxlen depends on where changes
4073
       * fall within the range, which is only known
4074
       * after xdiff runs; the max range span is the
4075
       * upper bound that guarantees correctness in a
4076
       * single pass.
4077
       */
4078
0
      for (i = 0; i < line_ranges->nr; i++) {
4079
0
        long span = line_ranges->ranges[i].end -
4080
0
              line_ranges->ranges[i].start;
4081
0
        if (span > max_span)
4082
0
          max_span = span;
4083
0
      }
4084
0
      if (max_span > xecfg.ctxlen)
4085
0
        xecfg.ctxlen = max_span;
4086
4087
0
      if (xdi_diff_outf(&mf1, &mf2,
4088
0
            line_range_hunk_fn,
4089
0
            line_range_line_fn,
4090
0
            &lr_state, &xpp, &xecfg))
4091
0
        die("unable to generate diff for %s",
4092
0
            one->path);
4093
4094
0
      flush_rhunk(&lr_state);
4095
0
      if (lr_state.ret)
4096
0
        die("unable to generate diff for %s",
4097
0
            one->path);
4098
0
      strbuf_release(&lr_state.rhunk);
4099
0
      strbuf_release(&lr_state.pending_rm);
4100
0
    } else if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
4101
0
           &ecbdata, &xpp, &xecfg))
4102
0
      die("unable to generate diff for %s", one->path);
4103
0
    if (o->word_diff)
4104
0
      free_diff_words_data(&ecbdata);
4105
0
    if (textconv_one)
4106
0
      free(mf1.ptr);
4107
0
    if (textconv_two)
4108
0
      free(mf2.ptr);
4109
0
    xdiff_clear_find_func(&xecfg);
4110
0
  }
4111
4112
0
 free_ab_and_return:
4113
0
  strbuf_release(&header);
4114
0
  diff_free_filespec_data(one);
4115
0
  diff_free_filespec_data(two);
4116
0
  free(a_one);
4117
0
  free(b_two);
4118
0
  return;
4119
0
}
4120
4121
static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
4122
0
{
4123
0
  if (!is_renamed) {
4124
0
    if (p->status == DIFF_STATUS_ADDED) {
4125
0
      if (S_ISLNK(p->two->mode))
4126
0
        return "new +l";
4127
0
      else if ((p->two->mode & 0777) == 0755)
4128
0
        return "new +x";
4129
0
      else
4130
0
        return "new";
4131
0
    } else if (p->status == DIFF_STATUS_DELETED)
4132
0
      return "gone";
4133
0
  }
4134
0
  if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
4135
0
    return "mode -l";
4136
0
  else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
4137
0
    return "mode +l";
4138
0
  else if ((p->one->mode & 0777) == 0644 &&
4139
0
     (p->two->mode & 0777) == 0755)
4140
0
    return "mode +x";
4141
0
  else if ((p->one->mode & 0777) == 0755 &&
4142
0
     (p->two->mode & 0777) == 0644)
4143
0
    return "mode -x";
4144
0
  return NULL;
4145
0
}
4146
4147
static void builtin_diffstat(const char *name_a, const char *name_b,
4148
           struct diff_filespec *one,
4149
           struct diff_filespec *two,
4150
           struct diffstat_t *diffstat,
4151
           struct diff_options *o,
4152
           struct diff_filepair *p)
4153
0
{
4154
0
  mmfile_t mf1, mf2;
4155
0
  struct diffstat_file *data;
4156
0
  int may_differ;
4157
0
  int complete_rewrite = 0;
4158
4159
0
  if (!DIFF_PAIR_UNMERGED(p)) {
4160
0
    if (p->status == DIFF_STATUS_MODIFIED && p->score)
4161
0
      complete_rewrite = 1;
4162
0
  }
4163
4164
0
  data = diffstat_add(diffstat, name_a, name_b);
4165
0
  data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
4166
0
  if (o->flags.stat_with_summary)
4167
0
    data->comments = get_compact_summary(p, data->is_renamed);
4168
4169
0
  if (!one || !two) {
4170
0
    data->is_unmerged = 1;
4171
0
    return;
4172
0
  }
4173
4174
  /* saves some reads if true, not a guarantee of diff outcome */
4175
0
  may_differ = !(one->oid_valid && two->oid_valid &&
4176
0
      oideq(&one->oid, &two->oid));
4177
4178
0
  if (diff_filespec_is_binary(o->repo, one) ||
4179
0
      diff_filespec_is_binary(o->repo, two)) {
4180
0
    data->is_binary = 1;
4181
0
    if (!may_differ) {
4182
0
      data->added = 0;
4183
0
      data->deleted = 0;
4184
0
    } else {
4185
0
      data->added = diff_filespec_size(o->repo, two);
4186
0
      data->deleted = diff_filespec_size(o->repo, one);
4187
0
    }
4188
0
  }
4189
4190
0
  else if (complete_rewrite) {
4191
0
    diff_populate_filespec(o->repo, one, NULL);
4192
0
    diff_populate_filespec(o->repo, two, NULL);
4193
0
    data->deleted = count_lines(one->data, one->size);
4194
0
    data->added = count_lines(two->data, two->size);
4195
0
  }
4196
4197
0
  else if (may_differ) {
4198
    /* Crazy xdl interfaces.. */
4199
0
    xpparam_t xpp;
4200
0
    xdemitconf_t xecfg;
4201
4202
0
    if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4203
0
        fill_mmfile(o->repo, &mf2, two) < 0)
4204
0
      die("unable to read files to diff");
4205
4206
0
    memset(&xpp, 0, sizeof(xpp));
4207
0
    memset(&xecfg, 0, sizeof(xecfg));
4208
0
    xpp.flags = o->xdl_opts;
4209
0
    xpp.ignore_regex = o->ignore_regex;
4210
0
    xpp.ignore_regex_nr = o->ignore_regex_nr;
4211
0
    xpp.anchors = o->anchors;
4212
0
    xpp.anchors_nr = o->anchors_nr;
4213
0
    xecfg.ctxlen = o->context;
4214
0
    xecfg.interhunkctxlen = o->interhunkcontext;
4215
0
    xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
4216
0
    if (xdi_diff_outf(&mf1, &mf2, NULL,
4217
0
          diffstat_consume, diffstat, &xpp, &xecfg))
4218
0
      die("unable to generate diffstat for %s", one->path);
4219
4220
0
    if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
4221
0
      struct diffstat_file *file =
4222
0
        diffstat->files[diffstat->nr - 1];
4223
      /*
4224
       * Omit diffstats of modified files where nothing changed.
4225
       * Even if may_differ, this might be the case due to
4226
       * ignoring whitespace changes, etc.
4227
       *
4228
       * But note that we special-case additions, deletions,
4229
       * renames, and mode changes as adding an empty file,
4230
       * for example is still of interest.
4231
       */
4232
0
      if ((p->status == DIFF_STATUS_MODIFIED)
4233
0
        && !file->added
4234
0
        && !file->deleted
4235
0
        && one->mode == two->mode) {
4236
0
        free_diffstat_file(file);
4237
0
        diffstat->nr--;
4238
0
      }
4239
0
    }
4240
0
  }
4241
4242
0
  diff_free_filespec_data(one);
4243
0
  diff_free_filespec_data(two);
4244
0
}
4245
4246
static void builtin_checkdiff(const char *name_a, const char *name_b,
4247
            const char *attr_path,
4248
            struct diff_filespec *one,
4249
            struct diff_filespec *two,
4250
            struct diff_options *o)
4251
0
{
4252
0
  mmfile_t mf1, mf2;
4253
0
  struct checkdiff_t data;
4254
4255
0
  if (!two)
4256
0
    return;
4257
4258
0
  memset(&data, 0, sizeof(data));
4259
0
  data.filename = name_b ? name_b : name_a;
4260
0
  data.lineno = 0;
4261
0
  data.o = o;
4262
0
  data.ws_rule = whitespace_rule(o->repo->index, attr_path);
4263
0
  data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
4264
4265
  /* symlink being an incomplete line is not a news */
4266
0
  if (DIFF_FILE_VALID(two) && S_ISLNK(two->mode))
4267
0
    data.ws_rule &= ~WS_INCOMPLETE_LINE;
4268
4269
0
  if (fill_mmfile(o->repo, &mf1, one) < 0 ||
4270
0
      fill_mmfile(o->repo, &mf2, two) < 0)
4271
0
    die("unable to read files to diff");
4272
4273
  /*
4274
   * All the other codepaths check both sides, but not checking
4275
   * the "old" side here is deliberate.  We are checking the newly
4276
   * introduced changes, and as long as the "new" side is text, we
4277
   * can and should check what it introduces.
4278
   */
4279
0
  if (diff_filespec_is_binary(o->repo, two))
4280
0
    goto free_and_return;
4281
0
  else {
4282
    /* Crazy xdl interfaces.. */
4283
0
    xpparam_t xpp;
4284
0
    xdemitconf_t xecfg;
4285
4286
0
    memset(&xpp, 0, sizeof(xpp));
4287
0
    memset(&xecfg, 0, sizeof(xecfg));
4288
0
    xecfg.ctxlen = 1; /* at least one context line */
4289
0
    xpp.flags = 0;
4290
0
    if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
4291
0
          checkdiff_consume, &data,
4292
0
          &xpp, &xecfg))
4293
0
      die("unable to generate checkdiff for %s", one->path);
4294
4295
0
    if (data.ws_rule & WS_BLANK_AT_EOF) {
4296
0
      struct emit_callback ecbdata;
4297
0
      int blank_at_eof;
4298
4299
0
      ecbdata.ws_rule = data.ws_rule;
4300
0
      check_blank_at_eof(&mf1, &mf2, &ecbdata);
4301
0
      blank_at_eof = ecbdata.blank_at_eof_in_postimage;
4302
4303
0
      if (blank_at_eof) {
4304
0
        static char *err;
4305
0
        if (!err)
4306
0
          err = whitespace_error_string(WS_BLANK_AT_EOF);
4307
0
        fprintf(o->file, "%s:%d: %s.\n",
4308
0
          data.filename, blank_at_eof, err);
4309
0
        data.status = 1; /* report errors */
4310
0
      }
4311
0
    }
4312
0
  }
4313
0
 free_and_return:
4314
0
  diff_free_filespec_data(one);
4315
0
  diff_free_filespec_data(two);
4316
0
  if (data.status)
4317
0
    o->flags.check_failed = 1;
4318
0
}
4319
4320
struct diff_filespec *alloc_filespec(const char *path)
4321
0
{
4322
0
  struct diff_filespec *spec;
4323
4324
0
  FLEXPTR_ALLOC_STR(spec, path, path);
4325
0
  spec->count = 1;
4326
0
  spec->is_binary = -1;
4327
0
  return spec;
4328
0
}
4329
4330
void free_filespec(struct diff_filespec *spec)
4331
0
{
4332
0
  if (!--spec->count) {
4333
0
    diff_free_filespec_data(spec);
4334
0
    free(spec);
4335
0
  }
4336
0
}
4337
4338
void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
4339
       int oid_valid, unsigned short mode)
4340
0
{
4341
0
  if (mode) {
4342
0
    spec->mode = canon_mode(mode);
4343
0
    oidcpy(&spec->oid, oid);
4344
0
    spec->oid_valid = oid_valid;
4345
0
  }
4346
0
}
4347
4348
/*
4349
 * Given a name and sha1 pair, if the index tells us the file in
4350
 * the work tree has that object contents, return true, so that
4351
 * prepare_temp_file() does not have to inflate and extract.
4352
 */
4353
static int reuse_worktree_file(struct index_state *istate,
4354
             const char *name,
4355
             const struct object_id *oid,
4356
             int want_file)
4357
0
{
4358
0
  const struct cache_entry *ce;
4359
0
  struct stat st;
4360
0
  int pos, len;
4361
4362
  /*
4363
   * We do not read the cache ourselves here, because the
4364
   * benchmark with my previous version that always reads cache
4365
   * shows that it makes things worse for diff-tree comparing
4366
   * two linux-2.6 kernel trees in an already checked out work
4367
   * tree.  This is because most diff-tree comparisons deal with
4368
   * only a small number of files, while reading the cache is
4369
   * expensive for a large project, and its cost outweighs the
4370
   * savings we get by not inflating the object to a temporary
4371
   * file.  Practically, this code only helps when we are used
4372
   * by diff-cache --cached, which does read the cache before
4373
   * calling us.
4374
   */
4375
0
  if (!istate->cache)
4376
0
    return 0;
4377
4378
  /* We want to avoid the working directory if our caller
4379
   * doesn't need the data in a normal file, this system
4380
   * is rather slow with its stat/open/mmap/close syscalls,
4381
   * and the object is contained in a pack file.  The pack
4382
   * is probably already open and will be faster to obtain
4383
   * the data through than the working directory.  Loose
4384
   * objects however would tend to be slower as they need
4385
   * to be individually opened and inflated.
4386
   */
4387
0
  if (!FAST_WORKING_DIRECTORY && !want_file &&
4388
0
      has_object_pack(istate->repo, oid))
4389
0
    return 0;
4390
4391
  /*
4392
   * Similarly, if we'd have to convert the file contents anyway, that
4393
   * makes the optimization not worthwhile.
4394
   */
4395
0
  if (!want_file && would_convert_to_git(istate, name))
4396
0
    return 0;
4397
4398
  /*
4399
   * If this path does not match our sparse-checkout definition,
4400
   * then the file will not be in the working directory.
4401
   */
4402
0
  if (!path_in_sparse_checkout(name, istate))
4403
0
    return 0;
4404
4405
0
  len = strlen(name);
4406
0
  pos = index_name_pos(istate, name, len);
4407
0
  if (pos < 0)
4408
0
    return 0;
4409
0
  ce = istate->cache[pos];
4410
4411
  /*
4412
   * This is not the sha1 we are looking for, or
4413
   * unreusable because it is not a regular file.
4414
   */
4415
0
  if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4416
0
    return 0;
4417
4418
  /*
4419
   * If ce is marked as "assume unchanged", there is no
4420
   * guarantee that work tree matches what we are looking for.
4421
   */
4422
0
  if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4423
0
    return 0;
4424
4425
  /*
4426
   * If ce matches the file in the work tree, we can reuse it.
4427
   */
4428
0
  if (ce_uptodate(ce) ||
4429
0
      (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4430
0
    return 1;
4431
4432
0
  return 0;
4433
0
}
4434
4435
static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4436
0
{
4437
0
  struct strbuf buf = STRBUF_INIT;
4438
0
  const char *dirty = "";
4439
4440
  /* Are we looking at the work tree? */
4441
0
  if (s->dirty_submodule)
4442
0
    dirty = "-dirty";
4443
4444
0
  strbuf_addf(&buf, "Subproject commit %s%s\n",
4445
0
        oid_to_hex(&s->oid), dirty);
4446
0
  s->size = buf.len;
4447
0
  if (size_only) {
4448
0
    s->data = NULL;
4449
0
    strbuf_release(&buf);
4450
0
  } else {
4451
0
    s->data = strbuf_detach(&buf, NULL);
4452
0
    s->should_free = 1;
4453
0
  }
4454
0
  return 0;
4455
0
}
4456
4457
/*
4458
 * While doing rename detection and pickaxe operation, we may need to
4459
 * grab the data for the blob (or file) for our own in-core comparison.
4460
 * diff_filespec has data and size fields for this purpose.
4461
 */
4462
int diff_populate_filespec(struct repository *r,
4463
         struct diff_filespec *s,
4464
         const struct diff_populate_filespec_options *options)
4465
0
{
4466
0
  int size_only = options ? options->check_size_only : 0;
4467
0
  int check_binary = options ? options->check_binary : 0;
4468
0
  int err = 0;
4469
0
  int conv_flags = global_conv_flags_eol;
4470
  /*
4471
   * demote FAIL to WARN to allow inspecting the situation
4472
   * instead of refusing.
4473
   */
4474
0
  if (conv_flags & CONV_EOL_RNDTRP_DIE)
4475
0
    conv_flags = CONV_EOL_RNDTRP_WARN;
4476
4477
0
  if (!DIFF_FILE_VALID(s))
4478
0
    die("internal error: asking to populate invalid file.");
4479
0
  if (S_ISDIR(s->mode))
4480
0
    return -1;
4481
4482
0
  if (s->data)
4483
0
    return 0;
4484
4485
0
  if (size_only && 0 < s->size)
4486
0
    return 0;
4487
4488
0
  if (S_ISGITLINK(s->mode))
4489
0
    return diff_populate_gitlink(s, size_only);
4490
4491
0
  if (!s->oid_valid ||
4492
0
      reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4493
0
    struct strbuf buf = STRBUF_INIT;
4494
0
    struct stat st;
4495
0
    int fd;
4496
4497
0
    if (lstat(s->path, &st) < 0) {
4498
0
    err_empty:
4499
0
      err = -1;
4500
0
    empty:
4501
0
      s->data = (char *)"";
4502
0
      s->size = 0;
4503
0
      return err;
4504
0
    }
4505
0
    s->size = xsize_t(st.st_size);
4506
0
    if (!s->size)
4507
0
      goto empty;
4508
0
    if (S_ISLNK(st.st_mode)) {
4509
0
      struct strbuf sb = STRBUF_INIT;
4510
4511
0
      if (strbuf_readlink(&sb, s->path, s->size))
4512
0
        goto err_empty;
4513
0
      s->size = sb.len;
4514
0
      s->data = strbuf_detach(&sb, NULL);
4515
0
      s->should_free = 1;
4516
0
      return 0;
4517
0
    }
4518
4519
    /*
4520
     * Even if the caller would be happy with getting
4521
     * only the size, we cannot return early at this
4522
     * point if the path requires us to run the content
4523
     * conversion.
4524
     */
4525
0
    if (size_only && !would_convert_to_git(r->index, s->path))
4526
0
      return 0;
4527
4528
    /*
4529
     * Note: this check uses xsize_t(st.st_size) that may
4530
     * not be the true size of the blob after it goes
4531
     * through convert_to_git().  This may not strictly be
4532
     * correct, but the whole point of big_file_threshold
4533
     * and is_binary check being that we want to avoid
4534
     * opening the file and inspecting the contents, this
4535
     * is probably fine.
4536
     */
4537
0
    if (check_binary &&
4538
0
        s->size > repo_settings_get_big_file_threshold(the_repository) &&
4539
0
        s->is_binary == -1) {
4540
0
      s->is_binary = 1;
4541
0
      return 0;
4542
0
    }
4543
0
    fd = open(s->path, O_RDONLY);
4544
0
    if (fd < 0)
4545
0
      goto err_empty;
4546
0
    s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4547
0
    close(fd);
4548
0
    s->should_munmap = 1;
4549
4550
    /*
4551
     * Convert from working tree format to canonical git format
4552
     */
4553
0
    if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4554
0
      size_t size = 0;
4555
0
      munmap(s->data, s->size);
4556
0
      s->should_munmap = 0;
4557
0
      s->data = strbuf_detach(&buf, &size);
4558
0
      s->size = size;
4559
0
      s->should_free = 1;
4560
0
    }
4561
0
  }
4562
0
  else {
4563
0
    size_t size_st = 0;
4564
0
    struct object_info info = {
4565
0
      .sizep = &size_st
4566
0
    };
4567
4568
0
    if (!(size_only || check_binary))
4569
      /*
4570
       * Set contentp, since there is no chance that merely
4571
       * the size is sufficient.
4572
       */
4573
0
      info.contentp = &s->data;
4574
4575
0
    if (options && options->missing_object_cb) {
4576
0
      if (!odb_read_object_info_extended(r->objects, &s->oid, &info,
4577
0
                 OBJECT_INFO_LOOKUP_REPLACE |
4578
0
                 OBJECT_INFO_SKIP_FETCH_OBJECT))
4579
0
        goto object_read;
4580
0
      options->missing_object_cb(options->missing_object_data);
4581
0
    }
4582
0
    if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4583
0
              OBJECT_INFO_LOOKUP_REPLACE))
4584
0
      die("unable to read %s", oid_to_hex(&s->oid));
4585
4586
0
object_read:
4587
0
    s->size = cast_size_t_to_ulong(size_st);
4588
0
    if (size_only || check_binary) {
4589
0
      if (size_only)
4590
0
        return 0;
4591
0
      if (s->size > repo_settings_get_big_file_threshold(the_repository) &&
4592
0
          s->is_binary == -1) {
4593
0
        s->is_binary = 1;
4594
0
        return 0;
4595
0
      }
4596
0
    }
4597
0
    if (!info.contentp) {
4598
0
      info.contentp = &s->data;
4599
0
      if (odb_read_object_info_extended(r->objects, &s->oid, &info,
4600
0
                OBJECT_INFO_LOOKUP_REPLACE))
4601
0
        die("unable to read %s", oid_to_hex(&s->oid));
4602
0
      s->size = cast_size_t_to_ulong(size_st);
4603
0
    }
4604
0
    s->should_free = 1;
4605
0
  }
4606
0
  return 0;
4607
0
}
4608
4609
void diff_free_filespec_blob(struct diff_filespec *s)
4610
0
{
4611
0
  if (s->should_free)
4612
0
    free(s->data);
4613
0
  else if (s->should_munmap)
4614
0
    munmap(s->data, s->size);
4615
4616
0
  if (s->should_free || s->should_munmap) {
4617
0
    s->should_free = s->should_munmap = 0;
4618
0
    s->data = NULL;
4619
0
  }
4620
0
}
4621
4622
void diff_free_filespec_data(struct diff_filespec *s)
4623
0
{
4624
0
  if (!s)
4625
0
    return;
4626
4627
0
  diff_free_filespec_blob(s);
4628
0
  FREE_AND_NULL(s->cnt_data);
4629
0
}
4630
4631
static void prep_temp_blob(struct index_state *istate,
4632
         const char *path, struct diff_tempfile *temp,
4633
         void *blob,
4634
         unsigned long size,
4635
         const struct object_id *oid,
4636
         int mode)
4637
0
{
4638
0
  struct strbuf buf = STRBUF_INIT;
4639
0
  char *path_dup = xstrdup(path);
4640
0
  const char *base = basename(path_dup);
4641
0
  struct checkout_metadata meta;
4642
4643
0
  init_checkout_metadata(&meta, NULL, NULL, oid);
4644
4645
0
  temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4646
0
  if (!temp->tempfile)
4647
0
    die_errno("unable to create temp-file");
4648
0
  if (convert_to_working_tree(istate, path,
4649
0
      (const char *)blob, (size_t)size, &buf, &meta)) {
4650
0
    blob = buf.buf;
4651
0
    size = buf.len;
4652
0
  }
4653
0
  if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4654
0
      close_tempfile_gently(temp->tempfile))
4655
0
    die_errno("unable to write temp-file");
4656
0
  temp->name = get_tempfile_path(temp->tempfile);
4657
0
  oid_to_hex_r(temp->hex, oid);
4658
0
  xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4659
0
  strbuf_release(&buf);
4660
0
  free(path_dup);
4661
0
}
4662
4663
static struct diff_tempfile *prepare_temp_file(struct repository *r,
4664
                 struct diff_filespec *one)
4665
0
{
4666
0
  struct diff_tempfile *temp = claim_diff_tempfile();
4667
4668
0
  if (!DIFF_FILE_VALID(one)) {
4669
0
  not_a_valid_file:
4670
    /* A '-' entry produces this for file-2, and
4671
     * a '+' entry produces this for file-1.
4672
     */
4673
0
    temp->name = "/dev/null";
4674
0
    xsnprintf(temp->hex, sizeof(temp->hex), ".");
4675
0
    xsnprintf(temp->mode, sizeof(temp->mode), ".");
4676
0
    return temp;
4677
0
  }
4678
4679
0
  if (!S_ISGITLINK(one->mode) &&
4680
0
      (!one->oid_valid ||
4681
0
       reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4682
0
    struct stat st;
4683
0
    if (lstat(one->path, &st) < 0) {
4684
0
      if (errno == ENOENT)
4685
0
        goto not_a_valid_file;
4686
0
      die_errno("stat(%s)", one->path);
4687
0
    }
4688
0
    if (S_ISLNK(st.st_mode)) {
4689
0
      struct strbuf sb = STRBUF_INIT;
4690
0
      if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4691
0
        die_errno("readlink(%s)", one->path);
4692
0
      prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4693
0
               (one->oid_valid ?
4694
0
          &one->oid : null_oid(the_hash_algo)),
4695
0
               (one->oid_valid ?
4696
0
          one->mode : S_IFLNK));
4697
0
      strbuf_release(&sb);
4698
0
    }
4699
0
    else {
4700
      /* we can borrow from the file in the work tree */
4701
0
      temp->name = one->path;
4702
0
      if (!one->oid_valid)
4703
0
        oid_to_hex_r(temp->hex, null_oid(the_hash_algo));
4704
0
      else
4705
0
        oid_to_hex_r(temp->hex, &one->oid);
4706
      /* Even though we may sometimes borrow the
4707
       * contents from the work tree, we always want
4708
       * one->mode.  mode is trustworthy even when
4709
       * !(one->oid_valid), as long as
4710
       * DIFF_FILE_VALID(one).
4711
       */
4712
0
      xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4713
0
    }
4714
0
    return temp;
4715
0
  }
4716
0
  else {
4717
0
    if (diff_populate_filespec(r, one, NULL))
4718
0
      die("cannot read data blob for %s", one->path);
4719
0
    prep_temp_blob(r->index, one->path, temp,
4720
0
             one->data, one->size,
4721
0
             &one->oid, one->mode);
4722
0
  }
4723
0
  return temp;
4724
0
}
4725
4726
static void add_external_diff_name(struct repository *r,
4727
           struct strvec *argv,
4728
           struct diff_filespec *df)
4729
0
{
4730
0
  struct diff_tempfile *temp = prepare_temp_file(r, df);
4731
0
  strvec_push(argv, temp->name);
4732
0
  strvec_push(argv, temp->hex);
4733
0
  strvec_push(argv, temp->mode);
4734
0
}
4735
4736
/* An external diff command takes:
4737
 *
4738
 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4739
 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
4740
 *
4741
 */
4742
static void run_external_diff(const struct external_diff *pgm,
4743
            const char *name,
4744
            const char *other,
4745
            struct diff_filespec *one,
4746
            struct diff_filespec *two,
4747
            const char *xfrm_msg,
4748
            struct diff_options *o)
4749
0
{
4750
0
  struct child_process cmd = CHILD_PROCESS_INIT;
4751
0
  struct diff_queue_struct *q = &diff_queued_diff;
4752
0
  int rc;
4753
4754
  /*
4755
   * Trivial equality is handled by diff_unmodified_pair() before
4756
   * we get here.  If we don't need to show the diff and the
4757
   * external diff program lacks the ability to tell us whether
4758
   * it's empty then we consider it non-empty without even asking.
4759
   */
4760
0
  if (!pgm->trust_exit_code && !o->file) {
4761
0
    o->found_changes = 1;
4762
0
    return;
4763
0
  }
4764
4765
0
  strvec_push(&cmd.args, pgm->cmd);
4766
0
  strvec_push(&cmd.args, name);
4767
4768
0
  if (one && two) {
4769
0
    add_external_diff_name(o->repo, &cmd.args, one);
4770
0
    add_external_diff_name(o->repo, &cmd.args, two);
4771
0
    if (other) {
4772
0
      strvec_push(&cmd.args, other);
4773
0
      if (xfrm_msg)
4774
0
        strvec_push(&cmd.args, xfrm_msg);
4775
0
    }
4776
0
  }
4777
4778
0
  strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4779
0
         ++o->diff_path_counter);
4780
0
  strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4781
4782
0
  diff_free_filespec_data(one);
4783
0
  diff_free_filespec_data(two);
4784
0
  cmd.use_shell = 1;
4785
0
  if (!o->file)
4786
0
    cmd.no_stdout = 1;
4787
0
  else if (o->file != stdout)
4788
0
    cmd.out = xdup(fileno(o->file));
4789
0
  rc = run_command(&cmd);
4790
0
  if (!pgm->trust_exit_code && rc == 0)
4791
0
    o->found_changes = 1;
4792
0
  else if (pgm->trust_exit_code && rc == 0)
4793
0
    ; /* nothing */
4794
0
  else if (pgm->trust_exit_code && rc == 1)
4795
0
    o->found_changes = 1;
4796
0
  else
4797
0
    die(_("external diff died, stopping at %s"), name);
4798
4799
0
  remove_tempfile();
4800
0
}
4801
4802
static int similarity_index(struct diff_filepair *p)
4803
0
{
4804
0
  return p->score * 100 / MAX_SCORE;
4805
0
}
4806
4807
static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4808
0
{
4809
0
  if (startup_info->have_repository)
4810
0
    return repo_find_unique_abbrev(the_repository, oid, abbrev);
4811
0
  else {
4812
0
    char *hex = oid_to_hex(oid);
4813
0
    if (abbrev < 0)
4814
0
      abbrev = FALLBACK_DEFAULT_ABBREV;
4815
0
    if (abbrev > the_hash_algo->hexsz)
4816
0
      BUG("oid abbreviation out of range: %d", abbrev);
4817
0
    if (abbrev)
4818
0
      hex[abbrev] = '\0';
4819
0
    return hex;
4820
0
  }
4821
0
}
4822
4823
static void fill_metainfo(struct strbuf *msg,
4824
        const char *name,
4825
        const char *other,
4826
        struct diff_filespec *one,
4827
        struct diff_filespec *two,
4828
        struct diff_options *o,
4829
        struct diff_filepair *p,
4830
        int *must_show_header,
4831
        enum git_colorbool use_color)
4832
0
{
4833
0
  const char *set = diff_get_color(use_color, DIFF_METAINFO);
4834
0
  const char *reset = diff_get_color(use_color, DIFF_RESET);
4835
0
  const char *line_prefix = diff_line_prefix(o);
4836
0
  struct string_list *more_headers = NULL;
4837
4838
0
  *must_show_header = 1;
4839
0
  strbuf_init(msg, PATH_MAX * 2 + 300);
4840
0
  switch (p->status) {
4841
0
  case DIFF_STATUS_COPIED:
4842
0
    strbuf_addf(msg, "%s%ssimilarity index %d%%",
4843
0
          line_prefix, set, similarity_index(p));
4844
0
    strbuf_addf(msg, "%s\n%s%scopy from ",
4845
0
          reset,  line_prefix, set);
4846
0
    quote_c_style(name, msg, NULL, 0);
4847
0
    strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4848
0
    quote_c_style(other, msg, NULL, 0);
4849
0
    strbuf_addf(msg, "%s\n", reset);
4850
0
    break;
4851
0
  case DIFF_STATUS_RENAMED:
4852
0
    strbuf_addf(msg, "%s%ssimilarity index %d%%",
4853
0
          line_prefix, set, similarity_index(p));
4854
0
    strbuf_addf(msg, "%s\n%s%srename from ",
4855
0
          reset, line_prefix, set);
4856
0
    quote_c_style(name, msg, NULL, 0);
4857
0
    strbuf_addf(msg, "%s\n%s%srename to ",
4858
0
          reset, line_prefix, set);
4859
0
    quote_c_style(other, msg, NULL, 0);
4860
0
    strbuf_addf(msg, "%s\n", reset);
4861
0
    break;
4862
0
  case DIFF_STATUS_MODIFIED:
4863
0
    if (p->score) {
4864
0
      strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4865
0
            line_prefix,
4866
0
            set, similarity_index(p), reset);
4867
0
      break;
4868
0
    }
4869
    /* fallthru */
4870
0
  default:
4871
0
    *must_show_header = 0;
4872
0
  }
4873
0
  if ((more_headers = additional_headers(o, name))) {
4874
0
    add_formatted_headers(msg, more_headers,
4875
0
              line_prefix, set, reset);
4876
0
    *must_show_header = 1;
4877
0
  }
4878
0
  if (one && two && !oideq(&one->oid, &two->oid)) {
4879
0
    const unsigned hexsz = the_hash_algo->hexsz;
4880
0
    int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4881
4882
0
    if (o->flags.full_index)
4883
0
      abbrev = hexsz;
4884
4885
0
    if (o->flags.binary) {
4886
0
      mmfile_t mf;
4887
0
      if ((!fill_mmfile(o->repo, &mf, one) &&
4888
0
           diff_filespec_is_binary(o->repo, one)) ||
4889
0
          (!fill_mmfile(o->repo, &mf, two) &&
4890
0
           diff_filespec_is_binary(o->repo, two)))
4891
0
        abbrev = hexsz;
4892
0
    }
4893
0
    strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4894
0
          diff_abbrev_oid(&one->oid, abbrev),
4895
0
          diff_abbrev_oid(&two->oid, abbrev));
4896
0
    if (one->mode == two->mode)
4897
0
      strbuf_addf(msg, " %06o", one->mode);
4898
0
    strbuf_addf(msg, "%s\n", reset);
4899
0
  }
4900
0
}
4901
4902
static void run_diff_cmd(const struct external_diff *pgm,
4903
       const char *name,
4904
       const char *other,
4905
       const char *attr_path,
4906
       struct diff_filespec *one,
4907
       struct diff_filespec *two,
4908
       struct strbuf *msg,
4909
       struct diff_options *o,
4910
       struct diff_filepair *p)
4911
0
{
4912
0
  const char *xfrm_msg = NULL;
4913
0
  int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4914
0
  int must_show_header = 0;
4915
0
  struct userdiff_driver *drv = NULL;
4916
4917
0
  if (o->flags.allow_external || !o->ignore_driver_algorithm)
4918
0
    drv = userdiff_find_by_path(o->repo->index, attr_path);
4919
4920
0
  if (o->flags.allow_external && drv && drv->external.cmd)
4921
0
    pgm = &drv->external;
4922
4923
0
  if (msg) {
4924
    /*
4925
     * don't use colors when the header is intended for an
4926
     * external diff driver
4927
     */
4928
0
    fill_metainfo(msg, name, other, one, two, o, p,
4929
0
            &must_show_header,
4930
0
            pgm ? GIT_COLOR_NEVER : o->use_color);
4931
0
    xfrm_msg = msg->len ? msg->buf : NULL;
4932
0
  }
4933
4934
0
  if (pgm) {
4935
0
    run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4936
0
    return;
4937
0
  }
4938
0
  if (one && two) {
4939
0
    if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4940
0
      set_diff_algorithm(o, drv->algorithm);
4941
4942
0
    builtin_diff(name, other ? other : name,
4943
0
           one, two, xfrm_msg, must_show_header,
4944
0
           o, complete_rewrite, p->line_ranges);
4945
0
    if (p->status == DIFF_STATUS_COPIED ||
4946
0
        p->status == DIFF_STATUS_RENAMED)
4947
0
      o->found_changes = 1;
4948
0
  } else {
4949
0
    if (o->file)
4950
0
      fprintf(o->file, "* Unmerged path %s\n", name);
4951
0
    o->found_changes = 1;
4952
0
  }
4953
0
}
4954
4955
static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4956
0
{
4957
0
  if (DIFF_FILE_VALID(one)) {
4958
0
    if (!one->oid_valid) {
4959
0
      struct stat st;
4960
0
      if (one->is_stdin) {
4961
0
        oidclr(&one->oid, the_repository->hash_algo);
4962
0
        return;
4963
0
      }
4964
0
      if (lstat(one->path, &st) < 0)
4965
0
        die_errno("stat '%s'", one->path);
4966
0
      if (index_path(istate, &one->oid, one->path, &st, 0))
4967
0
        die("cannot hash %s", one->path);
4968
0
    }
4969
0
  }
4970
0
  else
4971
0
    oidclr(&one->oid, the_repository->hash_algo);
4972
0
}
4973
4974
static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4975
0
{
4976
  /* Strip the prefix but do not molest /dev/null and absolute paths */
4977
0
  if (*namep && !is_absolute_path(*namep)) {
4978
0
    *namep += prefix_length;
4979
0
    if (**namep == '/')
4980
0
      ++*namep;
4981
0
  }
4982
0
  if (*otherp && !is_absolute_path(*otherp)) {
4983
0
    *otherp += prefix_length;
4984
0
    if (**otherp == '/')
4985
0
      ++*otherp;
4986
0
  }
4987
0
}
4988
4989
static void run_diff(struct diff_filepair *p, struct diff_options *o)
4990
0
{
4991
0
  const struct external_diff *pgm = external_diff();
4992
0
  struct strbuf msg;
4993
0
  struct diff_filespec *one = p->one;
4994
0
  struct diff_filespec *two = p->two;
4995
0
  const char *name;
4996
0
  const char *other;
4997
0
  const char *attr_path;
4998
4999
0
  name  = one->path;
5000
0
  other = (strcmp(name, two->path) ? two->path : NULL);
5001
0
  attr_path = name;
5002
0
  if (o->prefix_length)
5003
0
    strip_prefix(o->prefix_length, &name, &other);
5004
5005
0
  if (!o->flags.allow_external)
5006
0
    pgm = NULL;
5007
5008
0
  if (DIFF_PAIR_UNMERGED(p)) {
5009
0
    run_diff_cmd(pgm, name, NULL, attr_path,
5010
0
           NULL, NULL, NULL, o, p);
5011
0
    return;
5012
0
  }
5013
5014
0
  diff_fill_oid_info(one, o->repo->index);
5015
0
  diff_fill_oid_info(two, o->repo->index);
5016
5017
0
  if (!pgm &&
5018
0
      DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
5019
0
      (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
5020
    /*
5021
     * a filepair that changes between file and symlink
5022
     * needs to be split into deletion and creation.
5023
     */
5024
0
    struct diff_filespec *null = alloc_filespec(two->path);
5025
0
    run_diff_cmd(NULL, name, other, attr_path,
5026
0
           one, null, &msg,
5027
0
           o, p);
5028
0
    free(null);
5029
0
    strbuf_release(&msg);
5030
5031
0
    null = alloc_filespec(one->path);
5032
0
    run_diff_cmd(NULL, name, other, attr_path,
5033
0
           null, two, &msg, o, p);
5034
0
    free(null);
5035
0
  }
5036
0
  else
5037
0
    run_diff_cmd(pgm, name, other, attr_path,
5038
0
           one, two, &msg, o, p);
5039
5040
0
  strbuf_release(&msg);
5041
0
}
5042
5043
static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
5044
       struct diffstat_t *diffstat)
5045
0
{
5046
0
  const char *name;
5047
0
  const char *other;
5048
5049
0
  if (!o->ignore_driver_algorithm) {
5050
0
    struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
5051
0
                    p->one->path);
5052
5053
0
    if (drv && drv->algorithm)
5054
0
      set_diff_algorithm(o, drv->algorithm);
5055
0
  }
5056
5057
0
  if (DIFF_PAIR_UNMERGED(p)) {
5058
    /* unmerged */
5059
0
    builtin_diffstat(p->one->path, NULL, NULL, NULL,
5060
0
         diffstat, o, p);
5061
0
    return;
5062
0
  }
5063
5064
0
  name = p->one->path;
5065
0
  other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5066
5067
0
  if (o->prefix_length)
5068
0
    strip_prefix(o->prefix_length, &name, &other);
5069
5070
0
  diff_fill_oid_info(p->one, o->repo->index);
5071
0
  diff_fill_oid_info(p->two, o->repo->index);
5072
5073
0
  builtin_diffstat(name, other, p->one, p->two,
5074
0
       diffstat, o, p);
5075
0
}
5076
5077
static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
5078
0
{
5079
0
  const char *name;
5080
0
  const char *other;
5081
0
  const char *attr_path;
5082
5083
0
  if (DIFF_PAIR_UNMERGED(p)) {
5084
    /* unmerged */
5085
0
    return;
5086
0
  }
5087
5088
0
  name = p->one->path;
5089
0
  other = (strcmp(name, p->two->path) ? p->two->path : NULL);
5090
0
  attr_path = other ? other : name;
5091
5092
0
  if (o->prefix_length)
5093
0
    strip_prefix(o->prefix_length, &name, &other);
5094
5095
0
  diff_fill_oid_info(p->one, o->repo->index);
5096
0
  diff_fill_oid_info(p->two, o->repo->index);
5097
5098
0
  builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
5099
0
}
5100
5101
void repo_diff_setup(struct repository *r, struct diff_options *options)
5102
0
{
5103
0
  memcpy(options, &default_diff_options, sizeof(*options));
5104
5105
0
  options->file = stdout;
5106
0
  options->repo = r;
5107
5108
0
  options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
5109
0
  options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
5110
0
  options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
5111
0
  options->abbrev = DEFAULT_ABBREV;
5112
0
  options->line_termination = '\n';
5113
0
  options->break_opt = -1;
5114
0
  options->rename_limit = -1;
5115
0
  options->dirstat_permille = diff_dirstat_permille_default;
5116
0
  options->context = diff_context_default;
5117
0
  options->interhunkcontext = diff_interhunk_context_default;
5118
0
  options->ws_error_highlight = ws_error_highlight_default;
5119
0
  options->flags.rename_empty = 1;
5120
0
  options->flags.relative_name = diff_relative;
5121
0
  options->objfind = NULL;
5122
5123
  /* pathchange left =NULL by default */
5124
0
  options->change = diff_change;
5125
0
  options->add_remove = diff_addremove;
5126
0
  options->use_color = diff_use_color_default;
5127
0
  options->detect_rename = diff_detect_rename_default;
5128
0
  options->xdl_opts |= diff_algorithm;
5129
0
  if (diff_indent_heuristic)
5130
0
    DIFF_XDL_SET(options, INDENT_HEURISTIC);
5131
5132
0
  options->orderfile = xstrdup_or_null(diff_order_file_cfg);
5133
5134
0
  if (!options->flags.ignore_submodule_set)
5135
0
    options->flags.ignore_untracked_in_submodules = 1;
5136
5137
0
  if (diff_no_prefix) {
5138
0
    diff_set_noprefix(options);
5139
0
  } else if (!diff_mnemonic_prefix) {
5140
0
    diff_set_default_prefix(options);
5141
0
  }
5142
5143
0
  options->color_moved = diff_color_moved_default;
5144
0
  options->color_moved_ws_handling = diff_color_moved_ws_default;
5145
0
}
5146
5147
static const char diff_status_letters[] = {
5148
  DIFF_STATUS_ADDED,
5149
  DIFF_STATUS_COPIED,
5150
  DIFF_STATUS_DELETED,
5151
  DIFF_STATUS_MODIFIED,
5152
  DIFF_STATUS_RENAMED,
5153
  DIFF_STATUS_TYPE_CHANGED,
5154
  DIFF_STATUS_UNKNOWN,
5155
  DIFF_STATUS_UNMERGED,
5156
  DIFF_STATUS_FILTER_AON,
5157
  DIFF_STATUS_FILTER_BROKEN,
5158
  '\0',
5159
};
5160
5161
static unsigned int filter_bit['Z' + 1];
5162
5163
static void prepare_filter_bits(void)
5164
0
{
5165
0
  int i;
5166
5167
0
  if (!filter_bit[DIFF_STATUS_ADDED]) {
5168
0
    for (i = 0; diff_status_letters[i]; i++)
5169
0
      filter_bit[(int) diff_status_letters[i]] = (1 << i);
5170
0
  }
5171
0
}
5172
5173
static unsigned filter_bit_tst(char status, const struct diff_options *opt)
5174
0
{
5175
0
  return opt->filter & filter_bit[(int) status];
5176
0
}
5177
5178
unsigned diff_filter_bit(char status)
5179
0
{
5180
0
  prepare_filter_bits();
5181
0
  return filter_bit[(int) status];
5182
0
}
5183
5184
int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
5185
0
{
5186
0
  unsigned forbidden_magic;
5187
5188
0
  if (ps->nr != 1) {
5189
0
    if (die_on_error)
5190
0
      die(_("--follow requires exactly one pathspec"));
5191
0
    return 0;
5192
0
  }
5193
5194
0
  forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
5195
0
             PATHSPEC_LITERAL);
5196
0
  if (forbidden_magic) {
5197
0
    if (die_on_error) {
5198
0
      struct strbuf sb = STRBUF_INIT;
5199
0
      pathspec_magic_names(forbidden_magic, &sb);
5200
0
      die(_("pathspec magic not supported by --follow: %s"),
5201
0
          sb.buf);
5202
0
    }
5203
0
    return 0;
5204
0
  }
5205
5206
0
  return 1;
5207
0
}
5208
5209
void diff_setup_done(struct diff_options *options)
5210
0
{
5211
0
  unsigned check_mask = DIFF_FORMAT_NAME |
5212
0
            DIFF_FORMAT_NAME_STATUS |
5213
0
            DIFF_FORMAT_CHECKDIFF |
5214
0
            DIFF_FORMAT_NO_OUTPUT;
5215
  /*
5216
   * This must be signed because we're comparing against a potentially
5217
   * negative value.
5218
   */
5219
0
  const int hexsz = the_hash_algo->hexsz;
5220
5221
0
  if (options->set_default)
5222
0
    options->set_default(options);
5223
5224
0
  if (HAS_MULTI_BITS(options->output_format & check_mask))
5225
0
    die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
5226
0
      "--name-only", "--name-status", "--check", "-s");
5227
5228
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
5229
0
    die(_("options '%s', '%s', and '%s' cannot be used together"),
5230
0
      "-G", "-S", "--find-object");
5231
5232
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
5233
0
    die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
5234
0
      "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
5235
5236
0
  if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
5237
0
    die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
5238
0
      "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
5239
5240
  /*
5241
   * Most of the time we can say "there are changes"
5242
   * only by checking if there are changed paths, but
5243
   * --ignore-whitespace* options force us to look
5244
   * inside contents.
5245
   */
5246
5247
0
  if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
5248
0
      options->ignore_regex_nr)
5249
0
    options->flags.diff_from_contents = 1;
5250
0
  else
5251
0
    options->flags.diff_from_contents = 0;
5252
5253
0
  if (options->flags.find_copies_harder)
5254
0
    options->detect_rename = DIFF_DETECT_COPY;
5255
5256
0
  if (!options->flags.relative_name)
5257
0
    options->prefix = NULL;
5258
0
  if (options->prefix)
5259
0
    options->prefix_length = strlen(options->prefix);
5260
0
  else
5261
0
    options->prefix_length = 0;
5262
5263
  /*
5264
   * --name-only, --name-status, --checkdiff, and -s
5265
   * turn other output format off.
5266
   */
5267
0
  if (options->output_format & (DIFF_FORMAT_NAME |
5268
0
              DIFF_FORMAT_NAME_STATUS |
5269
0
              DIFF_FORMAT_CHECKDIFF |
5270
0
              DIFF_FORMAT_NO_OUTPUT))
5271
0
    options->output_format &= ~(DIFF_FORMAT_RAW |
5272
0
              DIFF_FORMAT_NUMSTAT |
5273
0
              DIFF_FORMAT_DIFFSTAT |
5274
0
              DIFF_FORMAT_SHORTSTAT |
5275
0
              DIFF_FORMAT_DIRSTAT |
5276
0
              DIFF_FORMAT_SUMMARY |
5277
0
              DIFF_FORMAT_PATCH);
5278
5279
  /*
5280
   * These cases always need recursive; we do not drop caller-supplied
5281
   * recursive bits for other formats here.
5282
   */
5283
0
  if (options->output_format & (DIFF_FORMAT_PATCH |
5284
0
              DIFF_FORMAT_NUMSTAT |
5285
0
              DIFF_FORMAT_DIFFSTAT |
5286
0
              DIFF_FORMAT_SHORTSTAT |
5287
0
              DIFF_FORMAT_DIRSTAT |
5288
0
              DIFF_FORMAT_SUMMARY |
5289
0
              DIFF_FORMAT_CHECKDIFF))
5290
0
    options->flags.recursive = 1;
5291
  /*
5292
   * Also pickaxe would not work very well if you do not say recursive
5293
   */
5294
0
  if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
5295
0
    options->flags.recursive = 1;
5296
  /*
5297
   * When patches are generated, submodules diffed against the work tree
5298
   * must be checked for dirtiness too so it can be shown in the output
5299
   */
5300
0
  if (options->output_format & DIFF_FORMAT_PATCH)
5301
0
    options->flags.dirty_submodules = 1;
5302
5303
0
  if (options->detect_rename && options->rename_limit < 0)
5304
0
    options->rename_limit = diff_rename_limit_default;
5305
0
  if (hexsz < options->abbrev)
5306
0
    options->abbrev = hexsz; /* full */
5307
5308
  /*
5309
   * It does not make sense to show the first hit we happened
5310
   * to have found.  It does not make sense not to return with
5311
   * exit code in such a case either.
5312
   */
5313
0
  if (options->flags.quick) {
5314
0
    options->output_format = DIFF_FORMAT_NO_OUTPUT;
5315
0
    options->flags.exit_with_status = 1;
5316
0
    options->detect_rename = 0;
5317
0
    options->flags.find_copies_harder = 0;
5318
0
  }
5319
5320
  /*
5321
   * External diffs could declare non-identical contents equal
5322
   * (think diff --ignore-space-change).
5323
   */
5324
0
  if (options->flags.allow_external && options->flags.exit_with_status)
5325
0
    options->flags.diff_from_contents = 1;
5326
5327
0
  options->diff_path_counter = 0;
5328
5329
0
  if (options->flags.follow_renames)
5330
0
    diff_check_follow_pathspec(&options->pathspec, 1);
5331
5332
0
  if (options->flags.allow_external && external_diff())
5333
0
    options->color_moved = 0;
5334
5335
0
  if (options->filter_not) {
5336
0
    if (!options->filter)
5337
0
      options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
5338
0
    options->filter &= ~options->filter_not;
5339
0
  }
5340
5341
0
  if (options->pathspec.has_wildcard && options->max_depth_valid)
5342
0
    die("max-depth cannot be used with wildcard pathspecs");
5343
0
}
5344
5345
int parse_long_opt(const char *opt, const char **argv,
5346
       const char **optarg)
5347
0
{
5348
0
  const char *arg = argv[0];
5349
0
  if (!skip_prefix(arg, "--", &arg))
5350
0
    return 0;
5351
0
  if (!skip_prefix(arg, opt, &arg))
5352
0
    return 0;
5353
0
  if (*arg == '=') { /* stuck form: --option=value */
5354
0
    *optarg = arg + 1;
5355
0
    return 1;
5356
0
  }
5357
0
  if (*arg != '\0')
5358
0
    return 0;
5359
  /* separate form: --option value */
5360
0
  if (!argv[1])
5361
0
    die("Option '--%s' requires a value", opt);
5362
0
  *optarg = argv[1];
5363
0
  return 2;
5364
0
}
5365
5366
static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5367
0
{
5368
0
  struct diff_options *options = opt->value;
5369
0
  int width = options->stat_width;
5370
0
  int name_width = options->stat_name_width;
5371
0
  int graph_width = options->stat_graph_width;
5372
0
  int count = options->stat_count;
5373
0
  char *end;
5374
5375
0
  BUG_ON_OPT_NEG(unset);
5376
5377
0
  if (!strcmp(opt->long_name, "stat")) {
5378
0
    if (value) {
5379
0
      width = strtoul(value, &end, 10);
5380
0
      if (*end == ',')
5381
0
        name_width = strtoul(end+1, &end, 10);
5382
0
      if (*end == ',')
5383
0
        count = strtoul(end+1, &end, 10);
5384
0
      if (*end)
5385
0
        return error(_("invalid --stat value: %s"), value);
5386
0
    }
5387
0
  } else if (!strcmp(opt->long_name, "stat-width")) {
5388
0
    width = strtoul(value, &end, 10);
5389
0
    if (*end)
5390
0
      return error(_("%s expects a numerical value"),
5391
0
             opt->long_name);
5392
0
  } else if (!strcmp(opt->long_name, "stat-name-width")) {
5393
0
    name_width = strtoul(value, &end, 10);
5394
0
    if (*end)
5395
0
      return error(_("%s expects a numerical value"),
5396
0
             opt->long_name);
5397
0
  } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5398
0
    graph_width = strtoul(value, &end, 10);
5399
0
    if (*end)
5400
0
      return error(_("%s expects a numerical value"),
5401
0
             opt->long_name);
5402
0
  } else if (!strcmp(opt->long_name, "stat-count")) {
5403
0
    count = strtoul(value, &end, 10);
5404
0
    if (*end)
5405
0
      return error(_("%s expects a numerical value"),
5406
0
             opt->long_name);
5407
0
  } else
5408
0
    BUG("%s should not get here", opt->long_name);
5409
5410
0
  options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5411
0
  options->output_format |= DIFF_FORMAT_DIFFSTAT;
5412
0
  options->stat_name_width = name_width;
5413
0
  options->stat_graph_width = graph_width;
5414
0
  options->stat_width = width;
5415
0
  options->stat_count = count;
5416
0
  return 0;
5417
0
}
5418
5419
static int parse_dirstat_opt(struct diff_options *options, const char *params)
5420
0
{
5421
0
  struct strbuf errmsg = STRBUF_INIT;
5422
0
  if (parse_dirstat_params(options, params, &errmsg))
5423
0
    die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5424
0
        errmsg.buf);
5425
0
  strbuf_release(&errmsg);
5426
  /*
5427
   * The caller knows a dirstat-related option is given from the command
5428
   * line; allow it to say "return this_function();"
5429
   */
5430
0
  options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5431
0
  options->output_format |= DIFF_FORMAT_DIRSTAT;
5432
0
  return 1;
5433
0
}
5434
5435
static int diff_opt_diff_filter(const struct option *option,
5436
        const char *optarg, int unset)
5437
0
{
5438
0
  struct diff_options *opt = option->value;
5439
0
  int i, optch;
5440
5441
0
  BUG_ON_OPT_NEG(unset);
5442
0
  prepare_filter_bits();
5443
5444
0
  for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5445
0
    unsigned int bit;
5446
0
    int negate;
5447
5448
0
    if ('a' <= optch && optch <= 'z') {
5449
0
      negate = 1;
5450
0
      optch = toupper(optch);
5451
0
    } else {
5452
0
      negate = 0;
5453
0
    }
5454
5455
0
    bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5456
0
    if (!bit)
5457
0
      return error(_("unknown change class '%c' in --diff-filter=%s"),
5458
0
             optarg[i], optarg);
5459
0
    if (negate)
5460
0
      opt->filter_not |= bit;
5461
0
    else
5462
0
      opt->filter |= bit;
5463
0
  }
5464
0
  return 0;
5465
0
}
5466
5467
static void enable_patch_output(int *fmt)
5468
0
{
5469
0
  *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5470
0
  *fmt |= DIFF_FORMAT_PATCH;
5471
0
}
5472
5473
static int diff_opt_ws_error_highlight(const struct option *option,
5474
               const char *arg, int unset)
5475
0
{
5476
0
  struct diff_options *opt = option->value;
5477
0
  int val = parse_ws_error_highlight(arg);
5478
5479
0
  BUG_ON_OPT_NEG(unset);
5480
0
  if (val < 0)
5481
0
    return error(_("unknown value after ws-error-highlight=%.*s"),
5482
0
           -1 - val, arg);
5483
0
  opt->ws_error_highlight = val;
5484
0
  return 0;
5485
0
}
5486
5487
static int diff_opt_find_object(const struct option *option,
5488
        const char *arg, int unset)
5489
0
{
5490
0
  struct diff_options *opt = option->value;
5491
0
  struct object_id oid;
5492
5493
0
  BUG_ON_OPT_NEG(unset);
5494
0
  if (!startup_info->have_repository)
5495
0
    return error(_("--find-object requires a git repository"));
5496
0
  if (repo_get_oid(the_repository, arg, &oid))
5497
0
    return error(_("unable to resolve '%s'"), arg);
5498
5499
0
  if (!opt->objfind)
5500
0
    CALLOC_ARRAY(opt->objfind, 1);
5501
5502
0
  opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5503
0
  opt->flags.recursive = 1;
5504
0
  opt->flags.tree_in_recursive = 1;
5505
0
  oidset_insert(opt->objfind, &oid);
5506
0
  return 0;
5507
0
}
5508
5509
static int diff_opt_anchored(const struct option *opt,
5510
           const char *arg, int unset)
5511
0
{
5512
0
  struct diff_options *options = opt->value;
5513
5514
0
  BUG_ON_OPT_NEG(unset);
5515
0
  options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5516
0
  ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5517
0
       options->anchors_alloc);
5518
0
  options->anchors[options->anchors_nr++] = xstrdup(arg);
5519
0
  return 0;
5520
0
}
5521
5522
static int diff_opt_binary(const struct option *opt,
5523
         const char *arg, int unset)
5524
0
{
5525
0
  struct diff_options *options = opt->value;
5526
5527
0
  BUG_ON_OPT_NEG(unset);
5528
0
  BUG_ON_OPT_ARG(arg);
5529
0
  enable_patch_output(&options->output_format);
5530
0
  options->flags.binary = 1;
5531
0
  return 0;
5532
0
}
5533
5534
static int diff_opt_break_rewrites(const struct option *opt,
5535
           const char *arg, int unset)
5536
0
{
5537
0
  int *break_opt = opt->value;
5538
0
  int opt1, opt2;
5539
5540
0
  BUG_ON_OPT_NEG(unset);
5541
0
  if (!arg)
5542
0
    arg = "";
5543
0
  opt1 = parse_rename_score(&arg);
5544
0
  if (*arg == 0)
5545
0
    opt2 = 0;
5546
0
  else if (*arg != '/')
5547
0
    return error(_("%s expects <n>/<m> form"), opt->long_name);
5548
0
  else {
5549
0
    arg++;
5550
0
    opt2 = parse_rename_score(&arg);
5551
0
  }
5552
0
  if (*arg != 0)
5553
0
    return error(_("%s expects <n>/<m> form"), opt->long_name);
5554
0
  *break_opt = opt1 | (opt2 << 16);
5555
0
  return 0;
5556
0
}
5557
5558
static int diff_opt_char(const struct option *opt,
5559
       const char *arg, int unset)
5560
0
{
5561
0
  char *value = opt->value;
5562
5563
0
  BUG_ON_OPT_NEG(unset);
5564
0
  if (arg[1])
5565
0
    return error(_("%s expects a character, got '%s'"),
5566
0
           opt->long_name, arg);
5567
0
  *value = arg[0];
5568
0
  return 0;
5569
0
}
5570
5571
static int diff_opt_color_moved(const struct option *opt,
5572
        const char *arg, int unset)
5573
0
{
5574
0
  struct diff_options *options = opt->value;
5575
5576
0
  if (unset) {
5577
0
    options->color_moved = COLOR_MOVED_NO;
5578
0
  } else if (!arg) {
5579
0
    if (diff_color_moved_default)
5580
0
      options->color_moved = diff_color_moved_default;
5581
0
    if (options->color_moved == COLOR_MOVED_NO)
5582
0
      options->color_moved = COLOR_MOVED_DEFAULT;
5583
0
  } else {
5584
0
    int cm = parse_color_moved(arg);
5585
0
    if (cm < 0)
5586
0
      return error(_("bad --color-moved argument: %s"), arg);
5587
0
    options->color_moved = cm;
5588
0
  }
5589
0
  return 0;
5590
0
}
5591
5592
static int diff_opt_color_moved_ws(const struct option *opt,
5593
           const char *arg, int unset)
5594
0
{
5595
0
  struct diff_options *options = opt->value;
5596
0
  unsigned cm;
5597
5598
0
  if (unset) {
5599
0
    options->color_moved_ws_handling = 0;
5600
0
    return 0;
5601
0
  }
5602
5603
0
  cm = parse_color_moved_ws(arg);
5604
0
  if (cm & COLOR_MOVED_WS_ERROR)
5605
0
    return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5606
0
  options->color_moved_ws_handling = cm;
5607
0
  return 0;
5608
0
}
5609
5610
static int diff_opt_color_words(const struct option *opt,
5611
        const char *arg, int unset)
5612
0
{
5613
0
  struct diff_options *options = opt->value;
5614
5615
0
  BUG_ON_OPT_NEG(unset);
5616
0
  options->use_color = GIT_COLOR_ALWAYS;
5617
0
  options->word_diff = DIFF_WORDS_COLOR;
5618
0
  options->word_regex = arg;
5619
0
  return 0;
5620
0
}
5621
5622
static int diff_opt_compact_summary(const struct option *opt,
5623
            const char *arg, int unset)
5624
0
{
5625
0
  struct diff_options *options = opt->value;
5626
5627
0
  BUG_ON_OPT_ARG(arg);
5628
0
  if (unset) {
5629
0
    options->flags.stat_with_summary = 0;
5630
0
  } else {
5631
0
    options->flags.stat_with_summary = 1;
5632
0
    options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5633
0
    options->output_format |= DIFF_FORMAT_DIFFSTAT;
5634
0
  }
5635
0
  return 0;
5636
0
}
5637
5638
static int diff_opt_diff_algorithm(const struct option *opt,
5639
           const char *arg, int unset)
5640
0
{
5641
0
  struct diff_options *options = opt->value;
5642
5643
0
  BUG_ON_OPT_NEG(unset);
5644
5645
0
  if (set_diff_algorithm(options, arg))
5646
0
    return error(_("option diff-algorithm accepts \"myers\", "
5647
0
             "\"minimal\", \"patience\" and \"histogram\""));
5648
5649
0
  options->ignore_driver_algorithm = 1;
5650
5651
0
  return 0;
5652
0
}
5653
5654
static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5655
           const char *arg, int unset)
5656
0
{
5657
0
  struct diff_options *options = opt->value;
5658
5659
0
  BUG_ON_OPT_NEG(unset);
5660
0
  BUG_ON_OPT_ARG(arg);
5661
5662
0
  if (set_diff_algorithm(options, opt->long_name))
5663
0
    BUG("available diff algorithms include \"myers\", "
5664
0
             "\"minimal\", \"patience\" and \"histogram\"");
5665
5666
0
  options->ignore_driver_algorithm = 1;
5667
5668
0
  return 0;
5669
0
}
5670
5671
static int diff_opt_dirstat(const struct option *opt,
5672
          const char *arg, int unset)
5673
0
{
5674
0
  struct diff_options *options = opt->value;
5675
5676
0
  BUG_ON_OPT_NEG(unset);
5677
0
  if (!strcmp(opt->long_name, "cumulative")) {
5678
0
    if (arg)
5679
0
      BUG("how come --cumulative take a value?");
5680
0
    arg = "cumulative";
5681
0
  } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5682
0
    parse_dirstat_opt(options, "files");
5683
0
  parse_dirstat_opt(options, arg ? arg : "");
5684
0
  return 0;
5685
0
}
5686
5687
static int diff_opt_find_copies(const struct option *opt,
5688
        const char *arg, int unset)
5689
0
{
5690
0
  struct diff_options *options = opt->value;
5691
5692
0
  BUG_ON_OPT_NEG(unset);
5693
0
  if (!arg)
5694
0
    arg = "";
5695
0
  options->rename_score = parse_rename_score(&arg);
5696
0
  if (*arg != 0)
5697
0
    return error(_("invalid argument to %s"), opt->long_name);
5698
5699
0
  if (options->detect_rename == DIFF_DETECT_COPY)
5700
0
    options->flags.find_copies_harder = 1;
5701
0
  else
5702
0
    options->detect_rename = DIFF_DETECT_COPY;
5703
5704
0
  return 0;
5705
0
}
5706
5707
static int diff_opt_find_renames(const struct option *opt,
5708
         const char *arg, int unset)
5709
0
{
5710
0
  struct diff_options *options = opt->value;
5711
5712
0
  BUG_ON_OPT_NEG(unset);
5713
0
  if (!arg)
5714
0
    arg = "";
5715
0
  options->rename_score = parse_rename_score(&arg);
5716
0
  if (*arg != 0)
5717
0
    return error(_("invalid argument to %s"), opt->long_name);
5718
5719
0
  options->detect_rename = DIFF_DETECT_RENAME;
5720
0
  return 0;
5721
0
}
5722
5723
static int diff_opt_follow(const struct option *opt,
5724
         const char *arg, int unset)
5725
0
{
5726
0
  struct diff_options *options = opt->value;
5727
5728
0
  BUG_ON_OPT_ARG(arg);
5729
0
  if (unset) {
5730
0
    options->flags.follow_renames = 0;
5731
0
    options->flags.default_follow_renames = 0;
5732
0
  } else {
5733
0
    options->flags.follow_renames = 1;
5734
0
  }
5735
0
  return 0;
5736
0
}
5737
5738
static int diff_opt_ignore_submodules(const struct option *opt,
5739
              const char *arg, int unset)
5740
0
{
5741
0
  struct diff_options *options = opt->value;
5742
5743
0
  BUG_ON_OPT_NEG(unset);
5744
0
  if (!arg)
5745
0
    arg = "all";
5746
0
  options->flags.override_submodule_config = 1;
5747
0
  handle_ignore_submodules_arg(options, arg);
5748
0
  return 0;
5749
0
}
5750
5751
static int diff_opt_line_prefix(const struct option *opt,
5752
        const char *optarg, int unset)
5753
0
{
5754
0
  struct diff_options *options = opt->value;
5755
5756
0
  BUG_ON_OPT_NEG(unset);
5757
0
  options->line_prefix = optarg;
5758
0
  graph_setup_line_prefix(options);
5759
0
  return 0;
5760
0
}
5761
5762
static int diff_opt_no_prefix(const struct option *opt,
5763
            const char *optarg, int unset)
5764
0
{
5765
0
  struct diff_options *options = opt->value;
5766
5767
0
  BUG_ON_OPT_NEG(unset);
5768
0
  BUG_ON_OPT_ARG(optarg);
5769
0
  diff_set_noprefix(options);
5770
0
  return 0;
5771
0
}
5772
5773
static int diff_opt_default_prefix(const struct option *opt,
5774
           const char *optarg, int unset)
5775
0
{
5776
0
  struct diff_options *options = opt->value;
5777
5778
0
  BUG_ON_OPT_NEG(unset);
5779
0
  BUG_ON_OPT_ARG(optarg);
5780
0
  FREE_AND_NULL(diff_src_prefix);
5781
0
  FREE_AND_NULL(diff_dst_prefix);
5782
0
  diff_set_default_prefix(options);
5783
0
  return 0;
5784
0
}
5785
5786
static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5787
               const struct option *opt,
5788
               const char *arg, int unset)
5789
0
{
5790
0
  struct diff_options *options = opt->value;
5791
0
  char *path;
5792
5793
0
  BUG_ON_OPT_NEG(unset);
5794
0
  path = prefix_filename(ctx->prefix, arg);
5795
0
  options->file = xfopen(path, "w");
5796
0
  options->close_file = 1;
5797
0
  if (options->use_color != GIT_COLOR_ALWAYS)
5798
0
    options->use_color = GIT_COLOR_NEVER;
5799
0
  free(path);
5800
0
  return 0;
5801
0
}
5802
5803
static int diff_opt_patience(const struct option *opt,
5804
           const char *arg, int unset)
5805
0
{
5806
0
  struct diff_options *options = opt->value;
5807
0
  int i;
5808
5809
0
  BUG_ON_OPT_NEG(unset);
5810
0
  BUG_ON_OPT_ARG(arg);
5811
  /*
5812
   * Both --patience and --anchored use PATIENCE_DIFF
5813
   * internally, so remove any anchors previously
5814
   * specified.
5815
   */
5816
0
  for (i = 0; i < options->anchors_nr; i++)
5817
0
    free(options->anchors[i]);
5818
0
  options->anchors_nr = 0;
5819
0
  options->ignore_driver_algorithm = 1;
5820
5821
0
  return set_diff_algorithm(options, "patience");
5822
0
}
5823
5824
static int diff_opt_ignore_regex(const struct option *opt,
5825
         const char *arg, int unset)
5826
0
{
5827
0
  struct diff_options *options = opt->value;
5828
0
  regex_t *regex;
5829
5830
0
  BUG_ON_OPT_NEG(unset);
5831
5832
0
  regex = xmalloc(sizeof(*regex));
5833
0
  if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5834
0
    free(regex);
5835
0
    return error(_("invalid regex given to -I: '%s'"), arg);
5836
0
  }
5837
5838
0
  ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5839
0
       options->ignore_regex_alloc);
5840
0
  options->ignore_regex[options->ignore_regex_nr++] = regex;
5841
0
  return 0;
5842
0
}
5843
5844
static int diff_opt_pickaxe_regex(const struct option *opt,
5845
          const char *arg, int unset)
5846
0
{
5847
0
  struct diff_options *options = opt->value;
5848
5849
0
  BUG_ON_OPT_NEG(unset);
5850
0
  options->pickaxe = arg;
5851
0
  options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5852
0
  if (arg && !*arg)
5853
0
    return error(_("-G requires a non-empty argument"));
5854
0
  return 0;
5855
0
}
5856
5857
static int diff_opt_pickaxe_string(const struct option *opt,
5858
           const char *arg, int unset)
5859
0
{
5860
0
  struct diff_options *options = opt->value;
5861
5862
0
  BUG_ON_OPT_NEG(unset);
5863
0
  options->pickaxe = arg;
5864
0
  options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5865
0
  if (arg && !*arg)
5866
0
    return error(_("-S requires a non-empty argument"));
5867
0
  return 0;
5868
0
}
5869
5870
static int diff_opt_relative(const struct option *opt,
5871
           const char *arg, int unset)
5872
0
{
5873
0
  struct diff_options *options = opt->value;
5874
5875
0
  options->flags.relative_name = !unset;
5876
0
  if (arg)
5877
0
    options->prefix = arg;
5878
0
  return 0;
5879
0
}
5880
5881
static int diff_opt_submodule(const struct option *opt,
5882
            const char *arg, int unset)
5883
0
{
5884
0
  struct diff_options *options = opt->value;
5885
5886
0
  BUG_ON_OPT_NEG(unset);
5887
0
  if (!arg)
5888
0
    arg = "log";
5889
0
  if (parse_submodule_params(options, arg))
5890
0
    return error(_("failed to parse --submodule option parameter: '%s'"),
5891
0
           arg);
5892
0
  return 0;
5893
0
}
5894
5895
static int diff_opt_textconv(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_ARG(arg);
5901
0
  if (unset) {
5902
0
    options->flags.allow_textconv = 0;
5903
0
  } else {
5904
0
    options->flags.allow_textconv = 1;
5905
0
    options->flags.textconv_set_via_cmdline = 1;
5906
0
  }
5907
0
  return 0;
5908
0
}
5909
5910
static int diff_opt_unified(const struct option *opt,
5911
          const char *arg, int unset)
5912
0
{
5913
0
  struct diff_options *options = opt->value;
5914
0
  char *s;
5915
5916
0
  BUG_ON_OPT_NEG(unset);
5917
5918
0
  if (arg) {
5919
0
    long val = strtol(arg, &s, 10);
5920
0
    if (*s)
5921
0
      return error(_("%s expects a numerical value"), "--unified");
5922
0
    if (val < 0)
5923
0
      return error(_("%s expects a non-negative integer"), "--unified");
5924
0
    options->context = val;
5925
0
  }
5926
0
  enable_patch_output(&options->output_format);
5927
5928
0
  return 0;
5929
0
}
5930
5931
static int diff_opt_word_diff(const struct option *opt,
5932
            const char *arg, int unset)
5933
0
{
5934
0
  struct diff_options *options = opt->value;
5935
5936
0
  BUG_ON_OPT_NEG(unset);
5937
0
  if (arg) {
5938
0
    if (!strcmp(arg, "plain"))
5939
0
      options->word_diff = DIFF_WORDS_PLAIN;
5940
0
    else if (!strcmp(arg, "color")) {
5941
0
      options->use_color = GIT_COLOR_ALWAYS;
5942
0
      options->word_diff = DIFF_WORDS_COLOR;
5943
0
    }
5944
0
    else if (!strcmp(arg, "porcelain"))
5945
0
      options->word_diff = DIFF_WORDS_PORCELAIN;
5946
0
    else if (!strcmp(arg, "none"))
5947
0
      options->word_diff = DIFF_WORDS_NONE;
5948
0
    else
5949
0
      return error(_("bad --word-diff argument: %s"), arg);
5950
0
  } else {
5951
0
    if (options->word_diff == DIFF_WORDS_NONE)
5952
0
      options->word_diff = DIFF_WORDS_PLAIN;
5953
0
  }
5954
0
  return 0;
5955
0
}
5956
5957
static int diff_opt_word_diff_regex(const struct option *opt,
5958
            const char *arg, int unset)
5959
0
{
5960
0
  struct diff_options *options = opt->value;
5961
5962
0
  BUG_ON_OPT_NEG(unset);
5963
0
  if (options->word_diff == DIFF_WORDS_NONE)
5964
0
    options->word_diff = DIFF_WORDS_PLAIN;
5965
0
  options->word_regex = arg;
5966
0
  return 0;
5967
0
}
5968
5969
static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5970
0
{
5971
0
  struct diff_options *options = opt->value;
5972
5973
0
  BUG_ON_OPT_NEG(unset);
5974
0
  if (!strcmp(opt->long_name, "skip-to"))
5975
0
    options->skip_instead_of_rotate = 1;
5976
0
  else
5977
0
    options->skip_instead_of_rotate = 0;
5978
0
  options->rotate_to = arg;
5979
0
  return 0;
5980
0
}
5981
5982
static int diff_opt_max_depth(const struct option *opt,
5983
            const char *arg, int unset)
5984
0
{
5985
0
  struct diff_options *options = opt->value;
5986
5987
0
  BUG_ON_OPT_NEG(unset);
5988
5989
0
  if (!git_parse_int(arg, &options->max_depth))
5990
0
    return error(_("invalid value for '%s': '%s'"),
5991
0
           "--max-depth", arg);
5992
5993
0
  options->flags.recursive = 1;
5994
0
  options->max_depth_valid = options->max_depth >= 0;
5995
5996
0
  return 0;
5997
0
}
5998
5999
/*
6000
 * Consider adding new flags to __git_diff_common_options
6001
 * in contrib/completion/git-completion.bash
6002
 */
6003
struct option *add_diff_options(const struct option *opts,
6004
        struct diff_options *options)
6005
0
{
6006
0
  struct option parseopts[] = {
6007
0
    OPT_GROUP(N_("Diff output format options")),
6008
0
    OPT_BITOP('p', "patch", &options->output_format,
6009
0
        N_("generate patch"),
6010
0
        DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6011
0
    OPT_SET_INT('s', "no-patch", &options->output_format,
6012
0
          N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
6013
0
    OPT_BITOP('u', NULL, &options->output_format,
6014
0
        N_("generate patch"),
6015
0
        DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
6016
0
    OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
6017
0
             N_("generate diffs with <n> lines context"),
6018
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
6019
0
    OPT_BOOL('W', "function-context", &options->flags.funccontext,
6020
0
       N_("generate diffs with <n> lines context")),
6021
0
    OPT_BITOP(0, "raw", &options->output_format,
6022
0
        N_("generate the diff in raw format"),
6023
0
        DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
6024
0
    OPT_BITOP(0, "patch-with-raw", &options->output_format,
6025
0
        N_("synonym for '-p --raw'"),
6026
0
        DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
6027
0
        DIFF_FORMAT_NO_OUTPUT),
6028
0
    OPT_BITOP(0, "patch-with-stat", &options->output_format,
6029
0
        N_("synonym for '-p --stat'"),
6030
0
        DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
6031
0
        DIFF_FORMAT_NO_OUTPUT),
6032
0
    OPT_BITOP(0, "numstat", &options->output_format,
6033
0
        N_("machine friendly --stat"),
6034
0
        DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
6035
0
    OPT_BITOP(0, "shortstat", &options->output_format,
6036
0
        N_("output only the last line of --stat"),
6037
0
        DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
6038
0
    OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
6039
0
             N_("output the distribution of relative amount of changes for each sub-directory"),
6040
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6041
0
             diff_opt_dirstat),
6042
0
    OPT_CALLBACK_F(0, "cumulative", options, NULL,
6043
0
             N_("synonym for --dirstat=cumulative"),
6044
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6045
0
             diff_opt_dirstat),
6046
0
    OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
6047
0
             N_("synonym for --dirstat=files,<param1>,<param2>..."),
6048
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6049
0
             diff_opt_dirstat),
6050
0
    OPT_BIT_F(0, "check", &options->output_format,
6051
0
        N_("warn if changes introduce conflict markers or whitespace errors"),
6052
0
        DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
6053
0
    OPT_BITOP(0, "summary", &options->output_format,
6054
0
        N_("condensed summary such as creations, renames and mode changes"),
6055
0
        DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
6056
0
    OPT_BIT_F(0, "name-only", &options->output_format,
6057
0
        N_("show only names of changed files"),
6058
0
        DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
6059
0
    OPT_BIT_F(0, "name-status", &options->output_format,
6060
0
        N_("show only names and status of changed files"),
6061
0
        DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
6062
0
    OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
6063
0
             N_("generate diffstat"),
6064
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
6065
0
    OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
6066
0
             N_("generate diffstat with a given width"),
6067
0
             PARSE_OPT_NONEG, diff_opt_stat),
6068
0
    OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
6069
0
             N_("generate diffstat with a given name width"),
6070
0
             PARSE_OPT_NONEG, diff_opt_stat),
6071
0
    OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
6072
0
             N_("generate diffstat with a given graph width"),
6073
0
             PARSE_OPT_NONEG, diff_opt_stat),
6074
0
    OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
6075
0
             N_("generate diffstat with limited lines"),
6076
0
             PARSE_OPT_NONEG, diff_opt_stat),
6077
0
    OPT_CALLBACK_F(0, "compact-summary", options, NULL,
6078
0
             N_("generate compact summary in diffstat"),
6079
0
             PARSE_OPT_NOARG, diff_opt_compact_summary),
6080
0
    OPT_CALLBACK_F(0, "binary", options, NULL,
6081
0
             N_("output a binary diff that can be applied"),
6082
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
6083
0
    OPT_BOOL(0, "full-index", &options->flags.full_index,
6084
0
       N_("show full pre- and post-image object names on the \"index\" lines")),
6085
0
    OPT_COLOR_FLAG(0, "color", &options->use_color,
6086
0
             N_("show colored diff")),
6087
0
    OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
6088
0
             N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
6089
0
             PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
6090
0
    OPT_SET_INT('z', NULL, &options->line_termination,
6091
0
          N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
6092
0
          0),
6093
0
    OPT__ABBREV(&options->abbrev),
6094
0
    OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
6095
0
           N_("show the given source prefix instead of \"a/\""),
6096
0
           PARSE_OPT_NONEG),
6097
0
    OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
6098
0
           N_("show the given destination prefix instead of \"b/\""),
6099
0
           PARSE_OPT_NONEG),
6100
0
    OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
6101
0
             N_("prepend an additional prefix to every line of output"),
6102
0
             PARSE_OPT_NONEG, diff_opt_line_prefix),
6103
0
    OPT_CALLBACK_F(0, "no-prefix", options, NULL,
6104
0
             N_("do not show any source or destination prefix"),
6105
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
6106
0
    OPT_CALLBACK_F(0, "default-prefix", options, NULL,
6107
0
             N_("use default prefixes a/ and b/"),
6108
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
6109
0
    OPT_UNSIGNED(0, "inter-hunk-context", &options->interhunkcontext,
6110
0
           N_("show context between diff hunks up to the specified number of lines")),
6111
0
    OPT_CALLBACK_F(0, "output-indicator-new",
6112
0
             &options->output_indicators[OUTPUT_INDICATOR_NEW],
6113
0
             N_("<char>"),
6114
0
             N_("specify the character to indicate a new line instead of '+'"),
6115
0
             PARSE_OPT_NONEG, diff_opt_char),
6116
0
    OPT_CALLBACK_F(0, "output-indicator-old",
6117
0
             &options->output_indicators[OUTPUT_INDICATOR_OLD],
6118
0
             N_("<char>"),
6119
0
             N_("specify the character to indicate an old line instead of '-'"),
6120
0
             PARSE_OPT_NONEG, diff_opt_char),
6121
0
    OPT_CALLBACK_F(0, "output-indicator-context",
6122
0
             &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
6123
0
             N_("<char>"),
6124
0
             N_("specify the character to indicate a context instead of ' '"),
6125
0
             PARSE_OPT_NONEG, diff_opt_char),
6126
6127
0
    OPT_GROUP(N_("Diff rename options")),
6128
0
    OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
6129
0
             N_("break complete rewrite changes into pairs of delete and create"),
6130
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6131
0
             diff_opt_break_rewrites),
6132
0
    OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
6133
0
             N_("detect renames"),
6134
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6135
0
             diff_opt_find_renames),
6136
0
    OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
6137
0
            N_("omit the preimage for deletes"),
6138
0
            1, PARSE_OPT_NONEG),
6139
0
    OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
6140
0
             N_("detect copies"),
6141
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6142
0
             diff_opt_find_copies),
6143
0
    OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
6144
0
       N_("use unmodified files as source to find copies")),
6145
0
    OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
6146
0
            N_("disable rename detection"),
6147
0
            0, PARSE_OPT_NONEG),
6148
0
    OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
6149
0
       N_("use empty blobs as rename source")),
6150
0
    OPT_CALLBACK_F(0, "follow", options, NULL,
6151
0
             N_("continue listing the history of a file beyond renames"),
6152
0
             PARSE_OPT_NOARG, diff_opt_follow),
6153
0
    OPT_INTEGER('l', NULL, &options->rename_limit,
6154
0
          N_("limit to cheap rename/copy detection if the number of rename/copy targets exceeds this value")),
6155
6156
0
    OPT_GROUP(N_("Diff algorithm options")),
6157
0
    OPT_CALLBACK_F(0, "minimal", options, NULL,
6158
0
             N_("produce the smallest possible diff"),
6159
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6160
0
             diff_opt_diff_algorithm_no_arg),
6161
0
    OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
6162
0
        N_("ignore whitespace when comparing lines"),
6163
0
        XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
6164
0
    OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
6165
0
        N_("ignore changes in amount of whitespace"),
6166
0
        XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
6167
0
    OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
6168
0
        N_("ignore changes in whitespace at EOL"),
6169
0
        XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
6170
0
    OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
6171
0
        N_("ignore carrier-return at the end of line"),
6172
0
        XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
6173
0
    OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
6174
0
        N_("ignore changes whose lines are all blank"),
6175
0
        XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
6176
0
    OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
6177
0
             N_("ignore changes whose all lines match <regex>"),
6178
0
             0, diff_opt_ignore_regex),
6179
0
    OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
6180
0
      N_("heuristic to shift diff hunk boundaries for easy reading"),
6181
0
      XDF_INDENT_HEURISTIC),
6182
0
    OPT_CALLBACK_F(0, "patience", options, NULL,
6183
0
             N_("generate diff using the \"patience diff\" algorithm"),
6184
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6185
0
             diff_opt_patience),
6186
0
    OPT_CALLBACK_F(0, "histogram", options, NULL,
6187
0
             N_("generate diff using the \"histogram diff\" algorithm"),
6188
0
             PARSE_OPT_NONEG | PARSE_OPT_NOARG,
6189
0
             diff_opt_diff_algorithm_no_arg),
6190
0
    OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
6191
0
             N_("choose a diff algorithm"),
6192
0
             PARSE_OPT_NONEG, diff_opt_diff_algorithm),
6193
0
    OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
6194
0
             N_("generate diff using the \"anchored diff\" algorithm"),
6195
0
             PARSE_OPT_NONEG, diff_opt_anchored),
6196
0
    OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
6197
0
             N_("show word diff, using <mode> to delimit changed words"),
6198
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
6199
0
    OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
6200
0
             N_("use <regex> to decide what a word is"),
6201
0
             PARSE_OPT_NONEG, diff_opt_word_diff_regex),
6202
0
    OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
6203
0
             N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
6204
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
6205
0
    OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
6206
0
             N_("moved lines of code are colored differently"),
6207
0
             PARSE_OPT_OPTARG, diff_opt_color_moved),
6208
0
    OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
6209
0
             N_("how white spaces are ignored in --color-moved"),
6210
0
             0, diff_opt_color_moved_ws),
6211
6212
0
    OPT_GROUP(N_("Other diff options")),
6213
0
    OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
6214
0
             N_("when run from subdir, exclude changes outside and show relative paths"),
6215
0
             PARSE_OPT_OPTARG,
6216
0
             diff_opt_relative),
6217
0
    OPT_BOOL('a', "text", &options->flags.text,
6218
0
       N_("treat all files as text")),
6219
0
    OPT_BOOL('R', NULL, &options->flags.reverse_diff,
6220
0
       N_("swap two inputs, reverse the diff")),
6221
0
    OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
6222
0
       N_("exit with 1 if there were differences, 0 otherwise")),
6223
0
    OPT_BOOL(0, "quiet", &options->flags.quick,
6224
0
       N_("disable all output of the program")),
6225
0
    OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
6226
0
       N_("allow an external diff helper to be executed")),
6227
0
    OPT_CALLBACK_F(0, "textconv", options, NULL,
6228
0
             N_("run external text conversion filters when comparing binary files"),
6229
0
             PARSE_OPT_NOARG, diff_opt_textconv),
6230
0
    OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
6231
0
             N_("ignore changes to submodules in the diff generation"),
6232
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6233
0
             diff_opt_ignore_submodules),
6234
0
    OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
6235
0
             N_("specify how differences in submodules are shown"),
6236
0
             PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
6237
0
             diff_opt_submodule),
6238
0
    OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
6239
0
            N_("hide 'git add -N' entries from the index"),
6240
0
            1, PARSE_OPT_NONEG),
6241
0
    OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
6242
0
            N_("treat 'git add -N' entries as real in the index"),
6243
0
            0, PARSE_OPT_NONEG),
6244
0
    OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
6245
0
             N_("look for differences that change the number of occurrences of the specified string"),
6246
0
             0, diff_opt_pickaxe_string),
6247
0
    OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
6248
0
             N_("look for differences that change the number of occurrences of the specified regex"),
6249
0
             0, diff_opt_pickaxe_regex),
6250
0
    OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
6251
0
        N_("show all changes in the changeset with -S or -G"),
6252
0
        DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
6253
0
    OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
6254
0
        N_("treat <string> in -S as extended POSIX regular expression"),
6255
0
        DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
6256
0
    OPT_FILENAME('O', NULL, &options->orderfile,
6257
0
           N_("control the order in which files appear in the output")),
6258
0
    OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
6259
0
             N_("show the change in the specified path first"),
6260
0
             PARSE_OPT_NONEG, diff_opt_rotate_to),
6261
0
    OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
6262
0
             N_("skip the output to the specified path"),
6263
0
             PARSE_OPT_NONEG, diff_opt_rotate_to),
6264
0
    OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
6265
0
             N_("look for differences that change the number of occurrences of the specified object"),
6266
0
             PARSE_OPT_NONEG, diff_opt_find_object),
6267
0
    OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
6268
0
             N_("select files by diff type"),
6269
0
             PARSE_OPT_NONEG, diff_opt_diff_filter),
6270
0
    OPT_CALLBACK_F(0, "max-depth", options, N_("<depth>"),
6271
0
             N_("maximum tree depth to recurse"),
6272
0
             PARSE_OPT_NONEG, diff_opt_max_depth),
6273
6274
0
    {
6275
0
      .type = OPTION_CALLBACK,
6276
0
      .long_name = "output",
6277
0
      .value = options,
6278
0
      .argh = N_("<file>"),
6279
0
      .help = N_("output to a specific file"),
6280
0
      .flags = PARSE_OPT_NONEG,
6281
0
      .ll_callback = diff_opt_output,
6282
0
    },
6283
0
    OPT_END()
6284
0
  };
6285
6286
0
  return parse_options_concat(opts, parseopts);
6287
0
}
6288
6289
int diff_opt_parse(struct diff_options *options,
6290
       const char **av, int ac, const char *prefix)
6291
0
{
6292
0
  struct option no_options[] = { OPT_END() };
6293
0
  struct option *parseopts = add_diff_options(no_options, options);
6294
6295
0
  if (!prefix)
6296
0
    prefix = "";
6297
6298
0
  ac = parse_options(ac, av, prefix, parseopts, NULL,
6299
0
         PARSE_OPT_KEEP_DASHDASH |
6300
0
         PARSE_OPT_KEEP_UNKNOWN_OPT |
6301
0
         PARSE_OPT_NO_INTERNAL_HELP |
6302
0
         PARSE_OPT_ONE_SHOT |
6303
0
         PARSE_OPT_STOP_AT_NON_OPTION);
6304
0
  free(parseopts);
6305
6306
0
  return ac;
6307
0
}
6308
6309
int parse_rename_score(const char **cp_p)
6310
0
{
6311
0
  unsigned long num, scale;
6312
0
  int ch, dot;
6313
0
  const char *cp = *cp_p;
6314
6315
0
  num = 0;
6316
0
  scale = 1;
6317
0
  dot = 0;
6318
0
  for (;;) {
6319
0
    ch = *cp;
6320
0
    if ( !dot && ch == '.' ) {
6321
0
      scale = 1;
6322
0
      dot = 1;
6323
0
    } else if ( ch == '%' ) {
6324
0
      scale = dot ? scale*100 : 100;
6325
0
      cp++; /* % is always at the end */
6326
0
      break;
6327
0
    } else if ( ch >= '0' && ch <= '9' ) {
6328
0
      if ( scale < 100000 ) {
6329
0
        scale *= 10;
6330
0
        num = (num*10) + (ch-'0');
6331
0
      }
6332
0
    } else {
6333
0
      break;
6334
0
    }
6335
0
    cp++;
6336
0
  }
6337
0
  *cp_p = cp;
6338
6339
  /* user says num divided by scale and we say internally that
6340
   * is MAX_SCORE * num / scale.
6341
   */
6342
0
  return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6343
0
}
6344
6345
struct diff_queue_struct diff_queued_diff;
6346
6347
void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
6348
0
{
6349
0
  ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6350
0
  queue->queue[queue->nr++] = dp;
6351
0
}
6352
6353
struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
6354
         struct diff_filespec *one,
6355
         struct diff_filespec *two)
6356
0
{
6357
0
  struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6358
0
  dp->one = one;
6359
0
  dp->two = two;
6360
0
  if (queue)
6361
0
    diff_q(queue, dp);
6362
0
  return dp;
6363
0
}
6364
6365
void diff_free_filepair(struct diff_filepair *p)
6366
0
{
6367
0
  free_filespec(p->one);
6368
0
  free_filespec(p->two);
6369
0
  free(p);
6370
0
}
6371
6372
void diff_queue_init(struct diff_queue_struct *q)
6373
0
{
6374
0
  struct diff_queue_struct blank = DIFF_QUEUE_INIT;
6375
0
  memcpy(q, &blank, sizeof(*q));
6376
0
}
6377
6378
void diff_queue_clear(struct diff_queue_struct *q)
6379
0
{
6380
0
  for (int i = 0; i < q->nr; i++)
6381
0
    diff_free_filepair(q->queue[i]);
6382
0
  free(q->queue);
6383
0
  diff_queue_init(q);
6384
0
}
6385
6386
const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6387
0
{
6388
0
  int abblen;
6389
0
  const char *abbrev;
6390
6391
  /* Do we want all 40 hex characters? */
6392
0
  if (len == the_hash_algo->hexsz)
6393
0
    return oid_to_hex(oid);
6394
6395
  /* An abbreviated value is fine, possibly followed by an ellipsis. */
6396
0
  abbrev = diff_abbrev_oid(oid, len);
6397
6398
0
  if (!print_sha1_ellipsis())
6399
0
    return abbrev;
6400
6401
0
  abblen = strlen(abbrev);
6402
6403
  /*
6404
   * In well-behaved cases, where the abbreviated result is the
6405
   * same as the requested length, append three dots after the
6406
   * abbreviation (hence the whole logic is limited to the case
6407
   * where abblen < 37); when the actual abbreviated result is a
6408
   * bit longer than the requested length, we reduce the number
6409
   * of dots so that they match the well-behaved ones.  However,
6410
   * if the actual abbreviation is longer than the requested
6411
   * length by more than three, we give up on aligning, and add
6412
   * three dots anyway, to indicate that the output is not the
6413
   * full object name.  Yes, this may be suboptimal, but this
6414
   * appears only in "diff --raw --abbrev" output and it is not
6415
   * worth the effort to change it now.  Note that this would
6416
   * likely to work fine when the automatic sizing of default
6417
   * abbreviation length is used--we would be fed -1 in "len" in
6418
   * that case, and will end up always appending three-dots, but
6419
   * the automatic sizing is supposed to give abblen that ensures
6420
   * uniqueness across all objects (statistically speaking).
6421
   */
6422
0
  if (abblen < the_hash_algo->hexsz - 3) {
6423
0
    static char hex[GIT_MAX_HEXSZ + 1];
6424
0
    if (len < abblen && abblen <= len + 2)
6425
0
      xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6426
0
    else
6427
0
      xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6428
0
    return hex;
6429
0
  }
6430
6431
0
  return oid_to_hex(oid);
6432
0
}
6433
6434
static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6435
0
{
6436
0
  int line_termination = opt->line_termination;
6437
0
  int inter_name_termination = line_termination ? '\t' : '\0';
6438
6439
0
  fprintf(opt->file, "%s", diff_line_prefix(opt));
6440
0
  if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6441
0
    fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6442
0
      diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6443
0
    fprintf(opt->file, "%s ",
6444
0
      diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6445
0
  }
6446
0
  if (p->score) {
6447
0
    fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6448
0
      inter_name_termination);
6449
0
  } else {
6450
0
    fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6451
0
  }
6452
6453
0
  if (p->status == DIFF_STATUS_COPIED ||
6454
0
      p->status == DIFF_STATUS_RENAMED) {
6455
0
    const char *name_a, *name_b;
6456
0
    name_a = p->one->path;
6457
0
    name_b = p->two->path;
6458
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6459
0
    write_name_quoted(name_a, opt->file, inter_name_termination);
6460
0
    write_name_quoted(name_b, opt->file, line_termination);
6461
0
  } else {
6462
0
    const char *name_a, *name_b;
6463
0
    name_a = p->one->mode ? p->one->path : p->two->path;
6464
0
    name_b = NULL;
6465
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6466
0
    write_name_quoted(name_a, opt->file, line_termination);
6467
0
  }
6468
0
}
6469
6470
int diff_unmodified_pair(struct diff_filepair *p)
6471
0
{
6472
  /* This function is written stricter than necessary to support
6473
   * the currently implemented transformers, but the idea is to
6474
   * let transformers to produce diff_filepairs any way they want,
6475
   * and filter and clean them up here before producing the output.
6476
   */
6477
0
  struct diff_filespec *one = p->one, *two = p->two;
6478
6479
0
  if (DIFF_PAIR_UNMERGED(p))
6480
0
    return 0; /* unmerged is interesting */
6481
6482
  /* deletion, addition, mode or type change
6483
   * and rename are all interesting.
6484
   */
6485
0
  if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6486
0
      DIFF_PAIR_MODE_CHANGED(p) ||
6487
0
      strcmp(one->path, two->path))
6488
0
    return 0;
6489
6490
  /* both are valid and point at the same path.  that is, we are
6491
   * dealing with a change.
6492
   */
6493
0
  if (one->oid_valid && two->oid_valid &&
6494
0
      oideq(&one->oid, &two->oid) &&
6495
0
      !one->dirty_submodule && !two->dirty_submodule)
6496
0
    return 1; /* no change */
6497
0
  if (!one->oid_valid && !two->oid_valid)
6498
0
    return 1; /* both look at the same file on the filesystem. */
6499
0
  return 0;
6500
0
}
6501
6502
static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6503
0
{
6504
0
  int include_conflict_headers =
6505
0
      (additional_headers(o, p->one->path) &&
6506
0
       !o->pickaxe_opts &&
6507
0
       (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6508
6509
  /*
6510
   * Check if we can return early without showing a diff.  Note that
6511
   * diff_filepair only stores {oid, path, mode, is_valid}
6512
   * information for each path, and thus diff_unmodified_pair() only
6513
   * considers those bits of info.  However, we do not want pairs
6514
   * created by create_filepairs_for_header_only_notifications()
6515
   * (which always look like unmodified pairs) to be ignored, so
6516
   * return early if both p is unmodified AND we don't want to
6517
   * include_conflict_headers.
6518
   */
6519
0
  if (diff_unmodified_pair(p) && !include_conflict_headers)
6520
0
    return;
6521
6522
  /* Actually, we can also return early to avoid showing tree diffs */
6523
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6524
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6525
0
    return;
6526
6527
0
  run_diff(p, o);
6528
0
}
6529
6530
/* return 1 if any change is found; otherwise, return 0 */
6531
static int diff_flush_patch_quietly(struct diff_filepair *p, struct diff_options *o)
6532
0
{
6533
0
  FILE *saved_file = o->file;
6534
0
  int saved_found_changes = o->found_changes;
6535
0
  int ret;
6536
6537
0
  o->file = NULL;
6538
0
  o->found_changes = 0;
6539
0
  diff_flush_patch(p, o);
6540
0
  ret = o->found_changes;
6541
0
  o->file = saved_file;
6542
0
  o->found_changes |= saved_found_changes;
6543
0
  return ret;
6544
0
}
6545
6546
static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6547
          struct diffstat_t *diffstat)
6548
0
{
6549
0
  if (diff_unmodified_pair(p))
6550
0
    return;
6551
6552
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6553
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6554
0
    return; /* no useful stat for tree diffs */
6555
6556
0
  run_diffstat(p, o, diffstat);
6557
0
}
6558
6559
static void diff_flush_checkdiff(struct diff_filepair *p,
6560
    struct diff_options *o)
6561
0
{
6562
0
  if (diff_unmodified_pair(p))
6563
0
    return;
6564
6565
0
  if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6566
0
      (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6567
0
    return; /* nothing to check in tree diffs */
6568
6569
0
  run_checkdiff(p, o);
6570
0
}
6571
6572
int diff_queue_is_empty(struct diff_options *o)
6573
0
{
6574
0
  struct diff_queue_struct *q = &diff_queued_diff;
6575
0
  int i;
6576
0
  int include_conflict_headers =
6577
0
      (o->additional_path_headers &&
6578
0
       strmap_get_size(o->additional_path_headers) &&
6579
0
       !o->pickaxe_opts &&
6580
0
       (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6581
6582
0
  if (include_conflict_headers)
6583
0
    return 0;
6584
6585
0
  for (i = 0; i < q->nr; i++)
6586
0
    if (!diff_unmodified_pair(q->queue[i]))
6587
0
      return 0;
6588
0
  return 1;
6589
0
}
6590
6591
#if DIFF_DEBUG
6592
void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6593
{
6594
  fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6595
    x, one ? one : "",
6596
    s->path,
6597
    DIFF_FILE_VALID(s) ? "valid" : "invalid",
6598
    s->mode,
6599
    s->oid_valid ? oid_to_hex(&s->oid) : "");
6600
  fprintf(stderr, "queue[%d] %s size %lu\n",
6601
    x, one ? one : "",
6602
    s->size);
6603
}
6604
6605
void diff_debug_filepair(const struct diff_filepair *p, int i)
6606
{
6607
  diff_debug_filespec(p->one, i, "one");
6608
  diff_debug_filespec(p->two, i, "two");
6609
  fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6610
    p->score, p->status ? p->status : '?',
6611
    p->one->rename_used, p->broken_pair);
6612
}
6613
6614
void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6615
{
6616
  int i;
6617
  if (msg)
6618
    fprintf(stderr, "%s\n", msg);
6619
  fprintf(stderr, "q->nr = %d\n", q->nr);
6620
  for (i = 0; i < q->nr; i++) {
6621
    struct diff_filepair *p = q->queue[i];
6622
    diff_debug_filepair(p, i);
6623
  }
6624
}
6625
#endif
6626
6627
static void diff_resolve_rename_copy(void)
6628
0
{
6629
0
  int i;
6630
0
  struct diff_filepair *p;
6631
0
  struct diff_queue_struct *q = &diff_queued_diff;
6632
6633
0
  diff_debug_queue("resolve-rename-copy", q);
6634
6635
0
  for (i = 0; i < q->nr; i++) {
6636
0
    p = q->queue[i];
6637
0
    p->status = 0; /* undecided */
6638
0
    if (DIFF_PAIR_UNMERGED(p))
6639
0
      p->status = DIFF_STATUS_UNMERGED;
6640
0
    else if (!DIFF_FILE_VALID(p->one))
6641
0
      p->status = DIFF_STATUS_ADDED;
6642
0
    else if (!DIFF_FILE_VALID(p->two))
6643
0
      p->status = DIFF_STATUS_DELETED;
6644
0
    else if (DIFF_PAIR_TYPE_CHANGED(p))
6645
0
      p->status = DIFF_STATUS_TYPE_CHANGED;
6646
6647
    /* from this point on, we are dealing with a pair
6648
     * whose both sides are valid and of the same type, i.e.
6649
     * either in-place edit or rename/copy edit.
6650
     */
6651
0
    else if (DIFF_PAIR_RENAME(p)) {
6652
      /*
6653
       * A rename might have re-connected a broken
6654
       * pair up, causing the pathnames to be the
6655
       * same again. If so, that's not a rename at
6656
       * all, just a modification..
6657
       *
6658
       * Otherwise, see if this source was used for
6659
       * multiple renames, in which case we decrement
6660
       * the count, and call it a copy.
6661
       */
6662
0
      if (!strcmp(p->one->path, p->two->path))
6663
0
        p->status = DIFF_STATUS_MODIFIED;
6664
0
      else if (--p->one->rename_used > 0)
6665
0
        p->status = DIFF_STATUS_COPIED;
6666
0
      else
6667
0
        p->status = DIFF_STATUS_RENAMED;
6668
0
    }
6669
0
    else if (!oideq(&p->one->oid, &p->two->oid) ||
6670
0
       p->one->mode != p->two->mode ||
6671
0
       p->one->dirty_submodule ||
6672
0
       p->two->dirty_submodule ||
6673
0
       is_null_oid(&p->one->oid))
6674
0
      p->status = DIFF_STATUS_MODIFIED;
6675
0
    else {
6676
      /* This is a "no-change" entry and should not
6677
       * happen anymore, but prepare for broken callers.
6678
       */
6679
0
      error("feeding unmodified %s to diffcore",
6680
0
            p->one->path);
6681
0
      p->status = DIFF_STATUS_UNKNOWN;
6682
0
    }
6683
0
  }
6684
0
  diff_debug_queue("resolve-rename-copy done", q);
6685
0
}
6686
6687
static int check_pair_status(struct diff_filepair *p)
6688
0
{
6689
0
  switch (p->status) {
6690
0
  case DIFF_STATUS_UNKNOWN:
6691
0
    return 0;
6692
0
  case 0:
6693
0
    die("internal error in diff-resolve-rename-copy");
6694
0
  default:
6695
0
    return 1;
6696
0
  }
6697
0
}
6698
6699
static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6700
0
{
6701
0
  int fmt = opt->output_format;
6702
6703
0
  if (fmt & DIFF_FORMAT_CHECKDIFF)
6704
0
    diff_flush_checkdiff(p, opt);
6705
0
  else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6706
0
    diff_flush_raw(p, opt);
6707
0
  else if (fmt & DIFF_FORMAT_NAME) {
6708
0
    const char *name_a, *name_b;
6709
0
    name_a = p->two->path;
6710
0
    name_b = NULL;
6711
0
    strip_prefix(opt->prefix_length, &name_a, &name_b);
6712
0
    fprintf(opt->file, "%s", diff_line_prefix(opt));
6713
0
    write_name_quoted(name_a, opt->file, opt->line_termination);
6714
0
  }
6715
6716
0
  opt->found_changes = 1;
6717
0
}
6718
6719
static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6720
0
{
6721
0
  struct strbuf sb = STRBUF_INIT;
6722
0
  if (fs->mode)
6723
0
    strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6724
0
  else
6725
0
    strbuf_addf(&sb, " %s ", newdelete);
6726
6727
0
  quote_c_style(fs->path, &sb, NULL, 0);
6728
0
  strbuf_addch(&sb, '\n');
6729
0
  emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6730
0
       sb.buf, sb.len, 0);
6731
0
  strbuf_release(&sb);
6732
0
}
6733
6734
static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6735
    int show_name)
6736
0
{
6737
0
  if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6738
0
    struct strbuf sb = STRBUF_INIT;
6739
0
    strbuf_addf(&sb, " mode change %06o => %06o",
6740
0
          p->one->mode, p->two->mode);
6741
0
    if (show_name) {
6742
0
      strbuf_addch(&sb, ' ');
6743
0
      quote_c_style(p->two->path, &sb, NULL, 0);
6744
0
    }
6745
0
    strbuf_addch(&sb, '\n');
6746
0
    emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6747
0
         sb.buf, sb.len, 0);
6748
0
    strbuf_release(&sb);
6749
0
  }
6750
0
}
6751
6752
static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6753
    struct diff_filepair *p)
6754
0
{
6755
0
  struct strbuf sb = STRBUF_INIT;
6756
0
  struct strbuf names = STRBUF_INIT;
6757
6758
0
  pprint_rename(&names, p->one->path, p->two->path);
6759
0
  strbuf_addf(&sb, " %s %s (%d%%)\n",
6760
0
        renamecopy, names.buf, similarity_index(p));
6761
0
  strbuf_release(&names);
6762
0
  emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6763
0
         sb.buf, sb.len, 0);
6764
0
  show_mode_change(opt, p, 0);
6765
0
  strbuf_release(&sb);
6766
0
}
6767
6768
static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6769
0
{
6770
0
  switch(p->status) {
6771
0
  case DIFF_STATUS_DELETED:
6772
0
    show_file_mode_name(opt, "delete", p->one);
6773
0
    break;
6774
0
  case DIFF_STATUS_ADDED:
6775
0
    show_file_mode_name(opt, "create", p->two);
6776
0
    break;
6777
0
  case DIFF_STATUS_COPIED:
6778
0
    show_rename_copy(opt, "copy", p);
6779
0
    break;
6780
0
  case DIFF_STATUS_RENAMED:
6781
0
    show_rename_copy(opt, "rename", p);
6782
0
    break;
6783
0
  default:
6784
0
    if (p->score) {
6785
0
      struct strbuf sb = STRBUF_INIT;
6786
0
      strbuf_addstr(&sb, " rewrite ");
6787
0
      quote_c_style(p->two->path, &sb, NULL, 0);
6788
0
      strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6789
0
      emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6790
0
           sb.buf, sb.len, 0);
6791
0
      strbuf_release(&sb);
6792
0
    }
6793
0
    show_mode_change(opt, p, !p->score);
6794
0
    break;
6795
0
  }
6796
0
}
6797
6798
struct patch_id_t {
6799
  struct git_hash_ctx *ctx;
6800
  int patchlen;
6801
};
6802
6803
static int remove_space(char *line, int len)
6804
0
{
6805
0
  int i;
6806
0
  char *dst = line;
6807
0
  unsigned char c;
6808
6809
0
  for (i = 0; i < len; i++)
6810
0
    if (!isspace((c = line[i])))
6811
0
      *dst++ = c;
6812
6813
0
  return dst - line;
6814
0
}
6815
6816
void flush_one_hunk(struct object_id *result, struct git_hash_ctx *ctx)
6817
0
{
6818
0
  unsigned char hash[GIT_MAX_RAWSZ];
6819
0
  unsigned short carry = 0;
6820
0
  int i;
6821
6822
0
  git_hash_final(hash, ctx);
6823
0
  git_hash_init(ctx, the_hash_algo);
6824
  /* 20-byte sum, with carry */
6825
0
  for (i = 0; i < the_hash_algo->rawsz; ++i) {
6826
0
    carry += result->hash[i] + hash[i];
6827
0
    result->hash[i] = carry;
6828
0
    carry >>= 8;
6829
0
  }
6830
0
}
6831
6832
static int patch_id_consume(void *priv, char *line, unsigned long len)
6833
0
{
6834
0
  struct patch_id_t *data = priv;
6835
0
  int new_len;
6836
6837
0
  if (len > 12 && starts_with(line, "\\ "))
6838
0
    return 0;
6839
0
  new_len = remove_space(line, len);
6840
6841
0
  git_hash_update(data->ctx, line, new_len);
6842
0
  data->patchlen += new_len;
6843
0
  return 0;
6844
0
}
6845
6846
static void patch_id_add_string(struct git_hash_ctx *ctx, const char *str)
6847
0
{
6848
0
  git_hash_update(ctx, str, strlen(str));
6849
0
}
6850
6851
static void patch_id_add_mode(struct git_hash_ctx *ctx, unsigned mode)
6852
0
{
6853
  /* large enough for 2^32 in octal */
6854
0
  char buf[12];
6855
0
  int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6856
0
  git_hash_update(ctx, buf, len);
6857
0
}
6858
6859
/* returns 0 upon success, and writes result into oid */
6860
static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6861
0
{
6862
0
  struct diff_queue_struct *q = &diff_queued_diff;
6863
0
  int i;
6864
0
  struct git_hash_ctx ctx;
6865
0
  struct patch_id_t data;
6866
6867
0
  git_hash_init(&ctx, the_hash_algo);
6868
0
  memset(&data, 0, sizeof(struct patch_id_t));
6869
0
  data.ctx = &ctx;
6870
0
  oidclr(oid, the_repository->hash_algo);
6871
6872
0
  for (i = 0; i < q->nr; i++) {
6873
0
    xpparam_t xpp;
6874
0
    xdemitconf_t xecfg;
6875
0
    mmfile_t mf1, mf2;
6876
0
    struct diff_filepair *p = q->queue[i];
6877
0
    int len1, len2;
6878
6879
0
    memset(&xpp, 0, sizeof(xpp));
6880
0
    memset(&xecfg, 0, sizeof(xecfg));
6881
0
    if (p->status == 0)
6882
0
      return error("internal diff status error");
6883
0
    if (p->status == DIFF_STATUS_UNKNOWN)
6884
0
      continue;
6885
0
    if (diff_unmodified_pair(p))
6886
0
      continue;
6887
0
    if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6888
0
        (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6889
0
      continue;
6890
0
    if (DIFF_PAIR_UNMERGED(p))
6891
0
      continue;
6892
6893
0
    diff_fill_oid_info(p->one, options->repo->index);
6894
0
    diff_fill_oid_info(p->two, options->repo->index);
6895
6896
0
    len1 = remove_space(p->one->path, strlen(p->one->path));
6897
0
    len2 = remove_space(p->two->path, strlen(p->two->path));
6898
0
    patch_id_add_string(&ctx, "diff--git");
6899
0
    patch_id_add_string(&ctx, "a/");
6900
0
    git_hash_update(&ctx, p->one->path, len1);
6901
0
    patch_id_add_string(&ctx, "b/");
6902
0
    git_hash_update(&ctx, p->two->path, len2);
6903
6904
0
    if (p->one->mode == 0) {
6905
0
      patch_id_add_string(&ctx, "newfilemode");
6906
0
      patch_id_add_mode(&ctx, p->two->mode);
6907
0
    } else if (p->two->mode == 0) {
6908
0
      patch_id_add_string(&ctx, "deletedfilemode");
6909
0
      patch_id_add_mode(&ctx, p->one->mode);
6910
0
    } else if (p->one->mode != p->two->mode) {
6911
0
      patch_id_add_string(&ctx, "oldmode");
6912
0
      patch_id_add_mode(&ctx, p->one->mode);
6913
0
      patch_id_add_string(&ctx, "newmode");
6914
0
      patch_id_add_mode(&ctx, p->two->mode);
6915
0
    }
6916
6917
0
    if (diff_header_only) {
6918
      /* don't do anything since we're only populating header info */
6919
0
    } else if (diff_filespec_is_binary(options->repo, p->one) ||
6920
0
        diff_filespec_is_binary(options->repo, p->two)) {
6921
0
      git_hash_update(&ctx, oid_to_hex(&p->one->oid),
6922
0
          the_hash_algo->hexsz);
6923
0
      git_hash_update(&ctx, oid_to_hex(&p->two->oid),
6924
0
          the_hash_algo->hexsz);
6925
0
    } else {
6926
0
      if (p->one->mode == 0) {
6927
0
        patch_id_add_string(&ctx, "---/dev/null");
6928
0
        patch_id_add_string(&ctx, "+++b/");
6929
0
        git_hash_update(&ctx, p->two->path, len2);
6930
0
      } else if (p->two->mode == 0) {
6931
0
        patch_id_add_string(&ctx, "---a/");
6932
0
        git_hash_update(&ctx, p->one->path, len1);
6933
0
        patch_id_add_string(&ctx, "+++/dev/null");
6934
0
      } else {
6935
0
        patch_id_add_string(&ctx, "---a/");
6936
0
        git_hash_update(&ctx, p->one->path, len1);
6937
0
        patch_id_add_string(&ctx, "+++b/");
6938
0
        git_hash_update(&ctx, p->two->path, len2);
6939
0
      }
6940
6941
0
      if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6942
0
          fill_mmfile(options->repo, &mf2, p->two) < 0)
6943
0
        return error("unable to read files to diff");
6944
0
      xpp.flags = 0;
6945
0
      xecfg.ctxlen = 3;
6946
0
      xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6947
0
      if (xdi_diff_outf(&mf1, &mf2, NULL,
6948
0
            patch_id_consume, &data, &xpp, &xecfg))
6949
0
        return error("unable to generate patch-id diff for %s",
6950
0
               p->one->path);
6951
0
    }
6952
0
    flush_one_hunk(oid, &ctx);
6953
0
  }
6954
6955
0
  git_hash_discard(&ctx);
6956
0
  return 0;
6957
0
}
6958
6959
int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6960
0
{
6961
0
  struct diff_queue_struct *q = &diff_queued_diff;
6962
0
  int result = diff_get_patch_id(options, oid, diff_header_only);
6963
6964
0
  diff_queue_clear(q);
6965
6966
0
  return result;
6967
0
}
6968
6969
static int is_summary_empty(const struct diff_queue_struct *q)
6970
0
{
6971
0
  int i;
6972
6973
0
  for (i = 0; i < q->nr; i++) {
6974
0
    const struct diff_filepair *p = q->queue[i];
6975
6976
0
    switch (p->status) {
6977
0
    case DIFF_STATUS_DELETED:
6978
0
    case DIFF_STATUS_ADDED:
6979
0
    case DIFF_STATUS_COPIED:
6980
0
    case DIFF_STATUS_RENAMED:
6981
0
      return 0;
6982
0
    default:
6983
0
      if (p->score)
6984
0
        return 0;
6985
0
      if (p->one->mode && p->two->mode &&
6986
0
          p->one->mode != p->two->mode)
6987
0
        return 0;
6988
0
      break;
6989
0
    }
6990
0
  }
6991
0
  return 1;
6992
0
}
6993
6994
static const char rename_limit_warning[] =
6995
N_("exhaustive rename detection was skipped due to too many files.");
6996
6997
static const char degrade_cc_to_c_warning[] =
6998
N_("only found copies from modified paths due to too many files.");
6999
7000
static const char rename_limit_advice[] =
7001
N_("you may want to set your %s variable to at least "
7002
   "%d and retry the command.");
7003
7004
void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
7005
0
{
7006
0
  fflush(stdout);
7007
0
  if (degraded_cc)
7008
0
    warning(_(degrade_cc_to_c_warning));
7009
0
  else if (needed)
7010
0
    warning(_(rename_limit_warning));
7011
0
  else
7012
0
    return;
7013
0
  if (0 < needed)
7014
0
    warning(_(rename_limit_advice), varname, needed);
7015
0
}
7016
7017
static void create_filepairs_for_header_only_notifications(struct diff_options *o)
7018
0
{
7019
0
  struct strset present;
7020
0
  struct diff_queue_struct *q = &diff_queued_diff;
7021
0
  struct hashmap_iter iter;
7022
0
  struct strmap_entry *e;
7023
0
  int i;
7024
7025
0
  strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
7026
7027
  /*
7028
   * Find out which paths exist in diff_queued_diff, preferring
7029
   * one->path for any pair that has multiple paths.
7030
   */
7031
0
  for (i = 0; i < q->nr; i++) {
7032
0
    struct diff_filepair *p = q->queue[i];
7033
0
    char *path = p->one->path ? p->one->path : p->two->path;
7034
7035
0
    if (strmap_contains(o->additional_path_headers, path))
7036
0
      strset_add(&present, path);
7037
0
  }
7038
7039
  /*
7040
   * Loop over paths in additional_path_headers; for each NOT already
7041
   * in diff_queued_diff, create a synthetic filepair and insert that
7042
   * into diff_queued_diff.
7043
   */
7044
0
  strmap_for_each_entry(o->additional_path_headers, &iter, e) {
7045
0
    if (!strset_contains(&present, e->key)) {
7046
0
      struct diff_filespec *one, *two;
7047
0
      struct diff_filepair *p;
7048
7049
0
      one = alloc_filespec(e->key);
7050
0
      two = alloc_filespec(e->key);
7051
0
      fill_filespec(one, null_oid(the_hash_algo), 0, 0);
7052
0
      fill_filespec(two, null_oid(the_hash_algo), 0, 0);
7053
0
      p = diff_queue(q, one, two);
7054
0
      p->status = DIFF_STATUS_MODIFIED;
7055
0
    }
7056
0
  }
7057
7058
  /* Re-sort the filepairs */
7059
0
  diffcore_fix_diff_index();
7060
7061
  /* Cleanup */
7062
0
  strset_clear(&present);
7063
0
}
7064
7065
static void diff_flush_patch_all_file_pairs(struct diff_options *o)
7066
0
{
7067
0
  int i;
7068
0
  static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
7069
0
  struct diff_queue_struct *q = &diff_queued_diff;
7070
7071
0
  if (WSEH_NEW & WS_RULE_MASK)
7072
0
    BUG("WS rules bit mask overlaps with diff symbol flags");
7073
7074
0
  if (o->color_moved && want_color(o->use_color))
7075
0
    o->emitted_symbols = &esm;
7076
7077
0
  if (o->additional_path_headers)
7078
0
    create_filepairs_for_header_only_notifications(o);
7079
7080
0
  for (i = 0; i < q->nr; i++) {
7081
0
    struct diff_filepair *p = q->queue[i];
7082
0
    if (check_pair_status(p))
7083
0
      diff_flush_patch(p, o);
7084
0
  }
7085
7086
0
  if (o->emitted_symbols) {
7087
0
    struct mem_pool entry_pool;
7088
0
    struct moved_entry_list *entry_list;
7089
7090
0
    mem_pool_init(&entry_pool, 1024 * 1024);
7091
0
    entry_list = add_lines_to_move_detection(o, &entry_pool);
7092
0
    mark_color_as_moved(o, entry_list);
7093
0
    if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
7094
0
      dim_moved_lines(o);
7095
7096
0
    mem_pool_discard(&entry_pool, 0);
7097
0
    free(entry_list);
7098
7099
0
    for (i = 0; i < esm.nr; i++)
7100
0
      emit_diff_symbol_from_struct(o, &esm.buf[i]);
7101
7102
0
    for (i = 0; i < esm.nr; i++)
7103
0
      free((void *)esm.buf[i].line);
7104
0
    esm.nr = 0;
7105
7106
0
    o->emitted_symbols = NULL;
7107
0
  }
7108
0
}
7109
7110
static void diff_free_file(struct diff_options *options)
7111
0
{
7112
0
  if (options->close_file && options->file) {
7113
0
    fclose(options->file);
7114
0
    options->file = NULL;
7115
0
  }
7116
0
}
7117
7118
static void diff_free_ignore_regex(struct diff_options *options)
7119
0
{
7120
0
  int i;
7121
7122
0
  for (i = 0; i < options->ignore_regex_nr; i++) {
7123
0
    regfree(options->ignore_regex[i]);
7124
0
    free(options->ignore_regex[i]);
7125
0
  }
7126
7127
0
  FREE_AND_NULL(options->ignore_regex);
7128
0
  options->ignore_regex_nr = 0;
7129
0
}
7130
7131
void diff_free(struct diff_options *options)
7132
0
{
7133
0
  if (options->no_free)
7134
0
    return;
7135
7136
0
  if (options->objfind) {
7137
0
    oidset_clear(options->objfind);
7138
0
    FREE_AND_NULL(options->objfind);
7139
0
  }
7140
7141
0
  FREE_AND_NULL(options->orderfile);
7142
0
  for (size_t i = 0; i < options->anchors_nr; i++)
7143
0
    free(options->anchors[i]);
7144
0
  FREE_AND_NULL(options->anchors);
7145
0
  options->anchors_nr = options->anchors_alloc = 0;
7146
7147
0
  diff_free_file(options);
7148
0
  diff_free_ignore_regex(options);
7149
0
  clear_pathspec(&options->pathspec);
7150
0
}
7151
7152
void diff_flush(struct diff_options *options)
7153
0
{
7154
0
  struct diff_queue_struct *q = &diff_queued_diff;
7155
0
  int i, output_format = options->output_format;
7156
0
  int separator = 0;
7157
0
  int dirstat_by_line = 0;
7158
7159
  /*
7160
   * Order: raw, stat, summary, patch
7161
   * or:    name/name-status/checkdiff (other bits clear)
7162
   */
7163
0
  if (!q->nr && !options->additional_path_headers)
7164
0
    goto free_queue;
7165
7166
0
  if (output_format & (DIFF_FORMAT_RAW |
7167
0
           DIFF_FORMAT_NAME |
7168
0
           DIFF_FORMAT_NAME_STATUS |
7169
0
           DIFF_FORMAT_CHECKDIFF)) {
7170
0
    for (i = 0; i < q->nr; i++) {
7171
0
      struct diff_filepair *p = q->queue[i];
7172
7173
0
      if (!check_pair_status(p))
7174
0
        continue;
7175
7176
0
      if (options->flags.diff_from_contents &&
7177
0
          !diff_flush_patch_quietly(p, options))
7178
0
        continue;
7179
7180
0
      flush_one_pair(p, options);
7181
0
    }
7182
0
    separator++;
7183
0
  }
7184
7185
0
  if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
7186
0
    dirstat_by_line = 1;
7187
7188
0
  if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
7189
0
      dirstat_by_line) {
7190
0
    struct diffstat_t diffstat;
7191
7192
0
    compute_diffstat(options, &diffstat, q);
7193
0
    if (output_format & DIFF_FORMAT_NUMSTAT)
7194
0
      show_numstat(&diffstat, options);
7195
0
    if (output_format & DIFF_FORMAT_DIFFSTAT)
7196
0
      show_stats(&diffstat, options);
7197
0
    if (output_format & DIFF_FORMAT_SHORTSTAT)
7198
0
      show_shortstats(&diffstat, options);
7199
0
    if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
7200
0
      show_dirstat_by_line(&diffstat, options);
7201
0
    free_diffstat_info(&diffstat);
7202
0
    separator++;
7203
0
  }
7204
0
  if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
7205
0
    show_dirstat(options);
7206
7207
0
  if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7208
0
    for (i = 0; i < q->nr; i++) {
7209
0
      diff_summary(options, q->queue[i]);
7210
0
    }
7211
0
    separator++;
7212
0
  }
7213
7214
0
  if (output_format & DIFF_FORMAT_PATCH) {
7215
0
    if (separator) {
7216
0
      emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
7217
0
      if (options->stat_sep)
7218
        /* attach patch instead of inline */
7219
0
        emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
7220
0
             NULL, 0, 0);
7221
0
    }
7222
7223
0
    diff_flush_patch_all_file_pairs(options);
7224
0
  }
7225
7226
0
  if (output_format & DIFF_FORMAT_CALLBACK)
7227
0
    options->format_callback(q, options, options->format_callback_data);
7228
7229
0
  if (output_format & DIFF_FORMAT_NO_OUTPUT &&
7230
0
      options->flags.exit_with_status &&
7231
0
      options->flags.diff_from_contents) {
7232
0
    for (i = 0; i < q->nr; i++) {
7233
0
      struct diff_filepair *p = q->queue[i];
7234
0
      if (check_pair_status(p))
7235
0
        diff_flush_patch_quietly(p, options);
7236
0
      if (options->found_changes)
7237
0
        break;
7238
0
    }
7239
0
  }
7240
7241
0
free_queue:
7242
0
  diff_queue_clear(q);
7243
0
  diff_free(options);
7244
7245
  /*
7246
   * Report the content-level differences with HAS_CHANGES;
7247
   * diff_addremove/diff_change does not set the bit when
7248
   * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
7249
   */
7250
0
  if (options->flags.diff_from_contents) {
7251
0
    if (options->found_changes)
7252
0
      options->flags.has_changes = 1;
7253
0
    else
7254
0
      options->flags.has_changes = 0;
7255
0
  }
7256
0
}
7257
7258
static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
7259
0
{
7260
0
  return (((p->status == DIFF_STATUS_MODIFIED) &&
7261
0
     ((p->score &&
7262
0
       filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
7263
0
      (!p->score &&
7264
0
       filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
7265
0
    ((p->status != DIFF_STATUS_MODIFIED) &&
7266
0
     filter_bit_tst(p->status, options)));
7267
0
}
7268
7269
static void diffcore_apply_filter(struct diff_options *options)
7270
0
{
7271
0
  int i;
7272
0
  struct diff_queue_struct *q = &diff_queued_diff;
7273
0
  struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7274
7275
0
  if (!options->filter)
7276
0
    return;
7277
7278
0
  if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
7279
0
    int found;
7280
0
    for (i = found = 0; !found && i < q->nr; i++) {
7281
0
      if (match_filter(options, q->queue[i]))
7282
0
        found++;
7283
0
    }
7284
0
    if (found)
7285
0
      return;
7286
7287
    /* otherwise we will clear the whole queue
7288
     * by copying the empty outq at the end of this
7289
     * function, but first clear the current entries
7290
     * in the queue.
7291
     */
7292
0
    for (i = 0; i < q->nr; i++)
7293
0
      diff_free_filepair(q->queue[i]);
7294
0
  }
7295
0
  else {
7296
    /* Only the matching ones */
7297
0
    for (i = 0; i < q->nr; i++) {
7298
0
      struct diff_filepair *p = q->queue[i];
7299
0
      if (match_filter(options, p))
7300
0
        diff_q(&outq, p);
7301
0
      else
7302
0
        diff_free_filepair(p);
7303
0
    }
7304
0
  }
7305
0
  free(q->queue);
7306
0
  *q = outq;
7307
0
}
7308
7309
/* Check whether two filespecs with the same mode and size are identical */
7310
static int diff_filespec_is_identical(struct repository *r,
7311
              struct diff_filespec *one,
7312
              struct diff_filespec *two)
7313
0
{
7314
0
  if (S_ISGITLINK(one->mode))
7315
0
    return 0;
7316
0
  if (diff_populate_filespec(r, one, NULL))
7317
0
    return 0;
7318
0
  if (diff_populate_filespec(r, two, NULL))
7319
0
    return 0;
7320
0
  return !memcmp(one->data, two->data, one->size);
7321
0
}
7322
7323
static int diff_filespec_check_stat_unmatch(struct repository *r,
7324
              struct diff_filepair *p)
7325
0
{
7326
0
  struct diff_populate_filespec_options dpf_options = {
7327
0
    .check_size_only = 1,
7328
0
    .missing_object_cb = diff_queued_diff_prefetch,
7329
0
    .missing_object_data = r,
7330
0
  };
7331
7332
0
  if (p->done_skip_stat_unmatch)
7333
0
    return p->skip_stat_unmatch_result;
7334
7335
0
  p->done_skip_stat_unmatch = 1;
7336
0
  p->skip_stat_unmatch_result = 0;
7337
  /*
7338
   * 1. Entries that come from stat info dirtiness
7339
   *    always have both sides (iow, not create/delete),
7340
   *    one side of the object name is unknown, with
7341
   *    the same mode and size.  Keep the ones that
7342
   *    do not match these criteria.  They have real
7343
   *    differences.
7344
   *
7345
   * 2. At this point, the file is known to be modified,
7346
   *    with the same mode and size, and the object
7347
   *    name of one side is unknown.  Need to inspect
7348
   *    the identical contents.
7349
   */
7350
0
  if (!DIFF_FILE_VALID(p->one) || /* (1) */
7351
0
      !DIFF_FILE_VALID(p->two) ||
7352
0
      (p->one->oid_valid && p->two->oid_valid) ||
7353
0
      (p->one->mode != p->two->mode) ||
7354
0
      diff_populate_filespec(r, p->one, &dpf_options) ||
7355
0
      diff_populate_filespec(r, p->two, &dpf_options) ||
7356
0
      (p->one->size != p->two->size) ||
7357
0
      !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
7358
0
    p->skip_stat_unmatch_result = 1;
7359
0
  return p->skip_stat_unmatch_result;
7360
0
}
7361
7362
static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
7363
0
{
7364
0
  int i;
7365
0
  struct diff_queue_struct *q = &diff_queued_diff;
7366
0
  struct diff_queue_struct outq = DIFF_QUEUE_INIT;
7367
7368
0
  for (i = 0; i < q->nr; i++) {
7369
0
    struct diff_filepair *p = q->queue[i];
7370
7371
0
    if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
7372
0
      diff_q(&outq, p);
7373
0
    else {
7374
      /*
7375
       * The caller can subtract 1 from skip_stat_unmatch
7376
       * to determine how many paths were dirty only
7377
       * due to stat info mismatch.
7378
       */
7379
0
      if (!diffopt->flags.no_index)
7380
0
        diffopt->skip_stat_unmatch++;
7381
0
      diff_free_filepair(p);
7382
0
      q->queue[i] = NULL;
7383
0
    }
7384
0
  }
7385
0
  free(q->queue);
7386
0
  *q = outq;
7387
0
}
7388
7389
static int diffnamecmp(const void *a_, const void *b_)
7390
0
{
7391
0
  const struct diff_filepair *a = *((const struct diff_filepair **)a_);
7392
0
  const struct diff_filepair *b = *((const struct diff_filepair **)b_);
7393
0
  const char *name_a, *name_b;
7394
7395
0
  name_a = a->one ? a->one->path : a->two->path;
7396
0
  name_b = b->one ? b->one->path : b->two->path;
7397
0
  return strcmp(name_a, name_b);
7398
0
}
7399
7400
void diffcore_fix_diff_index(void)
7401
0
{
7402
0
  struct diff_queue_struct *q = &diff_queued_diff;
7403
0
  QSORT(q->queue, q->nr, diffnamecmp);
7404
0
}
7405
7406
void diff_add_if_missing(struct repository *r,
7407
       struct oid_array *to_fetch,
7408
       const struct diff_filespec *filespec)
7409
0
{
7410
0
  if (filespec && filespec->oid_valid &&
7411
0
      !S_ISGITLINK(filespec->mode) &&
7412
0
      odb_read_object_info_extended(r->objects, &filespec->oid, NULL,
7413
0
            OBJECT_INFO_FOR_PREFETCH))
7414
0
    oid_array_append(to_fetch, &filespec->oid);
7415
0
}
7416
7417
void diff_queued_diff_prefetch(void *repository)
7418
0
{
7419
0
  struct repository *repo = repository;
7420
0
  int i;
7421
0
  struct diff_queue_struct *q = &diff_queued_diff;
7422
0
  struct oid_array to_fetch = OID_ARRAY_INIT;
7423
7424
0
  for (i = 0; i < q->nr; i++) {
7425
0
    struct diff_filepair *p = q->queue[i];
7426
7427
0
    if (!p)
7428
0
      continue;
7429
7430
0
    diff_add_if_missing(repo, &to_fetch, p->one);
7431
0
    diff_add_if_missing(repo, &to_fetch, p->two);
7432
0
  }
7433
7434
  /*
7435
   * NEEDSWORK: Consider deduplicating the OIDs sent.
7436
   */
7437
0
  promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7438
7439
0
  oid_array_clear(&to_fetch);
7440
0
}
7441
7442
void init_diffstat_widths(struct diff_options *options)
7443
0
{
7444
0
  options->stat_width = -1;        /* use full terminal width */
7445
0
  options->stat_name_width = -1;   /* respect diff.statNameWidth config */
7446
0
  options->stat_graph_width = -1;  /* respect diff.statGraphWidth config */
7447
0
}
7448
7449
void diffcore_std(struct diff_options *options)
7450
0
{
7451
0
  int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7452
0
    DIFF_FORMAT_NUMSTAT |
7453
0
    DIFF_FORMAT_PATCH |
7454
0
    DIFF_FORMAT_SHORTSTAT |
7455
0
    DIFF_FORMAT_DIRSTAT;
7456
7457
  /*
7458
   * Check if the user requested a blob-data-requiring diff output and/or
7459
   * break-rewrite detection (which requires blob data). If yes, prefetch
7460
   * the diff pairs.
7461
   *
7462
   * If no prefetching occurs, diffcore_rename() will prefetch if it
7463
   * decides that it needs inexact rename detection.
7464
   */
7465
0
  if (repo_has_promisor_remote(options->repo) &&
7466
0
      (options->output_format & output_formats_to_prefetch ||
7467
0
       options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7468
0
    diff_queued_diff_prefetch(options->repo);
7469
7470
  /* NOTE please keep the following in sync with diff_tree_combined() */
7471
0
  if (options->skip_stat_unmatch)
7472
0
    diffcore_skip_stat_unmatch(options);
7473
0
  if (!options->found_follow) {
7474
    /* See try_to_follow_renames() in tree-diff.c */
7475
0
    if (options->break_opt != -1)
7476
0
      diffcore_break(options->repo,
7477
0
               options->break_opt);
7478
0
    if (options->detect_rename)
7479
0
      diffcore_rename(options);
7480
0
    if (options->break_opt != -1)
7481
0
      diffcore_merge_broken();
7482
0
  }
7483
0
  if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7484
0
    diffcore_pickaxe(options);
7485
0
  if (options->orderfile)
7486
0
    diffcore_order(options->orderfile);
7487
0
  if (options->rotate_to)
7488
0
    diffcore_rotate(options);
7489
0
  if (!options->found_follow && !options->skip_resolving_statuses)
7490
    /* See try_to_follow_renames() in tree-diff.c */
7491
0
    diff_resolve_rename_copy();
7492
0
  diffcore_apply_filter(options);
7493
7494
0
  if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7495
0
    options->flags.has_changes = 1;
7496
0
  else
7497
0
    options->flags.has_changes = 0;
7498
7499
0
  options->found_follow = 0;
7500
0
}
7501
7502
int diff_result_code(struct rev_info *revs)
7503
0
{
7504
0
  struct diff_options *opt = &revs->diffopt;
7505
0
  int result = 0;
7506
7507
0
  if (revs->remerge_diff) {
7508
0
    tmp_objdir_destroy(revs->remerge_objdir);
7509
0
    revs->remerge_objdir = NULL;
7510
0
  }
7511
7512
0
  diff_warn_rename_limit("diff.renameLimit",
7513
0
             opt->needed_rename_limit,
7514
0
             opt->degraded_cc_to_c);
7515
7516
0
  if (opt->flags.exit_with_status &&
7517
0
      opt->flags.has_changes)
7518
0
    result |= 01;
7519
0
  if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7520
0
      opt->flags.check_failed)
7521
0
    result |= 02;
7522
0
  return result;
7523
0
}
7524
7525
int diff_can_quit_early(struct diff_options *opt)
7526
0
{
7527
0
  return (opt->flags.quick &&
7528
0
    !opt->filter &&
7529
0
    opt->flags.has_changes);
7530
0
}
7531
7532
/*
7533
 * Shall changes to this submodule be ignored?
7534
 *
7535
 * Submodule changes can be configured to be ignored separately for each path,
7536
 * but that configuration can be overridden from the command line.
7537
 */
7538
static int is_submodule_ignored(const char *path, struct diff_options *options)
7539
0
{
7540
0
  int ignored = 0;
7541
0
  struct diff_flags orig_flags = options->flags;
7542
0
  if (!options->flags.override_submodule_config)
7543
0
    set_diffopt_flags_from_submodule_config(options, path);
7544
0
  if (options->flags.ignore_submodules)
7545
0
    ignored = 1;
7546
0
  options->flags = orig_flags;
7547
0
  return ignored;
7548
0
}
7549
7550
void compute_diffstat(struct diff_options *options,
7551
          struct diffstat_t *diffstat,
7552
          struct diff_queue_struct *q)
7553
0
{
7554
0
  int i;
7555
7556
0
  memset(diffstat, 0, sizeof(struct diffstat_t));
7557
0
  for (i = 0; i < q->nr; i++) {
7558
0
    struct diff_filepair *p = q->queue[i];
7559
0
    if (check_pair_status(p))
7560
0
      diff_flush_stat(p, options, diffstat);
7561
0
  }
7562
0
  options->found_changes = !!diffstat->nr;
7563
0
}
7564
7565
struct diff_filepair *diff_queue_addremove(struct diff_queue_struct *queue,
7566
             struct diff_options *options,
7567
             int addremove, unsigned mode,
7568
             const struct object_id *oid,
7569
             int oid_valid,
7570
             const char *concatpath,
7571
             unsigned dirty_submodule)
7572
0
{
7573
0
  struct diff_filespec *one, *two;
7574
0
  struct diff_filepair *pair;
7575
7576
0
  if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7577
0
    return NULL;
7578
7579
  /* This may look odd, but it is a preparation for
7580
   * feeding "there are unchanged files which should
7581
   * not produce diffs, but when you are doing copy
7582
   * detection you would need them, so here they are"
7583
   * entries to the diff-core.  They will be prefixed
7584
   * with something like '=' or '*' (I haven't decided
7585
   * which but should not make any difference).
7586
   * Feeding the same new and old to diff_change()
7587
   * also has the same effect.
7588
   * Before the final output happens, they are pruned after
7589
   * merged into rename/copy pairs as appropriate.
7590
   */
7591
0
  if (options->flags.reverse_diff)
7592
0
    addremove = (addremove == '+' ? '-' :
7593
0
           addremove == '-' ? '+' : addremove);
7594
7595
0
  if (options->prefix &&
7596
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7597
0
    return NULL;
7598
7599
0
  one = alloc_filespec(concatpath);
7600
0
  two = alloc_filespec(concatpath);
7601
7602
0
  if (addremove != '+')
7603
0
    fill_filespec(one, oid, oid_valid, mode);
7604
0
  if (addremove != '-') {
7605
0
    fill_filespec(two, oid, oid_valid, mode);
7606
0
    two->dirty_submodule = dirty_submodule;
7607
0
  }
7608
7609
0
  pair = diff_queue(queue, one, two);
7610
0
  if (!options->flags.diff_from_contents)
7611
0
    options->flags.has_changes = 1;
7612
7613
0
  return pair;
7614
0
}
7615
7616
struct diff_filepair *diff_queue_change(struct diff_queue_struct *queue,
7617
          struct diff_options *options,
7618
          unsigned old_mode, unsigned new_mode,
7619
          const struct object_id *old_oid,
7620
          const struct object_id *new_oid,
7621
          int old_oid_valid, int new_oid_valid,
7622
          const char *concatpath,
7623
          unsigned old_dirty_submodule,
7624
          unsigned new_dirty_submodule)
7625
0
{
7626
0
  struct diff_filespec *one, *two;
7627
0
  struct diff_filepair *p;
7628
7629
0
  if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7630
0
      is_submodule_ignored(concatpath, options))
7631
0
    return NULL;
7632
7633
0
  if (options->flags.reverse_diff) {
7634
0
    SWAP(old_mode, new_mode);
7635
0
    SWAP(old_oid, new_oid);
7636
0
    SWAP(old_oid_valid, new_oid_valid);
7637
0
    SWAP(old_dirty_submodule, new_dirty_submodule);
7638
0
  }
7639
7640
0
  if (options->prefix &&
7641
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7642
0
    return NULL;
7643
7644
0
  one = alloc_filespec(concatpath);
7645
0
  two = alloc_filespec(concatpath);
7646
0
  fill_filespec(one, old_oid, old_oid_valid, old_mode);
7647
0
  fill_filespec(two, new_oid, new_oid_valid, new_mode);
7648
0
  one->dirty_submodule = old_dirty_submodule;
7649
0
  two->dirty_submodule = new_dirty_submodule;
7650
0
  p = diff_queue(queue, one, two);
7651
7652
0
  if (options->flags.diff_from_contents)
7653
0
    return p;
7654
7655
0
  if (options->flags.quick && options->skip_stat_unmatch &&
7656
0
      !diff_filespec_check_stat_unmatch(options->repo, p)) {
7657
0
    diff_free_filespec_data(p->one);
7658
0
    diff_free_filespec_data(p->two);
7659
0
    return p;
7660
0
  }
7661
7662
0
  options->flags.has_changes = 1;
7663
7664
0
  return p;
7665
0
}
7666
7667
void diff_addremove(struct diff_options *options, int addremove, unsigned mode,
7668
        const struct object_id *oid, int oid_valid,
7669
        const char *concatpath, unsigned dirty_submodule)
7670
0
{
7671
0
  diff_queue_addremove(&diff_queued_diff, options, addremove, mode, oid,
7672
0
           oid_valid, concatpath, dirty_submodule);
7673
0
}
7674
7675
void diff_change(struct diff_options *options,
7676
     unsigned old_mode, unsigned new_mode,
7677
     const struct object_id *old_oid,
7678
     const struct object_id *new_oid,
7679
     int old_oid_valid, int new_oid_valid,
7680
     const char *concatpath,
7681
     unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7682
0
{
7683
0
  diff_queue_change(&diff_queued_diff, options, old_mode, new_mode,
7684
0
        old_oid, new_oid, old_oid_valid, new_oid_valid,
7685
0
        concatpath, old_dirty_submodule, new_dirty_submodule);
7686
0
}
7687
7688
void diff_same(struct diff_options *options,
7689
         unsigned mode,
7690
         const struct object_id *oid,
7691
         const char *concatpath)
7692
0
{
7693
0
  struct diff_filespec *one;
7694
7695
0
  if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7696
0
    return;
7697
7698
0
  if (options->prefix &&
7699
0
      strncmp(concatpath, options->prefix, options->prefix_length))
7700
0
    return;
7701
7702
0
  one = alloc_filespec(concatpath);
7703
0
  fill_filespec(one, oid, 1, mode);
7704
0
  one->count++;
7705
0
  diff_queue(&diff_queued_diff, one, one);
7706
0
}
7707
7708
struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7709
0
{
7710
0
  struct diff_filepair *pair;
7711
0
  struct diff_filespec *one, *two;
7712
7713
0
  if (options->prefix &&
7714
0
      strncmp(path, options->prefix, options->prefix_length))
7715
0
    return NULL;
7716
7717
0
  one = alloc_filespec(path);
7718
0
  two = alloc_filespec(path);
7719
0
  pair = diff_queue(&diff_queued_diff, one, two);
7720
0
  pair->is_unmerged = 1;
7721
0
  return pair;
7722
0
}
7723
7724
static char *run_textconv(struct repository *r,
7725
        const char *pgm,
7726
        struct diff_filespec *spec,
7727
        size_t *outsize)
7728
0
{
7729
0
  struct diff_tempfile *temp;
7730
0
  struct child_process child = CHILD_PROCESS_INIT;
7731
0
  struct strbuf buf = STRBUF_INIT;
7732
0
  int err = 0;
7733
7734
0
  temp = prepare_temp_file(r, spec);
7735
0
  strvec_push(&child.args, pgm);
7736
0
  strvec_push(&child.args, temp->name);
7737
7738
0
  child.use_shell = 1;
7739
0
  child.out = -1;
7740
0
  if (start_command(&child)) {
7741
0
    remove_tempfile();
7742
0
    return NULL;
7743
0
  }
7744
7745
0
  if (strbuf_read(&buf, child.out, 0) < 0)
7746
0
    err = error("error reading from textconv command '%s'", pgm);
7747
0
  close(child.out);
7748
7749
0
  if (finish_command(&child) || err) {
7750
0
    strbuf_release(&buf);
7751
0
    remove_tempfile();
7752
0
    return NULL;
7753
0
  }
7754
0
  remove_tempfile();
7755
7756
0
  return strbuf_detach(&buf, outsize);
7757
0
}
7758
7759
size_t fill_textconv(struct repository *r,
7760
         struct userdiff_driver *driver,
7761
         struct diff_filespec *df,
7762
         char **outbuf)
7763
0
{
7764
0
  size_t size;
7765
7766
0
  if (!driver) {
7767
0
    if (!DIFF_FILE_VALID(df)) {
7768
0
      *outbuf = (char *) "";
7769
0
      return 0;
7770
0
    }
7771
0
    if (diff_populate_filespec(r, df, NULL))
7772
0
      die("unable to read files to diff");
7773
0
    *outbuf = df->data;
7774
0
    return df->size;
7775
0
  }
7776
7777
0
  if (!driver->textconv)
7778
0
    BUG("fill_textconv called with non-textconv driver");
7779
7780
0
  if (driver->textconv_cache && df->oid_valid) {
7781
0
    *outbuf = notes_cache_get(driver->textconv_cache,
7782
0
            &df->oid,
7783
0
            &size);
7784
0
    if (*outbuf)
7785
0
      return size;
7786
0
  }
7787
7788
0
  *outbuf = run_textconv(r, driver->textconv, df, &size);
7789
0
  if (!*outbuf)
7790
0
    die("unable to read files to diff");
7791
7792
0
  if (driver->textconv_cache && df->oid_valid) {
7793
    /* ignore errors, as we might be in a readonly repository */
7794
0
    notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7795
0
        size);
7796
    /*
7797
     * we could save up changes and flush them all at the end,
7798
     * but we would need an extra call after all diffing is done.
7799
     * Since generating a cache entry is the slow path anyway,
7800
     * this extra overhead probably isn't a big deal.
7801
     */
7802
0
    notes_cache_write(driver->textconv_cache);
7803
0
  }
7804
7805
0
  return size;
7806
0
}
7807
7808
int textconv_object(struct repository *r,
7809
        const char *path,
7810
        unsigned mode,
7811
        const struct object_id *oid,
7812
        int oid_valid,
7813
        char **buf,
7814
        unsigned long *buf_size)
7815
0
{
7816
0
  struct diff_filespec *df;
7817
0
  struct userdiff_driver *textconv;
7818
7819
0
  df = alloc_filespec(path);
7820
0
  fill_filespec(df, oid, oid_valid, mode);
7821
0
  textconv = get_textconv(r, df);
7822
0
  if (!textconv) {
7823
0
    free_filespec(df);
7824
0
    return 0;
7825
0
  }
7826
7827
0
  *buf_size = fill_textconv(r, textconv, df, buf);
7828
0
  free_filespec(df);
7829
0
  return 1;
7830
0
}
7831
7832
void setup_diff_pager(struct diff_options *opt)
7833
0
{
7834
  /*
7835
   * If the user asked for our exit code, then either they want --quiet
7836
   * or --exit-code. We should definitely not bother with a pager in the
7837
   * former case, as we will generate no output. Since we still properly
7838
   * report our exit code even when a pager is run, we _could_ run a
7839
   * pager with --exit-code. But since we have not done so historically,
7840
   * and because it is easy to find people oneline advising "git diff
7841
   * --exit-code" in hooks and other scripts, we do not do so.
7842
   */
7843
0
  if (!opt->flags.exit_with_status &&
7844
0
      check_pager_config(the_repository, "diff") != 0)
7845
0
    setup_pager(the_repository);
7846
0
}