add: remove dead code
[git] / builtin / add.c
1 /*
2  * "git add" builtin command
3  *
4  * Copyright (C) 2006 Linus Torvalds
5  */
6 #include "cache.h"
7 #include "builtin.h"
8 #include "dir.h"
9 #include "pathspec.h"
10 #include "exec_cmd.h"
11 #include "cache-tree.h"
12 #include "run-command.h"
13 #include "parse-options.h"
14 #include "diff.h"
15 #include "diffcore.h"
16 #include "revision.h"
17 #include "bulk-checkin.h"
18
19 static const char * const builtin_add_usage[] = {
20         N_("git add [options] [--] <pathspec>..."),
21         NULL
22 };
23 static int patch_interactive, add_interactive, edit_interactive;
24 static int take_worktree_changes;
25
26 struct update_callback_data {
27         int flags;
28         int add_errors;
29         /* only needed for 2.0 transition preparation */
30         int warn_add_would_remove;
31 };
32
33 static int fix_unmerged_status(struct diff_filepair *p,
34                                struct update_callback_data *data)
35 {
36         if (p->status != DIFF_STATUS_UNMERGED)
37                 return p->status;
38         if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
39                 /*
40                  * This is not an explicit add request, and the
41                  * path is missing from the working tree (deleted)
42                  */
43                 return DIFF_STATUS_DELETED;
44         else
45                 /*
46                  * Either an explicit add request, or path exists
47                  * in the working tree.  An attempt to explicitly
48                  * add a path that does not exist in the working tree
49                  * will be caught as an error by the caller immediately.
50                  */
51                 return DIFF_STATUS_MODIFIED;
52 }
53
54 static const char *add_would_remove_warning = N_(
55         "You ran 'git add' with neither '-A (--all)' or '--ignore-removal',\n"
56 "whose behaviour will change in Git 2.0 with respect to paths you removed.\n"
57 "Paths like '%s' that are\n"
58 "removed from your working tree are ignored with this version of Git.\n"
59 "\n"
60 "* 'git add --ignore-removal <pathspec>', which is the current default,\n"
61 "  ignores paths you removed from your working tree.\n"
62 "\n"
63 "* 'git add --all <pathspec>' will let you also record the removals.\n"
64 "\n"
65 "Run 'git status' to check the paths you removed from your working tree.\n");
66
67 static void warn_add_would_remove(const char *path)
68 {
69         warning(_(add_would_remove_warning), path);
70 }
71
72 static void update_callback(struct diff_queue_struct *q,
73                             struct diff_options *opt, void *cbdata)
74 {
75         int i;
76         struct update_callback_data *data = cbdata;
77
78         for (i = 0; i < q->nr; i++) {
79                 struct diff_filepair *p = q->queue[i];
80                 const char *path = p->one->path;
81                 switch (fix_unmerged_status(p, data)) {
82                 default:
83                         die(_("unexpected diff status %c"), p->status);
84                 case DIFF_STATUS_MODIFIED:
85                 case DIFF_STATUS_TYPE_CHANGED:
86                         if (add_file_to_index(&the_index, path, data->flags)) {
87                                 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
88                                         die(_("updating files failed"));
89                                 data->add_errors++;
90                         }
91                         break;
92                 case DIFF_STATUS_DELETED:
93                         if (data->warn_add_would_remove) {
94                                 warn_add_would_remove(path);
95                                 data->warn_add_would_remove = 0;
96                         }
97                         if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
98                                 break;
99                         if (!(data->flags & ADD_CACHE_PRETEND))
100                                 remove_file_from_index(&the_index, path);
101                         if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
102                                 printf(_("remove '%s'\n"), path);
103                         break;
104                 }
105         }
106 }
107
108 static void update_files_in_cache(const char *prefix,
109                                   const struct pathspec *pathspec,
110                                   struct update_callback_data *data)
111 {
112         struct rev_info rev;
113
114         init_revisions(&rev, prefix);
115         setup_revisions(0, NULL, &rev, NULL);
116         if (pathspec)
117                 copy_pathspec(&rev.prune_data, pathspec);
118         rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
119         rev.diffopt.format_callback = update_callback;
120         rev.diffopt.format_callback_data = data;
121         rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
122         run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
123 }
124
125 int add_files_to_cache(const char *prefix,
126                        const struct pathspec *pathspec, int flags)
127 {
128         struct update_callback_data data;
129
130         memset(&data, 0, sizeof(data));
131         data.flags = flags;
132         update_files_in_cache(prefix, pathspec, &data);
133         return !!data.add_errors;
134 }
135
136 static char *prune_directory(struct dir_struct *dir, struct pathspec *pathspec, int prefix)
137 {
138         char *seen;
139         int i;
140         struct dir_entry **src, **dst;
141
142         seen = xcalloc(pathspec->nr, 1);
143
144         src = dst = dir->entries;
145         i = dir->nr;
146         while (--i >= 0) {
147                 struct dir_entry *entry = *src++;
148                 if (dir_path_match(entry, pathspec, prefix, seen))
149                         *dst++ = entry;
150         }
151         dir->nr = dst - dir->entries;
152         add_pathspec_matches_against_index(pathspec, seen);
153         return seen;
154 }
155
156 static void refresh(int verbose, const struct pathspec *pathspec)
157 {
158         char *seen;
159         int i;
160
161         seen = xcalloc(pathspec->nr, 1);
162         refresh_index(&the_index, verbose ? REFRESH_IN_PORCELAIN : REFRESH_QUIET,
163                       pathspec, seen, _("Unstaged changes after refreshing the index:"));
164         for (i = 0; i < pathspec->nr; i++) {
165                 if (!seen[i])
166                         die(_("pathspec '%s' did not match any files"),
167                             pathspec->items[i].match);
168         }
169         free(seen);
170 }
171
172 int run_add_interactive(const char *revision, const char *patch_mode,
173                         const struct pathspec *pathspec)
174 {
175         int status, ac, i;
176         const char **args;
177
178         args = xcalloc(sizeof(const char *), (pathspec->nr + 6));
179         ac = 0;
180         args[ac++] = "add--interactive";
181         if (patch_mode)
182                 args[ac++] = patch_mode;
183         if (revision)
184                 args[ac++] = revision;
185         args[ac++] = "--";
186         for (i = 0; i < pathspec->nr; i++)
187                 /* pass original pathspec, to be re-parsed */
188                 args[ac++] = pathspec->items[i].original;
189
190         status = run_command_v_opt(args, RUN_GIT_CMD);
191         free(args);
192         return status;
193 }
194
195 int interactive_add(int argc, const char **argv, const char *prefix, int patch)
196 {
197         struct pathspec pathspec;
198
199         parse_pathspec(&pathspec, 0,
200                        PATHSPEC_PREFER_FULL |
201                        PATHSPEC_SYMLINK_LEADING_PATH |
202                        PATHSPEC_PREFIX_ORIGIN,
203                        prefix, argv);
204
205         return run_add_interactive(NULL,
206                                    patch ? "--patch" : NULL,
207                                    &pathspec);
208 }
209
210 static int edit_patch(int argc, const char **argv, const char *prefix)
211 {
212         char *file = git_pathdup("ADD_EDIT.patch");
213         const char *apply_argv[] = { "apply", "--recount", "--cached",
214                 NULL, NULL };
215         struct child_process child;
216         struct rev_info rev;
217         int out;
218         struct stat st;
219
220         apply_argv[3] = file;
221
222         git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
223
224         if (read_cache() < 0)
225                 die(_("Could not read the index"));
226
227         init_revisions(&rev, prefix);
228         rev.diffopt.context = 7;
229
230         argc = setup_revisions(argc, argv, &rev, NULL);
231         rev.diffopt.output_format = DIFF_FORMAT_PATCH;
232         rev.diffopt.use_color = 0;
233         DIFF_OPT_SET(&rev.diffopt, IGNORE_DIRTY_SUBMODULES);
234         out = open(file, O_CREAT | O_WRONLY, 0666);
235         if (out < 0)
236                 die(_("Could not open '%s' for writing."), file);
237         rev.diffopt.file = xfdopen(out, "w");
238         rev.diffopt.close_file = 1;
239         if (run_diff_files(&rev, 0))
240                 die(_("Could not write patch"));
241
242         launch_editor(file, NULL, NULL);
243
244         if (stat(file, &st))
245                 die_errno(_("Could not stat '%s'"), file);
246         if (!st.st_size)
247                 die(_("Empty patch. Aborted."));
248
249         memset(&child, 0, sizeof(child));
250         child.git_cmd = 1;
251         child.argv = apply_argv;
252         if (run_command(&child))
253                 die(_("Could not apply '%s'"), file);
254
255         unlink(file);
256         free(file);
257         return 0;
258 }
259
260 static struct lock_file lock_file;
261
262 static const char ignore_error[] =
263 N_("The following paths are ignored by one of your .gitignore files:\n");
264
265 static int verbose, show_only, ignored_too, refresh_only;
266 static int ignore_add_errors, intent_to_add, ignore_missing;
267
268 #define ADDREMOVE_DEFAULT 0 /* Change to 1 in Git 2.0 */
269 static int addremove = ADDREMOVE_DEFAULT;
270 static int addremove_explicit = -1; /* unspecified */
271
272 static int ignore_removal_cb(const struct option *opt, const char *arg, int unset)
273 {
274         /* if we are told to ignore, we are not adding removals */
275         *(int *)opt->value = !unset ? 0 : 1;
276         return 0;
277 }
278
279 static struct option builtin_add_options[] = {
280         OPT__DRY_RUN(&show_only, N_("dry run")),
281         OPT__VERBOSE(&verbose, N_("be verbose")),
282         OPT_GROUP(""),
283         OPT_BOOL('i', "interactive", &add_interactive, N_("interactive picking")),
284         OPT_BOOL('p', "patch", &patch_interactive, N_("select hunks interactively")),
285         OPT_BOOL('e', "edit", &edit_interactive, N_("edit current diff and apply")),
286         OPT__FORCE(&ignored_too, N_("allow adding otherwise ignored files")),
287         OPT_BOOL('u', "update", &take_worktree_changes, N_("update tracked files")),
288         OPT_BOOL('N', "intent-to-add", &intent_to_add, N_("record only the fact that the path will be added later")),
289         OPT_BOOL('A', "all", &addremove_explicit, N_("add changes from all tracked and untracked files")),
290         { OPTION_CALLBACK, 0, "ignore-removal", &addremove_explicit,
291           NULL /* takes no arguments */,
292           N_("ignore paths removed in the working tree (same as --no-all)"),
293           PARSE_OPT_NOARG, ignore_removal_cb },
294         OPT_BOOL( 0 , "refresh", &refresh_only, N_("don't add, only refresh the index")),
295         OPT_BOOL( 0 , "ignore-errors", &ignore_add_errors, N_("just skip files which cannot be added because of errors")),
296         OPT_BOOL( 0 , "ignore-missing", &ignore_missing, N_("check if - even missing - files are ignored in dry run")),
297         OPT_END(),
298 };
299
300 static int add_config(const char *var, const char *value, void *cb)
301 {
302         if (!strcmp(var, "add.ignoreerrors") ||
303             !strcmp(var, "add.ignore-errors")) {
304                 ignore_add_errors = git_config_bool(var, value);
305                 return 0;
306         }
307         return git_default_config(var, value, cb);
308 }
309
310 static int add_files(struct dir_struct *dir, int flags)
311 {
312         int i, exit_status = 0;
313
314         if (dir->ignored_nr) {
315                 fprintf(stderr, _(ignore_error));
316                 for (i = 0; i < dir->ignored_nr; i++)
317                         fprintf(stderr, "%s\n", dir->ignored[i]->name);
318                 fprintf(stderr, _("Use -f if you really want to add them.\n"));
319                 die(_("no files added"));
320         }
321
322         for (i = 0; i < dir->nr; i++)
323                 if (add_file_to_cache(dir->entries[i]->name, flags)) {
324                         if (!ignore_add_errors)
325                                 die(_("adding files failed"));
326                         exit_status = 1;
327                 }
328         return exit_status;
329 }
330
331 int cmd_add(int argc, const char **argv, const char *prefix)
332 {
333         int exit_status = 0;
334         int newfd;
335         struct pathspec pathspec;
336         struct dir_struct dir;
337         int flags;
338         int add_new_files;
339         int require_pathspec;
340         char *seen = NULL;
341         struct update_callback_data update_data;
342
343         git_config(add_config, NULL);
344
345         argc = parse_options(argc, argv, prefix, builtin_add_options,
346                           builtin_add_usage, PARSE_OPT_KEEP_ARGV0);
347         if (patch_interactive)
348                 add_interactive = 1;
349         if (add_interactive)
350                 exit(interactive_add(argc - 1, argv + 1, prefix, patch_interactive));
351
352         if (edit_interactive)
353                 return(edit_patch(argc, argv, prefix));
354         argc--;
355         argv++;
356
357         if (0 <= addremove_explicit)
358                 addremove = addremove_explicit;
359         else if (take_worktree_changes && ADDREMOVE_DEFAULT)
360                 addremove = 0; /* "-u" was given but not "-A" */
361
362         if (addremove && take_worktree_changes)
363                 die(_("-A and -u are mutually incompatible"));
364
365         /*
366          * Warn when "git add pathspec..." was given without "-u" or "-A"
367          * and pathspec... covers a removed path.
368          */
369         memset(&update_data, 0, sizeof(update_data));
370         if (!take_worktree_changes && addremove_explicit < 0)
371                 update_data.warn_add_would_remove = 1;
372
373         if (!take_worktree_changes && addremove_explicit < 0 && argc)
374                 /*
375                  * Turn "git add pathspec..." to "git add -A pathspec..."
376                  * in Git 2.0 but not yet
377                  */
378                 ; /* addremove = 1; */
379
380         if (!show_only && ignore_missing)
381                 die(_("Option --ignore-missing can only be used together with --dry-run"));
382
383         if ((addremove || take_worktree_changes) && !argc) {
384                 static const char *whole[2] = { ":/", NULL };
385                 argc = 1;
386                 argv = whole;
387         }
388
389         add_new_files = !take_worktree_changes && !refresh_only;
390         require_pathspec = !take_worktree_changes;
391
392         newfd = hold_locked_index(&lock_file, 1);
393
394         flags = ((verbose ? ADD_CACHE_VERBOSE : 0) |
395                  (show_only ? ADD_CACHE_PRETEND : 0) |
396                  (intent_to_add ? ADD_CACHE_INTENT : 0) |
397                  (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) |
398                  (!(addremove || take_worktree_changes)
399                   ? ADD_CACHE_IGNORE_REMOVAL : 0));
400
401         if (require_pathspec && argc == 0) {
402                 fprintf(stderr, _("Nothing specified, nothing added.\n"));
403                 fprintf(stderr, _("Maybe you wanted to say 'git add .'?\n"));
404                 return 0;
405         }
406
407         if (read_cache() < 0)
408                 die(_("index file corrupt"));
409
410         /*
411          * Check the "pathspec '%s' did not match any files" block
412          * below before enabling new magic.
413          */
414         parse_pathspec(&pathspec, 0,
415                        PATHSPEC_PREFER_FULL |
416                        PATHSPEC_SYMLINK_LEADING_PATH |
417                        PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE,
418                        prefix, argv);
419
420         if (add_new_files) {
421                 int baselen;
422
423                 /* Set up the default git porcelain excludes */
424                 memset(&dir, 0, sizeof(dir));
425                 if (!ignored_too) {
426                         dir.flags |= DIR_COLLECT_IGNORED;
427                         setup_standard_excludes(&dir);
428                 }
429
430                 /* This picks up the paths that are not tracked */
431                 baselen = fill_directory(&dir, &pathspec);
432                 if (pathspec.nr)
433                         seen = prune_directory(&dir, &pathspec, baselen);
434         }
435
436         if (refresh_only) {
437                 refresh(verbose, &pathspec);
438                 goto finish;
439         }
440
441         if (pathspec.nr) {
442                 int i;
443
444                 if (!seen)
445                         seen = find_pathspecs_matching_against_index(&pathspec);
446
447                 /*
448                  * file_exists() assumes exact match
449                  */
450                 GUARD_PATHSPEC(&pathspec,
451                                PATHSPEC_FROMTOP |
452                                PATHSPEC_LITERAL |
453                                PATHSPEC_GLOB |
454                                PATHSPEC_ICASE |
455                                PATHSPEC_EXCLUDE);
456
457                 for (i = 0; i < pathspec.nr; i++) {
458                         const char *path = pathspec.items[i].match;
459                         if (pathspec.items[i].magic & PATHSPEC_EXCLUDE)
460                                 continue;
461                         if (!seen[i] && path[0] &&
462                             ((pathspec.items[i].magic &
463                               (PATHSPEC_GLOB | PATHSPEC_ICASE)) ||
464                              !file_exists(path))) {
465                                 if (ignore_missing) {
466                                         int dtype = DT_UNKNOWN;
467                                         if (is_excluded(&dir, path, &dtype))
468                                                 dir_add_ignored(&dir, path, pathspec.items[i].len);
469                                 } else
470                                         die(_("pathspec '%s' did not match any files"),
471                                             pathspec.items[i].original);
472                         }
473                 }
474                 free(seen);
475         }
476
477         plug_bulk_checkin();
478
479         update_data.flags = flags;
480         update_files_in_cache(prefix, &pathspec, &update_data);
481
482         exit_status |= !!update_data.add_errors;
483         if (add_new_files)
484                 exit_status |= add_files(&dir, flags);
485
486         unplug_bulk_checkin();
487
488 finish:
489         if (active_cache_changed) {
490                 if (write_cache(newfd, active_cache, active_nr) ||
491                     commit_locked_index(&lock_file))
492                         die(_("Unable to write new index file"));
493         }
494
495         return exit_status;
496 }