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