update-index: fix xgetcwd() related memory leak
[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 "lockfile.h"
8 #include "quote.h"
9 #include "cache-tree.h"
10 #include "tree-walk.h"
11 #include "builtin.h"
12 #include "refs.h"
13 #include "resolve-undo.h"
14 #include "parse-options.h"
15 #include "pathspec.h"
16 #include "dir.h"
17 #include "split-index.h"
18
19 /*
20  * Default to not allowing changes to the list of files. The
21  * tool doesn't actually care, but this makes it harder to add
22  * files to the revision control by mistake by doing something
23  * like "git update-index *" and suddenly having all the object
24  * files be revision controlled.
25  */
26 static int allow_add;
27 static int allow_remove;
28 static int allow_replace;
29 static int info_only;
30 static int force_remove;
31 static int verbose;
32 static int mark_valid_only;
33 static int mark_skip_worktree_only;
34 #define MARK_FLAG 1
35 #define UNMARK_FLAG 2
36 static struct strbuf mtime_dir = STRBUF_INIT;
37
38 /* Untracked cache mode */
39 enum uc_mode {
40         UC_UNSPECIFIED = -1,
41         UC_DISABLE = 0,
42         UC_ENABLE,
43         UC_TEST,
44         UC_FORCE
45 };
46
47 __attribute__((format (printf, 1, 2)))
48 static void report(const char *fmt, ...)
49 {
50         va_list vp;
51
52         if (!verbose)
53                 return;
54
55         va_start(vp, fmt);
56         vprintf(fmt, vp);
57         putchar('\n');
58         va_end(vp);
59 }
60
61 static void remove_test_directory(void)
62 {
63         if (mtime_dir.len)
64                 remove_dir_recursively(&mtime_dir, 0);
65 }
66
67 static const char *get_mtime_path(const char *path)
68 {
69         static struct strbuf sb = STRBUF_INIT;
70         strbuf_reset(&sb);
71         strbuf_addf(&sb, "%s/%s", mtime_dir.buf, path);
72         return sb.buf;
73 }
74
75 static void xmkdir(const char *path)
76 {
77         path = get_mtime_path(path);
78         if (mkdir(path, 0700))
79                 die_errno(_("failed to create directory %s"), path);
80 }
81
82 static int xstat_mtime_dir(struct stat *st)
83 {
84         if (stat(mtime_dir.buf, st))
85                 die_errno(_("failed to stat %s"), mtime_dir.buf);
86         return 0;
87 }
88
89 static int create_file(const char *path)
90 {
91         int fd;
92         path = get_mtime_path(path);
93         fd = open(path, O_CREAT | O_RDWR, 0644);
94         if (fd < 0)
95                 die_errno(_("failed to create file %s"), path);
96         return fd;
97 }
98
99 static void xunlink(const char *path)
100 {
101         path = get_mtime_path(path);
102         if (unlink(path))
103                 die_errno(_("failed to delete file %s"), path);
104 }
105
106 static void xrmdir(const char *path)
107 {
108         path = get_mtime_path(path);
109         if (rmdir(path))
110                 die_errno(_("failed to delete directory %s"), path);
111 }
112
113 static void avoid_racy(void)
114 {
115         /*
116          * not use if we could usleep(10) if USE_NSEC is defined. The
117          * field nsec could be there, but the OS could choose to
118          * ignore it?
119          */
120         sleep(1);
121 }
122
123 static int test_if_untracked_cache_is_supported(void)
124 {
125         struct stat st;
126         struct stat_data base;
127         int fd, ret = 0;
128         char *cwd;
129
130         strbuf_addstr(&mtime_dir, "mtime-test-XXXXXX");
131         if (!mkdtemp(mtime_dir.buf))
132                 die_errno("Could not make temporary directory");
133
134         cwd = xgetcwd();
135         fprintf(stderr, _("Testing mtime in '%s' "), cwd);
136         free(cwd);
137
138         atexit(remove_test_directory);
139         xstat_mtime_dir(&st);
140         fill_stat_data(&base, &st);
141         fputc('.', stderr);
142
143         avoid_racy();
144         fd = create_file("newfile");
145         xstat_mtime_dir(&st);
146         if (!match_stat_data(&base, &st)) {
147                 close(fd);
148                 fputc('\n', stderr);
149                 fprintf_ln(stderr,_("directory stat info does not "
150                                     "change after adding a new file"));
151                 goto done;
152         }
153         fill_stat_data(&base, &st);
154         fputc('.', stderr);
155
156         avoid_racy();
157         xmkdir("new-dir");
158         xstat_mtime_dir(&st);
159         if (!match_stat_data(&base, &st)) {
160                 close(fd);
161                 fputc('\n', stderr);
162                 fprintf_ln(stderr, _("directory stat info does not change "
163                                      "after adding a new directory"));
164                 goto done;
165         }
166         fill_stat_data(&base, &st);
167         fputc('.', stderr);
168
169         avoid_racy();
170         write_or_die(fd, "data", 4);
171         close(fd);
172         xstat_mtime_dir(&st);
173         if (match_stat_data(&base, &st)) {
174                 fputc('\n', stderr);
175                 fprintf_ln(stderr, _("directory stat info changes "
176                                      "after updating a file"));
177                 goto done;
178         }
179         fputc('.', stderr);
180
181         avoid_racy();
182         close(create_file("new-dir/new"));
183         xstat_mtime_dir(&st);
184         if (match_stat_data(&base, &st)) {
185                 fputc('\n', stderr);
186                 fprintf_ln(stderr, _("directory stat info changes after "
187                                      "adding a file inside subdirectory"));
188                 goto done;
189         }
190         fputc('.', stderr);
191
192         avoid_racy();
193         xunlink("newfile");
194         xstat_mtime_dir(&st);
195         if (!match_stat_data(&base, &st)) {
196                 fputc('\n', stderr);
197                 fprintf_ln(stderr, _("directory stat info does not "
198                                      "change after deleting a file"));
199                 goto done;
200         }
201         fill_stat_data(&base, &st);
202         fputc('.', stderr);
203
204         avoid_racy();
205         xunlink("new-dir/new");
206         xrmdir("new-dir");
207         xstat_mtime_dir(&st);
208         if (!match_stat_data(&base, &st)) {
209                 fputc('\n', stderr);
210                 fprintf_ln(stderr, _("directory stat info does not "
211                                      "change after deleting a directory"));
212                 goto done;
213         }
214
215         if (rmdir(mtime_dir.buf))
216                 die_errno(_("failed to delete directory %s"), mtime_dir.buf);
217         fprintf_ln(stderr, _(" OK"));
218         ret = 1;
219
220 done:
221         strbuf_release(&mtime_dir);
222         return ret;
223 }
224
225 static int mark_ce_flags(const char *path, int flag, int mark)
226 {
227         int namelen = strlen(path);
228         int pos = cache_name_pos(path, namelen);
229         if (0 <= pos) {
230                 if (mark)
231                         active_cache[pos]->ce_flags |= flag;
232                 else
233                         active_cache[pos]->ce_flags &= ~flag;
234                 active_cache[pos]->ce_flags |= CE_UPDATE_IN_BASE;
235                 cache_tree_invalidate_path(&the_index, path);
236                 active_cache_changed |= CE_ENTRY_CHANGED;
237                 return 0;
238         }
239         return -1;
240 }
241
242 static int remove_one_path(const char *path)
243 {
244         if (!allow_remove)
245                 return error("%s: does not exist and --remove not passed", path);
246         if (remove_file_from_cache(path))
247                 return error("%s: cannot remove from the index", path);
248         return 0;
249 }
250
251 /*
252  * Handle a path that couldn't be lstat'ed. It's either:
253  *  - missing file (ENOENT or ENOTDIR). That's ok if we're
254  *    supposed to be removing it and the removal actually
255  *    succeeds.
256  *  - permission error. That's never ok.
257  */
258 static int process_lstat_error(const char *path, int err)
259 {
260         if (err == ENOENT || err == ENOTDIR)
261                 return remove_one_path(path);
262         return error("lstat(\"%s\"): %s", path, strerror(errno));
263 }
264
265 static int add_one_path(const struct cache_entry *old, const char *path, int len, struct stat *st)
266 {
267         int option, size;
268         struct cache_entry *ce;
269
270         /* Was the old index entry already up-to-date? */
271         if (old && !ce_stage(old) && !ce_match_stat(old, st, 0))
272                 return 0;
273
274         size = cache_entry_size(len);
275         ce = xcalloc(1, size);
276         memcpy(ce->name, path, len);
277         ce->ce_flags = create_ce_flags(0);
278         ce->ce_namelen = len;
279         fill_stat_cache_info(ce, st);
280         ce->ce_mode = ce_mode_from_stat(old, st->st_mode);
281
282         if (index_path(ce->sha1, path, st,
283                        info_only ? 0 : HASH_WRITE_OBJECT)) {
284                 free(ce);
285                 return -1;
286         }
287         option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
288         option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
289         if (add_cache_entry(ce, option))
290                 return error("%s: cannot add to the index - missing --add option?", path);
291         return 0;
292 }
293
294 /*
295  * Handle a path that was a directory. Four cases:
296  *
297  *  - it's already a gitlink in the index, and we keep it that
298  *    way, and update it if we can (if we cannot find the HEAD,
299  *    we're going to keep it unchanged in the index!)
300  *
301  *  - it's a *file* in the index, in which case it should be
302  *    removed as a file if removal is allowed, since it doesn't
303  *    exist as such any more. If removal isn't allowed, it's
304  *    an error.
305  *
306  *    (NOTE! This is old and arguably fairly strange behaviour.
307  *    We might want to make this an error unconditionally, and
308  *    use "--force-remove" if you actually want to force removal).
309  *
310  *  - it used to exist as a subdirectory (ie multiple files with
311  *    this particular prefix) in the index, in which case it's wrong
312  *    to try to update it as a directory.
313  *
314  *  - it doesn't exist at all in the index, but it is a valid
315  *    git directory, and it should be *added* as a gitlink.
316  */
317 static int process_directory(const char *path, int len, struct stat *st)
318 {
319         unsigned char sha1[20];
320         int pos = cache_name_pos(path, len);
321
322         /* Exact match: file or existing gitlink */
323         if (pos >= 0) {
324                 const struct cache_entry *ce = active_cache[pos];
325                 if (S_ISGITLINK(ce->ce_mode)) {
326
327                         /* Do nothing to the index if there is no HEAD! */
328                         if (resolve_gitlink_ref(path, "HEAD", sha1) < 0)
329                                 return 0;
330
331                         return add_one_path(ce, path, len, st);
332                 }
333                 /* Should this be an unconditional error? */
334                 return remove_one_path(path);
335         }
336
337         /* Inexact match: is there perhaps a subdirectory match? */
338         pos = -pos-1;
339         while (pos < active_nr) {
340                 const struct cache_entry *ce = active_cache[pos++];
341
342                 if (strncmp(ce->name, path, len))
343                         break;
344                 if (ce->name[len] > '/')
345                         break;
346                 if (ce->name[len] < '/')
347                         continue;
348
349                 /* Subdirectory match - error out */
350                 return error("%s: is a directory - add individual files instead", path);
351         }
352
353         /* No match - should we add it as a gitlink? */
354         if (!resolve_gitlink_ref(path, "HEAD", sha1))
355                 return add_one_path(NULL, path, len, st);
356
357         /* Error out. */
358         return error("%s: is a directory - add files inside instead", path);
359 }
360
361 static int process_path(const char *path)
362 {
363         int pos, len;
364         struct stat st;
365         const struct cache_entry *ce;
366
367         len = strlen(path);
368         if (has_symlink_leading_path(path, len))
369                 return error("'%s' is beyond a symbolic link", path);
370
371         pos = cache_name_pos(path, len);
372         ce = pos < 0 ? NULL : active_cache[pos];
373         if (ce && ce_skip_worktree(ce)) {
374                 /*
375                  * working directory version is assumed "good"
376                  * so updating it does not make sense.
377                  * On the other hand, removing it from index should work
378                  */
379                 if (allow_remove && remove_file_from_cache(path))
380                         return error("%s: cannot remove from the index", path);
381                 return 0;
382         }
383
384         /*
385          * First things first: get the stat information, to decide
386          * what to do about the pathname!
387          */
388         if (lstat(path, &st) < 0)
389                 return process_lstat_error(path, errno);
390
391         if (S_ISDIR(st.st_mode))
392                 return process_directory(path, len, &st);
393
394         return add_one_path(ce, path, len, &st);
395 }
396
397 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
398                          const char *path, int stage)
399 {
400         int size, len, option;
401         struct cache_entry *ce;
402
403         if (!verify_path(path))
404                 return error("Invalid path '%s'", path);
405
406         len = strlen(path);
407         size = cache_entry_size(len);
408         ce = xcalloc(1, size);
409
410         hashcpy(ce->sha1, sha1);
411         memcpy(ce->name, path, len);
412         ce->ce_flags = create_ce_flags(stage);
413         ce->ce_namelen = len;
414         ce->ce_mode = create_ce_mode(mode);
415         if (assume_unchanged)
416                 ce->ce_flags |= CE_VALID;
417         option = allow_add ? ADD_CACHE_OK_TO_ADD : 0;
418         option |= allow_replace ? ADD_CACHE_OK_TO_REPLACE : 0;
419         if (add_cache_entry(ce, option))
420                 return error("%s: cannot add to the index - missing --add option?",
421                              path);
422         report("add '%s'", path);
423         return 0;
424 }
425
426 static void chmod_path(int flip, const char *path)
427 {
428         int pos;
429         struct cache_entry *ce;
430         unsigned int mode;
431
432         pos = cache_name_pos(path, strlen(path));
433         if (pos < 0)
434                 goto fail;
435         ce = active_cache[pos];
436         mode = ce->ce_mode;
437         if (!S_ISREG(mode))
438                 goto fail;
439         switch (flip) {
440         case '+':
441                 ce->ce_mode |= 0111; break;
442         case '-':
443                 ce->ce_mode &= ~0111; break;
444         default:
445                 goto fail;
446         }
447         cache_tree_invalidate_path(&the_index, path);
448         ce->ce_flags |= CE_UPDATE_IN_BASE;
449         active_cache_changed |= CE_ENTRY_CHANGED;
450         report("chmod %cx '%s'", flip, path);
451         return;
452  fail:
453         die("git update-index: cannot chmod %cx '%s'", flip, path);
454 }
455
456 static void update_one(const char *path)
457 {
458         if (!verify_path(path)) {
459                 fprintf(stderr, "Ignoring path %s\n", path);
460                 return;
461         }
462         if (mark_valid_only) {
463                 if (mark_ce_flags(path, CE_VALID, mark_valid_only == MARK_FLAG))
464                         die("Unable to mark file %s", path);
465                 return;
466         }
467         if (mark_skip_worktree_only) {
468                 if (mark_ce_flags(path, CE_SKIP_WORKTREE, mark_skip_worktree_only == MARK_FLAG))
469                         die("Unable to mark file %s", path);
470                 return;
471         }
472
473         if (force_remove) {
474                 if (remove_file_from_cache(path))
475                         die("git update-index: unable to remove %s", path);
476                 report("remove '%s'", path);
477                 return;
478         }
479         if (process_path(path))
480                 die("Unable to process path %s", path);
481         report("add '%s'", path);
482 }
483
484 static void read_index_info(int line_termination)
485 {
486         struct strbuf buf = STRBUF_INIT;
487         struct strbuf uq = STRBUF_INIT;
488
489         while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
490                 char *ptr, *tab;
491                 char *path_name;
492                 unsigned char sha1[20];
493                 unsigned int mode;
494                 unsigned long ul;
495                 int stage;
496
497                 /* This reads lines formatted in one of three formats:
498                  *
499                  * (1) mode         SP sha1          TAB path
500                  * The first format is what "git apply --index-info"
501                  * reports, and used to reconstruct a partial tree
502                  * that is used for phony merge base tree when falling
503                  * back on 3-way merge.
504                  *
505                  * (2) mode SP type SP sha1          TAB path
506                  * The second format is to stuff "git ls-tree" output
507                  * into the index file.
508                  *
509                  * (3) mode         SP sha1 SP stage TAB path
510                  * This format is to put higher order stages into the
511                  * index file and matches "git ls-files --stage" output.
512                  */
513                 errno = 0;
514                 ul = strtoul(buf.buf, &ptr, 8);
515                 if (ptr == buf.buf || *ptr != ' '
516                     || errno || (unsigned int) ul != ul)
517                         goto bad_line;
518                 mode = ul;
519
520                 tab = strchr(ptr, '\t');
521                 if (!tab || tab - ptr < 41)
522                         goto bad_line;
523
524                 if (tab[-2] == ' ' && '0' <= tab[-1] && tab[-1] <= '3') {
525                         stage = tab[-1] - '0';
526                         ptr = tab + 1; /* point at the head of path */
527                         tab = tab - 2; /* point at tail of sha1 */
528                 }
529                 else {
530                         stage = 0;
531                         ptr = tab + 1; /* point at the head of path */
532                 }
533
534                 if (get_sha1_hex(tab - 40, sha1) || tab[-41] != ' ')
535                         goto bad_line;
536
537                 path_name = ptr;
538                 if (line_termination && path_name[0] == '"') {
539                         strbuf_reset(&uq);
540                         if (unquote_c_style(&uq, path_name, NULL)) {
541                                 die("git update-index: bad quoting of path name");
542                         }
543                         path_name = uq.buf;
544                 }
545
546                 if (!verify_path(path_name)) {
547                         fprintf(stderr, "Ignoring path %s\n", path_name);
548                         continue;
549                 }
550
551                 if (!mode) {
552                         /* mode == 0 means there is no such path -- remove */
553                         if (remove_file_from_cache(path_name))
554                                 die("git update-index: unable to remove %s",
555                                     ptr);
556                 }
557                 else {
558                         /* mode ' ' sha1 '\t' name
559                          * ptr[-1] points at tab,
560                          * ptr[-41] is at the beginning of sha1
561                          */
562                         ptr[-42] = ptr[-1] = 0;
563                         if (add_cacheinfo(mode, sha1, path_name, stage))
564                                 die("git update-index: unable to update %s",
565                                     path_name);
566                 }
567                 continue;
568
569         bad_line:
570                 die("malformed index info %s", buf.buf);
571         }
572         strbuf_release(&buf);
573         strbuf_release(&uq);
574 }
575
576 static const char * const update_index_usage[] = {
577         N_("git update-index [<options>] [--] [<file>...]"),
578         NULL
579 };
580
581 static unsigned char head_sha1[20];
582 static unsigned char merge_head_sha1[20];
583
584 static struct cache_entry *read_one_ent(const char *which,
585                                         unsigned char *ent, const char *path,
586                                         int namelen, int stage)
587 {
588         unsigned mode;
589         unsigned char sha1[20];
590         int size;
591         struct cache_entry *ce;
592
593         if (get_tree_entry(ent, path, sha1, &mode)) {
594                 if (which)
595                         error("%s: not in %s branch.", path, which);
596                 return NULL;
597         }
598         if (mode == S_IFDIR) {
599                 if (which)
600                         error("%s: not a blob in %s branch.", path, which);
601                 return NULL;
602         }
603         size = cache_entry_size(namelen);
604         ce = xcalloc(1, size);
605
606         hashcpy(ce->sha1, sha1);
607         memcpy(ce->name, path, namelen);
608         ce->ce_flags = create_ce_flags(stage);
609         ce->ce_namelen = namelen;
610         ce->ce_mode = create_ce_mode(mode);
611         return ce;
612 }
613
614 static int unresolve_one(const char *path)
615 {
616         int namelen = strlen(path);
617         int pos;
618         int ret = 0;
619         struct cache_entry *ce_2 = NULL, *ce_3 = NULL;
620
621         /* See if there is such entry in the index. */
622         pos = cache_name_pos(path, namelen);
623         if (0 <= pos) {
624                 /* already merged */
625                 pos = unmerge_cache_entry_at(pos);
626                 if (pos < active_nr) {
627                         const struct cache_entry *ce = active_cache[pos];
628                         if (ce_stage(ce) &&
629                             ce_namelen(ce) == namelen &&
630                             !memcmp(ce->name, path, namelen))
631                                 return 0;
632                 }
633                 /* no resolve-undo information; fall back */
634         } else {
635                 /* If there isn't, either it is unmerged, or
636                  * resolved as "removed" by mistake.  We do not
637                  * want to do anything in the former case.
638                  */
639                 pos = -pos-1;
640                 if (pos < active_nr) {
641                         const struct cache_entry *ce = active_cache[pos];
642                         if (ce_namelen(ce) == namelen &&
643                             !memcmp(ce->name, path, namelen)) {
644                                 fprintf(stderr,
645                                         "%s: skipping still unmerged path.\n",
646                                         path);
647                                 goto free_return;
648                         }
649                 }
650         }
651
652         /* Grab blobs from given path from HEAD and MERGE_HEAD,
653          * stuff HEAD version in stage #2,
654          * stuff MERGE_HEAD version in stage #3.
655          */
656         ce_2 = read_one_ent("our", head_sha1, path, namelen, 2);
657         ce_3 = read_one_ent("their", merge_head_sha1, path, namelen, 3);
658
659         if (!ce_2 || !ce_3) {
660                 ret = -1;
661                 goto free_return;
662         }
663         if (!hashcmp(ce_2->sha1, ce_3->sha1) &&
664             ce_2->ce_mode == ce_3->ce_mode) {
665                 fprintf(stderr, "%s: identical in both, skipping.\n",
666                         path);
667                 goto free_return;
668         }
669
670         remove_file_from_cache(path);
671         if (add_cache_entry(ce_2, ADD_CACHE_OK_TO_ADD)) {
672                 error("%s: cannot add our version to the index.", path);
673                 ret = -1;
674                 goto free_return;
675         }
676         if (!add_cache_entry(ce_3, ADD_CACHE_OK_TO_ADD))
677                 return 0;
678         error("%s: cannot add their version to the index.", path);
679         ret = -1;
680  free_return:
681         free(ce_2);
682         free(ce_3);
683         return ret;
684 }
685
686 static void read_head_pointers(void)
687 {
688         if (read_ref("HEAD", head_sha1))
689                 die("No HEAD -- no initial commit yet?");
690         if (read_ref("MERGE_HEAD", merge_head_sha1)) {
691                 fprintf(stderr, "Not in the middle of a merge.\n");
692                 exit(0);
693         }
694 }
695
696 static int do_unresolve(int ac, const char **av,
697                         const char *prefix, int prefix_length)
698 {
699         int i;
700         int err = 0;
701
702         /* Read HEAD and MERGE_HEAD; if MERGE_HEAD does not exist, we
703          * are not doing a merge, so exit with success status.
704          */
705         read_head_pointers();
706
707         for (i = 1; i < ac; i++) {
708                 const char *arg = av[i];
709                 char *p = prefix_path(prefix, prefix_length, arg);
710                 err |= unresolve_one(p);
711                 free(p);
712         }
713         return err;
714 }
715
716 static int do_reupdate(int ac, const char **av,
717                        const char *prefix, int prefix_length)
718 {
719         /* Read HEAD and run update-index on paths that are
720          * merged and already different between index and HEAD.
721          */
722         int pos;
723         int has_head = 1;
724         struct pathspec pathspec;
725
726         parse_pathspec(&pathspec, 0,
727                        PATHSPEC_PREFER_CWD,
728                        prefix, av + 1);
729
730         if (read_ref("HEAD", head_sha1))
731                 /* If there is no HEAD, that means it is an initial
732                  * commit.  Update everything in the index.
733                  */
734                 has_head = 0;
735  redo:
736         for (pos = 0; pos < active_nr; pos++) {
737                 const struct cache_entry *ce = active_cache[pos];
738                 struct cache_entry *old = NULL;
739                 int save_nr;
740                 char *path;
741
742                 if (ce_stage(ce) || !ce_path_match(ce, &pathspec, NULL))
743                         continue;
744                 if (has_head)
745                         old = read_one_ent(NULL, head_sha1,
746                                            ce->name, ce_namelen(ce), 0);
747                 if (old && ce->ce_mode == old->ce_mode &&
748                     !hashcmp(ce->sha1, old->sha1)) {
749                         free(old);
750                         continue; /* unchanged */
751                 }
752                 /* Be careful.  The working tree may not have the
753                  * path anymore, in which case, under 'allow_remove',
754                  * or worse yet 'allow_replace', active_nr may decrease.
755                  */
756                 save_nr = active_nr;
757                 path = xstrdup(ce->name);
758                 update_one(path);
759                 free(path);
760                 free(old);
761                 if (save_nr != active_nr)
762                         goto redo;
763         }
764         free_pathspec(&pathspec);
765         return 0;
766 }
767
768 struct refresh_params {
769         unsigned int flags;
770         int *has_errors;
771 };
772
773 static int refresh(struct refresh_params *o, unsigned int flag)
774 {
775         setup_work_tree();
776         read_cache_preload(NULL);
777         *o->has_errors |= refresh_cache(o->flags | flag);
778         return 0;
779 }
780
781 static int refresh_callback(const struct option *opt,
782                                 const char *arg, int unset)
783 {
784         return refresh(opt->value, 0);
785 }
786
787 static int really_refresh_callback(const struct option *opt,
788                                 const char *arg, int unset)
789 {
790         return refresh(opt->value, REFRESH_REALLY);
791 }
792
793 static int chmod_callback(const struct option *opt,
794                                 const char *arg, int unset)
795 {
796         char *flip = opt->value;
797         if ((arg[0] != '-' && arg[0] != '+') || arg[1] != 'x' || arg[2])
798                 return error("option 'chmod' expects \"+x\" or \"-x\"");
799         *flip = arg[0];
800         return 0;
801 }
802
803 static int resolve_undo_clear_callback(const struct option *opt,
804                                 const char *arg, int unset)
805 {
806         resolve_undo_clear();
807         return 0;
808 }
809
810 static int parse_new_style_cacheinfo(const char *arg,
811                                      unsigned int *mode,
812                                      unsigned char sha1[],
813                                      const char **path)
814 {
815         unsigned long ul;
816         char *endp;
817
818         if (!arg)
819                 return -1;
820
821         errno = 0;
822         ul = strtoul(arg, &endp, 8);
823         if (errno || endp == arg || *endp != ',' || (unsigned int) ul != ul)
824                 return -1; /* not a new-style cacheinfo */
825         *mode = ul;
826         endp++;
827         if (get_sha1_hex(endp, sha1) || endp[40] != ',')
828                 return -1;
829         *path = endp + 41;
830         return 0;
831 }
832
833 static int cacheinfo_callback(struct parse_opt_ctx_t *ctx,
834                                 const struct option *opt, int unset)
835 {
836         unsigned char sha1[20];
837         unsigned int mode;
838         const char *path;
839
840         if (!parse_new_style_cacheinfo(ctx->argv[1], &mode, sha1, &path)) {
841                 if (add_cacheinfo(mode, sha1, path, 0))
842                         die("git update-index: --cacheinfo cannot add %s", path);
843                 ctx->argv++;
844                 ctx->argc--;
845                 return 0;
846         }
847         if (ctx->argc <= 3)
848                 return error("option 'cacheinfo' expects <mode>,<sha1>,<path>");
849         if (strtoul_ui(*++ctx->argv, 8, &mode) ||
850             get_sha1_hex(*++ctx->argv, sha1) ||
851             add_cacheinfo(mode, sha1, *++ctx->argv, 0))
852                 die("git update-index: --cacheinfo cannot add %s", *ctx->argv);
853         ctx->argc -= 3;
854         return 0;
855 }
856
857 static int stdin_cacheinfo_callback(struct parse_opt_ctx_t *ctx,
858                               const struct option *opt, int unset)
859 {
860         int *line_termination = opt->value;
861
862         if (ctx->argc != 1)
863                 return error("option '%s' must be the last argument", opt->long_name);
864         allow_add = allow_replace = allow_remove = 1;
865         read_index_info(*line_termination);
866         return 0;
867 }
868
869 static int stdin_callback(struct parse_opt_ctx_t *ctx,
870                                 const struct option *opt, int unset)
871 {
872         int *read_from_stdin = opt->value;
873
874         if (ctx->argc != 1)
875                 return error("option '%s' must be the last argument", opt->long_name);
876         *read_from_stdin = 1;
877         return 0;
878 }
879
880 static int unresolve_callback(struct parse_opt_ctx_t *ctx,
881                                 const struct option *opt, int flags)
882 {
883         int *has_errors = opt->value;
884         const char *prefix = startup_info->prefix;
885
886         /* consume remaining arguments. */
887         *has_errors = do_unresolve(ctx->argc, ctx->argv,
888                                 prefix, prefix ? strlen(prefix) : 0);
889         if (*has_errors)
890                 active_cache_changed = 0;
891
892         ctx->argv += ctx->argc - 1;
893         ctx->argc = 1;
894         return 0;
895 }
896
897 static int reupdate_callback(struct parse_opt_ctx_t *ctx,
898                                 const struct option *opt, int flags)
899 {
900         int *has_errors = opt->value;
901         const char *prefix = startup_info->prefix;
902
903         /* consume remaining arguments. */
904         setup_work_tree();
905         *has_errors = do_reupdate(ctx->argc, ctx->argv,
906                                 prefix, prefix ? strlen(prefix) : 0);
907         if (*has_errors)
908                 active_cache_changed = 0;
909
910         ctx->argv += ctx->argc - 1;
911         ctx->argc = 1;
912         return 0;
913 }
914
915 int cmd_update_index(int argc, const char **argv, const char *prefix)
916 {
917         int newfd, entries, has_errors = 0, line_termination = '\n';
918         enum uc_mode untracked_cache = UC_UNSPECIFIED;
919         int read_from_stdin = 0;
920         int prefix_length = prefix ? strlen(prefix) : 0;
921         int preferred_index_format = 0;
922         char set_executable_bit = 0;
923         struct refresh_params refresh_args = {0, &has_errors};
924         int lock_error = 0;
925         int split_index = -1;
926         struct lock_file *lock_file;
927         struct parse_opt_ctx_t ctx;
928         int parseopt_state = PARSE_OPT_UNKNOWN;
929         struct option options[] = {
930                 OPT_BIT('q', NULL, &refresh_args.flags,
931                         N_("continue refresh even when index needs update"),
932                         REFRESH_QUIET),
933                 OPT_BIT(0, "ignore-submodules", &refresh_args.flags,
934                         N_("refresh: ignore submodules"),
935                         REFRESH_IGNORE_SUBMODULES),
936                 OPT_SET_INT(0, "add", &allow_add,
937                         N_("do not ignore new files"), 1),
938                 OPT_SET_INT(0, "replace", &allow_replace,
939                         N_("let files replace directories and vice-versa"), 1),
940                 OPT_SET_INT(0, "remove", &allow_remove,
941                         N_("notice files missing from worktree"), 1),
942                 OPT_BIT(0, "unmerged", &refresh_args.flags,
943                         N_("refresh even if index contains unmerged entries"),
944                         REFRESH_UNMERGED),
945                 {OPTION_CALLBACK, 0, "refresh", &refresh_args, NULL,
946                         N_("refresh stat information"),
947                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
948                         refresh_callback},
949                 {OPTION_CALLBACK, 0, "really-refresh", &refresh_args, NULL,
950                         N_("like --refresh, but ignore assume-unchanged setting"),
951                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
952                         really_refresh_callback},
953                 {OPTION_LOWLEVEL_CALLBACK, 0, "cacheinfo", NULL,
954                         N_("<mode>,<object>,<path>"),
955                         N_("add the specified entry to the index"),
956                         PARSE_OPT_NOARG | /* disallow --cacheinfo=<mode> form */
957                         PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
958                         (parse_opt_cb *) cacheinfo_callback},
959                 {OPTION_CALLBACK, 0, "chmod", &set_executable_bit, N_("(+/-)x"),
960                         N_("override the executable bit of the listed files"),
961                         PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
962                         chmod_callback},
963                 {OPTION_SET_INT, 0, "assume-unchanged", &mark_valid_only, NULL,
964                         N_("mark files as \"not changing\""),
965                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
966                 {OPTION_SET_INT, 0, "no-assume-unchanged", &mark_valid_only, NULL,
967                         N_("clear assumed-unchanged bit"),
968                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
969                 {OPTION_SET_INT, 0, "skip-worktree", &mark_skip_worktree_only, NULL,
970                         N_("mark files as \"index-only\""),
971                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, MARK_FLAG},
972                 {OPTION_SET_INT, 0, "no-skip-worktree", &mark_skip_worktree_only, NULL,
973                         N_("clear skip-worktree bit"),
974                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, UNMARK_FLAG},
975                 OPT_SET_INT(0, "info-only", &info_only,
976                         N_("add to index only; do not add content to object database"), 1),
977                 OPT_SET_INT(0, "force-remove", &force_remove,
978                         N_("remove named paths even if present in worktree"), 1),
979                 OPT_SET_INT('z', NULL, &line_termination,
980                         N_("with --stdin: input lines are terminated by null bytes"), '\0'),
981                 {OPTION_LOWLEVEL_CALLBACK, 0, "stdin", &read_from_stdin, NULL,
982                         N_("read list of paths to be updated from standard input"),
983                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
984                         (parse_opt_cb *) stdin_callback},
985                 {OPTION_LOWLEVEL_CALLBACK, 0, "index-info", &line_termination, NULL,
986                         N_("add entries from standard input to the index"),
987                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
988                         (parse_opt_cb *) stdin_cacheinfo_callback},
989                 {OPTION_LOWLEVEL_CALLBACK, 0, "unresolve", &has_errors, NULL,
990                         N_("repopulate stages #2 and #3 for the listed paths"),
991                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
992                         (parse_opt_cb *) unresolve_callback},
993                 {OPTION_LOWLEVEL_CALLBACK, 'g', "again", &has_errors, NULL,
994                         N_("only update entries that differ from HEAD"),
995                         PARSE_OPT_NONEG | PARSE_OPT_NOARG,
996                         (parse_opt_cb *) reupdate_callback},
997                 OPT_BIT(0, "ignore-missing", &refresh_args.flags,
998                         N_("ignore files missing from worktree"),
999                         REFRESH_IGNORE_MISSING),
1000                 OPT_SET_INT(0, "verbose", &verbose,
1001                         N_("report actions to standard output"), 1),
1002                 {OPTION_CALLBACK, 0, "clear-resolve-undo", NULL, NULL,
1003                         N_("(for porcelains) forget saved unresolved conflicts"),
1004                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
1005                         resolve_undo_clear_callback},
1006                 OPT_INTEGER(0, "index-version", &preferred_index_format,
1007                         N_("write index in this format")),
1008                 OPT_BOOL(0, "split-index", &split_index,
1009                         N_("enable or disable split index")),
1010                 OPT_BOOL(0, "untracked-cache", &untracked_cache,
1011                         N_("enable/disable untracked cache")),
1012                 OPT_SET_INT(0, "test-untracked-cache", &untracked_cache,
1013                             N_("test if the filesystem supports untracked cache"), UC_TEST),
1014                 OPT_SET_INT(0, "force-untracked-cache", &untracked_cache,
1015                             N_("enable untracked cache without testing the filesystem"), UC_FORCE),
1016                 OPT_END()
1017         };
1018
1019         if (argc == 2 && !strcmp(argv[1], "-h"))
1020                 usage_with_options(update_index_usage, options);
1021
1022         git_config(git_default_config, NULL);
1023
1024         /* We can't free this memory, it becomes part of a linked list parsed atexit() */
1025         lock_file = xcalloc(1, sizeof(struct lock_file));
1026
1027         newfd = hold_locked_index(lock_file, 0);
1028         if (newfd < 0)
1029                 lock_error = errno;
1030
1031         entries = read_cache();
1032         if (entries < 0)
1033                 die("cache corrupted");
1034
1035         /*
1036          * Custom copy of parse_options() because we want to handle
1037          * filename arguments as they come.
1038          */
1039         parse_options_start(&ctx, argc, argv, prefix,
1040                             options, PARSE_OPT_STOP_AT_NON_OPTION);
1041         while (ctx.argc) {
1042                 if (parseopt_state != PARSE_OPT_DONE)
1043                         parseopt_state = parse_options_step(&ctx, options,
1044                                                             update_index_usage);
1045                 if (!ctx.argc)
1046                         break;
1047                 switch (parseopt_state) {
1048                 case PARSE_OPT_HELP:
1049                         exit(129);
1050                 case PARSE_OPT_NON_OPTION:
1051                 case PARSE_OPT_DONE:
1052                 {
1053                         const char *path = ctx.argv[0];
1054                         char *p;
1055
1056                         setup_work_tree();
1057                         p = prefix_path(prefix, prefix_length, path);
1058                         update_one(p);
1059                         if (set_executable_bit)
1060                                 chmod_path(set_executable_bit, p);
1061                         free(p);
1062                         ctx.argc--;
1063                         ctx.argv++;
1064                         break;
1065                 }
1066                 case PARSE_OPT_UNKNOWN:
1067                         if (ctx.argv[0][1] == '-')
1068                                 error("unknown option '%s'", ctx.argv[0] + 2);
1069                         else
1070                                 error("unknown switch '%c'", *ctx.opt);
1071                         usage_with_options(update_index_usage, options);
1072                 }
1073         }
1074         argc = parse_options_end(&ctx);
1075         if (preferred_index_format) {
1076                 if (preferred_index_format < INDEX_FORMAT_LB ||
1077                     INDEX_FORMAT_UB < preferred_index_format)
1078                         die("index-version %d not in range: %d..%d",
1079                             preferred_index_format,
1080                             INDEX_FORMAT_LB, INDEX_FORMAT_UB);
1081
1082                 if (the_index.version != preferred_index_format)
1083                         active_cache_changed |= SOMETHING_CHANGED;
1084                 the_index.version = preferred_index_format;
1085         }
1086
1087         if (read_from_stdin) {
1088                 struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT;
1089
1090                 setup_work_tree();
1091                 while (strbuf_getline(&buf, stdin, line_termination) != EOF) {
1092                         char *p;
1093                         if (line_termination && buf.buf[0] == '"') {
1094                                 strbuf_reset(&nbuf);
1095                                 if (unquote_c_style(&nbuf, buf.buf, NULL))
1096                                         die("line is badly quoted");
1097                                 strbuf_swap(&buf, &nbuf);
1098                         }
1099                         p = prefix_path(prefix, prefix_length, buf.buf);
1100                         update_one(p);
1101                         if (set_executable_bit)
1102                                 chmod_path(set_executable_bit, p);
1103                         free(p);
1104                 }
1105                 strbuf_release(&nbuf);
1106                 strbuf_release(&buf);
1107         }
1108
1109         if (split_index > 0) {
1110                 init_split_index(&the_index);
1111                 the_index.cache_changed |= SPLIT_INDEX_ORDERED;
1112         } else if (!split_index && the_index.split_index) {
1113                 /*
1114                  * can't discard_split_index(&the_index); because that
1115                  * will destroy split_index->base->cache[], which may
1116                  * be shared with the_index.cache[]. So yeah we're
1117                  * leaking a bit here.
1118                  */
1119                 the_index.split_index = NULL;
1120                 the_index.cache_changed |= SOMETHING_CHANGED;
1121         }
1122
1123         switch (untracked_cache) {
1124         case UC_UNSPECIFIED:
1125                 break;
1126         case UC_DISABLE:
1127                 if (git_config_get_untracked_cache() == 1)
1128                         warning("core.untrackedCache is set to true; "
1129                                 "remove or change it, if you really want to "
1130                                 "disable the untracked cache");
1131                 remove_untracked_cache(&the_index);
1132                 report(_("Untracked cache disabled"));
1133                 break;
1134         case UC_TEST:
1135                 setup_work_tree();
1136                 return !test_if_untracked_cache_is_supported();
1137         case UC_ENABLE:
1138         case UC_FORCE:
1139                 if (git_config_get_untracked_cache() == 0)
1140                         warning("core.untrackedCache is set to false; "
1141                                 "remove or change it, if you really want to "
1142                                 "enable the untracked cache");
1143                 add_untracked_cache(&the_index);
1144                 report(_("Untracked cache enabled for '%s'"), get_git_work_tree());
1145                 break;
1146         default:
1147                 die("Bug: bad untracked_cache value: %d", untracked_cache);
1148         }
1149
1150         if (active_cache_changed) {
1151                 if (newfd < 0) {
1152                         if (refresh_args.flags & REFRESH_QUIET)
1153                                 exit(128);
1154                         unable_to_lock_die(get_index_file(), lock_error);
1155                 }
1156                 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1157                         die("Unable to write new index file");
1158         }
1159
1160         rollback_lock_file(lock_file);
1161
1162         return has_errors ? 1 : 0;
1163 }