MATLAB function to find the project root directory by .git folder from the current script path

This function locates the root directory of a Git repository by searching for the .git folder starting from the directory of the calling script. It traverses up the directory tree until it finds a directory containing a .git folder or reaches the root of the filesystem.

find_git_root.m

function rootDir = find_git_root(scriptFullPath)
% FIND_GIT_ROOT Navigates up the directory tree to locate the first directory containing a .git folder.
% rootDir = FIND_GIT_ROOT(scriptFullPath) starts from the directory of the provided scriptFullPath
% and traverses upwards until it finds a .git folder. If no .git folder is
% found, it throws an error.

    % Get the directory of the provided script full path
    scriptDirectory = fileparts(scriptFullPath);

    % Initialize the current directory to the script's directory
    currentDir = scriptDirectory;

    while true
        % Check if the current directory contains a .git folder
        if exist(fullfile(currentDir, '.git'), 'dir')
            fprintf('Directory containing ".git" found: %s\n', currentDir);
            rootDir = currentDir;
            return;
        end

        % Get the parent directory
        parentDir = fileparts(currentDir);

        % Check if we reached the root without finding the .git folder
        if strcmp(currentDir, parentDir)
            error('No directory containing ".git" was found in the path hierarchy.');
        end

        % Move up to the parent directory
        currentDir = parentDir;
    end
end

Usage example

To use this function, simply call it from any script within your Git repository. It will return the path to the root directory of the repository.

rootDir = find_git_root(mfilename('fullpath'));