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
19static const char * const builtin_add_usage[] = {
20 N_("git add [options] [--] <pathspec>..."),
21 NULL
22};
23static int patch_interactive, add_interactive, edit_interactive;
24static int take_worktree_changes;
25
26struct 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
33static 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
54static 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
67static void warn_add_would_remove(const char *path)
68{
69 warning(_(add_would_remove_warning), path);
70}
71
72static 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
108static void update_files_in_cache(const char *prefix, const char **pathspec,
109 struct update_callback_data *data)
110{
111 struct rev_info rev;
112
113 init_revisions(&rev, prefix);
114 setup_revisions(0, NULL, &rev, NULL);
115 init_pathspec(&rev.prune_data, pathspec);
116 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
117 rev.diffopt.format_callback = update_callback;
118 rev.diffopt.format_callback_data = data;
119 rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
120 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
121}
122
123int add_files_to_cache(const char *prefix, const char **pathspec, int flags)
124{
125 struct update_callback_data data;
126
127 memset(&data, 0, sizeof(data));
128 data.flags = flags;
129 update_files_in_cache(prefix, pathspec, &data);
130 return !!data.add_errors;
131}
132
133static char *prune_directory(struct dir_struct *dir, const char **pathspec, int prefix)
134{
135 char *seen;
136 int i, specs;
137 struct dir_entry **src, **dst;
138
139 for (specs = 0; pathspec[specs]; specs++)
140 /* nothing */;
141 seen = xcalloc(specs, 1);
142
143 src = dst = dir->entries;
144 i = dir->nr;
145 while (--i >= 0) {
146 struct dir_entry *entry = *src++;
147 if (match_pathspec(pathspec, entry->name, entry->len,
148 prefix, seen))
149 *dst++ = entry;
150 }
151 dir->nr = dst - dir->entries;
152 add_pathspec_matches_against_index(pathspec, seen, specs);
153 return seen;
154}
155
156/*
157 * Checks the index to see whether any path in pathspec refers to
158 * something inside a submodule. If so, dies with an error message.
159 */
160static void treat_gitlinks(const char **pathspec)
161{
162 int i;
163
164 if (!pathspec || !*pathspec)
165 return;
166
167 for (i = 0; pathspec[i]; i++)
168 pathspec[i] = check_path_for_gitlink(pathspec[i]);
169}
170
171static void refresh(int verbose, const char **pathspec)
172{
173 char *seen;
174 int i, specs;
175
176 for (specs = 0; pathspec[specs]; specs++)
177 /* nothing */;
178 seen = xcalloc(specs, 1);
179 refresh_index(&the_index, verbose ? REFRESH_IN_PORCELAIN : REFRESH_QUIET,
180 pathspec, seen, _("Unstaged changes after refreshing the index:"));
181 for (i = 0; i < specs; i++) {
182 if (!seen[i])
183 die(_("pathspec '%s' did not match any files"), pathspec[i]);
184 }
185 free(seen);
186}
187
188/*
189 * Normalizes argv relative to prefix, via get_pathspec(), and then
190 * runs die_if_path_beyond_symlink() on each path in the normalized
191 * list.
192 */
193static const char **validate_pathspec(const char **argv, const char *prefix)
194{
195 const char **pathspec = get_pathspec(prefix, argv);
196
197 if (pathspec) {
198 const char **p;
199 for (p = pathspec; *p; p++) {
200 die_if_path_beyond_symlink(*p, prefix);
201 }
202 }
203
204 return pathspec;
205}
206
207int run_add_interactive(const char *revision, const char *patch_mode,
208 const char **pathspec)
209{
210 int status, ac, pc = 0;
211 const char **args;
212
213 if (pathspec)
214 while (pathspec[pc])
215 pc++;
216
217 args = xcalloc(sizeof(const char *), (pc + 5));
218 ac = 0;
219 args[ac++] = "add--interactive";
220 if (patch_mode)
221 args[ac++] = patch_mode;
222 if (revision)
223 args[ac++] = revision;
224 args[ac++] = "--";
225 if (pc) {
226 memcpy(&(args[ac]), pathspec, sizeof(const char *) * pc);
227 ac += pc;
228 }
229 args[ac] = NULL;
230
231 status = run_command_v_opt(args, RUN_GIT_CMD);
232 free(args);
233 return status;
234}
235
236int interactive_add(int argc, const char **argv, const char *prefix, int patch)
237{
238 const char **pathspec = NULL;
239
240 if (argc) {
241 pathspec = validate_pathspec(argv, prefix);
242 if (!pathspec)
243 return -1;
244 }
245
246 return run_add_interactive(NULL,
247 patch ? "--patch" : NULL,
248 pathspec);
249}
250
251static int edit_patch(int argc, const char **argv, const char *prefix)
252{
253 char *file = git_pathdup("ADD_EDIT.patch");
254 const char *apply_argv[] = { "apply", "--recount", "--cached",
255 NULL, NULL };
256 struct child_process child;
257 struct rev_info rev;
258 int out;
259 struct stat st;
260
261 apply_argv[3] = file;
262
263 git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
264
265 if (read_cache() < 0)
266 die (_("Could not read the index"));
267
268 init_revisions(&rev, prefix);
269 rev.diffopt.context = 7;
270
271 argc = setup_revisions(argc, argv, &rev, NULL);
272 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
273 DIFF_OPT_SET(&rev.diffopt, IGNORE_DIRTY_SUBMODULES);
274 out = open(file, O_CREAT | O_WRONLY, 0666);
275 if (out < 0)
276 die (_("Could not open '%s' for writing."), file);
277 rev.diffopt.file = xfdopen(out, "w");
278 rev.diffopt.close_file = 1;
279 if (run_diff_files(&rev, 0))
280 die (_("Could not write patch"));
281
282 launch_editor(file, NULL, NULL);
283
284 if (stat(file, &st))
285 die_errno(_("Could not stat '%s'"), file);
286 if (!st.st_size)
287 die(_("Empty patch. Aborted."));
288
289 memset(&child, 0, sizeof(child));
290 child.git_cmd = 1;
291 child.argv = apply_argv;
292 if (run_command(&child))
293 die (_("Could not apply '%s'"), file);
294
295 unlink(file);
296 free(file);
297 return 0;
298}
299
300static struct lock_file lock_file;
301
302static const char ignore_error[] =
303N_("The following paths are ignored by one of your .gitignore files:\n");
304
305static int verbose, show_only, ignored_too, refresh_only;
306static int ignore_add_errors, intent_to_add, ignore_missing;
307
308#define ADDREMOVE_DEFAULT 0 /* Change to 1 in Git 2.0 */
309static int addremove = ADDREMOVE_DEFAULT;
310static int addremove_explicit = -1; /* unspecified */
311
312static int ignore_removal_cb(const struct option *opt, const char *arg, int unset)
313{
314 /* if we are told to ignore, we are not adding removals */
315 *(int *)opt->value = !unset ? 0 : 1;
316 return 0;
317}
318
319static struct option builtin_add_options[] = {
320 OPT__DRY_RUN(&show_only, N_("dry run")),
321 OPT__VERBOSE(&verbose, N_("be verbose")),
322 OPT_GROUP(""),
323 OPT_BOOL('i', "interactive", &add_interactive, N_("interactive picking")),
324 OPT_BOOL('p', "patch", &patch_interactive, N_("select hunks interactively")),
325 OPT_BOOL('e', "edit", &edit_interactive, N_("edit current diff and apply")),
326 OPT__FORCE(&ignored_too, N_("allow adding otherwise ignored files")),
327 OPT_BOOL('u', "update", &take_worktree_changes, N_("update tracked files")),
328 OPT_BOOL('N', "intent-to-add", &intent_to_add, N_("record only the fact that the path will be added later")),
329 OPT_BOOL('A', "all", &addremove_explicit, N_("add changes from all tracked and untracked files")),
330 { OPTION_CALLBACK, 0, "ignore-removal", &addremove_explicit,
331 NULL /* takes no arguments */,
332 N_("ignore paths removed in the working tree (same as --no-all)"),
333 PARSE_OPT_NOARG, ignore_removal_cb },
334 OPT_BOOL( 0 , "refresh", &refresh_only, N_("don't add, only refresh the index")),
335 OPT_BOOL( 0 , "ignore-errors", &ignore_add_errors, N_("just skip files which cannot be added because of errors")),
336 OPT_BOOL( 0 , "ignore-missing", &ignore_missing, N_("check if - even missing - files are ignored in dry run")),
337 OPT_END(),
338};
339
340static int add_config(const char *var, const char *value, void *cb)
341{
342 if (!strcmp(var, "add.ignoreerrors") ||
343 !strcmp(var, "add.ignore-errors")) {
344 ignore_add_errors = git_config_bool(var, value);
345 return 0;
346 }
347 return git_default_config(var, value, cb);
348}
349
350static int add_files(struct dir_struct *dir, int flags)
351{
352 int i, exit_status = 0;
353
354 if (dir->ignored_nr) {
355 fprintf(stderr, _(ignore_error));
356 for (i = 0; i < dir->ignored_nr; i++)
357 fprintf(stderr, "%s\n", dir->ignored[i]->name);
358 fprintf(stderr, _("Use -f if you really want to add them.\n"));
359 die(_("no files added"));
360 }
361
362 for (i = 0; i < dir->nr; i++)
363 if (add_file_to_cache(dir->entries[i]->name, flags)) {
364 if (!ignore_add_errors)
365 die(_("adding files failed"));
366 exit_status = 1;
367 }
368 return exit_status;
369}
370
371int cmd_add(int argc, const char **argv, const char *prefix)
372{
373 int exit_status = 0;
374 int newfd;
375 const char **pathspec;
376 struct dir_struct dir;
377 int flags;
378 int add_new_files;
379 int require_pathspec;
380 char *seen = NULL;
381 struct update_callback_data update_data;
382
383 git_config(add_config, NULL);
384
385 argc = parse_options(argc, argv, prefix, builtin_add_options,
386 builtin_add_usage, PARSE_OPT_KEEP_ARGV0);
387 if (patch_interactive)
388 add_interactive = 1;
389 if (add_interactive)
390 exit(interactive_add(argc - 1, argv + 1, prefix, patch_interactive));
391
392 if (edit_interactive)
393 return(edit_patch(argc, argv, prefix));
394 argc--;
395 argv++;
396
397 if (0 <= addremove_explicit)
398 addremove = addremove_explicit;
399 else if (take_worktree_changes && ADDREMOVE_DEFAULT)
400 addremove = 0; /* "-u" was given but not "-A" */
401
402 if (addremove && take_worktree_changes)
403 die(_("-A and -u are mutually incompatible"));
404
405 /*
406 * Warn when "git add pathspec..." was given without "-u" or "-A"
407 * and pathspec... covers a removed path.
408 */
409 memset(&update_data, 0, sizeof(update_data));
410 if (!take_worktree_changes && addremove_explicit < 0)
411 update_data.warn_add_would_remove = 1;
412
413 if (!take_worktree_changes && addremove_explicit < 0 && argc)
414 /*
415 * Turn "git add pathspec..." to "git add -A pathspec..."
416 * in Git 2.0 but not yet
417 */
418 ; /* addremove = 1; */
419
420 if (!show_only && ignore_missing)
421 die(_("Option --ignore-missing can only be used together with --dry-run"));
422
423 if ((addremove || take_worktree_changes) && !argc) {
424 static const char *whole[2] = { ":/", NULL };
425 argc = 1;
426 argv = whole;
427 }
428
429 add_new_files = !take_worktree_changes && !refresh_only;
430 require_pathspec = !take_worktree_changes;
431
432 newfd = hold_locked_index(&lock_file, 1);
433
434 flags = ((verbose ? ADD_CACHE_VERBOSE : 0) |
435 (show_only ? ADD_CACHE_PRETEND : 0) |
436 (intent_to_add ? ADD_CACHE_INTENT : 0) |
437 (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) |
438 (!(addremove || take_worktree_changes)
439 ? ADD_CACHE_IGNORE_REMOVAL : 0));
440
441 if (require_pathspec && argc == 0) {
442 fprintf(stderr, _("Nothing specified, nothing added.\n"));
443 fprintf(stderr, _("Maybe you wanted to say 'git add .'?\n"));
444 return 0;
445 }
446 pathspec = validate_pathspec(argv, prefix);
447
448 if (read_cache() < 0)
449 die(_("index file corrupt"));
450 treat_gitlinks(pathspec);
451
452 if (add_new_files) {
453 int baselen;
454
455 /* Set up the default git porcelain excludes */
456 memset(&dir, 0, sizeof(dir));
457 if (!ignored_too) {
458 dir.flags |= DIR_COLLECT_IGNORED;
459 setup_standard_excludes(&dir);
460 }
461
462 /* This picks up the paths that are not tracked */
463 baselen = fill_directory(&dir, pathspec);
464 if (pathspec)
465 seen = prune_directory(&dir, pathspec, baselen);
466 }
467
468 if (refresh_only) {
469 refresh(verbose, pathspec);
470 goto finish;
471 }
472
473 if (pathspec) {
474 int i;
475
476 if (!seen)
477 seen = find_pathspecs_matching_against_index(pathspec);
478 for (i = 0; pathspec[i]; i++) {
479 if (!seen[i] && pathspec[i][0]
480 && !file_exists(pathspec[i])) {
481 if (ignore_missing) {
482 int dtype = DT_UNKNOWN;
483 if (is_excluded(&dir, pathspec[i], &dtype))
484 dir_add_ignored(&dir, pathspec[i], strlen(pathspec[i]));
485 } else
486 die(_("pathspec '%s' did not match any files"),
487 pathspec[i]);
488 }
489 }
490 free(seen);
491 }
492
493 plug_bulk_checkin();
494
495 update_data.flags = flags;
496 update_files_in_cache(prefix, pathspec, &update_data);
497
498 exit_status |= !!update_data.add_errors;
499 if (add_new_files)
500 exit_status |= add_files(&dir, flags);
501
502 unplug_bulk_checkin();
503
504 finish:
505 if (active_cache_changed) {
506 if (write_cache(newfd, active_cache, active_nr) ||
507 commit_locked_index(&lock_file))
508 die(_("Unable to write new index file"));
509 }
510
511 return exit_status;
512}