@@ -70,19 +70,40 @@ def get_git_root(self) -> str:
70
70
"""
71
71
return check_output (["git" , "rev-parse" , "--show-toplevel" ], cwd = self .repo_path )
72
72
73
- def get_git_url (self , commit_hash : bool = True ) -> str :
73
+ def get_git_version (self ) -> tuple :
74
+ """Gets the version of git.
75
+
76
+ :return: The version of git, as a tuple of strings.
77
+
78
+ Example:
79
+ >>> get_git_version()
80
+ (2, 17, 1) # for git version 2.17.1
81
+ """
82
+ raw = check_output (["git" , "--version" ])
83
+ number_start_index = next (i for i , c in enumerate (raw ) if c .isdigit ())
84
+ return tuple (int (num ) for num in raw [number_start_index :].split ("." ))
85
+
86
+ def get_git_url (self , commit_hash : bool = True ) -> Optional [str ]:
74
87
"""Gets the https url of the git repo where the command is run.
75
88
76
89
:param commit_hash: If True, the url links to the latest local git commit hash.
77
90
If False, the url links to the general git url.
78
91
:return: The https url of the current git repo.
79
92
"""
80
93
# Get git url (either https or ssh)
94
+ input_remote = (
95
+ ["git" , "remote" , "get-url" , "origin" ]
96
+ if self .get_git_version () >= (2 , 0 )
97
+ else ["git" , "config" , "--get" , "remote.origin.url" ]
98
+ )
81
99
try :
82
- url = check_output (["git" , "remote" , "get-url" , "origin" ], cwd = self .repo_path )
83
- except subprocess .CalledProcessError :
84
- # For git versions <2.0
85
- url = check_output (["git" , "config" , "--get" , "remote.origin.url" ], cwd = self .repo_path )
100
+ url = check_output (input_remote , cwd = self .repo_path )
101
+ except subprocess .CalledProcessError as e :
102
+ if e .returncode == 2 :
103
+ # https://git-scm.com/docs/git-remote#_exit_status
104
+ # 2: The remote does not exist.
105
+ return None
106
+ raise e
86
107
87
108
# Remove .git at end
88
109
url = url [: - len (".git" )]
0 commit comments