Repository navigation
Expand file tree
/
Copy pathgit-https-to-ssh
More file actions
executable file
·58 lines (51 loc) · 1.82 KB
/
Copy pathgit-https-to-ssh
File metadata and controls
executable file
·58 lines (51 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/bin/bash
#
# Author: Jorge Yau (https://github.com/codenameyau/dotfiles)
#
# =========================================================================
# Alternatively, run this line below to configure git to use ssh by default:
# git config --global url."git@github.com:".insteadOf "https://github.com/"
# =========================================================================
#
# DESCRIPTION:
# Converts git repository remote url from https to ssh
#
# Syntax Docs:
# http://tldp.org/LDP/abs/html/string-manipulation.html
# http://tldp.org/LDP/abs/html/comparison-ops.html
#
# Before:
# origin https://github.com/USERNAME/REPOSITORY.git (fetch)
# origin https://github.com/USERNAME/REPOSITORY.git (push)
#
# After:
# origin git@github.com:USERNAME/REPOSITORY.git (fetch)
# origin git@github.com:USERNAME/REPOSITORY.git (push)
#
# USAGE:
# git-https-to-ssh
#
validate() {
if [ -z "$1" ]; then
echo "$2" && exit 1
fi
}
# Note: if your gitconfig has url."git@github.com:".insteadOf, git already uses ssh
# and get-url reports the rewritten ssh url, so there is nothing to convert.
remote_url=$(git remote get-url origin 2>/dev/null)
validate "$remote_url" "Could not find a remote named origin"
if [[ $remote_url != https://github.com/* ]]; then
echo "Remote is not a GitHub https url: $remote_url" && exit 1
fi
remote_path=${remote_url#https://github.com/}
remote_path=${remote_path%/}
remote_path=${remote_path%.git}
remote_user=${remote_path%%/*}
remote_repo=${remote_path#*/}
[ "$remote_repo" = "$remote_path" ] && remote_repo=""
new_remote_url="git@github.com:$remote_user/$remote_repo.git"
validate "$remote_user" "Could not validate repository user"
validate "$remote_repo" "Could not validate repository name"
git remote set-url origin "$new_remote_url"
echo "Old Remote: $remote_url"
echo "New Remote: $new_remote_url"