[Python] Using Azure Devops API in Python to fetch PR modified files and get the diff

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I have this function of getting modified files in Azure Devops PR:

    def fetch_pr_diff(pr_id):
    try:
    # Establish connection and get the Git client
    connection = get_azure_devops_connection()
    git_client = connection.clients.get_git_client()

    # Retrieve pull request iterations
    iterations = git_client.get_pull_request_iterations(
    repository_id=repository_id,
    project=project_name,
    pull_request_id=pr_id
    )

    # Get the latest iteration
    latest_iteration = max(iterations, key=lambda x: x.id)

    # Fetch changes for the latest iteration
    iteration_changes = git_client.get_pull_request_iteration_changes(
    repository_id=repository_id,
    project=project_name,
    pull_request_id=pr_id,
    iteration_id=latest_iteration.id
    )

    # Initialize the diff content
    diff_content = ""

    # Loop through the changes to extract diffs for each file
    for change in iteration_changes.change_entries:
    if change.additional_properties['item'] is not None: # Only process items with valid file information
    change = change.additional_properties['item']
    file_path = change['path']

    # Check the change type (e.g., modified, added, deleted)
    change_type = iteration_changes.change_entries[0].additional_properties['changeType']

    # Process modified files
    if change_type in ['edit', 'add']:
    # Fetch the file content of the latest version
    file_content = git_client.get_item_content(
    repository_id=repository_id,
    project=project_name,
    path=file_path
    )
    file_content_ = ''.join(chunk.decode('utf-8') for chunk in file_content)
    # Add file details to the diff content
    diff_content += f"File: {file_path}\n"
    diff_content += f"Change Type: {change_type}\n"
    diff_content += f"Content:\n{file_content_}\n\n"
    elif change_type == 'delete':
    # If the file is deleted, just log the deletion
    diff_content += f"File: {file_path}\n"
    diff_content += f"Change Type: {change_type}\n"
    diff_content += "Content: File deleted.\n\n"

    return diff_content


    the problem is that i want fetch only the modified part, and not the whole file. how can i just get the modified part between the commited file and the master? thanks!

    Continue reading...

Compartilhe esta Página