Azure devops azure管道删除旧的azure git分支(非回购)

Azure devops azure管道删除旧的azure git分支(非回购),azure-devops,devops,azure-devops-rest-api,azure-devops-extensions,azure-devops-server-2019,Azure Devops,Devops,Azure Devops Rest Api,Azure Devops Extensions,Azure Devops Server 2019,我正在尝试创建azure管道以删除旧的azure git分支(而不是回购) 因此,创建一个自动管道,该管道将采用以下参数 import requests import sys from datetime import datetime as dt import json from git import Repo import git import time username = '<u name>' auth_key = '<auth key>' class gitR

我正在尝试创建azure管道以删除旧的azure git分支(而不是回购)

因此,创建一个自动管道,该管道将采用以下参数

import requests
import sys
from datetime import datetime as dt
import json
from git import Repo
import git
import time

username = '<u name>'
auth_key = '<auth key>'

class gitRepoDeletion:

    def getRepo(self, organization_name, project_name, repo_name):
        """
        Getting the repo details
        from the user and
        flitering the master
        branch with date functionality(still implementing)
        """
        getting_repo_list = "https://dev.azure.com/" + organization_name + '/' + \
            project_name + "/_apis/git/repositories/" + repo_name + "/refs?api-version=5.0"

        get_reponse = requests.get(
            getting_repo_list, auth=(username,auth_key))

        try:
            repojson = json.loads(get_reponse.content)
        except ValueError:
            print("Error loading json file")
        output_json = [x for x in repojson['value']
                       if x['name'] != 'refs/heads/master']
        with open('/home/vsts/work/1/s/data.json', 'w', encoding='utf-8') as f:
            json.dump(output_json, f, ensure_ascii=False, indent=4)

    def filtering_branches(self, organization_name, project_name, repo_name, user_date):
        """ 
        Filtering branches according 
        to the date passed by user

        """

        git_url = "https://" + organization_name + "@dev.azure.com" + '/' + \
            organization_name + '/' + project_name + '/_git' + '/' + repo_name

        branches = Repo.clone_from(git_url, "./mylocaldir209")

        remote_branches = []
        for ref in branches.git.branch('-r').split('\n'):
            if ref != '  origin/HEAD -> origin/master':
                if ref != '  origin/master':
                    remote_branches.append(ref[9:])
                else:
                    pass

        branch_and_timing_dict = {}

        for listy in remote_branches:
            branches.git.checkout(listy)
            commit = branches.head.commit
            timing = time.asctime(time.gmtime(commit.committed_date))
            timing = time.strftime(
                "%d/%m/%Y", time.gmtime(commit.committed_date)).replace(' 0', ' ')
            branch_and_timing_dict[listy] = timing

        global filterlist
        filterlist = []

        for key, values in branch_and_timing_dict.items():
            d1 = dt.strptime(user_date, "%d/%m/%Y") 
            d2 = dt.strptime(key, "%d/%m/%Y")
            if d1 > d2:
                filterlist.append(values)
            else:
                pass
        return filterlist

    def repo_delete(self, organization_name, project_name, repo_name, dry_flag):
        """
        Deleting repo as
        per date input by user
        also exlucling master

        """

        all_repo_to_be_deleted = []

        newObjectId = "0000000000000000000000000000000000000000"

        filteredBranchesAsPerDateWithRef = []

        for value in filterlist:
            filteredBranchesAsPerDateWithRef.append("refs/heads/" + value)
            print(value)
        print(filteredBranchesAsPerDateWithRef)

        # Cluttering extra spaces and lowering the case of the dry flag value passed by the user

        # Reading data.json file, which is fetched by the getRepo() method after excluding the master branch
        with open('/home/vsts/work/1/s/data.json') as data_file:
            json_data = json.load(data_file)
        for item in json_data:
            name_of_branch = item['name']
            objectId = item['objectId']
            # Adding name_of_branch in all_repo_to_be_deleted list
            all_repo_to_be_deleted.append(name_of_branch)
            # Adding objectId in all_repo_to_be_deleted list
            # all_repo_to_be_deleted.append(objectId)
            passing_branch_name = "https://dev.azure.com/" + organization_name + '/' + \
                project_name + "/_apis/git/repositories/" + repo_name + "/refs?api-version=5.0"
            headers = {'Content-type': 'application/json'}

        for nameOfBranchWithref in filteredBranchesAsPerDateWithRef:
            print(nameOfBranchWithref)
            nameOfBranchWithref = nameOfBranchWithref

            data = [
                {
                    "name": nameOfBranchWithref,
                    "newObjectId": newObjectId,
                    "oldObjectId": objectId,
                }
            ]

            dry_flag = dry_flag.lower().strip()
            if dry_flag == 'true':
                repo_delete = requests.post(passing_branch_name, data=json.dumps(
                    data), headers=headers, auth=(username, auth_key))
                print(repo_delete)

            else:
                with open('delete_repo.txt', 'w') as d:
                    for item in all_repo_to_be_deleted:
                        d.write("%s\n" % item)
                print("---- This is Dry Run ----")
                print("These are the repo to be deleted: ", all_repo_to_be_deleted)


