File tree Expand file tree Collapse file tree 3 files changed +58
-0
lines changed
Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -304,6 +304,18 @@ GIT_EXTERN(int) git_branch_remote_name(
304304 */
305305 GIT_EXTERN (int ) git_branch_upstream_remote (git_buf * buf , git_repository * repo , const char * refname );
306306
307+ /**
308+ * Determine whether a branch name is valid, meaning that (when prefixed
309+ * with `refs/heads/`) that it is a valid reference name, and that any
310+ * additional branch name restrictions are imposed (eg, it cannot start
311+ * with a `-`).
312+ *
313+ * @param valid output pointer to set with validity of given branch name
314+ * @param name a branch name to test
315+ * @return 0 on success or an error code
316+ */
317+ GIT_EXTERN (int ) git_branch_name_is_valid (int * valid , const char * name );
318+
307319/** @} */
308320GIT_END_DECL
309321#endif
Original file line number Diff line number Diff line change @@ -723,3 +723,32 @@ int git_branch_is_head(
723723
724724 return is_same ;
725725}
726+
727+ int git_branch_name_is_valid (int * valid , const char * name )
728+ {
729+ git_buf ref_name = GIT_BUF_INIT ;
730+ int error = 0 ;
731+
732+ GIT_ASSERT (valid );
733+
734+ * valid = 0 ;
735+
736+ /*
737+ * Discourage branch name starting with dash,
738+ * https://github.com/git/git/commit/6348624010888b
739+ * and discourage HEAD as branch name,
740+ * https://github.com/git/git/commit/a625b092cc5994
741+ */
742+ if (!name || name [0 ] == '-' || !git__strcmp (name , "HEAD" ))
743+ goto done ;
744+
745+ if ((error = git_buf_puts (& ref_name , GIT_REFS_HEADS_DIR )) < 0 ||
746+ (error = git_buf_puts (& ref_name , name )) < 0 )
747+ goto done ;
748+
749+ error = git_reference_name_is_valid (valid , ref_name .ptr );
750+
751+ done :
752+ git_buf_dispose (& ref_name );
753+ return error ;
754+ }
Original file line number Diff line number Diff line change @@ -43,3 +43,20 @@ void test_refs_branches_name__error_when_ref_is_no_branch(void)
4343 cl_git_pass (git_reference_lookup (& ref ,repo ,"refs/notes/fanout" ));
4444 cl_git_fail (git_branch_name (& name ,ref ));
4545}
46+
47+ static int name_is_valid (const char * name )
48+ {
49+ int valid ;
50+ cl_git_pass (git_branch_name_is_valid (& valid , name ));
51+ return valid ;
52+ }
53+
54+ void test_refs_branches_is_name_valid (void )
55+ {
56+ cl_assert_equal_i (true, name_is_valid ("master" ));
57+ cl_assert_equal_i (true, name_is_valid ("test/master" ));
58+
59+ cl_assert_equal_i (false, name_is_valid ("" ));
60+ cl_assert_equal_i (false, name_is_valid ("HEAD" ));
61+ cl_assert_equal_i (false, name_is_valid ("-dash" ));
62+ }
You can’t perform that action at this time.
0 commit comments