# -*- coding: utf-8 -*-"""This module implements the logic to find the corresponding web urlof a local file in a local git repo.Basically, it locate the ``.git/config`` file, extract the remote origin url,parse it, and then generate the web url."""importtypingasTfrompathlibimportPathfrom.vendor.git_cliimportget_git_commit_id_from_git_clifrom.utilsimport(locate_git_repo_dir,extract_remote_origin_url,extract_current_branch,)from.parserimportPlatformEnumfrom.find_repo_urlimportparse_aws_codecommit_remote_origin_url,get_repo_urlclass_CurrentBranch:"""Sentinel class representing the current git branch."""passclass_DefaultBranch:"""Sentinel class representing the default branch (main/master)."""passCURRENT_BRANCH:_CurrentBranch=_CurrentBranch()DEFAULT_BRANCH:_DefaultBranch=_DefaultBranch()
[docs]defget_web_url(path:Path,branch:T.Union[str,_CurrentBranch,_DefaultBranch]=CURRENT_BRANCH,):# pragma: no cover""" This module implements the logic to find the corresponding web url of a local file in a local git repo. :param path: The local file or directory path. :param branch: The branch to use in the URL. - CURRENT_BRANCH: use current branch (default behavior) - DEFAULT_BRANCH: use the default branch (URL without explicit branch) - str: use the specified branch name """p_git_repo_dir=locate_git_repo_dir(path)remote_origin_url=extract_remote_origin_url(p_git_repo_dir.joinpath(".git","config"))repo_url,res=get_repo_url(remote_origin_url)# Determine git_branch based on branch parameterifisinstance(branch,_CurrentBranch):git_branch=extract_current_branch(p_git_repo_dir.joinpath(".git","HEAD"))elifisinstance(branch,_DefaultBranch):git_branch=None# Will generate URL without branch (default branch)else:git_branch=branchrelative_path=str(path.relative_to(p_git_repo_dir))ifrelative_path==".":# if the path is already the root of the reporelative_path=""ifres.platformisPlatformEnum.aws_codecommit:aws_region=parse_aws_codecommit_remote_origin_url(remote_origin_url)ifgit_branchisNone:returnf"{repo_url}?region={aws_region}"else:returnf"{repo_url}/browse/refs/heads/{git_branch}/--/{relative_path}?region={aws_region}"elifres.platformisPlatformEnum.bitbucket:# bitbucket saasifres.domain=="bitbucket.org":ifgit_branchisNone:ifrelative_path:returnf"{repo_url}/src/{relative_path}"else:returnf"{repo_url}"else:commit_id=get_git_commit_id_from_git_cli(p_git_repo_dir)returnf"{repo_url}/src/{commit_id}/{relative_path}?at={git_branch}"else:# bitbucket serverifgit_branchisNone:ifrelative_path:returnf"{repo_url}/browse/{relative_path}"else:returnf"{repo_url}"else:returnf"{repo_url}/browse/{relative_path}?at=refs/heads/{git_branch}"else:ifgit_branchisNone:ifrelative_path:ifpath.is_file():returnf"{repo_url}/blob/{relative_path}"else:returnf"{repo_url}/tree/{relative_path}"else:returnf"{repo_url}"else:ifpath.is_file():returnf"{repo_url}/blob/{git_branch}/{relative_path}"else:returnf"{repo_url}/tree/{git_branch}/{relative_path}"