Skip to content

Commit

Permalink
Fix PATCH /repos/{owner}/{repo} panic (#14637)
Browse files Browse the repository at this point in the history
* Fix a runtime error when modifying a repository through API call

Using the `PATCH /repos/{owner}/{repo}` endpoint and attempting to
modify `default_branch` on an empty repository will cause a
panic. This commit adds a check for a nil pointer before attempting
to dereference it.

* Apply suggestions from code review

* Apply suggestions from code review

* Ensure that the git repository is loaded

If you change the default branch for a repository you must change it in
git too. Therefore you must open the repository before changing the
default branch.

Signed-off-by: Andrew Thornton <art27@cantab.net>

* Allow empty repos to have their default branches changed

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: Anton Khimich <anton.khimicha@mail.utoronto.ca>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Andrew Thornton <art27@cantab.net>
  • Loading branch information
4 people authored Feb 11, 2021
1 parent 441f3f0 commit 5a18712
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions routers/api/v1/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -574,8 +574,20 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
repo.IsTemplate = *opts.Template
}

// Default branch only updated if changed and exist
if opts.DefaultBranch != nil && repo.DefaultBranch != *opts.DefaultBranch && ctx.Repo.GitRepo.IsBranchExist(*opts.DefaultBranch) {
if ctx.Repo.GitRepo == nil {
var err error
ctx.Repo.GitRepo, err = git.OpenRepository(ctx.Repo.Repository.RepoPath())
if err != nil {
ctx.Error(http.StatusInternalServerError, "Unable to OpenRepository", err)
return err
}
defer ctx.Repo.GitRepo.Close()
}

// Default branch only updated if changed and exist or the repository is empty
if opts.DefaultBranch != nil &&
repo.DefaultBranch != *opts.DefaultBranch &&
(ctx.Repo.Repository.IsEmpty || ctx.Repo.GitRepo.IsBranchExist(*opts.DefaultBranch)) {
if err := ctx.Repo.GitRepo.SetDefaultBranch(*opts.DefaultBranch); err != nil {
if !git.IsErrUnsupportedVersion(err) {
ctx.Error(http.StatusInternalServerError, "SetDefaultBranch", err)
Expand Down

0 comments on commit 5a18712

Please sign in to comment.