2 * "git add" builtin command
4 * Copyright (C) 2006 Linus Torvalds
9 #include "cache-tree.h"
11 static const char builtin_add_usage
[] =
12 "git-add [-n] [-v] <filepattern>...";
14 static void prune_directory(struct dir_struct
*dir
, const char **pathspec
, int prefix
)
18 struct dir_entry
**src
, **dst
;
20 for (specs
= 0; pathspec
[specs
]; specs
++)
22 seen
= xcalloc(specs
, 1);
24 src
= dst
= dir
->entries
;
27 struct dir_entry
*entry
= *src
++;
28 if (!match_pathspec(pathspec
, entry
->name
, entry
->len
, prefix
, seen
)) {
34 dir
->nr
= dst
- dir
->entries
;
36 for (i
= 0; i
< specs
; i
++) {
42 /* Existing file? We must have ignored it */
44 if (!match
[0] || !lstat(match
, &st
))
46 die("pathspec '%s' did not match any files", match
);
50 static void fill_directory(struct dir_struct
*dir
, const char **pathspec
)
52 const char *path
, *base
;
55 /* Set up the default git porcelain excludes */
56 memset(dir
, 0, sizeof(*dir
));
57 dir
->exclude_per_dir
= ".gitignore";
58 path
= git_path("info/exclude");
59 if (!access(path
, R_OK
))
60 add_excludes_from_file(dir
, path
);
63 * Calculate common prefix for the pathspec, and
64 * use that to optimize the directory walk
66 baselen
= common_prefix(pathspec
);
70 char *common
= xmalloc(baselen
+ 1);
71 memcpy(common
, *pathspec
, baselen
);
76 /* Read the directory and prune it */
77 read_directory(dir
, path
, base
, baselen
);
79 prune_directory(dir
, pathspec
, baselen
);
82 static struct lock_file lock_file
;
84 int cmd_add(int argc
, const char **argv
, const char *prefix
)
87 int verbose
= 0, show_only
= 0;
88 const char **pathspec
;
89 struct dir_struct dir
;
91 git_config(git_default_config
);
93 newfd
= hold_lock_file_for_update(&lock_file
, get_index_file(), 1);
95 for (i
= 1; i
< argc
; i
++) {
96 const char *arg
= argv
[i
];
100 if (!strcmp(arg
, "--")) {
104 if (!strcmp(arg
, "-n")) {
108 if (!strcmp(arg
, "-v")) {
112 usage(builtin_add_usage
);
115 fprintf(stderr
, "Nothing specified, nothing added.\n");
116 fprintf(stderr
, "Maybe you wanted to say 'git add .'?\n");
119 pathspec
= get_pathspec(prefix
, argv
+ i
);
121 fill_directory(&dir
, pathspec
);
124 const char *sep
= "", *eof
= "";
125 for (i
= 0; i
< dir
.nr
; i
++) {
126 printf("%s%s", sep
, dir
.entries
[i
]->name
);
134 if (read_cache() < 0)
135 die("index file corrupt");
137 for (i
= 0; i
< dir
.nr
; i
++)
138 add_file_to_index(dir
.entries
[i
]->name
, verbose
);
140 if (active_cache_changed
) {
141 if (write_cache(newfd
, active_cache
, active_nr
) ||
142 close(newfd
) || commit_lock_file(&lock_file
))
143 die("Unable to write new index file");