2 * "git add" builtin command
4 * Copyright (C) 2006 Linus Torvalds
11 #include "cache-tree.h"
13 static const char builtin_add_usage
[] =
14 "git-add [-n] [-v] <filepattern>...";
16 static void prune_directory(struct dir_struct
*dir
, const char **pathspec
, int prefix
)
20 struct dir_entry
**src
, **dst
;
22 for (specs
= 0; pathspec
[specs
]; specs
++)
24 seen
= xcalloc(specs
, 1);
26 src
= dst
= dir
->entries
;
29 struct dir_entry
*entry
= *src
++;
30 if (!match_pathspec(pathspec
, entry
->name
, entry
->len
, prefix
, seen
)) {
36 dir
->nr
= dst
- dir
->entries
;
38 for (i
= 0; i
< specs
; i
++) {
44 /* Existing file? We must have ignored it */
46 if (!match
[0] || !lstat(match
, &st
))
48 die("pathspec '%s' did not match any files", match
);
52 static void fill_directory(struct dir_struct
*dir
, const char **pathspec
)
54 const char *path
, *base
;
57 /* Set up the default git porcelain excludes */
58 memset(dir
, 0, sizeof(*dir
));
59 dir
->exclude_per_dir
= ".gitignore";
60 path
= git_path("info/exclude");
61 if (!access(path
, R_OK
))
62 add_excludes_from_file(dir
, path
);
65 * Calculate common prefix for the pathspec, and
66 * use that to optimize the directory walk
68 baselen
= common_prefix(pathspec
);
72 char *common
= xmalloc(baselen
+ 1);
73 common
= xmalloc(baselen
+ 1);
74 memcpy(common
, *pathspec
, baselen
);
79 /* Read the directory and prune it */
80 read_directory(dir
, path
, base
, baselen
);
82 prune_directory(dir
, pathspec
, baselen
);
85 static struct lock_file lock_file
;
87 int cmd_add(int argc
, const char **argv
, char **envp
)
90 int verbose
= 0, show_only
= 0;
91 const char *prefix
= setup_git_directory();
92 const char **pathspec
;
93 struct dir_struct dir
;
95 git_config(git_default_config
);
97 newfd
= hold_lock_file_for_update(&lock_file
, get_index_file());
99 die("unable to create new index file");
101 if (read_cache() < 0)
102 die("index file corrupt");
104 for (i
= 1; i
< argc
; i
++) {
105 const char *arg
= argv
[i
];
109 if (!strcmp(arg
, "--")) {
113 if (!strcmp(arg
, "-n")) {
117 if (!strcmp(arg
, "-v")) {
121 die(builtin_add_usage
);
123 pathspec
= get_pathspec(prefix
, argv
+ i
);
125 fill_directory(&dir
, pathspec
);
128 const char *sep
= "", *eof
= "";
129 for (i
= 0; i
< dir
.nr
; i
++) {
130 printf("%s%s", sep
, dir
.entries
[i
]->name
);
138 for (i
= 0; i
< dir
.nr
; i
++)
139 add_file_to_index(dir
.entries
[i
]->name
, verbose
);
141 if (active_cache_changed
) {
142 if (write_cache(newfd
, active_cache
, active_nr
) ||
143 close(newfd
) || commit_lock_file(&lock_file
))
144 die("Unable to write new index file");