Make "update file" API can create a new file when SHA is not set (#35738)

Fix #19008, use GitHub's behavior (empty SHA to create a new file)
This commit is contained in:
wxiaoguang
2025-10-24 12:46:54 +08:00
committed by GitHub
parent 397d666432
commit 9a73a1fb83
5 changed files with 58 additions and 50 deletions

View File

@@ -525,7 +525,7 @@ func CreateFile(ctx *context.APIContext) {
func UpdateFile(ctx *context.APIContext) {
// swagger:operation PUT /repos/{owner}/{repo}/contents/{filepath} repository repoUpdateFile
// ---
// summary: Update a file in a repository
// summary: Update a file in a repository if SHA is set, or create the file if SHA is not set
// consumes:
// - application/json
// produces:
@@ -554,6 +554,8 @@ func UpdateFile(ctx *context.APIContext) {
// responses:
// "200":
// "$ref": "#/responses/FileResponse"
// "201":
// "$ref": "#/responses/FileResponse"
// "403":
// "$ref": "#/responses/error"
// "404":
@@ -572,8 +574,9 @@ func UpdateFile(ctx *context.APIContext) {
ctx.APIError(http.StatusUnprocessableEntity, err)
return
}
willCreate := apiOpts.SHA == ""
opts.Files = append(opts.Files, &files_service.ChangeRepoFile{
Operation: "update",
Operation: util.Iif(willCreate, "create", "update"),
ContentReader: contentReader,
SHA: apiOpts.SHA,
FromTreePath: apiOpts.FromPath,
@@ -587,7 +590,7 @@ func UpdateFile(ctx *context.APIContext) {
handleChangeRepoFilesError(ctx, err)
} else {
fileResponse := files_service.GetFileResponseFromFilesResponse(filesResponse, 0)
ctx.JSON(http.StatusOK, fileResponse)
ctx.JSON(util.Iif(willCreate, http.StatusCreated, http.StatusOK), fileResponse)
}
}