2 * "git add" builtin command
4 * Copyright (C) 2006 Linus Torvalds
12 #include "cache-tree.h"
14 static const char builtin_add_usage
[] =
15 "git-add [-n] [-v] <filepattern>...";
17 static void prune_directory(struct dir_struct
*dir
, const char **pathspec
, int prefix
)
21 struct dir_entry
**src
, **dst
;
23 for (specs
= 0; pathspec
[specs
]; specs
++)
25 seen
= xcalloc(specs
, 1);
27 src
= dst
= dir
->entries
;
30 struct dir_entry
*entry
= *src
++;
31 if (!match_pathspec(pathspec
, entry
->name
, entry
->len
, prefix
, seen
)) {
37 dir
->nr
= dst
- dir
->entries
;
39 for (i
= 0; i
< specs
; i
++) {
45 /* Existing file? We must have ignored it */
47 if (!match
[0] || !lstat(match
, &st
))
49 die("pathspec '%s' did not match any files", match
);
53 static void fill_directory(struct dir_struct
*dir
, const char **pathspec
)
55 const char *path
, *base
;
58 /* Set up the default git porcelain excludes */
59 memset(dir
, 0, sizeof(*dir
));
60 dir
->exclude_per_dir
= ".gitignore";
61 path
= git_path("info/exclude");
62 if (!access(path
, R_OK
))
63 add_excludes_from_file(dir
, path
);
66 * Calculate common prefix for the pathspec, and
67 * use that to optimize the directory walk
69 baselen
= common_prefix(pathspec
);
73 char *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
, const char *prefix
)
90 int verbose
= 0, show_only
= 0;
91 const char **pathspec
;
92 struct dir_struct dir
;
93 int add_interactive
= 0;
95 for (i
= 1; i
< argc
; i
++) {
96 if (!strcmp("--interactive", argv
[i
]))
99 if (add_interactive
) {
100 const char *args
[] = { "add--interactive", NULL
};
102 if (add_interactive
!= 1 || argc
!= 2)
103 die("add --interactive does not take any parameters");
108 git_config(git_default_config
);
110 newfd
= hold_lock_file_for_update(&lock_file
, get_index_file(), 1);
112 for (i
= 1; i
< argc
; i
++) {
113 const char *arg
= argv
[i
];
117 if (!strcmp(arg
, "--")) {
121 if (!strcmp(arg
, "-n")) {
125 if (!strcmp(arg
, "-v")) {
129 usage(builtin_add_usage
);
131 pathspec
= get_pathspec(prefix
, argv
+ i
);
133 fill_directory(&dir
, pathspec
);
136 const char *sep
= "", *eof
= "";
137 for (i
= 0; i
< dir
.nr
; i
++) {
138 printf("%s%s", sep
, dir
.entries
[i
]->name
);
146 if (read_cache() < 0)
147 die("index file corrupt");
149 for (i
= 0; i
< dir
.nr
; i
++)
150 add_file_to_index(dir
.entries
[i
]->name
, verbose
);
152 if (active_cache_changed
) {
153 if (write_cache(newfd
, active_cache
, active_nr
) ||
154 close(newfd
) || commit_lock_file(&lock_file
))
155 die("Unable to write new index file");