欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python獲取當(dāng)前git的repo地址的示例代碼

 更新時(shí)間:2024年09月29日 08:41:09   作者:胡少俠7  
大家好,當(dāng)談及版本控制系統(tǒng)時(shí),Git是最為廣泛使用的一種,而Python作為一門多用途的編程語言,在處理Git倉庫時(shí)也展現(xiàn)了其強(qiáng)大的能力,本文給大家介紹了python獲取當(dāng)前git的repo地址的方法,需要的朋友可以參考下

要獲取當(dāng)前 Git 倉庫的遠(yuǎn)程地址,可以使用 subprocess 模塊執(zhí)行 Git 命令。下面是如何做到這一點(diǎn)的示例代碼:

import subprocess

def get_git_remote_url():
    try:
        # 獲取遠(yuǎn)程 URL
        result = subprocess.run(
            ['git', 'config', '--get', 'remote.origin.url'],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 獲取并返回輸出
        remote_url = result.stdout.strip()
        return remote_url

    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")
        return None

# 使用示例
remote_url = get_git_remote_url()
if remote_url:
    print(f"Remote URL: {remote_url}")
else:
    print("Failed to retrieve the remote URL.")

注意事項(xiàng):

  • Git 必須安裝:確保本地環(huán)境已安裝 Git 并且正在 Git 倉庫的目錄中運(yùn)行。
  • 錯(cuò)誤處理:代碼簡單處理了可能發(fā)生的錯(cuò)誤,可根據(jù)需要增加異常處理和日志記錄。
  • 遠(yuǎn)程名稱:示例使用了默認(rèn)的 origin,若遠(yuǎn)程名稱不同,請更改命令中的相應(yīng)部分。

拓展:python操作git gitpython模塊

安裝模塊

pip3 install gitpython

基本使用

import os
from git.repo import Repo

# 創(chuàng)建本地路徑用來存放遠(yuǎn)程倉庫下載的代碼
download_path = os.path.join('NB')
# 拉取代碼
Repo.clone_from('https://github.com/DominicJi/TeachTest.git',to_path=download_path,branch='master')

其他常見操作

# ############## 2. pull最新代碼 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
repo.git.pull()


# ############## 3. 獲取所有分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
branches = repo.remote().refs
for item in branches:
    print(item.remote_head)
    

# ############## 4. 獲取所有版本 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
for tag in repo.tags:
    print(tag.name)


# ############## 5. 獲取所有commit ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
# 將所有提交記錄結(jié)果格式成json格式字符串 方便后續(xù)反序列化操作
commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,
                          date='format:%Y-%m-%d %H:%M')
log_list = commit_log.split("\n")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)
 

 # ############## 6. 切換分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
before = repo.git.branch()
print(before)
repo.git.checkout('master')
after = repo.git.branch()
print(after)
repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8')


 
# ############## 7. 打包代碼 ##############
import os
from git.repo import Repo

local_path = os.path.join(NB')
repo = Repo(local_path)

with open(os.path.join('NB.tar'), 'wb') as fp:
    repo.archive(fp)

所有的方法封裝到類中

import os
from git.repo import Repo
from git.repo.fun import is_git_dir


class GitRepository(object):
    """
    git倉庫管理
    """
    def __init__(self, local_path, repo_url, branch='master'):
        self.local_path = local_path
        self.repo_url = repo_url
        self.repo = None
        self.initial(repo_url, branch)

    def initial(self, repo_url, branch):
        """
        初始化git倉庫
        :param repo_url:
        :param branch:
        :return:
        """
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
        else:
            self.repo = Repo(self.local_path)

    def pull(self):
        """
        從線上拉最新代碼
        :return:
        """
        self.repo.git.pull()

    def branches(self):
        """
        獲取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
        獲取所有提交記錄
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def tags(self):
        """
        獲取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切換分值
        :param branch:
        :return:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切換commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切換tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)


if __name__ == '__main__':
    local_path = os.path.join('codes', 'luffycity')
    repo = GitRepository(local_path,remote_path)
    branch_list = repo.branches()
    print(branch_list)
    repo.change_to_branch('dev')
    repo.pull()

到此這篇關(guān)于python獲取當(dāng)前git的repo地址的示例代碼的文章就介紹到這了,更多相關(guān)python獲取git repo地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何基于python生成list的所有的子集

    如何基于python生成list的所有的子集

    這篇文章主要介紹了如何基于python生成list的所有的子集,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • 如何使用Python進(jìn)行OCR識別圖片中的文字

    如何使用Python進(jìn)行OCR識別圖片中的文字

    這篇文章主要介紹了使用Python進(jìn)行OCR識別圖片中的文字 ,本文通過實(shí)例代碼加文字說明的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • 基于Python制作短信發(fā)送程序

    基于Python制作短信發(fā)送程序

    這篇文章主要為大家詳細(xì)介紹了如何利用Python制作短信發(fā)送程序,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下
    2023-01-01
  • Python實(shí)現(xiàn)從log日志中提取ip的方法【正則提取】

    Python實(shí)現(xiàn)從log日志中提取ip的方法【正則提取】

    這篇文章主要介紹了Python實(shí)現(xiàn)從log日志中提取ip的方法,涉及Python文件讀取、數(shù)據(jù)遍歷、正則匹配等相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • Python?Plotly庫安裝及使用教程

    Python?Plotly庫安裝及使用教程

    這篇文章主要介紹了包括安裝、導(dǎo)入庫、Plotly的基本結(jié)構(gòu)、常見圖表類型、樣式定制以及如何與Pandas數(shù)據(jù)框結(jié)合使用,通過示例代碼和解釋,幫助讀者快速掌握Plotly的使用技巧,需要的朋友可以參考下
    2025-03-03
  • 關(guān)于Numpy中的行向量和列向量詳解

    關(guān)于Numpy中的行向量和列向量詳解

    今天小編就為大家分享一篇關(guān)于Numpy中的行向量和列向量詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • python處理xml文件的方法小結(jié)

    python處理xml文件的方法小結(jié)

    這篇文章主要介紹了python處理xml文件的方法,結(jié)合實(shí)例形式總結(jié)分析了Python常見的xml文件處理技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-05-05
  • Python 中字符串拼接的多種方法

    Python 中字符串拼接的多種方法

    本篇文章給大家介紹python中字符串拼接的多種方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2018-07-07
  • Python中的TfidfVectorizer參數(shù)使用解析

    Python中的TfidfVectorizer參數(shù)使用解析

    這篇文章主要介紹了Python中的TfidfVectorizer參數(shù)使用解析,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • pycharm使用anaconda全過程

    pycharm使用anaconda全過程

    這篇文章主要介紹了pycharm使用anaconda全過程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02

最新評論