completion: complete --default-prefix
[git/debian.git] / builtin / add.c
blob76cc026a68a992a750b24a9ac23d05f4899dacc2
1 /*
2 * "git add" builtin command
4 * Copyright (C) 2006 Linus Torvalds
5 */
6 #define USE_THE_INDEX_VARIABLE
7 #include "cache.h"
8 #include "advice.h"
9 #include "config.h"
10 #include "builtin.h"
11 #include "lockfile.h"
12 #include "editor.h"
13 #include "dir.h"
14 #include "gettext.h"
15 #include "pathspec.h"
16 #include "exec-cmd.h"
17 #include "cache-tree.h"
18 #include "run-command.h"
19 #include "parse-options.h"
20 #include "diff.h"
21 #include "diffcore.h"
22 #include "revision.h"
23 #include "bulk-checkin.h"
24 #include "strvec.h"
25 #include "submodule.h"
26 #include "add-interactive.h"
28 static const char * const builtin_add_usage[] = {
29 N_("git add [<options>] [--] <pathspec>..."),
30 NULL
32 static int patch_interactive, add_interactive, edit_interactive;
33 static int take_worktree_changes;
34 static int add_renormalize;
35 static int pathspec_file_nul;
36 static int include_sparse;
37 static const char *pathspec_from_file;
39 struct update_callback_data {
40 int flags;
41 int add_errors;
44 static int chmod_pathspec(struct pathspec *pathspec, char flip, int show_only)
46 int i, ret = 0;
48 for (i = 0; i < the_index.cache_nr; i++) {
49 struct cache_entry *ce = the_index.cache[i];
50 int err;
52 if (!include_sparse &&
53 (ce_skip_worktree(ce) ||
54 !path_in_sparse_checkout(ce->name, &the_index)))
55 continue;
57 if (pathspec && !ce_path_match(&the_index, ce, pathspec, NULL))
58 continue;
60 if (!show_only)
61 err = chmod_index_entry(&the_index, ce, flip);
62 else
63 err = S_ISREG(ce->ce_mode) ? 0 : -1;
65 if (err < 0)
66 ret = error(_("cannot chmod %cx '%s'"), flip, ce->name);
69 return ret;
72 static int fix_unmerged_status(struct diff_filepair *p,
73 struct update_callback_data *data)
75 if (p->status != DIFF_STATUS_UNMERGED)
76 return p->status;
77 if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
79 * This is not an explicit add request, and the
80 * path is missing from the working tree (deleted)
82 return DIFF_STATUS_DELETED;
83 else
85 * Either an explicit add request, or path exists
86 * in the working tree. An attempt to explicitly
87 * add a path that does not exist in the working tree
88 * will be caught as an error by the caller immediately.
90 return DIFF_STATUS_MODIFIED;
93 static void update_callback(struct diff_queue_struct *q,
94 struct diff_options *opt UNUSED, void *cbdata)
96 int i;
97 struct update_callback_data *data = cbdata;
99 for (i = 0; i < q->nr; i++) {
100 struct diff_filepair *p = q->queue[i];
101 const char *path = p->one->path;
103 if (!include_sparse && !path_in_sparse_checkout(path, &the_index))
104 continue;
106 switch (fix_unmerged_status(p, data)) {
107 default:
108 die(_("unexpected diff status %c"), p->status);
109 case DIFF_STATUS_MODIFIED:
110 case DIFF_STATUS_TYPE_CHANGED:
111 if (add_file_to_index(&the_index, path, data->flags)) {
112 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
113 die(_("updating files failed"));
114 data->add_errors++;
116 break;
117 case DIFF_STATUS_DELETED:
118 if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
119 break;
120 if (!(data->flags & ADD_CACHE_PRETEND))
121 remove_file_from_index(&the_index, path);
122 if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
123 printf(_("remove '%s'\n"), path);
124 break;
129 int add_files_to_cache(const char *prefix,
130 const struct pathspec *pathspec, int flags)
132 struct update_callback_data data;
133 struct rev_info rev;
135 memset(&data, 0, sizeof(data));
136 data.flags = flags;
138 repo_init_revisions(the_repository, &rev, prefix);
139 setup_revisions(0, NULL, &rev, NULL);
140 if (pathspec)
141 copy_pathspec(&rev.prune_data, pathspec);
142 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
143 rev.diffopt.format_callback = update_callback;
144 rev.diffopt.format_callback_data = &data;
145 rev.diffopt.flags.override_submodule_config = 1;
146 rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
149 * Use an ODB transaction to optimize adding multiple objects.
150 * This function is invoked from commands other than 'add', which
151 * may not have their own transaction active.
153 begin_odb_transaction();
154 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
155 end_odb_transaction();
157 release_revisions(&rev);
158 return !!data.add_errors;
161 static int renormalize_tracked_files(const struct pathspec *pathspec, int flags)
163 int i, retval = 0;
165 for (i = 0; i < the_index.cache_nr; i++) {
166 struct cache_entry *ce = the_index.cache[i];
168 if (!include_sparse &&
169 (ce_skip_worktree(ce) ||
170 !path_in_sparse_checkout(ce->name, &the_index)))
171 continue;
172 if (ce_stage(ce))
173 continue; /* do not touch unmerged paths */
174 if (!S_ISREG(ce->ce_mode) && !S_ISLNK(ce->ce_mode))
175 continue; /* do not touch non blobs */
176 if (pathspec && !ce_path_match(&the_index, ce, pathspec, NULL))
177 continue;
178 retval |= add_file_to_index(&the_index, ce->name,
179 flags | ADD_CACHE_RENORMALIZE);
182 return retval;
185 static char *prune_directory(struct dir_struct *dir, struct pathspec *pathspec, int prefix)
187 char *seen;
188 int i;
189 struct dir_entry **src, **dst;
191 seen = xcalloc(pathspec->nr, 1);
193 src = dst = dir->entries;
194 i = dir->nr;
195 while (--i >= 0) {
196 struct dir_entry *entry = *src++;
197 if (dir_path_match(&the_index, entry, pathspec, prefix, seen))
198 *dst++ = entry;
200 dir->nr = dst - dir->entries;
201 add_pathspec_matches_against_index(pathspec, &the_index, seen,
202 PS_IGNORE_SKIP_WORKTREE);
203 return seen;
206 static int refresh(int verbose, const struct pathspec *pathspec)
208 char *seen;
209 int i, ret = 0;
210 char *skip_worktree_seen = NULL;
211 struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
212 int flags = REFRESH_IGNORE_SKIP_WORKTREE |
213 (verbose ? REFRESH_IN_PORCELAIN : REFRESH_QUIET);
215 seen = xcalloc(pathspec->nr, 1);
216 refresh_index(&the_index, flags, pathspec, seen,
217 _("Unstaged changes after refreshing the index:"));
218 for (i = 0; i < pathspec->nr; i++) {
219 if (!seen[i]) {
220 const char *path = pathspec->items[i].original;
222 if (matches_skip_worktree(pathspec, i, &skip_worktree_seen) ||
223 !path_in_sparse_checkout(path, &the_index)) {
224 string_list_append(&only_match_skip_worktree,
225 pathspec->items[i].original);
226 } else {
227 die(_("pathspec '%s' did not match any files"),
228 pathspec->items[i].original);
233 if (only_match_skip_worktree.nr) {
234 advise_on_updating_sparse_paths(&only_match_skip_worktree);
235 ret = 1;
238 free(seen);
239 free(skip_worktree_seen);
240 string_list_clear(&only_match_skip_worktree, 0);
241 return ret;
244 int interactive_add(const char **argv, const char *prefix, int patch)
246 struct pathspec pathspec;
247 int unused;
249 if (!git_config_get_bool("add.interactive.usebuiltin", &unused))
250 warning(_("the add.interactive.useBuiltin setting has been removed!\n"
251 "See its entry in 'git help config' for details."));
253 parse_pathspec(&pathspec, 0,
254 PATHSPEC_PREFER_FULL |
255 PATHSPEC_SYMLINK_LEADING_PATH |
256 PATHSPEC_PREFIX_ORIGIN,
257 prefix, argv);
259 if (patch)
260 return !!run_add_p(the_repository, ADD_P_ADD, NULL, &pathspec);
261 else
262 return !!run_add_i(the_repository, &pathspec);
265 static int edit_patch(int argc, const char **argv, const char *prefix)
267 char *file = git_pathdup("ADD_EDIT.patch");
268 struct child_process child = CHILD_PROCESS_INIT;
269 struct rev_info rev;
270 int out;
271 struct stat st;
273 git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
275 if (repo_read_index(the_repository) < 0)
276 die(_("Could not read the index"));
278 repo_init_revisions(the_repository, &rev, prefix);
279 rev.diffopt.context = 7;
281 argc = setup_revisions(argc, argv, &rev, NULL);
282 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
283 rev.diffopt.use_color = 0;
284 rev.diffopt.flags.ignore_dirty_submodules = 1;
285 out = xopen(file, O_CREAT | O_WRONLY | O_TRUNC, 0666);
286 rev.diffopt.file = xfdopen(out, "w");
287 rev.diffopt.close_file = 1;
288 if (run_diff_files(&rev, 0))
289 die(_("Could not write patch"));
291 if (launch_editor(file, NULL, NULL))
292 die(_("editing patch failed"));
294 if (stat(file, &st))
295 die_errno(_("Could not stat '%s'"), file);
296 if (!st.st_size)
297 die(_("Empty patch. Aborted."));
299 child.git_cmd = 1;
300 strvec_pushl(&child.args, "apply", "--recount", "--cached", file,
301 NULL);
302 if (run_command(&child))
303 die(_("Could not apply '%s'"), file);
305 unlink(file);
306 free(file);
307 release_revisions(&rev);
308 return 0;
311 static const char ignore_error[] =
312 N_("The following paths are ignored by one of your .gitignore files:\n");
314 static int verbose, show_only, ignored_too, refresh_only;
315 static int ignore_add_errors, intent_to_add, ignore_missing;
316 static int warn_on_embedded_repo = 1;
318 #define ADDREMOVE_DEFAULT 1
319 static int addremove = ADDREMOVE_DEFAULT;
320 static int addremove_explicit = -1; /* unspecified */
322 static char *chmod_arg;
324 static int ignore_removal_cb(const struct option *opt, const char *arg, int unset)
326 /* if we are told to ignore, we are not adding removals */
327 *(int *)opt->value = !unset ? 0 : 1;
328 return 0;
331 static struct option builtin_add_options[] = {
332 OPT__DRY_RUN(&show_only, N_("dry run")),
333 OPT__VERBOSE(&verbose, N_("be verbose")),
334 OPT_GROUP(""),
335 OPT_BOOL('i', "interactive", &add_interactive, N_("interactive picking")),
336 OPT_BOOL('p', "patch", &patch_interactive, N_("select hunks interactively")),
337 OPT_BOOL('e', "edit", &edit_interactive, N_("edit current diff and apply")),
338 OPT__FORCE(&ignored_too, N_("allow adding otherwise ignored files"), 0),
339 OPT_BOOL('u', "update", &take_worktree_changes, N_("update tracked files")),
340 OPT_BOOL(0, "renormalize", &add_renormalize, N_("renormalize EOL of tracked files (implies -u)")),
341 OPT_BOOL('N', "intent-to-add", &intent_to_add, N_("record only the fact that the path will be added later")),
342 OPT_BOOL('A', "all", &addremove_explicit, N_("add changes from all tracked and untracked files")),
343 OPT_CALLBACK_F(0, "ignore-removal", &addremove_explicit,
344 NULL /* takes no arguments */,
345 N_("ignore paths removed in the working tree (same as --no-all)"),
346 PARSE_OPT_NOARG, ignore_removal_cb),
347 OPT_BOOL( 0 , "refresh", &refresh_only, N_("don't add, only refresh the index")),
348 OPT_BOOL( 0 , "ignore-errors", &ignore_add_errors, N_("just skip files which cannot be added because of errors")),
349 OPT_BOOL( 0 , "ignore-missing", &ignore_missing, N_("check if - even missing - files are ignored in dry run")),
350 OPT_BOOL(0, "sparse", &include_sparse, N_("allow updating entries outside of the sparse-checkout cone")),
351 OPT_STRING(0, "chmod", &chmod_arg, "(+|-)x",
352 N_("override the executable bit of the listed files")),
353 OPT_HIDDEN_BOOL(0, "warn-embedded-repo", &warn_on_embedded_repo,
354 N_("warn when adding an embedded repository")),
355 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
356 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
357 OPT_END(),
360 static int add_config(const char *var, const char *value, void *cb)
362 if (!strcmp(var, "add.ignoreerrors") ||
363 !strcmp(var, "add.ignore-errors")) {
364 ignore_add_errors = git_config_bool(var, value);
365 return 0;
368 return git_default_config(var, value, cb);
371 static const char embedded_advice[] = N_(
372 "You've added another git repository inside your current repository.\n"
373 "Clones of the outer repository will not contain the contents of\n"
374 "the embedded repository and will not know how to obtain it.\n"
375 "If you meant to add a submodule, use:\n"
376 "\n"
377 " git submodule add <url> %s\n"
378 "\n"
379 "If you added this path by mistake, you can remove it from the\n"
380 "index with:\n"
381 "\n"
382 " git rm --cached %s\n"
383 "\n"
384 "See \"git help submodule\" for more information."
387 static void check_embedded_repo(const char *path)
389 struct strbuf name = STRBUF_INIT;
390 static int adviced_on_embedded_repo = 0;
392 if (!warn_on_embedded_repo)
393 return;
394 if (!ends_with(path, "/"))
395 return;
397 /* Drop trailing slash for aesthetics */
398 strbuf_addstr(&name, path);
399 strbuf_strip_suffix(&name, "/");
401 warning(_("adding embedded git repository: %s"), name.buf);
402 if (!adviced_on_embedded_repo &&
403 advice_enabled(ADVICE_ADD_EMBEDDED_REPO)) {
404 advise(embedded_advice, name.buf, name.buf);
405 adviced_on_embedded_repo = 1;
408 strbuf_release(&name);
411 static int add_files(struct dir_struct *dir, int flags)
413 int i, exit_status = 0;
414 struct string_list matched_sparse_paths = STRING_LIST_INIT_NODUP;
416 if (dir->ignored_nr) {
417 fprintf(stderr, _(ignore_error));
418 for (i = 0; i < dir->ignored_nr; i++)
419 fprintf(stderr, "%s\n", dir->ignored[i]->name);
420 if (advice_enabled(ADVICE_ADD_IGNORED_FILE))
421 advise(_("Use -f if you really want to add them.\n"
422 "Turn this message off by running\n"
423 "\"git config advice.addIgnoredFile false\""));
424 exit_status = 1;
427 for (i = 0; i < dir->nr; i++) {
428 if (!include_sparse &&
429 !path_in_sparse_checkout(dir->entries[i]->name, &the_index)) {
430 string_list_append(&matched_sparse_paths,
431 dir->entries[i]->name);
432 continue;
434 if (add_file_to_index(&the_index, dir->entries[i]->name, flags)) {
435 if (!ignore_add_errors)
436 die(_("adding files failed"));
437 exit_status = 1;
438 } else {
439 check_embedded_repo(dir->entries[i]->name);
443 if (matched_sparse_paths.nr) {
444 advise_on_updating_sparse_paths(&matched_sparse_paths);
445 exit_status = 1;
448 string_list_clear(&matched_sparse_paths, 0);
450 return exit_status;
453 int cmd_add(int argc, const char **argv, const char *prefix)
455 int exit_status = 0;
456 struct pathspec pathspec;
457 struct dir_struct dir = DIR_INIT;
458 int flags;
459 int add_new_files;
460 int require_pathspec;
461 char *seen = NULL;
462 struct lock_file lock_file = LOCK_INIT;
464 git_config(add_config, NULL);
466 argc = parse_options(argc, argv, prefix, builtin_add_options,
467 builtin_add_usage, PARSE_OPT_KEEP_ARGV0);
468 if (patch_interactive)
469 add_interactive = 1;
470 if (add_interactive) {
471 if (show_only)
472 die(_("options '%s' and '%s' cannot be used together"), "--dry-run", "--interactive/--patch");
473 if (pathspec_from_file)
474 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
475 exit(interactive_add(argv + 1, prefix, patch_interactive));
478 if (edit_interactive) {
479 if (pathspec_from_file)
480 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--edit");
481 return(edit_patch(argc, argv, prefix));
483 argc--;
484 argv++;
486 if (0 <= addremove_explicit)
487 addremove = addremove_explicit;
488 else if (take_worktree_changes && ADDREMOVE_DEFAULT)
489 addremove = 0; /* "-u" was given but not "-A" */
491 if (addremove && take_worktree_changes)
492 die(_("options '%s' and '%s' cannot be used together"), "-A", "-u");
494 if (!show_only && ignore_missing)
495 die(_("the option '%s' requires '%s'"), "--ignore-missing", "--dry-run");
497 if (chmod_arg && ((chmod_arg[0] != '-' && chmod_arg[0] != '+') ||
498 chmod_arg[1] != 'x' || chmod_arg[2]))
499 die(_("--chmod param '%s' must be either -x or +x"), chmod_arg);
501 add_new_files = !take_worktree_changes && !refresh_only && !add_renormalize;
502 require_pathspec = !(take_worktree_changes || (0 < addremove_explicit));
504 prepare_repo_settings(the_repository);
505 the_repository->settings.command_requires_full_index = 0;
507 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
510 * Check the "pathspec '%s' did not match any files" block
511 * below before enabling new magic.
513 parse_pathspec(&pathspec, PATHSPEC_ATTR,
514 PATHSPEC_PREFER_FULL |
515 PATHSPEC_SYMLINK_LEADING_PATH,
516 prefix, argv);
518 if (pathspec_from_file) {
519 if (pathspec.nr)
520 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
522 parse_pathspec_file(&pathspec, PATHSPEC_ATTR,
523 PATHSPEC_PREFER_FULL |
524 PATHSPEC_SYMLINK_LEADING_PATH,
525 prefix, pathspec_from_file, pathspec_file_nul);
526 } else if (pathspec_file_nul) {
527 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
530 if (require_pathspec && pathspec.nr == 0) {
531 fprintf(stderr, _("Nothing specified, nothing added.\n"));
532 if (advice_enabled(ADVICE_ADD_EMPTY_PATHSPEC))
533 advise( _("Maybe you wanted to say 'git add .'?\n"
534 "Turn this message off by running\n"
535 "\"git config advice.addEmptyPathspec false\""));
536 return 0;
539 if (!take_worktree_changes && addremove_explicit < 0 && pathspec.nr)
540 /* Turn "git add pathspec..." to "git add -A pathspec..." */
541 addremove = 1;
543 flags = ((verbose ? ADD_CACHE_VERBOSE : 0) |
544 (show_only ? ADD_CACHE_PRETEND : 0) |
545 (intent_to_add ? ADD_CACHE_INTENT : 0) |
546 (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) |
547 (!(addremove || take_worktree_changes)
548 ? ADD_CACHE_IGNORE_REMOVAL : 0));
550 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
551 die(_("index file corrupt"));
553 die_in_unpopulated_submodule(&the_index, prefix);
554 die_path_inside_submodule(&the_index, &pathspec);
556 if (add_new_files) {
557 int baselen;
559 /* Set up the default git porcelain excludes */
560 if (!ignored_too) {
561 dir.flags |= DIR_COLLECT_IGNORED;
562 setup_standard_excludes(&dir);
565 /* This picks up the paths that are not tracked */
566 baselen = fill_directory(&dir, &the_index, &pathspec);
567 if (pathspec.nr)
568 seen = prune_directory(&dir, &pathspec, baselen);
571 if (refresh_only) {
572 exit_status |= refresh(verbose, &pathspec);
573 goto finish;
576 if (pathspec.nr) {
577 int i;
578 char *skip_worktree_seen = NULL;
579 struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
581 if (!seen)
582 seen = find_pathspecs_matching_against_index(&pathspec,
583 &the_index, PS_IGNORE_SKIP_WORKTREE);
586 * file_exists() assumes exact match
588 GUARD_PATHSPEC(&pathspec,
589 PATHSPEC_FROMTOP |
590 PATHSPEC_LITERAL |
591 PATHSPEC_GLOB |
592 PATHSPEC_ICASE |
593 PATHSPEC_EXCLUDE);
595 for (i = 0; i < pathspec.nr; i++) {
596 const char *path = pathspec.items[i].match;
598 if (pathspec.items[i].magic & PATHSPEC_EXCLUDE)
599 continue;
600 if (seen[i])
601 continue;
603 if (!include_sparse &&
604 matches_skip_worktree(&pathspec, i, &skip_worktree_seen)) {
605 string_list_append(&only_match_skip_worktree,
606 pathspec.items[i].original);
607 continue;
610 /* Don't complain at 'git add .' on empty repo */
611 if (!path[0])
612 continue;
614 if ((pathspec.items[i].magic & (PATHSPEC_GLOB | PATHSPEC_ICASE)) ||
615 !file_exists(path)) {
616 if (ignore_missing) {
617 int dtype = DT_UNKNOWN;
618 if (is_excluded(&dir, &the_index, path, &dtype))
619 dir_add_ignored(&dir, &the_index,
620 path, pathspec.items[i].len);
621 } else
622 die(_("pathspec '%s' did not match any files"),
623 pathspec.items[i].original);
628 if (only_match_skip_worktree.nr) {
629 advise_on_updating_sparse_paths(&only_match_skip_worktree);
630 exit_status = 1;
633 free(seen);
634 free(skip_worktree_seen);
635 string_list_clear(&only_match_skip_worktree, 0);
638 begin_odb_transaction();
640 if (add_renormalize)
641 exit_status |= renormalize_tracked_files(&pathspec, flags);
642 else
643 exit_status |= add_files_to_cache(prefix, &pathspec, flags);
645 if (add_new_files)
646 exit_status |= add_files(&dir, flags);
648 if (chmod_arg && pathspec.nr)
649 exit_status |= chmod_pathspec(&pathspec, chmod_arg[0], show_only);
650 end_odb_transaction();
652 finish:
653 if (write_locked_index(&the_index, &lock_file,
654 COMMIT_LOCK | SKIP_IF_UNCHANGED))
655 die(_("Unable to write new index file"));
657 dir_clear(&dir);
658 clear_pathspec(&pathspec);
659 return exit_status;