Coverage Report

Created: 2026-02-14 06:27

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