read-cache.c: fix memory leaks caused by removed cache entries
[git] / builtin / update-index.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  */
6 #include "cache.h"
7 #include "quote.h"
8 #include "cache-tree.h"
9 #include "tree-walk.h"
10 #include "builtin.h"
11 #include "refs.h"
12 #include "resolve-undo.h"
13 #include "parse-options.h"
14 #include "pathspec.h"
15
16 /*
17  * Default to not allowing changes to the list of files. The
18  * tool doesn't actually care, but this makes it harder to add
19  * files to the revision control by mistake by doing something
20  * like "git update-index *" and suddenly having all the object
21  * files be revision controlled.
22  */
23 static int allow_add;
24 static int allow_remove;
25 static int allow_replace;
26 static int info_only;
27 static int force_remove;
28 static int verbose;
29 static int mark_valid_only;
30 static int mark_skip_worktree_only;
31 #define MARK_FLAG 1
32 #define UNMARK_FLAG 2
33
34 __attribute__((format (printf, 1, 2)))
35 static void report(const char *fmt, ...)
36 {
37         va_list vp;
38
39         if (!verbose)
40                 return;
41
42         va_start(vp, fmt);
43         vprintf(fmt, vp);
44         putchar('\n');
45         va_end(vp);
46 }
47
48 static int mark_ce_flags(const char *path, int flag, int mark)
49 {
50         int namelen = strlen(path);
51         int pos = cache_name_pos(path, namelen);
52         if (0 <= pos) {
53                 if (mark)
54                         active_cache[pos]->ce_flags |= flag;
55                 else
56                         active_cache[pos]->ce_flags &= ~flag;
57                 cache_tree_invalidate_path(active_cache_tree, path);
58                 active_cache_changed = 1;
59                 return 0;
60         }
61         return -1;
62 }
63
64 static int remove_one_path(const char *path)
65 {
66         if (!allow_remove)
67                 return error("%s: does not exist and --remove not passed", path);
68         if (remove_file_from_cache(path))
69                 return error("%s: cannot remove from the index", path);
70         return 0;
71 }
72
73 /*
74  * Handle a path that couldn't be lstat'ed. It's either:
75  *  - missing file (ENOENT or ENOTDIR). That's ok if we're
76  *    supposed to be removing it and the removal actually
77  *    succeeds.
78  *  - permission error. That's never ok.
79  */
80 static int process_lstat_error(const char *path, int err)
81 {
82         if (err == ENOENT || err == ENOTDIR)
83                 return remove_one_path(path);
84         return error("lstat(\"%s\"): %s", path, strerror(errno));
85 }
86
87 static int add_one_path(const struct cache_entry *old, const char *path, int len, struct stat *st)
88 {
89         int option, size;
90         struct cache_entry *ce;
91
92         /* Was the old index entry already up-to-date? */
93         if (old && !ce_stage(old) && !ce_match_stat(old, st, 0))
94                 return 0;
95
96         size = cache_entry_size(len);
97         ce = xcalloc(1, size);
98         memcpy(ce->name, path, len);
99         ce->ce_flags = create_ce_flags(0);
100         ce->ce_namelen = len;
101         fill_stat_cache_info(ce, st);
102         ce->ce_mode = ce_mode_from_stat(old, st->st_mode);
103
104         if (index_path(ce->sha1, path, st,
105                        info_only ? 0 : HASH_WRITE_OBJECT)) {
106                 free(ce);
107                 return -1;
108         }
109         option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
110         option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
111         if (add_cache_entry(ce, option))
112                 return error("%s: cannot add to the index - missing --add option?", path);
113         return 0;
114 }
115
116 /*
117  * Handle a path that was a directory. Four cases:
118  *
119  *  - it's already a gitlink in the index, and we keep it that
120  *    way, and update it if we can (if we cannot find the HEAD,
121  *    we're going to keep it unchanged in the index!)
122  *
123  *  - it's a *file* in the index, in which case it should be
124  *    removed as a file if removal is allowed, since it doesn't
125  *    exist as such any more. If removal isn't allowed, it's
126  *    an error.
127  *
128  *    (NOTE! This is old and arguably fairly strange behaviour.
129  *    We might want to make this an error unconditionally, and
130  *    use "--force-remove" if you actually want to force removal).
131  *
132  *  - it used to exist as a subdirectory (ie multiple files with
133  *    this particular prefix) in the index, in which case it's wrong
134  *    to try to update it as a directory.
135  *
136  *  - it doesn't exist at all in the index, but it is a valid
137  *    git directory, and it should be *added* as a gitlink.
138  */
139 static int process_directory(const char *path, int len, struct stat *st)
140 {
141         unsigned char sha1[20];
142         int pos = cache_name_pos(path, len);
143
144         /* Exact match: file or existing gitlink */
145         if (pos >= 0) {
146                 const struct cache_entry *ce = active_cache[pos];
147                 if (S_ISGITLINK(ce->ce_mode)) {
148
149                         /* Do nothing to the index if there is no HEAD! */
150                         if (resolve_gitlink_ref(path, "HEAD", sha1) < 0)
151                                 return 0;
152
153                         return add_one_path(ce, path, len, st);
154                 }
155                 /* Should this be an unconditional error? */
156                 return remove_one_path(path);
157         }
158
159         /* Inexact match: is there perhaps a subdirectory match? */
160         pos = -pos-1;
161         while (pos < active_nr) {
162                 const struct cache_entry *ce = active_cache[pos++];
163
164                 if (strncmp(ce->name, path, len))
165                         break;
166                 if (ce->name[len] > '/')
167                         break;
168                 if (ce->name[len] < '/')
169                         continue;
170
171                 /* Subdirectory match - error out */
172                 return error("%s: is a directory - add individual files instead", path);
173         }
174
175         /* No match - should we add it as a gitlink? */
176         if (!resolve_gitlink_ref(path, "HEAD", sha1))
177                 return add_one_path(NULL, path, len, st);
178
179         /* Error out. */
180         return error("%s: is a directory - add files inside instead", path);
181 }
182
183 static int process_path(const char *path)
184 {
185         int pos, len;
186         struct stat st;
187         const struct cache_entry *ce;
188
189         len = strlen(path);
190         if (has_symlink_leading_path(path, len))
191                 return error("'%s' is beyond a symbolic link", path);
192
193         pos = cache_name_pos(path, len);
194         ce = pos < 0 ? NULL : active_cache[pos];
195         if (ce && ce_skip_worktree(ce)) {
196                 /*
197                  * working directory version is assumed "good"
198                  * so updating it does not make sense.
199                  * On the other hand, removing it from index should work
200                  */
201                 if (allow_remove && remove_file_from_cache(path))
202                         return error("%s: cannot remove from the index", path);
203                 return 0;
204         }
205
206         /*
207          * First things first: get the stat information, to decide
208          * what to do about the pathname!
209          */
210         if (lstat(path, &st) < 0)
211                 return process_lstat_error(path, errno);
212
213         if (S_ISDIR(st.st_mode))
214                 return process_directory(path, len, &st);
215
216         return add_one_path(ce, path, len, &st);
217 }
218
219 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
220                          const char *path, int stage)
221 {
222         int size, len, option;
223         struct cache_entry *ce;
224
225         if (!verify_path(path))
226                 return error("Invalid path '%s'", path);
227
228         len = strlen(path);
229         size = cache_entry_size(len);
230         ce = xcalloc(1, size);
231
232         hashcpy(ce->sha1, sha1);
233         memcpy(ce->name, path, len);
234         ce->ce_flags = create_ce_flags(stage);
235         ce->ce_namelen = len;
236         ce->ce_mode = create_ce_mode(mode);
237         if (assume_unchanged)
238                 ce->ce_flags |= CE_VALID;
239         option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
240         option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
241         if (add_cache_entry(ce, option))
242                 return error("%s: cannot add to the index - missing --add option?",
243                              path);
244         report("add '%s'", path);
245         return 0;
246 }
247
248 static void chmod_path(int flip, const char *path)
249 {
250         int pos;
251         struct cache_entry *ce;
252         unsigned int mode;
253
254         pos = cache_name_pos(path, strlen(path));
255         if (pos < 0)
256                 goto fail;
257         ce = active_cache[pos];
258         mode = ce->ce_mode;
259         if (!S_ISREG(mode))
260                 goto fail;
261         switch (flip) {
262         case '+':
263                 ce->ce_mode |= 0111; break;
264         case '-':
265                 ce->ce_mode &= ~0111; break;
266         default:
267                 goto fail;
268         }
269         cache_tree_invalidate_path(active_cache_tree, path);
270         active_cache_changed = 1;
271         report("chmod %cx '%s'", flip, path);
272         return;
273  fail:
274         die("git update-index: cannot chmod %cx '%s'", flip, path);
275 }
276
277 static void update_one(const char *path)
278 {
279         if (!verify_path(path)) {
280                 fprintf(stderr, "Ignoring path %s\n", path);
281                 return;
282         }
283         if (mark_valid_only) {
284                 if (mark_ce_flags(path, CE_VALID, mark_valid_only == MARK_FLAG))
285                         die("Unable to mark file %s", path);
286                 return;
287         }
288         if (mark_skip_worktree_only) {
289                 if (mark_ce_flags(path, CE_SKIP_WORKTREE, mark_skip_worktree_only == MARK_FLAG))
290                         die("Unable to mark file %s", path);
291                 return;
292         }
293
294         if (force_remove) {
295                 if (remove_file_from_cache(path))
296                         die("git update-index: unable to remove %s", path);
297                 report("remove '%s'", path);
298                 return;
299         }
300         if (process_path(path))
301                 die("Unable to process path %s", path);
302         report("add '%s'", path);
303 }
304
305 static void read_index_info(int line_termination)
306 {
307         struct strbuf buf = STRBUF_INIT;
308         struct strbuf uq = STRBUF_INIT;
309
310         while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
311                 char *ptr, *tab;
312                 char *path_name;
313                 unsigned char sha1[20];
314                 unsigned int mode;
315                 unsigned long ul;
316                 int stage;
317
318                 /* This reads lines formatted in one of three formats:
319                  *
320                  * (1) mode         SP sha1          TAB path
321                  * The first format is what "git apply --index-info"
322                  * reports, and used to reconstruct a partial tree
323                  * that is used for phony merge base tree when falling
324                  * back on 3-way merge.
325                  *
326                  * (2) mode SP type SP sha1          TAB path
327                  * The second format is to stuff "git ls-tree" output
328                  * into the index file.
329                  *
330                  * (3) mode         SP sha1 SP stage TAB path
331                  * This format is to put higher order stages into the
332                  * index file and matches "git ls-files --stage" output.
333                  */
334                 errno = 0;
335                 ul = strtoul(buf.buf, &ptr, 8);
336                 if (ptr == buf.buf || *ptr != ' '
337                     || errno || (unsigned int) ul != ul)
338                         goto bad_line;
339                 mode = ul;
340
341                 tab = strchr(ptr, '\t');
342                 if (!tab || tab - ptr < 41)
343                         goto bad_line;
344
345                 if (tab[-2] == ' ' && '0' <= tab[-1] && tab[-1] <= '3') {
346                         stage = tab[-1] - '0';
347                         ptr = tab + 1; /* point at the head of path */
348                         tab = tab - 2; /* point at tail of sha1 */
349                 }
350                 else {
351                         stage = 0;
352                         ptr = tab + 1; /* point at the head of path */
353                 }
354
355                 if (get_sha1_hex(tab - 40, sha1) || tab[-41] != ' ')
356                         goto bad_line;
357
358                 path_name = ptr;
359                 if (line_termination && path_name[0] == '"') {
360                         strbuf_reset(&uq);
361                         if (unquote_c_style(&uq, path_name, NULL)) {
362                                 die("git update-index: bad quoting of path name");
363                         }
364                         path_name = uq.buf;
365                 }
366
367                 if (!verify_path(path_name)) {
368                         fprintf(stderr, "Ignoring path %s\n", path_name);
369                         continue;
370                 }
371
372                 if (!mode) {
373                         /* mode == 0 means there is no such path -- remove */
374                         if (remove_file_from_cache(path_name))
375                                 die("git update-index: unable to remove %s",
376                                     ptr);
377                 }
378                 else {
379                         /* mode ' ' sha1 '\t' name
380                          * ptr[-1] points at tab,
381                          * ptr[-41] is at the beginning of sha1
382                          */
383                         ptr[-42] = ptr[-1] = 0;
384                         if (add_cacheinfo(mode, sha1, path_name, stage))
385                                 die("git update-index: unable to update %s",
386                                     path_name);
387                 }
388                 continue;
389
390         bad_line:
391                 die("malformed index info %s", buf.buf);
392         }
393         strbuf_release(&buf);
394         strbuf_release(&uq);
395 }
396
397 static const char * const update_index_usage[] = {
398         N_("git update-index [options] [--] [<file>...]"),
399         NULL
400 };
401
402 static unsigned char head_sha1[20];
403 static unsigned char merge_head_sha1[20];
404
405 static struct cache_entry *read_one_ent(const char *which,
406                                         unsigned char *ent, const char *path,
407                                         int namelen, int stage)
408 {
409         unsigned mode;
410         unsigned char sha1[20];
411         int size;
412         struct cache_entry *ce;
413
414         if (get_tree_entry(ent, path, sha1, &mode)) {
415                 if (which)
416                         error("%s: not in %s branch.", path, which);
417                 return NULL;
418         }
419         if (mode == S_IFDIR) {
420                 if (which)
421                         error("%s: not a blob in %s branch.", path, which);
422                 return NULL;
423         }
424         size = cache_entry_size(namelen);
425         ce = xcalloc(1, size);
426
427         hashcpy(ce->sha1, sha1);
428         memcpy(ce->name, path, namelen);
429         ce->ce_flags = create_ce_flags(stage);
430         ce->ce_namelen = namelen;
431         ce->ce_mode = create_ce_mode(mode);
432         return ce;
433 }
434
435 static int unresolve_one(const char *path)
436 {
437         int namelen = strlen(path);
438         int pos;
439         int ret = 0;
440         struct cache_entry *ce_2 = NULL, *ce_3 = NULL;
441
442         /* See if there is such entry in the index. */
443         pos = cache_name_pos(path, namelen);
444         if (0 <= pos) {
445                 /* already merged */
446                 pos = unmerge_cache_entry_at(pos);
447                 if (pos < active_nr) {
448                         const struct cache_entry *ce = active_cache[pos];
449                         if (ce_stage(ce) &&
450                             ce_namelen(ce) == namelen &&
451                             !memcmp(ce->name, path, namelen))
452                                 return 0;
453                 }
454                 /* no resolve-undo information; fall back */
455         } else {
456                 /* If there isn't, either it is unmerged, or
457                  * resolved as "removed" by mistake.  We do not
458                  * want to do anything in the former case.
459                  */
460                 pos = -pos-1;
461                 if (pos < active_nr) {
462                         const struct cache_entry *ce = active_cache[pos];
463                         if (ce_namelen(ce) == namelen &&
464                             !memcmp(ce->name, path, namelen)) {
465                                 fprintf(stderr,
466                                         "%s: skipping still unmerged path.\n",
467                                         path);
468                                 goto free_return;
469                         }
470                 }
471         }
472
473         /* Grab blobs from given path from HEAD and MERGE_HEAD,
474          * stuff HEAD version in stage #2,
475          * stuff MERGE_HEAD version in stage #3.
476          */
477         ce_2 = read_one_ent("our", head_sha1, path, namelen, 2);
478         ce_3 = read_one_ent("their", merge_head_sha1, path, namelen, 3);
479
480         if (!ce_2 || !ce_3) {
481                 ret = -1;
482                 goto free_return;
483         }
484         if (!hashcmp(ce_2->sha1, ce_3->sha1) &&
485             ce_2->ce_mode == ce_3->ce_mode) {
486                 fprintf(stderr, "%s: identical in both, skipping.\n",
487                         path);
488                 goto free_return;
489         }
490
491         remove_file_from_cache(path);
492         if (add_cache_entry(ce_2, ADD_CACHE_OK_TO_ADD)) {
493                 error("%s: cannot add our version to the index.", path);
494                 ret = -1;
495                 goto free_return;
496         }
497         if (!add_cache_entry(ce_3, ADD_CACHE_OK_TO_ADD))
498                 return 0;
499         error("%s: cannot add their version to the index.", path);
500         ret = -1;
501  free_return:
502         free(ce_2);
503         free(ce_3);
504         return ret;
505 }
506
507 static void read_head_pointers(void)
508 {
509         if (read_ref("HEAD", head_sha1))
510                 die("No HEAD -- no initial commit yet?");
511         if (read_ref("MERGE_HEAD", merge_head_sha1)) {
512                 fprintf(stderr, "Not in the middle of a merge.\n");
513                 exit(0);
514         }
515 }
516
517 static int do_unresolve(int ac, const char **av,
518                         const char *prefix, int prefix_length)
519 {
520         int i;
521         int err = 0;
522
523         /* Read HEAD and MERGE_HEAD; if MERGE_HEAD does not exist, we
524          * are not doing a merge, so exit with success status.
525          */
526         read_head_pointers();
527
528         for (i = 1; i < ac; i++) {
529                 const char *arg = av[i];
530                 const char *p = prefix_path(prefix, prefix_length, arg);
531                 err |= unresolve_one(p);
532                 if (p < arg || p > arg + strlen(arg))
533                         free((char *)p);
534         }
535         return err;
536 }
537
538 static int do_reupdate(int ac, const char **av,
539                        const char *prefix, int prefix_length)
540 {
541         /* Read HEAD and run update-index on paths that are
542          * merged and already different between index and HEAD.
543          */
544         int pos;
545         int has_head = 1;
546         struct pathspec pathspec;
547
548         parse_pathspec(&pathspec, 0,
549                        PATHSPEC_PREFER_CWD,
550                        prefix, av + 1);
551
552         if (read_ref("HEAD", head_sha1))
553                 /* If there is no HEAD, that means it is an initial
554                  * commit.  Update everything in the index.
555                  */
556                 has_head = 0;
557  redo:
558         for (pos = 0; pos < active_nr; pos++) {
559                 const struct cache_entry *ce = active_cache[pos];
560                 struct cache_entry *old = NULL;
561                 int save_nr;
562                 char *path;
563
564                 if (ce_stage(ce) || !ce_path_match(ce, &pathspec))
565                         continue;
566                 if (has_head)
567                         old = read_one_ent(NULL, head_sha1,
568                                            ce->name, ce_namelen(ce), 0);
569                 if (old && ce->ce_mode == old->ce_mode &&
570                     !hashcmp(ce->sha1, old->sha1)) {
571                         free(old);
572                         continue; /* unchanged */
573                 }
574                 /* Be careful.  The working tree may not have the
575                  * path anymore, in which case, under 'allow_remove',
576                  * or worse yet 'allow_replace', active_nr may decrease.
577                  */
578                 save_nr = active_nr;
579                 path = xstrdup(ce->name);
580                 update_one(path);
581                 free(path);
582                 if (save_nr != active_nr)
583                         goto redo;
584         }
585         free_pathspec(&pathspec);
586         return 0;
587 }
588
589 struct refresh_params {
590         unsigned int flags;
591         int *has_errors;
592 };
593
594 static int refresh(struct refresh_params *o, unsigned int flag)
595 {
596         setup_work_tree();
597         read_cache_preload(NULL);
598         *o->has_errors |= refresh_cache(o->flags | flag);
599         return 0;
600 }
601
602 static int refresh_callback(const struct option *opt,
603                                 const char *arg, int unset)
604 {
605         return refresh(opt->value, 0);
606 }
607
608 static int really_refresh_callback(const struct option *opt,
609                                 const char *arg, int unset)
610 {
611         return refresh(opt->value, REFRESH_REALLY);
612 }
613
614 static int chmod_callback(const struct option *opt,
615                                 const char *arg, int unset)
616 {
617         char *flip = opt->value;
618         if ((arg[0] != '-' && arg[0] != '+') || arg[1] != 'x' || arg[2])
619                 return error("option 'chmod' expects \"+x\" or \"-x\"");
620         *flip = arg[0];
621         return 0;
622 }
623
624 static int resolve_undo_clear_callback(const struct option *opt,
625                                 const char *arg, int unset)
626 {
627         resolve_undo_clear();
628         return 0;
629 }
630
631 static int cacheinfo_callback(struct parse_opt_ctx_t *ctx,
632                                 const struct option *opt, int unset)
633 {
634         unsigned char sha1[20];
635         unsigned int mode;
636
637         if (ctx->argc <= 3)
638                 return error("option 'cacheinfo' expects three arguments");
639         if (strtoul_ui(*++ctx->argv, 8, &mode) ||
640             get_sha1_hex(*++ctx->argv, sha1) ||
641             add_cacheinfo(mode, sha1, *++ctx->argv, 0))
642                 die("git update-index: --cacheinfo cannot add %s", *ctx->argv);
643         ctx->argc -= 3;
644         return 0;
645 }
646
647 static int stdin_cacheinfo_callback(struct parse_opt_ctx_t *ctx,
648                               const struct option *opt, int unset)
649 {
650         int *line_termination = opt->value;
651
652         if (ctx->argc != 1)
653                 return error("option '%s' must be the last argument", opt->long_name);
654         allow_add = allow_replace = allow_remove = 1;
655         read_index_info(*line_termination);
656         return 0;
657 }
658
659 static int stdin_callback(struct parse_opt_ctx_t *ctx,
660                                 const struct option *opt, int unset)
661 {
662         int *read_from_stdin = opt->value;
663
664         if (ctx->argc != 1)
665                 return error("option '%s' must be the last argument", opt->long_name);
666         *read_from_stdin = 1;
667         return 0;
668 }
669
670 static int unresolve_callback(struct parse_opt_ctx_t *ctx,
671                                 const struct option *opt, int flags)
672 {
673         int *has_errors = opt->value;
674         const char *prefix = startup_info->prefix;
675
676         /* consume remaining arguments. */
677         *has_errors = do_unresolve(ctx->argc, ctx->argv,
678                                 prefix, prefix ? strlen(prefix) : 0);
679         if (*has_errors)
680                 active_cache_changed = 0;
681
682         ctx->argv += ctx->argc - 1;
683         ctx->argc = 1;
684         return 0;
685 }
686
687 static int reupdate_callback(struct parse_opt_ctx_t *ctx,
688                                 const struct option *opt, int flags)
689 {
690         int *has_errors = opt->value;
691         const char *prefix = startup_info->prefix;
692
693         /* consume remaining arguments. */
694         setup_work_tree();
695         *has_errors = do_reupdate(ctx->argc, ctx->argv,
696                                 prefix, prefix ? strlen(prefix) : 0);
697         if (*has_errors)
698                 active_cache_changed = 0;
699
700         ctx->argv += ctx->argc - 1;
701         ctx->argc = 1;
702         return 0;
703 }
704
705 int cmd_update_index(int argc, const char **argv, const char *prefix)
706 {
707         int newfd, entries, has_errors = 0, line_termination = '\n';
708         int read_from_stdin = 0;
709         int prefix_length = prefix ? strlen(prefix) : 0;
710         int preferred_index_format = 0;
711         char set_executable_bit = 0;
712         struct refresh_params refresh_args = {0, &has_errors};
713         int lock_error = 0;
714         struct lock_file *lock_file;
715         struct parse_opt_ctx_t ctx;
716         int parseopt_state = PARSE_OPT_UNKNOWN;
717         struct option options[] = {
718                 OPT_BIT('q', NULL, &refresh_args.flags,
719                         N_("continue refresh even when index needs update"),
720                         REFRESH_QUIET),
721                 OPT_BIT(0, "ignore-submodules", &refresh_args.flags,
722                         N_("refresh: ignore submodules"),
723                         REFRESH_IGNORE_SUBMODULES),
724                 OPT_SET_INT(0, "add", &allow_add,
725                         N_("do not ignore new files"), 1),
726                 OPT_SET_INT(0, "replace", &allow_replace,
727                         N_("let files replace directories and vice-versa"), 1),
728                 OPT_SET_INT(0, "remove", &allow_remove,
729                         N_("notice files missing from worktree"), 1),
730                 OPT_BIT(0, "unmerged", &refresh_args.flags,
731                         N_("refresh even if index contains unmerged entries"),
732                         REFRESH_UNMERGED),
733                 {OPTION_CALLBACK, 0, "refresh", &refresh_args, NULL,
734                         N_("refresh stat information"),
735                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
736                         refresh_callback},
737                 {OPTION_CALLBACK, 0, "really-refresh", &refresh_args, NULL,
738                         N_("like --refresh, but ignore assume-unchanged setting"),
739                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
740                         really_refresh_callback},
741                 {OPTION_LOWLEVEL_CALLBACK, 0, "cacheinfo", NULL,
742                         N_("<mode> <object> <path>"),
743                         N_("add the specified entry to the index"),
744                         PARSE_OPT_NOARG |       /* disallow --cacheinfo=<mode> form */
745                         PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
746                         (parse_opt_cb *) cacheinfo_callback},
747                 {OPTION_CALLBACK, 0, "chmod", &set_executable_bit, N_("(+/-)x"),
748                         N_("override the executable bit of the listed files"),
749                         PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
750                         chmod_callback},
751                 {OPTION_SET_INT, 0, "assume-unchanged", &mark_valid_only, NULL,
752                         N_("mark files as \"not changing\""),
753                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
754                 {OPTION_SET_INT, 0, "no-assume-unchanged", &mark_valid_only, NULL,
755                         N_("clear assumed-unchanged bit"),
756                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
757                 {OPTION_SET_INT, 0, "skip-worktree", &mark_skip_worktree_only, NULL,
758                         N_("mark files as \"index-only\""),
759                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
760                 {OPTION_SET_INT, 0, "no-skip-worktree", &mark_skip_worktree_only, NULL,
761                         N_("clear skip-worktree bit"),
762                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
763                 OPT_SET_INT(0, "info-only", &info_only,
764                         N_("add to index only; do not add content to object database"), 1),
765                 OPT_SET_INT(0, "force-remove", &force_remove,
766                         N_("remove named paths even if present in worktree"), 1),
767                 OPT_SET_INT('z', NULL, &line_termination,
768                         N_("with --stdin: input lines are terminated by null bytes"), '\0'),
769                 {OPTION_LOWLEVEL_CALLBACK, 0, "stdin", &read_from_stdin, NULL,
770                         N_("read list of paths to be updated from standard input"),
771                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
772                         (parse_opt_cb *) stdin_callback},
773                 {OPTION_LOWLEVEL_CALLBACK, 0, "index-info", &line_termination, NULL,
774                         N_("add entries from standard input to the index"),
775                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
776                         (parse_opt_cb *) stdin_cacheinfo_callback},
777                 {OPTION_LOWLEVEL_CALLBACK, 0, "unresolve", &has_errors, NULL,
778                         N_("repopulate stages #2 and #3 for the listed paths"),
779                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
780                         (parse_opt_cb *) unresolve_callback},
781                 {OPTION_LOWLEVEL_CALLBACK, 'g', "again", &has_errors, NULL,
782                         N_("only update entries that differ from HEAD"),
783                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
784                         (parse_opt_cb *) reupdate_callback},
785                 OPT_BIT(0, "ignore-missing", &refresh_args.flags,
786                         N_("ignore files missing from worktree"),
787                         REFRESH_IGNORE_MISSING),
788                 OPT_SET_INT(0, "verbose", &verbose,
789                         N_("report actions to standard output"), 1),
790                 {OPTION_CALLBACK, 0, "clear-resolve-undo", NULL, NULL,
791                         N_("(for porcelains) forget saved unresolved conflicts"),
792                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
793                         resolve_undo_clear_callback},
794                 OPT_INTEGER(0, "index-version", &preferred_index_format,
795                         N_("write index in this format")),
796                 OPT_END()
797         };
798
799         if (argc == 2 && !strcmp(argv[1], "-h"))
800                 usage_with_options(update_index_usage, options);
801
802         git_config(git_default_config, NULL);
803
804         /* We can't free this memory, it becomes part of a linked list parsed atexit() */
805         lock_file = xcalloc(1, sizeof(struct lock_file));
806
807         newfd = hold_locked_index(lock_file, 0);
808         if (newfd < 0)
809                 lock_error = errno;
810
811         entries = read_cache();
812         if (entries < 0)
813                 die("cache corrupted");
814
815         /*
816          * Custom copy of parse_options() because we want to handle
817          * filename arguments as they come.
818          */
819         parse_options_start(&ctx, argc, argv, prefix,
820                             options, PARSE_OPT_STOP_AT_NON_OPTION);
821         while (ctx.argc) {
822                 if (parseopt_state != PARSE_OPT_DONE)
823                         parseopt_state = parse_options_step(&ctx, options,
824                                                             update_index_usage);
825                 if (!ctx.argc)
826                         break;
827                 switch (parseopt_state) {
828                 case PARSE_OPT_HELP:
829                         exit(129);
830                 case PARSE_OPT_NON_OPTION:
831                 case PARSE_OPT_DONE:
832                 {
833                         const char *path = ctx.argv[0];
834                         const char *p;
835
836                         setup_work_tree();
837                         p = prefix_path(prefix, prefix_length, path);
838                         update_one(p);
839                         if (set_executable_bit)
840                                 chmod_path(set_executable_bit, p);
841                         free((char *)p);
842                         ctx.argc--;
843                         ctx.argv++;
844                         break;
845                 }
846                 case PARSE_OPT_UNKNOWN:
847                         if (ctx.argv[0][1] == '-')
848                                 error("unknown option '%s'", ctx.argv[0] + 2);
849                         else
850                                 error("unknown switch '%c'", *ctx.opt);
851                         usage_with_options(update_index_usage, options);
852                 }
853         }
854         argc = parse_options_end(&ctx);
855         if (preferred_index_format) {
856                 if (preferred_index_format < INDEX_FORMAT_LB ||
857                     INDEX_FORMAT_UB < preferred_index_format)
858                         die("index-version %d not in range: %d..%d",
859                             preferred_index_format,
860                             INDEX_FORMAT_LB, INDEX_FORMAT_UB);
861
862                 if (the_index.version != preferred_index_format)
863                         active_cache_changed = 1;
864                 the_index.version = preferred_index_format;
865         }
866
867         if (read_from_stdin) {
868                 struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT;
869
870                 setup_work_tree();
871                 while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
872                         const char *p;
873                         if (line_termination && buf.buf[0] == '"') {
874                                 strbuf_reset(&nbuf);
875                                 if (unquote_c_style(&nbuf, buf.buf, NULL))
876                                         die("line is badly quoted");
877                                 strbuf_swap(&buf, &nbuf);
878                         }
879                         p = prefix_path(prefix, prefix_length, buf.buf);
880                         update_one(p);
881                         if (set_executable_bit)
882                                 chmod_path(set_executable_bit, p);
883                         free((char *)p);
884                 }
885                 strbuf_release(&nbuf);
886                 strbuf_release(&buf);
887         }
888
889         if (active_cache_changed) {
890                 if (newfd < 0) {
891                         if (refresh_args.flags & REFRESH_QUIET)
892                                 exit(128);
893                         unable_to_lock_index_die(get_index_file(), lock_error);
894                 }
895                 if (write_cache(newfd, active_cache, active_nr) ||
896                     commit_locked_index(lock_file))
897                         die("Unable to write new index file");
898         }
899
900         rollback_lock_file(lock_file);
901
902         return has_errors ? 1 : 0;
903 }