Coverage Report

Created: 2024-09-08 06:23

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