Refactor type_from_string() to allow continuing after detecting an error
In the next commits, we will enhance the fsck_tag() function to check tag objects more thoroughly. To this end, we need a function to verify that a given string is a valid object type, but that does not die() in the negative case. While at it, prepare type_from_string() for counted strings, i.e. strings with an explicitly specified length rather than a NUL termination. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Johannes Schindelin committed
Sep 10, 2014 at 15:52 UTC
fe8e3b71805cd13d139b62fa5a0c75387568c9ea
2 files changed
+11
-3
object.c
+9
-2
@@ -33,13 +33,20 @@ const char *typename(unsigned int type)
33
return object_type_strings[type];
34
}
35
36
-int type_from_string(const char *str)
36
+int type_from_string_gently(const char *str, ssize_t len, int gentle)
37
{
38
int i;
39
40
+ if (len < 0)
41
+ len = strlen(str);
42
+
43
for (i = 1; i < ARRAY_SIZE(object_type_strings); i++)
41
- if (!strcmp(str, object_type_strings[i]))
44
+ if (!strncmp(str, object_type_strings[i], len))
45
return i;
46
+
47
+ if (gentle)
48
+ return -1;
49
+
50
die("invalid object type \"%s\"", str);
51
}
52
object.h
+2
-1
@@ -53,7 +53,8 @@ struct object {
53
};
54
55
extern const char *typename(unsigned int type);
56
-extern int type_from_string(const char *str);
56
+extern int type_from_string_gently(const char *str, ssize_t, int gentle);
57
+#define type_from_string(str) type_from_string_gently(str, -1, 0)
58
59
/*
60
* Return the current number of buckets in the object hashmap.