Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Created January 30, 2021 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithrbennett/580a604266002667c0663b6671231645 to your computer and use it in GitHub Desktop.
Save keithrbennett/580a604266002667c0663b6671231645 to your computer and use it in GitHub Desktop.
Ruby script that outputs to stdout the project URL corresponding to a git remote URL
#!/usr/bin/env ruby
# git-project-url
#
# Outputs to stdout the project URL corresponding to a git remote URL.
#
# Example:
#
# (`open` is for Mac, use `xdg-open` on Linux, `start` on Windows)
# open $(git-project-url) # Opens 'origin' project page ('origin' is default)
# open $(git-project-url origin) # Opens 'origin' project page
# open $(git-project-url upstream) # Opens 'upstream' project page
#
# You might find it easier to type backticks:
#
# open `git-project-url`
# If the remote does not exist, something like the following will be displayed on $stderr after the command:
# % git-project-url xyz
# fatal: No such remote 'xyz'
# Syntax is `git-project-url [remote_name]`. Available remotes are:
# origin https://github.com/keithrbennett/benchmark.git (fetch)
# origin https://github.com/keithrbennett/benchmark.git (push)
def validate_base_url(url)
if url.empty?
$stderr.puts "Syntax is `git-project-url [remote_name]`. Default remote name is 'origin'. Available remotes are:\n" \
+ `git remote -v`
exit -1
end
end
def get_base_url
remote = ARGV.first || 'origin'
base_url = `git remote get-url #{remote}` # git will output "fatal: No such remote..." if not found.
validate_base_url(base_url)
base_url
end
def convert_git_url_to_https_project_url(git_url)
site, rest = git_url.split(':')
site.gsub!(/^git@/, '')
"https://#{site}/#{rest}"
end
def url_is_git_url?(url)
/^git@/.match?(url)
end
def main
base_url = get_base_url
project_url = url_is_git_url?(base_url) ? convert_git_url_to_https_project_url(base_url) : base_url
puts project_url
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment