Commit 29715d4082ef97d54ce2bf24943425f558335796

Edward Thomson 2020-10-11T12:50:52

refs: introduce git_reference_name_is_valid Provide a function that can check reference name validity but can also signal when an error occurs. Use the name "name_is_valid", which is more suggestive of checking a given name, rather than "is_valid_name", which suggests that the function checks the validity of the current reference's name.

diff --git a/include/git2/refs.h b/include/git2/refs.h
index c9cce22..6145811 100644
--- a/include/git2/refs.h
+++ b/include/git2/refs.h
@@ -743,6 +743,23 @@ GIT_EXTERN(int) git_reference_peel(
  *    the characters '~', '^', ':', '\\', '?', '[', and '*', and the
  *    sequences ".." and "@{" which have special meaning to revparse.
  *
+ * @param valid output pointer to set with validity of given reference name
+ * @param refname name to be checked.
+ * @return 0 on success or an error code
+ */
+GIT_EXTERN(int) git_reference_name_is_valid(int *valid, const char *refname);
+
+/**
+ * Ensure the reference name is well-formed.
+ *
+ * Valid reference names must follow one of two patterns:
+ *
+ * 1. Top-level names must contain only capital letters and underscores,
+ *    and must begin and end with a letter. (e.g. "HEAD", "ORIG_HEAD").
+ * 2. Names prefixed with "refs/" can be almost anything.  You must avoid
+ *    the characters '~', '^', ':', '\\', '?', '[', and '*', and the
+ *    sequences ".." and "@{" which have special meaning to revparse.
+ *
  * @param refname name to be checked.
  * @return 1 if the reference name is acceptable; 0 if it isn't
  */
diff --git a/src/fetch.c b/src/fetch.c
index f4a4c9f..dedbb54 100644
--- a/src/fetch.c
+++ b/src/fetch.c
@@ -21,9 +21,12 @@
 
 static int maybe_want(git_remote *remote, git_remote_head *head, git_odb *odb, git_refspec *tagspec, git_remote_autotag_option_t tagopt)
 {
-	int match = 0;
+	int match = 0, valid;
 
-	if (!git_reference_is_valid_name(head->name))
+	if (git_reference_name_is_valid(&valid, head->name) < 0)
+		return -1;
+
+	if (!valid)
 		return 0;
 
 	if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
diff --git a/src/refs.c b/src/refs.c
index bb83d9b..da12d02 100644
--- a/src/refs.c
+++ b/src/refs.c
@@ -1294,6 +1294,8 @@ int git_reference__name_is_valid(
 {
 	int error;
 
+	GIT_ASSERT(valid && refname);
+
 	*valid = 0;
 
 	error = git_reference__normalize_name(NULL, refname, flags);
@@ -1306,6 +1308,11 @@ int git_reference__name_is_valid(
 	return error;
 }
 
+int git_reference_name_is_valid(int *valid, const char *refname)
+{
+	return git_reference__name_is_valid(valid, refname, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL);
+}
+
 int git_reference_is_valid_name(const char *refname)
 {
 	int valid = 0;