1 /*
2  * "git add" builtin command
3  *
4  * Copyright (C) 2006 Linus Torvalds
5  */
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
7 #include "cache.h"
8 #include "config.h"
9 #include "builtin.h"
10 #include "lockfile.h"
11 #include "dir.h"
12 #include "pathspec.h"
13 #include "exec-cmd.h"
14 #include "cache-tree.h"
15 #include "run-command.h"
16 #include "parse-options.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "revision.h"
20 #include "bulk-checkin.h"
21 #include "strvec.h"
22 #include "submodule.h"
23 #include "add-interactive.h"
24 
25 static const char * const builtin_add_usage[] = {
26 	N_("git add [<options>] [--] <pathspec>..."),
27 	NULL
28 };
29 static int patch_interactive, add_interactive, edit_interactive;
30 static int take_worktree_changes;
31 static int add_renormalize;
32 static int pathspec_file_nul;
33 static int include_sparse;
34 static const char *pathspec_from_file;
35 static int legacy_stash_p; /* support for the scripted `git stash` */
36 
37 struct update_callback_data {
38 	int flags;
39 	int add_errors;
40 };
41 
chmod_pathspec(struct pathspec * pathspec,char flip,int show_only)42 static int chmod_pathspec(struct pathspec *pathspec, char flip, int show_only)
43 {
44 	int i, ret = 0;
45 
46 	for (i = 0; i < active_nr; i++) {
47 		struct cache_entry *ce = active_cache[i];
48 		int err;
49 
50 		if (!include_sparse &&
51 		    (ce_skip_worktree(ce) ||
52 		     !path_in_sparse_checkout(ce->name, &the_index)))
53 			continue;
54 
55 		if (pathspec && !ce_path_match(&the_index, ce, pathspec, NULL))
56 			continue;
57 
58 		if (!show_only)
59 			err = chmod_cache_entry(ce, flip);
60 		else
61 			err = S_ISREG(ce->ce_mode) ? 0 : -1;
62 
63 		if (err < 0)
64 			ret = error(_("cannot chmod %cx '%s'"), flip, ce->name);
65 	}
66 
67 	return ret;
68 }
69 
fix_unmerged_status(struct diff_filepair * p,struct update_callback_data * data)70 static int fix_unmerged_status(struct diff_filepair *p,
71 			       struct update_callback_data *data)
72 {
73 	if (p->status != DIFF_STATUS_UNMERGED)
74 		return p->status;
75 	if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
76 		/*
77 		 * This is not an explicit add request, and the
78 		 * path is missing from the working tree (deleted)
79 		 */
80 		return DIFF_STATUS_DELETED;
81 	else
82 		/*
83 		 * Either an explicit add request, or path exists
84 		 * in the working tree.  An attempt to explicitly
85 		 * add a path that does not exist in the working tree
86 		 * will be caught as an error by the caller immediately.
87 		 */
88 		return DIFF_STATUS_MODIFIED;
89 }
90 
update_callback(struct diff_queue_struct * q,struct diff_options * opt,void * cbdata)91 static void update_callback(struct diff_queue_struct *q,
92 			    struct diff_options *opt, void *cbdata)
93 {
94 	int i;
95 	struct update_callback_data *data = cbdata;
96 
97 	for (i = 0; i < q->nr; i++) {
98 		struct diff_filepair *p = q->queue[i];
99 		const char *path = p->one->path;
100 
101 		if (!include_sparse && !path_in_sparse_checkout(path, &the_index))
102 			continue;
103 
104 		switch (fix_unmerged_status(p, data)) {
105 		default:
106 			die(_("unexpected diff status %c"), p->status);
107 		case DIFF_STATUS_MODIFIED:
108 		case DIFF_STATUS_TYPE_CHANGED:
109 			if (add_file_to_index(&the_index, path,	data->flags)) {
110 				if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
111 					die(_("updating files failed"));
112 				data->add_errors++;
113 			}
114 			break;
115 		case DIFF_STATUS_DELETED:
116 			if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
117 				break;
118 			if (!(data->flags & ADD_CACHE_PRETEND))
119 				remove_file_from_index(&the_index, path);
120 			if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
121 				printf(_("remove '%s'\n"), path);
122 			break;
123 		}
124 	}
125 }
126 
add_files_to_cache(const char * prefix,const struct pathspec * pathspec,int flags)127 int add_files_to_cache(const char *prefix,
128 		       const struct pathspec *pathspec, int flags)
129 {
130 	struct update_callback_data data;
131 	struct rev_info rev;
132 
133 	memset(&data, 0, sizeof(data));
134 	data.flags = flags;
135 
136 	repo_init_revisions(the_repository, &rev, prefix);
137 	setup_revisions(0, NULL, &rev, NULL);
138 	if (pathspec)
139 		copy_pathspec(&rev.prune_data, pathspec);
140 	rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
141 	rev.diffopt.format_callback = update_callback;
142 	rev.diffopt.format_callback_data = &data;
143 	rev.diffopt.flags.override_submodule_config = 1;
144 	rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
145 	run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
146 	clear_pathspec(&rev.prune_data);
147 	return !!data.add_errors;
148 }
149 
renormalize_tracked_files(const struct pathspec * pathspec,int flags)150 static int renormalize_tracked_files(const struct pathspec *pathspec, int flags)
151 {
152 	int i, retval = 0;
153 
154 	for (i = 0; i < active_nr; i++) {
155 		struct cache_entry *ce = active_cache[i];
156 
157 		if (!include_sparse &&
158 		    (ce_skip_worktree(ce) ||
159 		     !path_in_sparse_checkout(ce->name, &the_index)))
160 			continue;
161 		if (ce_stage(ce))
162 			continue; /* do not touch unmerged paths */
163 		if (!S_ISREG(ce->ce_mode) && !S_ISLNK(ce->ce_mode))
164 			continue; /* do not touch non blobs */
165 		if (pathspec && !ce_path_match(&the_index, ce, pathspec, NULL))
166 			continue;
167 		retval |= add_file_to_cache(ce->name, flags | ADD_CACHE_RENORMALIZE);
168 	}
169 
170 	return retval;
171 }
172 
prune_directory(struct dir_struct * dir,struct pathspec * pathspec,int prefix)173 static char *prune_directory(struct dir_struct *dir, struct pathspec *pathspec, int prefix)
174 {
175 	char *seen;
176 	int i;
177 	struct dir_entry **src, **dst;
178 
179 	seen = xcalloc(pathspec->nr, 1);
180 
181 	src = dst = dir->entries;
182 	i = dir->nr;
183 	while (--i >= 0) {
184 		struct dir_entry *entry = *src++;
185 		if (dir_path_match(&the_index, entry, pathspec, prefix, seen))
186 			*dst++ = entry;
187 	}
188 	dir->nr = dst - dir->entries;
189 	add_pathspec_matches_against_index(pathspec, &the_index, seen,
190 					   PS_IGNORE_SKIP_WORKTREE);
191 	return seen;
192 }
193 
refresh(int verbose,const struct pathspec * pathspec)194 static int refresh(int verbose, const struct pathspec *pathspec)
195 {
196 	char *seen;
197 	int i, ret = 0;
198 	char *skip_worktree_seen = NULL;
199 	struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
200 	int flags = REFRESH_IGNORE_SKIP_WORKTREE |
201 		    (verbose ? REFRESH_IN_PORCELAIN : REFRESH_QUIET);
202 
203 	seen = xcalloc(pathspec->nr, 1);
204 	refresh_index(&the_index, flags, pathspec, seen,
205 		      _("Unstaged changes after refreshing the index:"));
206 	for (i = 0; i < pathspec->nr; i++) {
207 		if (!seen[i]) {
208 			const char *path = pathspec->items[i].original;
209 
210 			if (matches_skip_worktree(pathspec, i, &skip_worktree_seen) ||
211 			    !path_in_sparse_checkout(path, &the_index)) {
212 				string_list_append(&only_match_skip_worktree,
213 						   pathspec->items[i].original);
214 			} else {
215 				die(_("pathspec '%s' did not match any files"),
216 				    pathspec->items[i].original);
217 			}
218 		}
219 	}
220 
221 	if (only_match_skip_worktree.nr) {
222 		advise_on_updating_sparse_paths(&only_match_skip_worktree);
223 		ret = 1;
224 	}
225 
226 	free(seen);
227 	free(skip_worktree_seen);
228 	string_list_clear(&only_match_skip_worktree, 0);
229 	return ret;
230 }
231 
run_add_interactive(const char * revision,const char * patch_mode,const struct pathspec * pathspec)232 int run_add_interactive(const char *revision, const char *patch_mode,
233 			const struct pathspec *pathspec)
234 {
235 	int status, i;
236 	struct strvec argv = STRVEC_INIT;
237 	int use_builtin_add_i =
238 		git_env_bool("GIT_TEST_ADD_I_USE_BUILTIN", -1);
239 
240 	if (use_builtin_add_i < 0) {
241 		int experimental;
242 		if (!git_config_get_bool("add.interactive.usebuiltin",
243 					 &use_builtin_add_i))
244 			; /* ok */
245 		else if (!git_config_get_bool("feature.experimental", &experimental) &&
246 			 experimental)
247 			use_builtin_add_i = 1;
248 	}
249 
250 	if (use_builtin_add_i == 1) {
251 		enum add_p_mode mode;
252 
253 		if (!patch_mode)
254 			return !!run_add_i(the_repository, pathspec);
255 
256 		if (!strcmp(patch_mode, "--patch"))
257 			mode = ADD_P_ADD;
258 		else if (!strcmp(patch_mode, "--patch=stash"))
259 			mode = ADD_P_STASH;
260 		else if (!strcmp(patch_mode, "--patch=reset"))
261 			mode = ADD_P_RESET;
262 		else if (!strcmp(patch_mode, "--patch=checkout"))
263 			mode = ADD_P_CHECKOUT;
264 		else if (!strcmp(patch_mode, "--patch=worktree"))
265 			mode = ADD_P_WORKTREE;
266 		else
267 			die("'%s' not supported", patch_mode);
268 
269 		return !!run_add_p(the_repository, mode, revision, pathspec);
270 	}
271 
272 	strvec_push(&argv, "add--interactive");
273 	if (patch_mode)
274 		strvec_push(&argv, patch_mode);
275 	if (revision)
276 		strvec_push(&argv, revision);
277 	strvec_push(&argv, "--");
278 	for (i = 0; i < pathspec->nr; i++)
279 		/* pass original pathspec, to be re-parsed */
280 		strvec_push(&argv, pathspec->items[i].original);
281 
282 	status = run_command_v_opt(argv.v, RUN_GIT_CMD);
283 	strvec_clear(&argv);
284 	return status;
285 }
286 
interactive_add(const char ** argv,const char * prefix,int patch)287 int interactive_add(const char **argv, const char *prefix, int patch)
288 {
289 	struct pathspec pathspec;
290 
291 	parse_pathspec(&pathspec, 0,
292 		       PATHSPEC_PREFER_FULL |
293 		       PATHSPEC_SYMLINK_LEADING_PATH |
294 		       PATHSPEC_PREFIX_ORIGIN,
295 		       prefix, argv);
296 
297 	return run_add_interactive(NULL,
298 				   patch ? "--patch" : NULL,
299 				   &pathspec);
300 }
301 
edit_patch(int argc,const char ** argv,const char * prefix)302 static int edit_patch(int argc, const char **argv, const char *prefix)
303 {
304 	char *file = git_pathdup("ADD_EDIT.patch");
305 	const char *apply_argv[] = { "apply", "--recount", "--cached",
306 		NULL, NULL };
307 	struct child_process child = CHILD_PROCESS_INIT;
308 	struct rev_info rev;
309 	int out;
310 	struct stat st;
311 
312 	apply_argv[3] = file;
313 
314 	git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
315 
316 	if (read_cache() < 0)
317 		die(_("Could not read the index"));
318 
319 	repo_init_revisions(the_repository, &rev, prefix);
320 	rev.diffopt.context = 7;
321 
322 	argc = setup_revisions(argc, argv, &rev, NULL);
323 	rev.diffopt.output_format = DIFF_FORMAT_PATCH;
324 	rev.diffopt.use_color = 0;
325 	rev.diffopt.flags.ignore_dirty_submodules = 1;
326 	out = xopen(file, O_CREAT | O_WRONLY | O_TRUNC, 0666);
327 	rev.diffopt.file = xfdopen(out, "w");
328 	rev.diffopt.close_file = 1;
329 	if (run_diff_files(&rev, 0))
330 		die(_("Could not write patch"));
331 
332 	if (launch_editor(file, NULL, NULL))
333 		die(_("editing patch failed"));
334 
335 	if (stat(file, &st))
336 		die_errno(_("Could not stat '%s'"), file);
337 	if (!st.st_size)
338 		die(_("Empty patch. Aborted."));
339 
340 	child.git_cmd = 1;
341 	child.argv = apply_argv;
342 	if (run_command(&child))
343 		die(_("Could not apply '%s'"), file);
344 
345 	unlink(file);
346 	free(file);
347 	return 0;
348 }
349 
350 static const char ignore_error[] =
351 N_("The following paths are ignored by one of your .gitignore files:\n");
352 
353 static int verbose, show_only, ignored_too, refresh_only;
354 static int ignore_add_errors, intent_to_add, ignore_missing;
355 static int warn_on_embedded_repo = 1;
356 
357 #define ADDREMOVE_DEFAULT 1
358 static int addremove = ADDREMOVE_DEFAULT;
359 static int addremove_explicit = -1; /* unspecified */
360 
361 static char *chmod_arg;
362 
ignore_removal_cb(const struct option * opt,const char * arg,int unset)363 static int ignore_removal_cb(const struct option *opt, const char *arg, int unset)
364 {
365 	/* if we are told to ignore, we are not adding removals */
366 	*(int *)opt->value = !unset ? 0 : 1;
367 	return 0;
368 }
369 
370 static struct option builtin_add_options[] = {
371 	OPT__DRY_RUN(&show_only, N_("dry run")),
372 	OPT__VERBOSE(&verbose, N_("be verbose")),
373 	OPT_GROUP(""),
374 	OPT_BOOL('i', "interactive", &add_interactive, N_("interactive picking")),
375 	OPT_BOOL('p', "patch", &patch_interactive, N_("select hunks interactively")),
376 	OPT_BOOL('e', "edit", &edit_interactive, N_("edit current diff and apply")),
377 	OPT__FORCE(&ignored_too, N_("allow adding otherwise ignored files"), 0),
378 	OPT_BOOL('u', "update", &take_worktree_changes, N_("update tracked files")),
379 	OPT_BOOL(0, "renormalize", &add_renormalize, N_("renormalize EOL of tracked files (implies -u)")),
380 	OPT_BOOL('N', "intent-to-add", &intent_to_add, N_("record only the fact that the path will be added later")),
381 	OPT_BOOL('A', "all", &addremove_explicit, N_("add changes from all tracked and untracked files")),
382 	OPT_CALLBACK_F(0, "ignore-removal", &addremove_explicit,
383 	  NULL /* takes no arguments */,
384 	  N_("ignore paths removed in the working tree (same as --no-all)"),
385 	  PARSE_OPT_NOARG, ignore_removal_cb),
386 	OPT_BOOL( 0 , "refresh", &refresh_only, N_("don't add, only refresh the index")),
387 	OPT_BOOL( 0 , "ignore-errors", &ignore_add_errors, N_("just skip files which cannot be added because of errors")),
388 	OPT_BOOL( 0 , "ignore-missing", &ignore_missing, N_("check if - even missing - files are ignored in dry run")),
389 	OPT_BOOL(0, "sparse", &include_sparse, N_("allow updating entries outside of the sparse-checkout cone")),
390 	OPT_STRING(0, "chmod", &chmod_arg, "(+|-)x",
391 		   N_("override the executable bit of the listed files")),
392 	OPT_HIDDEN_BOOL(0, "warn-embedded-repo", &warn_on_embedded_repo,
393 			N_("warn when adding an embedded repository")),
394 	OPT_HIDDEN_BOOL(0, "legacy-stash-p", &legacy_stash_p,
395 			N_("backend for `git stash -p`")),
396 	OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
397 	OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
398 	OPT_END(),
399 };
400 
add_config(const char * var,const char * value,void * cb)401 static int add_config(const char *var, const char *value, void *cb)
402 {
403 	if (!strcmp(var, "add.ignoreerrors") ||
404 	    !strcmp(var, "add.ignore-errors")) {
405 		ignore_add_errors = git_config_bool(var, value);
406 		return 0;
407 	}
408 
409 	return git_default_config(var, value, cb);
410 }
411 
412 static const char embedded_advice[] = N_(
413 "You've added another git repository inside your current repository.\n"
414 "Clones of the outer repository will not contain the contents of\n"
415 "the embedded repository and will not know how to obtain it.\n"
416 "If you meant to add a submodule, use:\n"
417 "\n"
418 "	git submodule add <url> %s\n"
419 "\n"
420 "If you added this path by mistake, you can remove it from the\n"
421 "index with:\n"
422 "\n"
423 "	git rm --cached %s\n"
424 "\n"
425 "See \"git help submodule\" for more information."
426 );
427 
check_embedded_repo(const char * path)428 static void check_embedded_repo(const char *path)
429 {
430 	struct strbuf name = STRBUF_INIT;
431 	static int adviced_on_embedded_repo = 0;
432 
433 	if (!warn_on_embedded_repo)
434 		return;
435 	if (!ends_with(path, "/"))
436 		return;
437 
438 	/* Drop trailing slash for aesthetics */
439 	strbuf_addstr(&name, path);
440 	strbuf_strip_suffix(&name, "/");
441 
442 	warning(_("adding embedded git repository: %s"), name.buf);
443 	if (!adviced_on_embedded_repo &&
444 	    advice_enabled(ADVICE_ADD_EMBEDDED_REPO)) {
445 		advise(embedded_advice, name.buf, name.buf);
446 		adviced_on_embedded_repo = 1;
447 	}
448 
449 	strbuf_release(&name);
450 }
451 
add_files(struct dir_struct * dir,int flags)452 static int add_files(struct dir_struct *dir, int flags)
453 {
454 	int i, exit_status = 0;
455 	struct string_list matched_sparse_paths = STRING_LIST_INIT_NODUP;
456 
457 	if (dir->ignored_nr) {
458 		fprintf(stderr, _(ignore_error));
459 		for (i = 0; i < dir->ignored_nr; i++)
460 			fprintf(stderr, "%s\n", dir->ignored[i]->name);
461 		if (advice_enabled(ADVICE_ADD_IGNORED_FILE))
462 			advise(_("Use -f if you really want to add them.\n"
463 				"Turn this message off by running\n"
464 				"\"git config advice.addIgnoredFile false\""));
465 		exit_status = 1;
466 	}
467 
468 	for (i = 0; i < dir->nr; i++) {
469 		if (!include_sparse &&
470 		    !path_in_sparse_checkout(dir->entries[i]->name, &the_index)) {
471 			string_list_append(&matched_sparse_paths,
472 					   dir->entries[i]->name);
473 			continue;
474 		}
475 		if (add_file_to_index(&the_index, dir->entries[i]->name, flags)) {
476 			if (!ignore_add_errors)
477 				die(_("adding files failed"));
478 			exit_status = 1;
479 		} else {
480 			check_embedded_repo(dir->entries[i]->name);
481 		}
482 	}
483 
484 	if (matched_sparse_paths.nr) {
485 		advise_on_updating_sparse_paths(&matched_sparse_paths);
486 		exit_status = 1;
487 	}
488 
489 	string_list_clear(&matched_sparse_paths, 0);
490 
491 	return exit_status;
492 }
493 
cmd_add(int argc,const char ** argv,const char * prefix)494 int cmd_add(int argc, const char **argv, const char *prefix)
495 {
496 	int exit_status = 0;
497 	struct pathspec pathspec;
498 	struct dir_struct dir = DIR_INIT;
499 	int flags;
500 	int add_new_files;
501 	int require_pathspec;
502 	char *seen = NULL;
503 	struct lock_file lock_file = LOCK_INIT;
504 
505 	git_config(add_config, NULL);
506 
507 	argc = parse_options(argc, argv, prefix, builtin_add_options,
508 			  builtin_add_usage, PARSE_OPT_KEEP_ARGV0);
509 	if (patch_interactive)
510 		add_interactive = 1;
511 	if (add_interactive) {
512 		if (show_only)
513 			die(_("--dry-run is incompatible with --interactive/--patch"));
514 		if (pathspec_from_file)
515 			die(_("--pathspec-from-file is incompatible with --interactive/--patch"));
516 		exit(interactive_add(argv + 1, prefix, patch_interactive));
517 	}
518 	if (legacy_stash_p) {
519 		struct pathspec pathspec;
520 
521 		parse_pathspec(&pathspec, 0,
522 			PATHSPEC_PREFER_FULL |
523 			PATHSPEC_SYMLINK_LEADING_PATH |
524 			PATHSPEC_PREFIX_ORIGIN,
525 			prefix, argv);
526 
527 		return run_add_interactive(NULL, "--patch=stash", &pathspec);
528 	}
529 
530 	if (edit_interactive) {
531 		if (pathspec_from_file)
532 			die(_("--pathspec-from-file is incompatible with --edit"));
533 		return(edit_patch(argc, argv, prefix));
534 	}
535 	argc--;
536 	argv++;
537 
538 	if (0 <= addremove_explicit)
539 		addremove = addremove_explicit;
540 	else if (take_worktree_changes && ADDREMOVE_DEFAULT)
541 		addremove = 0; /* "-u" was given but not "-A" */
542 
543 	if (addremove && take_worktree_changes)
544 		die(_("-A and -u are mutually incompatible"));
545 
546 	if (!show_only && ignore_missing)
547 		die(_("Option --ignore-missing can only be used together with --dry-run"));
548 
549 	if (chmod_arg && ((chmod_arg[0] != '-' && chmod_arg[0] != '+') ||
550 			  chmod_arg[1] != 'x' || chmod_arg[2]))
551 		die(_("--chmod param '%s' must be either -x or +x"), chmod_arg);
552 
553 	add_new_files = !take_worktree_changes && !refresh_only && !add_renormalize;
554 	require_pathspec = !(take_worktree_changes || (0 < addremove_explicit));
555 
556 	prepare_repo_settings(the_repository);
557 	the_repository->settings.command_requires_full_index = 0;
558 
559 	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
560 
561 	/*
562 	 * Check the "pathspec '%s' did not match any files" block
563 	 * below before enabling new magic.
564 	 */
565 	parse_pathspec(&pathspec, PATHSPEC_ATTR,
566 		       PATHSPEC_PREFER_FULL |
567 		       PATHSPEC_SYMLINK_LEADING_PATH,
568 		       prefix, argv);
569 
570 	if (pathspec_from_file) {
571 		if (pathspec.nr)
572 			die(_("--pathspec-from-file is incompatible with pathspec arguments"));
573 
574 		parse_pathspec_file(&pathspec, PATHSPEC_ATTR,
575 				    PATHSPEC_PREFER_FULL |
576 				    PATHSPEC_SYMLINK_LEADING_PATH,
577 				    prefix, pathspec_from_file, pathspec_file_nul);
578 	} else if (pathspec_file_nul) {
579 		die(_("--pathspec-file-nul requires --pathspec-from-file"));
580 	}
581 
582 	if (require_pathspec && pathspec.nr == 0) {
583 		fprintf(stderr, _("Nothing specified, nothing added.\n"));
584 		if (advice_enabled(ADVICE_ADD_EMPTY_PATHSPEC))
585 			advise( _("Maybe you wanted to say 'git add .'?\n"
586 				"Turn this message off by running\n"
587 				"\"git config advice.addEmptyPathspec false\""));
588 		return 0;
589 	}
590 
591 	if (!take_worktree_changes && addremove_explicit < 0 && pathspec.nr)
592 		/* Turn "git add pathspec..." to "git add -A pathspec..." */
593 		addremove = 1;
594 
595 	flags = ((verbose ? ADD_CACHE_VERBOSE : 0) |
596 		 (show_only ? ADD_CACHE_PRETEND : 0) |
597 		 (intent_to_add ? ADD_CACHE_INTENT : 0) |
598 		 (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) |
599 		 (!(addremove || take_worktree_changes)
600 		  ? ADD_CACHE_IGNORE_REMOVAL : 0));
601 
602 	if (read_cache_preload(&pathspec) < 0)
603 		die(_("index file corrupt"));
604 
605 	die_in_unpopulated_submodule(&the_index, prefix);
606 	die_path_inside_submodule(&the_index, &pathspec);
607 
608 	if (add_new_files) {
609 		int baselen;
610 
611 		/* Set up the default git porcelain excludes */
612 		if (!ignored_too) {
613 			dir.flags |= DIR_COLLECT_IGNORED;
614 			setup_standard_excludes(&dir);
615 		}
616 
617 		/* This picks up the paths that are not tracked */
618 		baselen = fill_directory(&dir, &the_index, &pathspec);
619 		if (pathspec.nr)
620 			seen = prune_directory(&dir, &pathspec, baselen);
621 	}
622 
623 	if (refresh_only) {
624 		exit_status |= refresh(verbose, &pathspec);
625 		goto finish;
626 	}
627 
628 	if (pathspec.nr) {
629 		int i;
630 		char *skip_worktree_seen = NULL;
631 		struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
632 
633 		if (!seen)
634 			seen = find_pathspecs_matching_against_index(&pathspec,
635 					&the_index, PS_IGNORE_SKIP_WORKTREE);
636 
637 		/*
638 		 * file_exists() assumes exact match
639 		 */
640 		GUARD_PATHSPEC(&pathspec,
641 			       PATHSPEC_FROMTOP |
642 			       PATHSPEC_LITERAL |
643 			       PATHSPEC_GLOB |
644 			       PATHSPEC_ICASE |
645 			       PATHSPEC_EXCLUDE);
646 
647 		for (i = 0; i < pathspec.nr; i++) {
648 			const char *path = pathspec.items[i].match;
649 
650 			if (pathspec.items[i].magic & PATHSPEC_EXCLUDE)
651 				continue;
652 			if (seen[i])
653 				continue;
654 
655 			if (!include_sparse &&
656 			    matches_skip_worktree(&pathspec, i, &skip_worktree_seen)) {
657 				string_list_append(&only_match_skip_worktree,
658 						   pathspec.items[i].original);
659 				continue;
660 			}
661 
662 			/* Don't complain at 'git add .' on empty repo */
663 			if (!path[0])
664 				continue;
665 
666 			if ((pathspec.items[i].magic & (PATHSPEC_GLOB | PATHSPEC_ICASE)) ||
667 			    !file_exists(path)) {
668 				if (ignore_missing) {
669 					int dtype = DT_UNKNOWN;
670 					if (is_excluded(&dir, &the_index, path, &dtype))
671 						dir_add_ignored(&dir, &the_index,
672 								path, pathspec.items[i].len);
673 				} else
674 					die(_("pathspec '%s' did not match any files"),
675 					    pathspec.items[i].original);
676 			}
677 		}
678 
679 
680 		if (only_match_skip_worktree.nr) {
681 			advise_on_updating_sparse_paths(&only_match_skip_worktree);
682 			exit_status = 1;
683 		}
684 
685 		free(seen);
686 		free(skip_worktree_seen);
687 		string_list_clear(&only_match_skip_worktree, 0);
688 	}
689 
690 	plug_bulk_checkin();
691 
692 	if (add_renormalize)
693 		exit_status |= renormalize_tracked_files(&pathspec, flags);
694 	else
695 		exit_status |= add_files_to_cache(prefix, &pathspec, flags);
696 
697 	if (add_new_files)
698 		exit_status |= add_files(&dir, flags);
699 
700 	if (chmod_arg && pathspec.nr)
701 		exit_status |= chmod_pathspec(&pathspec, chmod_arg[0], show_only);
702 	unplug_bulk_checkin();
703 
704 finish:
705 	if (write_locked_index(&the_index, &lock_file,
706 			       COMMIT_LOCK | SKIP_IF_UNCHANGED))
707 		die(_("Unable to write new index file"));
708 
709 	dir_clear(&dir);
710 	UNLEAK(pathspec);
711 	return exit_status;
712 }
713