Skip to content

Commit 0caa465

Browse files
cswareethomson
authored andcommitted
Add git_tag_name_is_valid
Signed-off-by: Sven Strickroth <email@cs-ware.de>
1 parent fe11160 commit 0caa465

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

include/git2/tag.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,18 @@ GIT_EXTERN(int) git_tag_peel(
365365
*/
366366
GIT_EXTERN(int) git_tag_dup(git_tag **out, git_tag *source);
367367

368+
/**
369+
* Determine whether a tag name is valid, meaning that (when prefixed
370+
* with `refs/tags/`) that it is a valid reference name, and that any
371+
* additional tag name restrictions are imposed (eg, it cannot start
372+
* with a `-`).
373+
*
374+
* @param valid output pointer to set with validity of given tag name
375+
* @param name a tag name to test
376+
* @return 0 on success or an error code
377+
*/
378+
GIT_EXTERN(int) git_tag_name_is_valid(int *valid, const char *name);
379+
368380
/** @} */
369381
GIT_END_DECL
370382
#endif

src/tag.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,31 @@ int git_tag_peel(git_object **tag_target, const git_tag *tag)
522522
return git_object_peel(tag_target, (const git_object *)tag, GIT_OBJECT_ANY);
523523
}
524524

525+
int git_tag_name_is_valid(int *valid, const char *name)
526+
{
527+
git_buf ref_name = GIT_BUF_INIT;
528+
int error = 0;
529+
530+
GIT_ASSERT(valid);
531+
532+
/*
533+
* Discourage tag name starting with dash,
534+
* https://github.com/git/git/commit/4f0accd638b8d2
535+
*/
536+
if (!name || name[0] == '-')
537+
goto done;
538+
539+
if ((error = git_buf_puts(&ref_name, GIT_REFS_TAGS_DIR)) < 0 ||
540+
(error = git_buf_puts(&ref_name, name)) < 0)
541+
goto done;
542+
543+
error = git_reference_name_is_valid(valid, ref_name.ptr);
544+
545+
done:
546+
git_buf_dispose(&ref_name);
547+
return error;
548+
}
549+
525550
/* Deprecated Functions */
526551

527552
#ifndef GIT_DEPRECATE_HARD

tests/refs/tags/name.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include "clar_libgit2.h"
2+
3+
static int name_is_valid(const char *name)
4+
{
5+
int valid;
6+
cl_git_pass(git_tag_name_is_valid(&valid, name));
7+
return valid;
8+
}
9+
10+
void test_refs_tags_is_name_valid(void)
11+
{
12+
cl_assert_equal_i(true, name_is_valid("sometag"));
13+
cl_assert_equal_i(true, name_is_valid("test/sometag"));
14+
15+
cl_assert_equal_i(false, name_is_valid(""));
16+
cl_assert_equal_i(false, name_is_valid("-dash"));
17+
}

0 commit comments

Comments
 (0)