From 7f50d48c01917f6490464320d22cefd6e1319be3 Mon Sep 17 00:00:00 2001 From: 6543 <6543@noreply.gitea.io> Date: Tue, 9 Jun 2020 10:11:14 +0000 Subject: [PATCH] File Create/Update/Delete detect DefaultBranch if Branch not set for old Versions (#352) Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions Co-authored-by: 6543 <6543@obermui.de> Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/352 Reviewed-by: techknowlogick Reviewed-by: Andrew Thornton --- gitea/repo_file.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/gitea/repo_file.go b/gitea/repo_file.go index 3ef6fa5..1881859 100644 --- a/gitea/repo_file.go +++ b/gitea/repo_file.go @@ -128,6 +128,11 @@ func (c *Client) GetContents(owner, repo, ref, filepath string) (*ContentsRespon // CreateFile create a file in a repository func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, error) { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return nil, err + } + body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -138,6 +143,11 @@ func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) // UpdateFile update a file in a repository func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, error) { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return nil, err + } + body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -148,6 +158,11 @@ func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) // DeleteFile delete a file from repository func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) error { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return err + } + body, err := json.Marshal(&opt) if err != nil { return err @@ -161,3 +176,17 @@ func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) } return nil } + +func (c *Client) setDefaultBranchForOldVersions(owner, repo, branch string) (string, error) { + if len(branch) == 0 { + // Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + r, err := c.GetRepo(owner, repo) + if err != nil { + return "", err + } + return r.DefaultBranch, nil + } + } + return branch, nil +}