我想对我的分支中更改的文件运行一些 pytest 测试,包含所有步骤的构建管道正在运行。我有这个
displayName: 'Get changed files in the latest commit'
inputs:
targetType: 'inline'
script: |
git diff-tree --no-commit-id --name-status -r $(Build.SourceVersion)^ $(Build.SourceVersion) > changed_files.txt
cat changed_files.txt
但这不起作用 - 我得到
fatal: ambiguous argument 'c971d4f8f356595b603d87c3055055fb43ca2752^': unknown revision or path not in the working tree.
我已经尝试了 Stackoverflow 上发布的所有解决方案 - 以零深度结帐,使用添加到 url 的 PAT 获取,没有任何效果。我只需要该分支中已修改的所有文件的列表,不仅仅是最新提交中的文件,而是所有文件。
要在不使用
git
命令的情况下获取 Azure DevOps 分支中更改的所有文件的列表,您可以使用 Azure DevOps REST API。
git/commits
API 允许您列出分支中的提交,然后您可以获取与每个提交关联的更改(文件)。
请参阅此链接,了解如何在 Azure DevOps Git 中使用 REST API。
下面的代码用于获取 Azure DevOps 分支中更改的所有文件的列表:
import requests
import base64
org_url = "https://dev.azure.com/ORG_Name"
project_name = "Project_Name"
repo_name = "Repo_Name"
pat = "YOUR_PERSONAL_ACCESS_TOKEN"
query_string = "api-version=7.1-preview.1"
token = base64.b64encode(f":{pat}".encode('ascii')).decode('ascii')
headers = {'Authorization': f"Basic {token}"}
def fetch_commits(branch_name):
commits_url = f"{org_url}/{project_name}/_apis/git/repositories/{repo_name}/commits?searchCriteria.itemVersion.version={branch_name}&{query_string}"
response = requests.get(commits_url, headers=headers)
if response.status_code == 200:
commits = response.json()
print(f"Commits on branch {branch_name}:")
for commit in commits['value']:
print(f"Commit ID: {commit['commitId']} - {commit['comment']}")
fetch_changes(commit['commitId'])
else:
print(f"Failed to fetch commits: {response.text}")
def fetch_changes(commit_id):
changes_url = f"{org_url}/{project_name}/_apis/git/repositories/{repo_name}/commits/{commit_id}/changes?{query_string}"
response = requests.get(changes_url, headers=headers)
if response.status_code == 200:
changes = response.json()
if 'value' in changes: # Check if 'value' key exists
print(f"Files changed in commit {commit_id}:")
for change in changes['value']:
print(f"File: {change['item']['path']}")
else:
print(f"No changes found in commit {commit_id}.")
else:
print(f"Failed to fetch changes for commit {commit_id}: {response.text}")
branch_name = "main"
fetch_commits(branch_name)