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