MATLAB 函数:从当前脚本路径通过 .git 文件夹查找项目根目录
此函数通过从调用脚本的目录开始搜索 .git 文件夹来定位 Git 仓库的根目录。它会向上遍历目录树,直到找到包含 .git 文件夹的目录或到达文件系统根目录。
find_git_root.m
find_git_root.m
function rootDir = find_git_root(scriptFullPath)
% FIND_GIT_ROOT 向上遍历目录树以定位第一个包含 .git 文件夹的目录。
% rootDir = FIND_GIT_ROOT(scriptFullPath) 从提供的 scriptFullPath 的目录开始,
% 向上遍历直到找到 .git 文件夹。如果未找到 .git 文件夹,
% 则抛出错误。
% 获取提供的脚本完整路径的目录
scriptDirectory = fileparts(scriptFullPath);
% 将当前目录初始化为脚本的目录
currentDir = scriptDirectory;
while true
% 检查当前目录是否包含 .git 文件夹
if exist(fullfile(currentDir, '.git'), 'dir')
fprintf('Directory containing ".git" found: %s\n', currentDir);
rootDir = currentDir;
return;
end
% 获取父目录
parentDir = fileparts(currentDir);
% 检查是否已到达根目录但未找到 .git 文件夹
if strcmp(currentDir, parentDir)
error('No directory containing ".git" was found in the path hierarchy.');
end
% 上移到父目录
currentDir = parentDir;
end
end使用示例
要使用此函数,只需从 Git 仓库中的任何脚本调用它。它将返回仓库根目录的路径。
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