Merge branch 'nd/fopen-errors'
[git/gitster.git] / builtin / fsck.c
blob3a2c27f2413e5e377926e0e7df339549c37a76b3
1 #include "builtin.h"
2 #include "cache.h"
3 #include "commit.h"
4 #include "tree.h"
5 #include "blob.h"
6 #include "tag.h"
7 #include "refs.h"
8 #include "pack.h"
9 #include "cache-tree.h"
10 #include "tree-walk.h"
11 #include "fsck.h"
12 #include "parse-options.h"
13 #include "dir.h"
14 #include "progress.h"
15 #include "streaming.h"
16 #include "decorate.h"
18 #define REACHABLE 0x0001
19 #define SEEN 0x0002
20 #define HAS_OBJ 0x0004
22 static int show_root;
23 static int show_tags;
24 static int show_unreachable;
25 static int include_reflogs = 1;
26 static int check_full = 1;
27 static int connectivity_only;
28 static int check_strict;
29 static int keep_cache_objects;
30 static struct fsck_options fsck_walk_options = FSCK_OPTIONS_DEFAULT;
31 static struct fsck_options fsck_obj_options = FSCK_OPTIONS_DEFAULT;
32 static struct object_id head_oid;
33 static const char *head_points_at;
34 static int errors_found;
35 static int write_lost_and_found;
36 static int verbose;
37 static int show_progress = -1;
38 static int show_dangling = 1;
39 static int name_objects;
40 #define ERROR_OBJECT 01
41 #define ERROR_REACHABLE 02
42 #define ERROR_PACK 04
43 #define ERROR_REFS 010
45 static const char *describe_object(struct object *obj)
47 static struct strbuf buf = STRBUF_INIT;
48 char *name = name_objects ?
49 lookup_decoration(fsck_walk_options.object_names, obj) : NULL;
51 strbuf_reset(&buf);
52 strbuf_addstr(&buf, oid_to_hex(&obj->oid));
53 if (name)
54 strbuf_addf(&buf, " (%s)", name);
56 return buf.buf;
59 static const char *printable_type(struct object *obj)
61 const char *ret;
63 if (obj->type == OBJ_NONE) {
64 enum object_type type = sha1_object_info(obj->oid.hash, NULL);
65 if (type > 0)
66 object_as_type(obj, type, 0);
69 ret = typename(obj->type);
70 if (!ret)
71 ret = "unknown";
73 return ret;
76 static int fsck_config(const char *var, const char *value, void *cb)
78 if (strcmp(var, "fsck.skiplist") == 0) {
79 const char *path;
80 struct strbuf sb = STRBUF_INIT;
82 if (git_config_pathname(&path, var, value))
83 return 1;
84 strbuf_addf(&sb, "skiplist=%s", path);
85 free((char *)path);
86 fsck_set_msg_types(&fsck_obj_options, sb.buf);
87 strbuf_release(&sb);
88 return 0;
91 if (skip_prefix(var, "fsck.", &var)) {
92 fsck_set_msg_type(&fsck_obj_options, var, value);
93 return 0;
96 return git_default_config(var, value, cb);
99 static void objreport(struct object *obj, const char *msg_type,
100 const char *err)
102 fprintf(stderr, "%s in %s %s: %s\n",
103 msg_type, printable_type(obj), describe_object(obj), err);
106 static int objerror(struct object *obj, const char *err)
108 errors_found |= ERROR_OBJECT;
109 objreport(obj, "error", err);
110 return -1;
113 static int fsck_error_func(struct fsck_options *o,
114 struct object *obj, int type, const char *message)
116 objreport(obj, (type == FSCK_WARN) ? "warning" : "error", message);
117 return (type == FSCK_WARN) ? 0 : 1;
120 static struct object_array pending;
122 static int mark_object(struct object *obj, int type, void *data, struct fsck_options *options)
124 struct object *parent = data;
127 * The only case data is NULL or type is OBJ_ANY is when
128 * mark_object_reachable() calls us. All the callers of
129 * that function has non-NULL obj hence ...
131 if (!obj) {
132 /* ... these references to parent->fld are safe here */
133 printf("broken link from %7s %s\n",
134 printable_type(parent), describe_object(parent));
135 printf("broken link from %7s %s\n",
136 (type == OBJ_ANY ? "unknown" : typename(type)), "unknown");
137 errors_found |= ERROR_REACHABLE;
138 return 1;
141 if (type != OBJ_ANY && obj->type != type)
142 /* ... and the reference to parent is safe here */
143 objerror(parent, "wrong object type in link");
145 if (obj->flags & REACHABLE)
146 return 0;
147 obj->flags |= REACHABLE;
148 if (!(obj->flags & HAS_OBJ)) {
149 if (parent && !has_object_file(&obj->oid)) {
150 printf("broken link from %7s %s\n",
151 printable_type(parent), describe_object(parent));
152 printf(" to %7s %s\n",
153 printable_type(obj), describe_object(obj));
154 errors_found |= ERROR_REACHABLE;
156 return 1;
159 add_object_array(obj, NULL, &pending);
160 return 0;
163 static void mark_object_reachable(struct object *obj)
165 mark_object(obj, OBJ_ANY, NULL, NULL);
168 static int traverse_one_object(struct object *obj)
170 int result;
171 struct tree *tree = NULL;
173 if (obj->type == OBJ_TREE) {
174 tree = (struct tree *)obj;
175 if (parse_tree(tree) < 0)
176 return 1; /* error already displayed */
178 result = fsck_walk(obj, obj, &fsck_walk_options);
179 if (tree)
180 free_tree_buffer(tree);
181 return result;
184 static int traverse_reachable(void)
186 struct progress *progress = NULL;
187 unsigned int nr = 0;
188 int result = 0;
189 if (show_progress)
190 progress = start_progress_delay(_("Checking connectivity"), 0, 0, 2);
191 while (pending.nr) {
192 struct object_array_entry *entry;
193 struct object *obj;
195 entry = pending.objects + --pending.nr;
196 obj = entry->item;
197 result |= traverse_one_object(obj);
198 display_progress(progress, ++nr);
200 stop_progress(&progress);
201 return !!result;
204 static int mark_used(struct object *obj, int type, void *data, struct fsck_options *options)
206 if (!obj)
207 return 1;
208 obj->used = 1;
209 return 0;
213 * Check a single reachable object
215 static void check_reachable_object(struct object *obj)
218 * We obviously want the object to be parsed,
219 * except if it was in a pack-file and we didn't
220 * do a full fsck
222 if (!(obj->flags & HAS_OBJ)) {
223 if (has_sha1_pack(obj->oid.hash))
224 return; /* it is in pack - forget about it */
225 printf("missing %s %s\n", printable_type(obj),
226 describe_object(obj));
227 errors_found |= ERROR_REACHABLE;
228 return;
233 * Check a single unreachable object
235 static void check_unreachable_object(struct object *obj)
238 * Missing unreachable object? Ignore it. It's not like
239 * we miss it (since it can't be reached), nor do we want
240 * to complain about it being unreachable (since it does
241 * not exist).
243 if (!(obj->flags & HAS_OBJ))
244 return;
247 * Unreachable object that exists? Show it if asked to,
248 * since this is something that is prunable.
250 if (show_unreachable) {
251 printf("unreachable %s %s\n", printable_type(obj),
252 describe_object(obj));
253 return;
257 * "!used" means that nothing at all points to it, including
258 * other unreachable objects. In other words, it's the "tip"
259 * of some set of unreachable objects, usually a commit that
260 * got dropped.
262 * Such starting points are more interesting than some random
263 * set of unreachable objects, so we show them even if the user
264 * hasn't asked for _all_ unreachable objects. If you have
265 * deleted a branch by mistake, this is a prime candidate to
266 * start looking at, for example.
268 if (!obj->used) {
269 if (show_dangling)
270 printf("dangling %s %s\n", printable_type(obj),
271 describe_object(obj));
272 if (write_lost_and_found) {
273 char *filename = git_pathdup("lost-found/%s/%s",
274 obj->type == OBJ_COMMIT ? "commit" : "other",
275 describe_object(obj));
276 FILE *f;
278 if (safe_create_leading_directories_const(filename)) {
279 error("Could not create lost-found");
280 free(filename);
281 return;
283 f = xfopen(filename, "w");
284 if (obj->type == OBJ_BLOB) {
285 if (stream_blob_to_fd(fileno(f), &obj->oid, NULL, 1))
286 die_errno("Could not write '%s'", filename);
287 } else
288 fprintf(f, "%s\n", describe_object(obj));
289 if (fclose(f))
290 die_errno("Could not finish '%s'",
291 filename);
292 free(filename);
294 return;
298 * Otherwise? It's there, it's unreachable, and some other unreachable
299 * object points to it. Ignore it - it's not interesting, and we showed
300 * all the interesting cases above.
304 static void check_object(struct object *obj)
306 if (verbose)
307 fprintf(stderr, "Checking %s\n", describe_object(obj));
309 if (obj->flags & REACHABLE)
310 check_reachable_object(obj);
311 else
312 check_unreachable_object(obj);
315 static void check_connectivity(void)
317 int i, max;
319 /* Traverse the pending reachable objects */
320 traverse_reachable();
322 /* Look up all the requirements, warn about missing objects.. */
323 max = get_max_object_index();
324 if (verbose)
325 fprintf(stderr, "Checking connectivity (%d objects)\n", max);
327 for (i = 0; i < max; i++) {
328 struct object *obj = get_indexed_object(i);
330 if (obj)
331 check_object(obj);
335 static int fsck_obj(struct object *obj)
337 if (obj->flags & SEEN)
338 return 0;
339 obj->flags |= SEEN;
341 if (verbose)
342 fprintf(stderr, "Checking %s %s\n",
343 printable_type(obj), describe_object(obj));
345 if (fsck_walk(obj, NULL, &fsck_obj_options))
346 objerror(obj, "broken links");
347 if (fsck_object(obj, NULL, 0, &fsck_obj_options))
348 return -1;
350 if (obj->type == OBJ_TREE) {
351 struct tree *item = (struct tree *) obj;
353 free_tree_buffer(item);
356 if (obj->type == OBJ_COMMIT) {
357 struct commit *commit = (struct commit *) obj;
359 free_commit_buffer(commit);
361 if (!commit->parents && show_root)
362 printf("root %s\n", describe_object(&commit->object));
365 if (obj->type == OBJ_TAG) {
366 struct tag *tag = (struct tag *) obj;
368 if (show_tags && tag->tagged) {
369 printf("tagged %s %s", printable_type(tag->tagged),
370 describe_object(tag->tagged));
371 printf(" (%s) in %s\n", tag->tag,
372 describe_object(&tag->object));
376 return 0;
379 static int fsck_obj_buffer(const struct object_id *oid, enum object_type type,
380 unsigned long size, void *buffer, int *eaten)
383 * Note, buffer may be NULL if type is OBJ_BLOB. See
384 * verify_packfile(), data_valid variable for details.
386 struct object *obj;
387 obj = parse_object_buffer(oid, type, size, buffer, eaten);
388 if (!obj) {
389 errors_found |= ERROR_OBJECT;
390 return error("%s: object corrupt or missing", oid_to_hex(oid));
392 obj->flags = HAS_OBJ;
393 return fsck_obj(obj);
396 static int default_refs;
398 static void fsck_handle_reflog_oid(const char *refname, struct object_id *oid,
399 timestamp_t timestamp)
401 struct object *obj;
403 if (!is_null_oid(oid)) {
404 obj = lookup_object(oid->hash);
405 if (obj && (obj->flags & HAS_OBJ)) {
406 if (timestamp && name_objects)
407 add_decoration(fsck_walk_options.object_names,
408 obj,
409 xstrfmt("%s@{%"PRItime"}", refname, timestamp));
410 obj->used = 1;
411 mark_object_reachable(obj);
412 } else {
413 error("%s: invalid reflog entry %s", refname, oid_to_hex(oid));
414 errors_found |= ERROR_REACHABLE;
419 static int fsck_handle_reflog_ent(struct object_id *ooid, struct object_id *noid,
420 const char *email, timestamp_t timestamp, int tz,
421 const char *message, void *cb_data)
423 const char *refname = cb_data;
425 if (verbose)
426 fprintf(stderr, "Checking reflog %s->%s\n",
427 oid_to_hex(ooid), oid_to_hex(noid));
429 fsck_handle_reflog_oid(refname, ooid, 0);
430 fsck_handle_reflog_oid(refname, noid, timestamp);
431 return 0;
434 static int fsck_handle_reflog(const char *logname, const struct object_id *oid,
435 int flag, void *cb_data)
437 for_each_reflog_ent(logname, fsck_handle_reflog_ent, (void *)logname);
438 return 0;
441 static int fsck_handle_ref(const char *refname, const struct object_id *oid,
442 int flag, void *cb_data)
444 struct object *obj;
446 obj = parse_object(oid);
447 if (!obj) {
448 error("%s: invalid sha1 pointer %s", refname, oid_to_hex(oid));
449 errors_found |= ERROR_REACHABLE;
450 /* We'll continue with the rest despite the error.. */
451 return 0;
453 if (obj->type != OBJ_COMMIT && is_branch(refname)) {
454 error("%s: not a commit", refname);
455 errors_found |= ERROR_REFS;
457 default_refs++;
458 obj->used = 1;
459 if (name_objects)
460 add_decoration(fsck_walk_options.object_names,
461 obj, xstrdup(refname));
462 mark_object_reachable(obj);
464 return 0;
467 static void get_default_heads(void)
469 if (head_points_at && !is_null_oid(&head_oid))
470 fsck_handle_ref("HEAD", &head_oid, 0, NULL);
471 for_each_rawref(fsck_handle_ref, NULL);
472 if (include_reflogs)
473 for_each_reflog(fsck_handle_reflog, NULL);
476 * Not having any default heads isn't really fatal, but
477 * it does mean that "--unreachable" no longer makes any
478 * sense (since in this case everything will obviously
479 * be unreachable by definition.
481 * Showing dangling objects is valid, though (as those
482 * dangling objects are likely lost heads).
484 * So we just print a warning about it, and clear the
485 * "show_unreachable" flag.
487 if (!default_refs) {
488 fprintf(stderr, "notice: No default references\n");
489 show_unreachable = 0;
493 static struct object *parse_loose_object(const struct object_id *oid,
494 const char *path)
496 struct object *obj;
497 void *contents;
498 enum object_type type;
499 unsigned long size;
500 int eaten;
502 if (read_loose_object(path, oid->hash, &type, &size, &contents) < 0)
503 return NULL;
505 if (!contents && type != OBJ_BLOB)
506 die("BUG: read_loose_object streamed a non-blob");
508 obj = parse_object_buffer(oid, type, size, contents, &eaten);
510 if (!eaten)
511 free(contents);
512 return obj;
515 static int fsck_loose(const struct object_id *oid, const char *path, void *data)
517 struct object *obj = parse_loose_object(oid, path);
519 if (!obj) {
520 errors_found |= ERROR_OBJECT;
521 error("%s: object corrupt or missing: %s",
522 oid_to_hex(oid), path);
523 return 0; /* keep checking other objects */
526 obj->flags = HAS_OBJ;
527 if (fsck_obj(obj))
528 errors_found |= ERROR_OBJECT;
529 return 0;
532 static int fsck_cruft(const char *basename, const char *path, void *data)
534 if (!starts_with(basename, "tmp_obj_"))
535 fprintf(stderr, "bad sha1 file: %s\n", path);
536 return 0;
539 static int fsck_subdir(int nr, const char *path, void *progress)
541 display_progress(progress, nr + 1);
542 return 0;
545 static void fsck_object_dir(const char *path)
547 struct progress *progress = NULL;
549 if (verbose)
550 fprintf(stderr, "Checking object directory\n");
552 if (show_progress)
553 progress = start_progress(_("Checking object directories"), 256);
555 for_each_loose_file_in_objdir(path, fsck_loose, fsck_cruft, fsck_subdir,
556 progress);
557 display_progress(progress, 256);
558 stop_progress(&progress);
561 static int fsck_head_link(void)
563 int null_is_error = 0;
565 if (verbose)
566 fprintf(stderr, "Checking HEAD link\n");
568 head_points_at = resolve_ref_unsafe("HEAD", 0, head_oid.hash, NULL);
569 if (!head_points_at) {
570 errors_found |= ERROR_REFS;
571 return error("Invalid HEAD");
573 if (!strcmp(head_points_at, "HEAD"))
574 /* detached HEAD */
575 null_is_error = 1;
576 else if (!starts_with(head_points_at, "refs/heads/")) {
577 errors_found |= ERROR_REFS;
578 return error("HEAD points to something strange (%s)",
579 head_points_at);
581 if (is_null_oid(&head_oid)) {
582 if (null_is_error) {
583 errors_found |= ERROR_REFS;
584 return error("HEAD: detached HEAD points at nothing");
586 fprintf(stderr, "notice: HEAD points to an unborn branch (%s)\n",
587 head_points_at + 11);
589 return 0;
592 static int fsck_cache_tree(struct cache_tree *it)
594 int i;
595 int err = 0;
597 if (verbose)
598 fprintf(stderr, "Checking cache tree\n");
600 if (0 <= it->entry_count) {
601 struct object *obj = parse_object(&it->oid);
602 if (!obj) {
603 error("%s: invalid sha1 pointer in cache-tree",
604 oid_to_hex(&it->oid));
605 errors_found |= ERROR_REFS;
606 return 1;
608 obj->used = 1;
609 if (name_objects)
610 add_decoration(fsck_walk_options.object_names,
611 obj, xstrdup(":"));
612 mark_object_reachable(obj);
613 if (obj->type != OBJ_TREE)
614 err |= objerror(obj, "non-tree in cache-tree");
616 for (i = 0; i < it->subtree_nr; i++)
617 err |= fsck_cache_tree(it->down[i]->cache_tree);
618 return err;
621 static void mark_object_for_connectivity(const struct object_id *oid)
623 struct object *obj = lookup_unknown_object(oid->hash);
624 obj->flags |= HAS_OBJ;
627 static int mark_loose_for_connectivity(const struct object_id *oid,
628 const char *path,
629 void *data)
631 mark_object_for_connectivity(oid);
632 return 0;
635 static int mark_packed_for_connectivity(const struct object_id *oid,
636 struct packed_git *pack,
637 uint32_t pos,
638 void *data)
640 mark_object_for_connectivity(oid);
641 return 0;
644 static char const * const fsck_usage[] = {
645 N_("git fsck [<options>] [<object>...]"),
646 NULL
649 static struct option fsck_opts[] = {
650 OPT__VERBOSE(&verbose, N_("be verbose")),
651 OPT_BOOL(0, "unreachable", &show_unreachable, N_("show unreachable objects")),
652 OPT_BOOL(0, "dangling", &show_dangling, N_("show dangling objects")),
653 OPT_BOOL(0, "tags", &show_tags, N_("report tags")),
654 OPT_BOOL(0, "root", &show_root, N_("report root nodes")),
655 OPT_BOOL(0, "cache", &keep_cache_objects, N_("make index objects head nodes")),
656 OPT_BOOL(0, "reflogs", &include_reflogs, N_("make reflogs head nodes (default)")),
657 OPT_BOOL(0, "full", &check_full, N_("also consider packs and alternate objects")),
658 OPT_BOOL(0, "connectivity-only", &connectivity_only, N_("check only connectivity")),
659 OPT_BOOL(0, "strict", &check_strict, N_("enable more strict checking")),
660 OPT_BOOL(0, "lost-found", &write_lost_and_found,
661 N_("write dangling objects in .git/lost-found")),
662 OPT_BOOL(0, "progress", &show_progress, N_("show progress")),
663 OPT_BOOL(0, "name-objects", &name_objects, N_("show verbose names for reachable objects")),
664 OPT_END(),
667 int cmd_fsck(int argc, const char **argv, const char *prefix)
669 int i, heads;
670 struct alternate_object_database *alt;
672 errors_found = 0;
673 check_replace_refs = 0;
675 argc = parse_options(argc, argv, prefix, fsck_opts, fsck_usage, 0);
677 fsck_walk_options.walk = mark_object;
678 fsck_obj_options.walk = mark_used;
679 fsck_obj_options.error_func = fsck_error_func;
680 if (check_strict)
681 fsck_obj_options.strict = 1;
683 if (show_progress == -1)
684 show_progress = isatty(2);
685 if (verbose)
686 show_progress = 0;
688 if (write_lost_and_found) {
689 check_full = 1;
690 include_reflogs = 0;
693 if (name_objects)
694 fsck_walk_options.object_names =
695 xcalloc(1, sizeof(struct decoration));
697 git_config(fsck_config, NULL);
699 fsck_head_link();
700 if (connectivity_only) {
701 for_each_loose_object(mark_loose_for_connectivity, NULL, 0);
702 for_each_packed_object(mark_packed_for_connectivity, NULL, 0);
703 } else {
704 fsck_object_dir(get_object_directory());
706 prepare_alt_odb();
707 for (alt = alt_odb_list; alt; alt = alt->next)
708 fsck_object_dir(alt->path);
710 if (check_full) {
711 struct packed_git *p;
712 uint32_t total = 0, count = 0;
713 struct progress *progress = NULL;
715 prepare_packed_git();
717 if (show_progress) {
718 for (p = packed_git; p; p = p->next) {
719 if (open_pack_index(p))
720 continue;
721 total += p->num_objects;
724 progress = start_progress(_("Checking objects"), total);
726 for (p = packed_git; p; p = p->next) {
727 /* verify gives error messages itself */
728 if (verify_pack(p, fsck_obj_buffer,
729 progress, count))
730 errors_found |= ERROR_PACK;
731 count += p->num_objects;
733 stop_progress(&progress);
737 heads = 0;
738 for (i = 0; i < argc; i++) {
739 const char *arg = argv[i];
740 unsigned char sha1[20];
741 if (!get_sha1(arg, sha1)) {
742 struct object *obj = lookup_object(sha1);
744 if (!obj || !(obj->flags & HAS_OBJ)) {
745 error("%s: object missing", sha1_to_hex(sha1));
746 errors_found |= ERROR_OBJECT;
747 continue;
750 obj->used = 1;
751 if (name_objects)
752 add_decoration(fsck_walk_options.object_names,
753 obj, xstrdup(arg));
754 mark_object_reachable(obj);
755 heads++;
756 continue;
758 error("invalid parameter: expected sha1, got '%s'", arg);
759 errors_found |= ERROR_OBJECT;
763 * If we've not been given any explicit head information, do the
764 * default ones from .git/refs. We also consider the index file
765 * in this case (ie this implies --cache).
767 if (!argc) {
768 get_default_heads();
769 keep_cache_objects = 1;
772 if (keep_cache_objects) {
773 verify_index_checksum = 1;
774 read_cache();
775 for (i = 0; i < active_nr; i++) {
776 unsigned int mode;
777 struct blob *blob;
778 struct object *obj;
780 mode = active_cache[i]->ce_mode;
781 if (S_ISGITLINK(mode))
782 continue;
783 blob = lookup_blob(&active_cache[i]->oid);
784 if (!blob)
785 continue;
786 obj = &blob->object;
787 obj->used = 1;
788 if (name_objects)
789 add_decoration(fsck_walk_options.object_names,
790 obj,
791 xstrfmt(":%s", active_cache[i]->name));
792 mark_object_reachable(obj);
794 if (active_cache_tree)
795 fsck_cache_tree(active_cache_tree);
798 check_connectivity();
799 return errors_found;