if __name__ == "__main__":
    gitRepoDeletion().getRepo('sushmasureshyadav202', 'my_delete_git', 'my_delete_git')

    gitRepoDeletion().filtering_branches(
        "<azure org name>", '<azure project>', '<azure repo>', "31/1/2020")
    gitRepoDeletion().repo_delete("<azure org name>", '<azure project>', '<azure repo>', 'true')
  • 项目名称
  • 回购协议名称
  • 目标日期
  • 根据提供的输入,应删除在给定回购目标日期之前创建的所有分支机构。 注意:-我们将只删除子分支而不是主分支

    规则

    如果标志为真,则仅应根据be dry run标志删除分支机构在给定目标日期内删除回购中的所有分支机构,不包括主分支机构


    最好是用python编写代码。

    我使用rest azure rest api调用分支,但不能按日期参数删除。

    我使用rest azure rest api调用分支,但不能按日期参数删除

    import requests
    import sys
    from datetime import datetime as dt
    import json
    from git import Repo
    import git
    import time
    
    username = '<u name>'
    auth_key = '<auth key>'
    
    class gitRepoDeletion:
    
        def getRepo(self, organization_name, project_name, repo_name):
            """
            Getting the repo details
            from the user and
            flitering the master
            branch with date functionality(still implementing)
            """
            getting_repo_list = "https://dev.azure.com/" + organization_name + '/' + \
                project_name + "/_apis/git/repositories/" + repo_name + "/refs?api-version=5.0"
    
            get_reponse = requests.get(
                getting_repo_list, auth=(username,auth_key))
    
            try:
                repojson = json.loads(get_reponse.content)
            except ValueError:
                print("Error loading json file")
            output_json = [x for x in repojson['value']
                           if x['name'] != 'refs/heads/master']
            with open('/home/vsts/work/1/s/data.json', 'w', encoding='utf-8') as f:
                json.dump(output_json, f, ensure_ascii=False, indent=4)
    
        def filtering_branches(self, organization_name, project_name, repo_name, user_date):
            """ 
            Filtering branches according 
            to the date passed by user
    
            """
    
            git_url = "https://" + organization_name + "@dev.azure.com" + '/' + \
                organization_name + '/' + project_name + '/_git' + '/' + repo_name
    
            branches = Repo.clone_from(git_url, "./mylocaldir209")
    
            remote_branches = []
            for ref in branches.git.branch('-r').split('\n'):
                if ref != '  origin/HEAD -> origin/master':
                    if ref != '  origin/master':
                        remote_branches.append(ref[9:])
                    else:
                        pass
    
            branch_and_timing_dict = {}
    
            for listy in remote_branches:
                branches.git.checkout(listy)
                commit = branches.head.commit
                timing = time.asctime(time.gmtime(commit.committed_date))
                timing = time.strftime(
                    "%d/%m/%Y", time.gmtime(commit.committed_date)).replace(' 0', ' ')
                branch_and_timing_dict[listy] = timing
    
            global filterlist
            filterlist = []
    
            for key, values in branch_and_timing_dict.items():
                d1 = dt.strptime(user_date, "%d/%m/%Y") 
                d2 = dt.strptime(key, "%d/%m/%Y")
                if d1 > d2:
                    filterlist.append(values)
                else:
                    pass
            return filterlist
    
        def repo_delete(self, organization_name, project_name, repo_name, dry_flag):
            """
            Deleting repo as
            per date input by user
            also exlucling master
    
            """
    
            all_repo_to_be_deleted = []
    
            newObjectId = "0000000000000000000000000000000000000000"
    
            filteredBranchesAsPerDateWithRef = []
    
            for value in filterlist:
                filteredBranchesAsPerDateWithRef.append("refs/heads/" + value)
                print(value)
            print(filteredBranchesAsPerDateWithRef)
    
            # Cluttering extra spaces and lowering the case of the dry flag value passed by the user
    
            # Reading data.json file, which is fetched by the getRepo() method after excluding the master branch
            with open('/home/vsts/work/1/s/data.json') as data_file:
                json_data = json.load(data_file)
            for item in json_data:
                name_of_branch = item['name']
                objectId = item['objectId']
                # Adding name_of_branch in all_repo_to_be_deleted list
                all_repo_to_be_deleted.append(name_of_branch)
                # Adding objectId in all_repo_to_be_deleted list
                # all_repo_to_be_deleted.append(objectId)
                passing_branch_name = "https://dev.azure.com/" + organization_name + '/' + \
                    project_name + "/_apis/git/repositories/" + repo_name + "/refs?api-version=5.0"
                headers = {'Content-type': 'application/json'}
    
            for nameOfBranchWithref in filteredBranchesAsPerDateWithRef:
                print(nameOfBranchWithref)
                nameOfBranchWithref = nameOfBranchWithref
    
                data = [
                    {
                        "name": nameOfBranchWithref,
                        "newObjectId": newObjectId,
                        "oldObjectId": objectId,
                    }
                ]
    
                dry_flag = dry_flag.lower().strip()
                if dry_flag == 'true':
                    repo_delete = requests.post(passing_branch_name, data=json.dumps(
                        data), headers=headers, auth=(username, auth_key))
                    print(repo_delete)
    
                else:
                    with open('delete_repo.txt', 'w') as d:
                        for item in all_repo_to_be_deleted:
                            d.write("%s\n" % item)
                    print("---- This is Dry Run ----")
                    print("These are the repo to be deleted: ", all_repo_to_be_deleted)
    
    
    if __name__ == "__main__":
        gitRepoDeletion().getRepo('sushmasureshyadav202', 'my_delete_git', 'my_delete_git')
    
        gitRepoDeletion().filtering_branches(
            "<azure org name>", '<azure project>', '<azure repo>', "31/1/2020")
        gitRepoDeletion().repo_delete("<azure org name>", '<azure project>', '<azure repo>', 'true')
    
    导入请求
    导入系统
    从日期时间导入日期时间作为dt
    导入json
    从git进口回购
    进口吉特
    导入时间
    用户名=“”
    验证密钥=“”
    类删除:
    def getRepo(自身、组织名称、项目名称、repo名称):
    """
    获取回购协议的详细信息
    从用户和
    飞行大师
    具有日期功能的分支(仍在实施)
    """
    获取回购清单=”https://dev.azure.com/“+组织机构名称+”/“+\
    项目名称+“/\u api/git/repositories/”+repo\u名称+“/refs?api版本=5.0”
    get\u response=requests.get(
    获取\u repo\u列表,auth=(用户名,auth\u键))
    尝试:
    repojson=json.loads(get_reponse.content)
    除值错误外:
    打印(“加载json文件时出错”)
    输出_json=[x代表reposon['value']
    如果x['name']!='refs/heads/master']
    将open('/home/vsts/work/1/s/data.json','w',encoding='utf-8')作为f:
    dump(输出json,f,确保ascii=False,缩进=4)
    def筛选分支机构(自身、组织名称、项目名称、回购名称、用户日期):
    """ 
    根据
    到用户传递的日期
    """
    git_url=“https://”+organization_name+“@dev.azure.com”+'/'+\
    组织机构名称+'/'+项目名称+'/'/git'+'/'+回购名称
    Branchs=Repo.clone\u from(git\u url,“./mylocaldir209”)
    远程_分支=[]
    对于branchs.git.branch('-r').split('\n')中的ref:
    如果ref!='原点/磁头->原点/主节点':
    如果ref!='原产地/主产地:
    远程分支。追加(参考文献[9:])
    其他:
    通过
    分支和定时dict={}
    对于远程分支中的列表:
    branchs.git.checkout(listy)
    commit=branchs.head.commit
    计时=time.asctime(time.gmtime(commit.committed_date))
    计时=time.strftime(
    “%d/%m/%Y”,time.gmtime(commit.committed_date)).replace('0','')
    分支和定时命令[列表]=定时
    全局过滤器列表
    过滤器列表=[]
    对于键,分支_和_计时_dict.items()中的值:
    d1=dt.strtime(用户日期,“%d/%m/%Y”)
    d2=dt.strtime(键,“%d/%m/%Y”)
    如果d1>d2:
    filterlist.append(值)
    其他:
    通过
    返回过滤器列表
    def回购删除(自身、组织名称、项目名称、回购名称、干燥标志):
    """
    将回购协议删除为
    用户输入的每个日期
    也揭示了大师
    """
    所有待删除的回购协议=[]
    newObjectId=“0000000000000000000000000000”
    FilteredBranchesSpecardateWithRef=[]
    对于过滤器列表中的值:
    FilteredBranchesSpecardatewithref.append(“refs/heads/”+value)
    打印(值)
    打印(FilteredBranchesSpecrdateWithRef)
    #凌乱额外的空间并降低用户传递的干标志值的大小写
    #正在读取data.json文件,该文件在排除主分支后由getRepo()方法获取
    以open('/home/vsts/work/1/s/data.json')作为数据文件:
    json_data=json.load(数据文件)
    对于json_数据中的项:
    分支机构名称=项目['name']
    objectId=项目['objectId']
    #将所有回购中的分支机构名称添加到待删除列表中
    所有待删除的回购。追加(分支机构名称)
    #将objectId添加到所有待删除列表中
    #要删除的所有报告。追加(objectId)
    正在传递分支名称=”https://dev.azure.com/“+组织机构名称+”/“+\
    项目名称+“/\u api/git/repositories/”+repo\u名称+“/refs?api版本=5.0”
    headers={'Content-type':'application/json'}
    对于FilteredBranchesSpecardateWithRef中的BranchWithRef名称:
    打印(BranchOfBranchWithRef的名称)
    nameOfBranchWithref=nameOfBranchWithref
    数据=[
    {
    “名称”:BranchWithRef的名称,
    “newObjectId”:newObjectId,
    “oldObjectId”:objectId,
    }
    ]
    dry_flag=dry_flag.lower().strip()
    如果dry_标志=='true':
    repo_delete=requests.post(传递分支名称,数据=json.dumps(
    数据),标题=标题,身份验证=(用户名,身份验证密钥))
    打印(报告删除)
    其他:
    打开('delete_repo.txt','w')作为d:
    对于要删除的所有回购中的项目:
    d、 写入(“%s\n”%item)
    打印(“----这是干运行--”)
    打印(“这些是要删除的回购:”,所有要删除的回购)
    如果名称=“\uuuuu main\uuuuuuuu”:
    gitrepodeletation().getRepo('sushmasureshyadav202','my\u delete\u git','my\u delete\u git')
    gitRepoDeletion()。筛选\u分支(
    "", '', '', "31/1/2020")