diff: pass whole pending entry in blobinfo
[git] / builtin / diff.c
1 /*
2  * Builtin "git diff"
3  *
4  * Copyright (c) 2006 Junio C Hamano
5  */
6 #include "cache.h"
7 #include "lockfile.h"
8 #include "color.h"
9 #include "commit.h"
10 #include "blob.h"
11 #include "tag.h"
12 #include "diff.h"
13 #include "diffcore.h"
14 #include "revision.h"
15 #include "log-tree.h"
16 #include "builtin.h"
17 #include "submodule.h"
18 #include "sha1-array.h"
19
20 #define DIFF_NO_INDEX_EXPLICIT 1
21 #define DIFF_NO_INDEX_IMPLICIT 2
22
23 static const char builtin_diff_usage[] =
24 "git diff [<options>] [<commit> [<commit>]] [--] [<path>...]";
25
26 static void stuff_change(struct diff_options *opt,
27                          unsigned old_mode, unsigned new_mode,
28                          const struct object_id *old_oid,
29                          const struct object_id *new_oid,
30                          int old_oid_valid,
31                          int new_oid_valid,
32                          const char *old_name,
33                          const char *new_name)
34 {
35         struct diff_filespec *one, *two;
36
37         if (!is_null_oid(old_oid) && !is_null_oid(new_oid) &&
38             !oidcmp(old_oid, new_oid) && (old_mode == new_mode))
39                 return;
40
41         if (DIFF_OPT_TST(opt, REVERSE_DIFF)) {
42                 SWAP(old_mode, new_mode);
43                 SWAP(old_oid, new_oid);
44                 SWAP(old_name, new_name);
45         }
46
47         if (opt->prefix &&
48             (strncmp(old_name, opt->prefix, opt->prefix_length) ||
49              strncmp(new_name, opt->prefix, opt->prefix_length)))
50                 return;
51
52         one = alloc_filespec(old_name);
53         two = alloc_filespec(new_name);
54         fill_filespec(one, old_oid->hash, old_oid_valid, old_mode);
55         fill_filespec(two, new_oid->hash, new_oid_valid, new_mode);
56
57         diff_queue(&diff_queued_diff, one, two);
58 }
59
60 static int builtin_diff_b_f(struct rev_info *revs,
61                             int argc, const char **argv,
62                             struct object_array_entry **blob)
63 {
64         /* Blob vs file in the working tree*/
65         struct stat st;
66         const char *path;
67
68         if (argc > 1)
69                 usage(builtin_diff_usage);
70
71         GUARD_PATHSPEC(&revs->prune_data, PATHSPEC_FROMTOP | PATHSPEC_LITERAL);
72         path = revs->prune_data.items[0].match;
73
74         if (lstat(path, &st))
75                 die_errno(_("failed to stat '%s'"), path);
76         if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
77                 die(_("'%s': not a regular file or symlink"), path);
78
79         diff_set_mnemonic_prefix(&revs->diffopt, "o/", "w/");
80
81         if (blob[0]->mode == S_IFINVALID)
82                 blob[0]->mode = canon_mode(st.st_mode);
83
84         stuff_change(&revs->diffopt,
85                      blob[0]->mode, canon_mode(st.st_mode),
86                      &blob[0]->item->oid, &null_oid,
87                      1, 0,
88                      path, path);
89         diffcore_std(&revs->diffopt);
90         diff_flush(&revs->diffopt);
91         return 0;
92 }
93
94 static int builtin_diff_blobs(struct rev_info *revs,
95                               int argc, const char **argv,
96                               struct object_array_entry **blob)
97 {
98         unsigned mode = canon_mode(S_IFREG | 0644);
99
100         if (argc > 1)
101                 usage(builtin_diff_usage);
102
103         if (blob[0]->mode == S_IFINVALID)
104                 blob[0]->mode = mode;
105
106         if (blob[1]->mode == S_IFINVALID)
107                 blob[1]->mode = mode;
108
109         stuff_change(&revs->diffopt,
110                      blob[0]->mode, blob[1]->mode,
111                      &blob[0]->item->oid, &blob[1]->item->oid,
112                      1, 1,
113                      blob[0]->name, blob[1]->name);
114         diffcore_std(&revs->diffopt);
115         diff_flush(&revs->diffopt);
116         return 0;
117 }
118
119 static int builtin_diff_index(struct rev_info *revs,
120                               int argc, const char **argv)
121 {
122         int cached = 0;
123         while (1 < argc) {
124                 const char *arg = argv[1];
125                 if (!strcmp(arg, "--cached") || !strcmp(arg, "--staged"))
126                         cached = 1;
127                 else
128                         usage(builtin_diff_usage);
129                 argv++; argc--;
130         }
131         /*
132          * Make sure there is one revision (i.e. pending object),
133          * and there is no revision filtering parameters.
134          */
135         if (revs->pending.nr != 1 ||
136             revs->max_count != -1 || revs->min_age != -1 ||
137             revs->max_age != -1)
138                 usage(builtin_diff_usage);
139         if (!cached) {
140                 setup_work_tree();
141                 if (read_cache_preload(&revs->diffopt.pathspec) < 0) {
142                         perror("read_cache_preload");
143                         return -1;
144                 }
145         } else if (read_cache() < 0) {
146                 perror("read_cache");
147                 return -1;
148         }
149         return run_diff_index(revs, cached);
150 }
151
152 static int builtin_diff_tree(struct rev_info *revs,
153                              int argc, const char **argv,
154                              struct object_array_entry *ent0,
155                              struct object_array_entry *ent1)
156 {
157         const struct object_id *(oid[2]);
158         int swap = 0;
159
160         if (argc > 1)
161                 usage(builtin_diff_usage);
162
163         /*
164          * We saw two trees, ent0 and ent1.  If ent1 is uninteresting,
165          * swap them.
166          */
167         if (ent1->item->flags & UNINTERESTING)
168                 swap = 1;
169         oid[swap] = &ent0->item->oid;
170         oid[1 - swap] = &ent1->item->oid;
171         diff_tree_sha1(oid[0]->hash, oid[1]->hash, "", &revs->diffopt);
172         log_tree_diff_flush(revs);
173         return 0;
174 }
175
176 static int builtin_diff_combined(struct rev_info *revs,
177                                  int argc, const char **argv,
178                                  struct object_array_entry *ent,
179                                  int ents)
180 {
181         struct oid_array parents = OID_ARRAY_INIT;
182         int i;
183
184         if (argc > 1)
185                 usage(builtin_diff_usage);
186
187         if (!revs->dense_combined_merges && !revs->combine_merges)
188                 revs->dense_combined_merges = revs->combine_merges = 1;
189         for (i = 1; i < ents; i++)
190                 oid_array_append(&parents, &ent[i].item->oid);
191         diff_tree_combined(ent[0].item->oid.hash, &parents,
192                            revs->dense_combined_merges, revs);
193         oid_array_clear(&parents);
194         return 0;
195 }
196
197 static void refresh_index_quietly(void)
198 {
199         struct lock_file *lock_file;
200         int fd;
201
202         lock_file = xcalloc(1, sizeof(struct lock_file));
203         fd = hold_locked_index(lock_file, 0);
204         if (fd < 0)
205                 return;
206         discard_cache();
207         read_cache();
208         refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
209         update_index_if_able(&the_index, lock_file);
210 }
211
212 static int builtin_diff_files(struct rev_info *revs, int argc, const char **argv)
213 {
214         unsigned int options = 0;
215
216         while (1 < argc && argv[1][0] == '-') {
217                 if (!strcmp(argv[1], "--base"))
218                         revs->max_count = 1;
219                 else if (!strcmp(argv[1], "--ours"))
220                         revs->max_count = 2;
221                 else if (!strcmp(argv[1], "--theirs"))
222                         revs->max_count = 3;
223                 else if (!strcmp(argv[1], "-q"))
224                         options |= DIFF_SILENT_ON_REMOVED;
225                 else if (!strcmp(argv[1], "-h"))
226                         usage(builtin_diff_usage);
227                 else
228                         return error(_("invalid option: %s"), argv[1]);
229                 argv++; argc--;
230         }
231
232         /*
233          * "diff --base" should not combine merges because it was not
234          * asked to.  "diff -c" should not densify (if the user wants
235          * dense one, --cc can be explicitly asked for, or just rely
236          * on the default).
237          */
238         if (revs->max_count == -1 && !revs->combine_merges &&
239             (revs->diffopt.output_format & DIFF_FORMAT_PATCH))
240                 revs->combine_merges = revs->dense_combined_merges = 1;
241
242         setup_work_tree();
243         if (read_cache_preload(&revs->diffopt.pathspec) < 0) {
244                 perror("read_cache_preload");
245                 return -1;
246         }
247         return run_diff_files(revs, options);
248 }
249
250 int cmd_diff(int argc, const char **argv, const char *prefix)
251 {
252         int i;
253         struct rev_info rev;
254         struct object_array ent = OBJECT_ARRAY_INIT;
255         int blobs = 0, paths = 0;
256         struct object_array_entry *blob[2];
257         int nongit = 0, no_index = 0;
258         int result = 0;
259
260         /*
261          * We could get N tree-ish in the rev.pending_objects list.
262          * Also there could be M blobs there, and P pathspecs.
263          *
264          * N=0, M=0:
265          *      cache vs files (diff-files)
266          * N=0, M=2:
267          *      compare two random blobs.  P must be zero.
268          * N=0, M=1, P=1:
269          *      compare a blob with a working tree file.
270          *
271          * N=1, M=0:
272          *      tree vs cache (diff-index --cached)
273          *
274          * N=2, M=0:
275          *      tree vs tree (diff-tree)
276          *
277          * N=0, M=0, P=2:
278          *      compare two filesystem entities (aka --no-index).
279          *
280          * Other cases are errors.
281          */
282
283         /* Were we asked to do --no-index explicitly? */
284         for (i = 1; i < argc; i++) {
285                 if (!strcmp(argv[i], "--")) {
286                         i++;
287                         break;
288                 }
289                 if (!strcmp(argv[i], "--no-index"))
290                         no_index = DIFF_NO_INDEX_EXPLICIT;
291                 if (argv[i][0] != '-')
292                         break;
293         }
294
295         prefix = setup_git_directory_gently(&nongit);
296
297         if (!no_index) {
298                 /*
299                  * Treat git diff with at least one path outside of the
300                  * repo the same as if the command would have been executed
301                  * outside of a git repository.  In this case it behaves
302                  * the same way as "git diff --no-index <a> <b>", which acts
303                  * as a colourful "diff" replacement.
304                  */
305                 if (nongit || ((argc == i + 2) &&
306                                (!path_inside_repo(prefix, argv[i]) ||
307                                 !path_inside_repo(prefix, argv[i + 1]))))
308                         no_index = DIFF_NO_INDEX_IMPLICIT;
309         }
310
311         if (!no_index)
312                 gitmodules_config();
313         init_diff_ui_defaults();
314         git_config(git_diff_ui_config, NULL);
315         precompose_argv(argc, argv);
316
317         init_revisions(&rev, prefix);
318
319         if (no_index && argc != i + 2) {
320                 if (no_index == DIFF_NO_INDEX_IMPLICIT) {
321                         /*
322                          * There was no --no-index and there were not two
323                          * paths. It is possible that the user intended
324                          * to do an inside-repository operation.
325                          */
326                         fprintf(stderr, "Not a git repository\n");
327                         fprintf(stderr,
328                                 "To compare two paths outside a working tree:\n");
329                 }
330                 /* Give the usage message for non-repository usage and exit. */
331                 usagef("git diff %s <path> <path>",
332                        no_index == DIFF_NO_INDEX_EXPLICIT ?
333                        "--no-index" : "[--no-index]");
334
335         }
336         if (no_index)
337                 /* If this is a no-index diff, just run it and exit there. */
338                 diff_no_index(&rev, argc, argv);
339
340         /* Otherwise, we are doing the usual "git" diff */
341         rev.diffopt.skip_stat_unmatch = !!diff_auto_refresh_index;
342
343         /* Scale to real terminal size and respect statGraphWidth config */
344         rev.diffopt.stat_width = -1;
345         rev.diffopt.stat_graph_width = -1;
346
347         /* Default to let external and textconv be used */
348         DIFF_OPT_SET(&rev.diffopt, ALLOW_EXTERNAL);
349         DIFF_OPT_SET(&rev.diffopt, ALLOW_TEXTCONV);
350
351         if (nongit)
352                 die(_("Not a git repository"));
353         argc = setup_revisions(argc, argv, &rev, NULL);
354         if (!rev.diffopt.output_format) {
355                 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
356                 diff_setup_done(&rev.diffopt);
357         }
358
359         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
360
361         setup_diff_pager(&rev.diffopt);
362
363         /*
364          * Do we have --cached and not have a pending object, then
365          * default to HEAD by hand.  Eek.
366          */
367         if (!rev.pending.nr) {
368                 int i;
369                 for (i = 1; i < argc; i++) {
370                         const char *arg = argv[i];
371                         if (!strcmp(arg, "--"))
372                                 break;
373                         else if (!strcmp(arg, "--cached") ||
374                                  !strcmp(arg, "--staged")) {
375                                 add_head_to_pending(&rev);
376                                 if (!rev.pending.nr) {
377                                         struct tree *tree;
378                                         tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
379                                         add_pending_object(&rev, &tree->object, "HEAD");
380                                 }
381                                 break;
382                         }
383                 }
384         }
385
386         for (i = 0; i < rev.pending.nr; i++) {
387                 struct object_array_entry *entry = &rev.pending.objects[i];
388                 struct object *obj = entry->item;
389                 const char *name = entry->name;
390                 int flags = (obj->flags & UNINTERESTING);
391                 if (!obj->parsed)
392                         obj = parse_object(obj->oid.hash);
393                 obj = deref_tag(obj, NULL, 0);
394                 if (!obj)
395                         die(_("invalid object '%s' given."), name);
396                 if (obj->type == OBJ_COMMIT)
397                         obj = &((struct commit *)obj)->tree->object;
398
399                 if (obj->type == OBJ_TREE) {
400                         obj->flags |= flags;
401                         add_object_array(obj, name, &ent);
402                 } else if (obj->type == OBJ_BLOB) {
403                         if (2 <= blobs)
404                                 die(_("more than two blobs given: '%s'"), name);
405                         blob[blobs] = entry;
406                         blobs++;
407
408                 } else {
409                         die(_("unhandled object '%s' given."), name);
410                 }
411         }
412         if (rev.prune_data.nr)
413                 paths += rev.prune_data.nr;
414
415         /*
416          * Now, do the arguments look reasonable?
417          */
418         if (!ent.nr) {
419                 switch (blobs) {
420                 case 0:
421                         result = builtin_diff_files(&rev, argc, argv);
422                         break;
423                 case 1:
424                         if (paths != 1)
425                                 usage(builtin_diff_usage);
426                         result = builtin_diff_b_f(&rev, argc, argv, blob);
427                         break;
428                 case 2:
429                         if (paths)
430                                 usage(builtin_diff_usage);
431                         result = builtin_diff_blobs(&rev, argc, argv, blob);
432                         break;
433                 default:
434                         usage(builtin_diff_usage);
435                 }
436         }
437         else if (blobs)
438                 usage(builtin_diff_usage);
439         else if (ent.nr == 1)
440                 result = builtin_diff_index(&rev, argc, argv);
441         else if (ent.nr == 2)
442                 result = builtin_diff_tree(&rev, argc, argv,
443                                            &ent.objects[0], &ent.objects[1]);
444         else if (ent.objects[0].item->flags & UNINTERESTING) {
445                 /*
446                  * diff A...B where there is at least one merge base
447                  * between A and B.  We have ent.objects[0] ==
448                  * merge-base, ent.objects[ents-2] == A, and
449                  * ent.objects[ents-1] == B.  Show diff between the
450                  * base and B.  Note that we pick one merge base at
451                  * random if there are more than one.
452                  */
453                 result = builtin_diff_tree(&rev, argc, argv,
454                                            &ent.objects[0],
455                                            &ent.objects[ent.nr-1]);
456         } else
457                 result = builtin_diff_combined(&rev, argc, argv,
458                                                ent.objects, ent.nr);
459         result = diff_result_code(&rev.diffopt, result);
460         if (1 < rev.diffopt.skip_stat_unmatch)
461                 refresh_index_quietly();
462         return result;
463 }