Bitbucket Cloud API能否编辑仓库文件?用于自动更新流水线版本号
Bitbucket Cloud API 编辑文件的实现方法
Bitbucket Cloud API 没有提供像Bitbucket Server那样直接编辑文件的PUT端点,必须通过获取文件内容→修改内容→提交新版本的间接流程来实现,完全可以满足你生产发布后自动更新流水线YAML版本号的需求。
实现步骤
- 调用API获取目标文件的最新内容、对应的commit哈希值以及文件路径信息
- 在本地修改文件内容(替换版本号)
- 调用API提交修改后的内容,生成新的commit
Python 示例代码
以下是针对你的场景(更新流水线YAML版本号)的完整实现:
import requests import base64 import json # 配置信息 BITBUCKET_CLOUD_BASE_URL = "https://api.bitbucket.org/2.0" WORKSPACE = "你的工作区名称" REPO_SLUG = "你的仓库名称" FILE_PATH = "bitbucket-pipelines.yml" # 目标文件路径 APP_PASSWORD = "你的Bitbucket App Password" # 需开启仓库读写权限 USERNAME = "你的Bitbucket用户名" NEW_VERSION = "v1.2.3" # 要更新的版本号 # 1. 获取目标文件的最新信息 def get_file_info(): url = f"{BITBUCKET_CLOUD_BASE_URL}/repositories/{WORKSPACE}/{REPO_SLUG}/src/main/{FILE_PATH}" auth = (USERNAME, APP_PASSWORD) response = requests.get(url, auth=auth) response.raise_for_status() file_data = response.json() # 解码base64格式的文件内容 content = base64.b64decode(file_data["content"]).decode("utf-8") return content, file_data["commit"]["hash"] # 2. 修改文件中的版本号 def update_version(content): # 这里根据你的YAML结构调整替换逻辑,示例假设版本号在image标签后 updated_content = content.replace("image: your-image:old-version", f"image: your-image:{NEW_VERSION}") return updated_content # 3. 提交修改后的内容 def commit_changes(updated_content, commit_hash): url = f"{BITBUCKET_CLOUD_BASE_URL}/repositories/{WORKSPACE}/{REPO_SLUG}/src" auth = (USERNAME, APP_PASSWORD) payload = { "message": f"Update pipeline version to {NEW_VERSION}", "branch": "main", # 目标分支 "source_commit": commit_hash, "files": [ { "path": FILE_PATH, "content": base64.b64encode(updated_content.encode("utf-8")).decode("utf-8") } ] } response = requests.post(url, json=payload, auth=auth) response.raise_for_status() return response.json() # 执行流程 if __name__ == "__main__": try: content, commit_hash = get_file_info() updated_content = update_version(content) result = commit_changes(updated_content, commit_hash) print(json.dumps(result, indent=4)) print(f"版本号已成功更新为 {NEW_VERSION}") except Exception as e: print(f"操作失败: {str(e)}")
关键说明
- 必须使用Bitbucket App Password进行认证,需给该密码分配仓库读写权限
- 提交时必须指定
source_commit,确保修改基于最新版本,避免冲突 - 文件内容需用Base64编码后传输,这是Bitbucket Cloud API的要求
内容的提问来源于stack exchange,提问作者Niall Hodgen
相关产品推荐
相关产品推荐

