Coverage Report

Created: 2026-01-09 07:10

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