2 * "git add" builtin command
4 * Copyright (C) 2006 Linus Torvalds
10 #include "cache-tree.h"
12 static const char builtin_add_usage
[] =
13 "git-add [-n] [-v] [--interactive] [--] <filepattern>...";
15 static void prune_directory(struct dir_struct
*dir
, const char **pathspec
, int prefix
)
19 struct dir_entry
**src
, **dst
;
21 for (specs
= 0; pathspec
[specs
]; specs
++)
23 seen
= xcalloc(specs
, 1);
25 src
= dst
= dir
->entries
;
28 struct dir_entry
*entry
= *src
++;
29 if (!match_pathspec(pathspec
, entry
->name
, entry
->len
, prefix
, seen
)) {
35 dir
->nr
= dst
- dir
->entries
;
37 for (i
= 0; i
< specs
; i
++) {
43 /* Existing file? We must have ignored it */
45 if (!match
[0] || !lstat(match
, &st
))
47 die("pathspec '%s' did not match any files", match
);
51 static void fill_directory(struct dir_struct
*dir
, const char **pathspec
)
53 const char *path
, *base
;
56 /* Set up the default git porcelain excludes */
57 memset(dir
, 0, sizeof(*dir
));
58 dir
->exclude_per_dir
= ".gitignore";
59 path
= git_path("info/exclude");
60 if (!access(path
, R_OK
))
61 add_excludes_from_file(dir
, path
);
64 * Calculate common prefix for the pathspec, and
65 * use that to optimize the directory walk
67 baselen
= common_prefix(pathspec
);
71 char *common
= xmalloc(baselen
+ 1);
72 memcpy(common
, *pathspec
, baselen
);
77 /* Read the directory and prune it */
78 read_directory(dir
, path
, base
, baselen
);
80 prune_directory(dir
, pathspec
, baselen
);
83 static struct lock_file lock_file
;
85 int cmd_add(int argc
, const char **argv
, const char *prefix
)
88 int verbose
= 0, show_only
= 0;
89 const char **pathspec
;
90 struct dir_struct dir
;
91 int add_interactive
= 0;
93 for (i
= 1; i
< argc
; i
++) {
94 if (!strcmp("--interactive", argv
[i
]))
97 if (add_interactive
) {
98 const char *args
[] = { "add--interactive", NULL
};
100 if (add_interactive
!= 1 || argc
!= 2)
101 die("add --interactive does not take any parameters");
106 git_config(git_default_config
);
108 newfd
= hold_lock_file_for_update(&lock_file
, get_index_file(), 1);
110 for (i
= 1; i
< argc
; i
++) {
111 const char *arg
= argv
[i
];
115 if (!strcmp(arg
, "--")) {
119 if (!strcmp(arg
, "-n")) {
123 if (!strcmp(arg
, "-v")) {
127 usage(builtin_add_usage
);
130 fprintf(stderr
, "Nothing specified, nothing added.\n");
131 fprintf(stderr
, "Maybe you wanted to say 'git add .'?\n");
134 pathspec
= get_pathspec(prefix
, argv
+ i
);
136 fill_directory(&dir
, pathspec
);
139 const char *sep
= "", *eof
= "";
140 for (i
= 0; i
< dir
.nr
; i
++) {
141 printf("%s%s", sep
, dir
.entries
[i
]->name
);
149 if (read_cache() < 0)
150 die("index file corrupt");
152 for (i
= 0; i
< dir
.nr
; i
++)
153 add_file_to_index(dir
.entries
[i
]->name
, verbose
);
155 if (active_cache_changed
) {
156 if (write_cache(newfd
, active_cache
, active_nr
) ||
157 close(newfd
) || commit_lock_file(&lock_file
))
158 die("Unable to write new index file");