@@ -465,8 +465,19 @@ function(git_switch_back)
465465 message (STATUS "Switch back failed. Trying to checkout previous branch" )
466466 execute_process (
467467 COMMAND "${GIT_EXECUTABLE} " "checkout" "-" WORKING_DIRECTORY "${_fun_REPOSITORY_PATH} "
468- COMMAND_ERROR_IS_FATAL LAST
468+ RESULT_VARIABLE _checkout_result
469469 )
470+
471+ # if the checkout failed, try to checkout the default branch
472+ if (NOT ${_checkout_result} EQUAL 0)
473+ message (STATUS "Checkout previous branch failed. Trying to checkout default branch" )
474+ git_default_branch (default_branch REPOSITORY_PATH "${_fun_REPOSITORY_PATH} " )
475+ execute_process (
476+ COMMAND "${GIT_EXECUTABLE} " "checkout" "${default_branch} "
477+ WORKING_DIRECTORY "${_fun_REPOSITORY_PATH} " COMMAND_ERROR_IS_FATAL LAST
478+ )
479+ endif ()
480+
470481 endif ()
471482 endif ()
472483endfunction ()
@@ -512,3 +523,56 @@ function(git_wait)
512523 endif ()
513524 endwhile ()
514525endfunction ()
526+
527+ #[[ .rst:
528+
529+ ``git_default_branch``
530+ ======================
531+ Get the default branch of the given repository. Defaults to master in case of failure
532+
533+ Input variables:
534+ - ``REPOSITORY_PATH``: The path to the repository
535+
536+ Output variables:
537+ - ``default_branch``: The variable to store the default branch in
538+
539+
540+ .. code:: cmake
541+
542+ git_default_branch(
543+ REPOSITORY_PATH
544+ "$ENV{HOME}/vcpkg"
545+ default_branch
546+ )
547+
548+ ]]
549+ function (git_default_branch default_branch )
550+ # use git symbolic-ref refs/remotes/origin/HEAD to get the default branch
551+
552+ set (oneValueArgs REPOSITORY_PATH)
553+ cmake_parse_arguments (_fun "" "${oneValueArgs} " "" ${ARGN} )
554+
555+ if ("${_fun_REPOSITORY_PATH} " STREQUAL "" )
556+ message (FATAL_ERROR "REPOSITORY_PATH is required" )
557+ endif ()
558+
559+ find_program (GIT_EXECUTABLE "git" REQUIRED )
560+ execute_process (
561+ COMMAND "${GIT_EXECUTABLE} " "symbolic-ref" "refs/remotes/origin/HEAD"
562+ OUTPUT_VARIABLE _default_branch
563+ WORKING_DIRECTORY "${_fun_REPOSITORY_PATH} "
564+ OUTPUT_STRIP_TRAILING_WHITESPACE
565+ RESULT_VARIABLE _default_branch_result
566+ )
567+
568+ if (${_default_branch_result} EQUAL 0)
569+ string (REGEX REPLACE "refs/remotes/origin/" "" _default_branch "${_default_branch} " )
570+ else ()
571+ message (
572+ WARNING "Could not get default branch of ${_fun_REPOSITORY_PATH} . Considering it as master"
573+ )
574+ set (_default_branch "master" )
575+ endif ()
576+
577+ set (${default_branch} ${_default_branch} PARENT_SCOPE )
578+ endfunction ()
0 commit comments