This is a simple alias that will open the current terminal git repo's source repo in the browser. So if you clones https://github.com/NathanaelA/fluentreports and you did a git open it will open it in your browser. This alias works for all the known types of urls I've personally run into on my computer... But if you run into any others, let me know and I'll update the alias...
This should work on Linux and Mac! I am pretty sure it won't work on windows (will work in WSL2 though, as WSL2 has access to sed, pipes and xargs... )
Edit your ~/.gitconfig and go to the
[alias] section and add:
open = !git ls-remote --get-url | sed 's/:[[:digit:]]\\+//g' | sed 's/^ssh:\\/\\///' | sed 's/:/\\//g' | sed 's/^\\(http\\|https\\)\\/\\/\\//https:\\/\\//i' | sed 's/^git@/https:\\/\\//i' | sed 's/\\.git$//' | xargs open > /dev/null
Note: every single "\" must be escaped to be "\\" for git to shell out properly...
So far this works for all the cases I've run into for who a git url might be formatted, although it is possible if your https server is not on the default port it will remove your port because on the first
sed command in the link. I have git ssh on some other ports for some of my repos, so I need to strip them out.
1. the "!" tells git it is shelling to run a command. We have to run this in a shell because of all the piping...
git ls-remote --get-url will return the first remote url in your repo's configuration file. This can be formated as http(s):// or git@... or ssh://git@...
sed 's/:[[:digit:]]\+//g' strips out a
:12345 port if it is in the URL returned by ls-remote... This is technically the corner case I was talking about above, if you use http(s) on a different port then you probably want to remove this sed command from the
sed 's/^ssh:\/\///' strips out any "ssh://" that starts the string, we don't need it...
sed 's/:/\//g' replaces all the colons in the line with a / character. This is the only crappy hack, as in the git@... ends with a : without a port and we need to change that colon to actually be converted to a /. However this means that if the string started instead as https:// instead of ssh:// it will now be https///. (Notice the three /// and no colon).
sed 's/^\(http\|https\)\/\/\//https:\/\//i' is used to fix this prior created issue it checks for it starting with either http/// or https/// (case-insensitive) and replaces it with https://
sed 's/^git@/https:\/\//i' is used to replace any urls that start with git@site to now be https://site so that they link to the site.
8. The final
sed 's/\.git$//' removes any .git extension, not all git web front ends handle this properly, so might as well play it safe and just strip it off...
9. The final string is then piped into
xargs open > /dev/null which then opens the site in your default browser. The output from xargs is directed to /dev/null as some xargs output things like "Opening in your Default Browser"...