我正在使用 Git,我想获取克隆到本地存储库的 Git 服务器上特定文件的完整路径。
示例:本地存储库中的文件为:
/home/.../source/android/frameworks/av/media/libstagefright/CameraSource.cpp
Run Code Online (Sandbox Code Playgroud)
我想在 Git 服务器上获取该文件的链接,如下所示:
https://android.git.sec..../plugins/gitiles/platform/frameworks/av/+/refs/heads/main/o-one/media/libstagefright/CameraSource.cpp
Run Code Online (Sandbox Code Playgroud)
如何在 Linux 上使用 Bash 命令来做到这一点?
这是一个很长的自定义脚本,可用于任何远程https://github.com托管存储库。我会尽快修改它,因为它可能容易出现边缘情况错误。
要使其正常工作,请将代码片段保存到git_relative.sh文件中并将其放置在任何位置,目前将其放置在~/主目录中。
现在通过添加此行来修改您的~/.bashrcor~/.zshrc或~/.bash_profile
alias git_remote_path='source ~/git_relative.sh'
重新启动终端或执行您添加的相应 bash 脚本。然后转到任意 git 存储库并执行git_remote_path. 这将打印 git 远程服务器中的完整路径。
您给出的示例似乎具有与传统github.com. 要使其正常工作,只需更改我在注释中指定的行即可。
注意:该脚本适用于https://github.com远程 URL,如果您想获取自定义 URL 的路径,则需要稍微修改代码以匹配存储库 URL 约定的需要。代码片段中包含一个示例作为注释。
is_git=false
relative_to_git=""
check=""
initial=$(pwd)
current_dir=""
count=0
if [ ! $(git rev-parse --is-inside-work-tree 2> /dev/null) ]; then
echo "NOT INSIDE A VALID GIT REPOSITORY"
return
fi
git_remote=$(git config --get remote.origin.url)
git_remote=${git_remote%.git}
git_branch=$(git rev-parse --abbrev-ref HEAD)
while [ $is_git=true ]
do
if [ -d ".git" ]; then
break
fi
current_dir=${PWD##*/}
relative_to_git="$current_dir/$relative_to_git"
cd ../
done
# echo "$git_remote/+/$git_branch/$relative_to_git"
# For andoid.googlesource.com uncomment the above and comment the below lines
echo "$git_remote/tree/$git_branch/$relative_to_git"
cd $initial
Run Code Online (Sandbox Code Playgroud)