@@ -2032,6 +2032,49 @@ int git_repository_head_detached(git_repository *repo)
20322032 return exists ;
20332033}
20342034
2035+ static int read_worktree_head (git_buf * out , git_repository * repo , const char * name )
2036+ {
2037+ git_buf path = GIT_BUF_INIT ;
2038+ int err ;
2039+
2040+ assert (out && repo && name );
2041+
2042+ git_buf_clear (out );
2043+
2044+ if ((err = git_buf_printf (& path , "%s/worktrees/%s/HEAD" , repo -> commondir , name )) < 0 )
2045+ goto out ;
2046+ if (!git_path_exists (path .ptr ))
2047+ {
2048+ err = -1 ;
2049+ goto out ;
2050+ }
2051+
2052+ if ((err = git_futils_readbuffer (out , path .ptr )) < 0 )
2053+ goto out ;
2054+ git_buf_rtrim (out );
2055+
2056+ out :
2057+ git_buf_free (& path );
2058+
2059+ return err ;
2060+ }
2061+
2062+ int git_repository_head_detached_for_worktree (git_repository * repo , const char * name )
2063+ {
2064+ git_buf buf = GIT_BUF_INIT ;
2065+ int ret ;
2066+
2067+ assert (repo && name );
2068+
2069+ if (read_worktree_head (& buf , repo , name ) < 0 )
2070+ return -1 ;
2071+
2072+ ret = git__strncmp (buf .ptr , GIT_SYMREF , strlen (GIT_SYMREF )) != 0 ;
2073+ git_buf_free (& buf );
2074+
2075+ return ret ;
2076+ }
2077+
20352078int git_repository_head (git_reference * * head_out , git_repository * repo )
20362079{
20372080 git_reference * head ;
@@ -2051,6 +2094,48 @@ int git_repository_head(git_reference **head_out, git_repository *repo)
20512094 return error == GIT_ENOTFOUND ? GIT_EUNBORNBRANCH : error ;
20522095}
20532096
2097+ int git_repository_head_for_worktree (git_reference * * out , git_repository * repo , const char * name )
2098+ {
2099+ git_buf buf = GIT_BUF_INIT ;
2100+ git_reference * head ;
2101+ int err ;
2102+
2103+ assert (out && repo && name );
2104+
2105+ * out = NULL ;
2106+
2107+ if (git_repository_head_detached_for_worktree (repo , name ))
2108+ return -1 ;
2109+ if ((err = read_worktree_head (& buf , repo , name )) < 0 )
2110+ goto out ;
2111+
2112+ /* We can only resolve symbolic references */
2113+ if (git__strncmp (buf .ptr , GIT_SYMREF , strlen (GIT_SYMREF )))
2114+ {
2115+ err = -1 ;
2116+ goto out ;
2117+ }
2118+ git_buf_consume (& buf , buf .ptr + strlen (GIT_SYMREF ));
2119+
2120+ if ((err = git_reference_lookup (& head , repo , buf .ptr )) < 0 )
2121+ goto out ;
2122+ if (git_reference_type (head ) == GIT_REF_OID )
2123+ {
2124+ * out = head ;
2125+ err = 0 ;
2126+ goto out ;
2127+ }
2128+
2129+ err = git_reference_lookup_resolved (
2130+ out , repo , git_reference_symbolic_target (head ), -1 );
2131+ git_reference_free (head );
2132+
2133+ out :
2134+ git_buf_free (& buf );
2135+
2136+ return err ;
2137+ }
2138+
20542139int git_repository_head_unborn (git_repository * repo )
20552140{
20562141 git_reference * ref = NULL ;
0 commit comments