From bb393596689ee7c33ecb041806ae2c9e8dc5dfab Mon Sep 17 00:00:00 2001
From: a1012112796 <1012112796@qq.com>
Date: Sat, 9 Oct 2021 01:03:04 +0800
Subject: Add a simple way to rename branch like gh (#15870)

- Update default branch if needed
- Update protected branch if needed
- Update all not merged pull request base branch name
- Rename git branch
- Record this rename work and auto redirect for old branch on ui

Signed-off-by: a1012112796 <1012112796@qq.com>
Co-authored-by: delvh <dev.lh@web.de>
---
 routers/web/repo/setting_protected_branch.go | 38 ++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)

(limited to 'routers/web/repo/setting_protected_branch.go')

diff --git a/routers/web/repo/setting_protected_branch.go b/routers/web/repo/setting_protected_branch.go
index c48ab9471a..876ff9ba46 100644
--- a/routers/web/repo/setting_protected_branch.go
+++ b/routers/web/repo/setting_protected_branch.go
@@ -19,6 +19,7 @@ import (
 	"code.gitea.io/gitea/modules/web"
 	"code.gitea.io/gitea/services/forms"
 	pull_service "code.gitea.io/gitea/services/pull"
+	"code.gitea.io/gitea/services/repository"
 )
 
 // ProtectedBranch render the page to protect the repository
@@ -285,3 +286,40 @@ func SettingsProtectedBranchPost(ctx *context.Context) {
 		ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
 	}
 }
+
+// RenameBranchPost responses for rename a branch
+func RenameBranchPost(ctx *context.Context) {
+	form := web.GetForm(ctx).(*forms.RenameBranchForm)
+
+	if !ctx.Repo.CanCreateBranch() {
+		ctx.NotFound("RenameBranch", nil)
+		return
+	}
+
+	if ctx.HasError() {
+		ctx.Flash.Error(ctx.GetErrMsg())
+		ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+		return
+	}
+
+	msg, err := repository.RenameBranch(ctx.Repo.Repository, ctx.User, ctx.Repo.GitRepo, form.From, form.To)
+	if err != nil {
+		ctx.ServerError("RenameBranch", err)
+		return
+	}
+
+	if msg == "target_exist" {
+		ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_exist", form.To))
+		ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+		return
+	}
+
+	if msg == "from_not_exist" {
+		ctx.Flash.Error(ctx.Tr("repo.settings.rename_branch_failed_not_exist", form.From))
+		ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+		return
+	}
+
+	ctx.Flash.Success(ctx.Tr("repo.settings.rename_branch_success", form.From, form.To))
+	ctx.Redirect(fmt.Sprintf("%s/settings/branches", ctx.Repo.RepoLink))
+}
-- 
cgit v1.2.3