MATLAB-Funktion zum Finden des Projekt-Stammverzeichnisses anhand des .git-Ordners vom aktuellen Skriptpfad
Diese Funktion lokalisiert das Stammverzeichnis eines Git-Repositories durch Suche nach dem .git-Ordner, beginnend beim Verzeichnis des aufrufenden Skripts. Sie durchläuft den Verzeichnisbaum nach oben, bis sie ein Verzeichnis findet, das einen .git-Ordner enthält, oder die Wurzel des Dateisystems erreicht.
find_git_root.m
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
endVerwendungsbeispiel
Um diese Funktion zu verwenden, rufen Sie sie einfach von einem beliebigen Skript innerhalb Ihres Git-Repositories auf. Sie gibt den Pfad zum Stammverzeichnis des Repositories zurück.
find_git_root_usage.m
rootDir = find_git_root(mfilename('fullpath'));Check out similar posts by category:
MATLAB/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow