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