Merge branch '36010-api-v4-allows-setting-a-branch-that-doesn-t-exist-as-the-default-one' into 'master'

Resolve "API v4 allows setting a branch that doesn't exist as the default one"

Closes #36010

See merge request !13359
This commit is contained in:
Rémy Coutable 2017-08-08 15:16:54 +00:00
commit 143b5293b0
5 changed files with 29 additions and 8 deletions

View File

@ -1046,13 +1046,18 @@ class Project < ActiveRecord::Base
end
def change_head(branch)
repository.before_change_head
repository.rugged.references.create('HEAD',
"refs/heads/#{branch}",
force: true)
repository.copy_gitattributes(branch)
repository.after_change_head
reload_default_branch
if repository.branch_exists?(branch)
repository.before_change_head
repository.rugged.references.create('HEAD',
"refs/heads/#{branch}",
force: true)
repository.copy_gitattributes(branch)
repository.after_change_head
reload_default_branch
else
errors.add(:base, "Could not change HEAD: branch '#{branch}' does not exist")
false
end
end
def forked_from?(project)

View File

@ -10,7 +10,7 @@ module Projects
end
if changing_default_branch?
project.change_head(params[:default_branch])
return error("Could not set the default branch") unless project.change_head(params[:default_branch])
end
if project.update_attributes(params.except(:default_branch))

View File

@ -0,0 +1,4 @@
---
title: Add checks for branch existence before changing HEAD
merge_request: 13359
author: Vitaliy @blackst0ne Klachkov

View File

@ -1832,6 +1832,11 @@ describe Project do
describe '#change_head' do
let(:project) { create(:project, :repository) }
it 'returns error if branch does not exist' do
expect(project.change_head('unexisted-branch')).to be false
expect(project.errors.size).to eq(1)
end
it 'calls the before_change_head and after_change_head methods' do
expect(project.repository).to receive(:before_change_head)
expect(project.repository).to receive(:after_change_head)

View File

@ -101,6 +101,13 @@ describe Projects::UpdateService, '#execute' do
expect(Project.find(project.id).default_branch).to eq 'feature'
end
it 'does not change a default branch' do
# The branch 'unexisted-branch' does not exist.
update_project(project, admin, default_branch: 'unexisted-branch')
expect(Project.find(project.id).default_branch).to eq 'master'
end
end
context 'when updating a project that contains container images' do