Skip to content

Edit file workflow for creating a fork and proposing changes #34240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
2 changes: 1 addition & 1 deletion models/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ func (repo *Repository) AllowsPulls(ctx context.Context) bool {

// CanEnableEditor returns true if repository meets the requirements of web editor.
func (repo *Repository) CanEnableEditor() bool {
return !repo.IsMirror
return !repo.IsMirror && !repo.IsArchived
}

// DescriptionHTML does special handles to description and return HTML string.
Expand Down
7 changes: 7 additions & 0 deletions options/locale/locale_en-US.ini
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,13 @@ editor.revert = Revert %s onto:
editor.failed_to_commit = Failed to commit changes.
editor.failed_to_commit_summary = Error Message:

editor.fork_create = Fork Repository to Propose Changes
editor.fork_create_description = You can not edit this repository directly. Instead you can create a fork, make edits and create a pull request.
editor.fork_edit_description = You can not edit this repository directly. The changes will be written to your fork <b>%s</b>, so you can create a pull request.
editor.fork_not_editable = You have forked this repository but your fork is not editable.
editor.fork_failed_to_push_branch = Failed to push branch %s to your repository.
editor.fork_branch_exists = Branch "%s" already exists in your fork, please choose a new branch name.

commits.desc = Browse source code change history.
commits.commits = Commits
commits.no_commits = No commits in common. "%s" and "%s" have entirely different histories.
Expand Down
159 changes: 106 additions & 53 deletions routers/web/repo/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/charset"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
Expand All @@ -39,26 +40,36 @@ const (
editorCommitChoiceNewBranch string = "commit-to-new-branch"
)

func prepareEditorCommitFormOptions(ctx *context.Context, editorAction string) {
func prepareEditorCommitFormOptions(ctx *context.Context, editorAction string) *context.CommitFormOptions {
cleanedTreePath := files_service.CleanGitTreePath(ctx.Repo.TreePath)
if cleanedTreePath != ctx.Repo.TreePath {
redirectTo := fmt.Sprintf("%s/%s/%s/%s", ctx.Repo.RepoLink, editorAction, util.PathEscapeSegments(ctx.Repo.BranchName), util.PathEscapeSegments(cleanedTreePath))
if ctx.Req.URL.RawQuery != "" {
redirectTo += "?" + ctx.Req.URL.RawQuery
}
ctx.Redirect(redirectTo)
return
return nil
}

commitFormBehaviors, err := ctx.Repo.PrepareCommitFormBehaviors(ctx, ctx.Doer)
commitFormOptions, err := context.PrepareCommitFormOptions(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.Permission, ctx.Repo.RefFullName)
if err != nil {
ctx.ServerError("PrepareCommitFormBehaviors", err)
return
ctx.ServerError("PrepareCommitFormOptions", err)
return nil
}

if commitFormOptions.NeedFork {
ForkToEdit(ctx)
return nil
}

if commitFormOptions.WillSubmitToFork && !commitFormOptions.TargetRepo.CanEnableEditor() {
ctx.Data["NotFoundPrompt"] = ctx.Locale.Tr("repo.editor.fork_not_editable")
ctx.NotFound(nil)
}

ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL()
ctx.Data["TreePath"] = ctx.Repo.TreePath
ctx.Data["CommitFormBehaviors"] = commitFormBehaviors
ctx.Data["CommitFormOptions"] = commitFormOptions

// for online editor
ctx.Data["PreviewableExtensions"] = strings.Join(markup.PreviewableExtensions(), ",")
Expand All @@ -69,33 +80,35 @@ func prepareEditorCommitFormOptions(ctx *context.Context, editorAction string) {
// form fields
ctx.Data["commit_summary"] = ""
ctx.Data["commit_message"] = ""
ctx.Data["commit_choice"] = util.Iif(commitFormBehaviors.CanCommitToBranch, editorCommitChoiceDirect, editorCommitChoiceNewBranch)
ctx.Data["new_branch_name"] = getUniquePatchBranchName(ctx, ctx.Doer.LowerName, ctx.Repo.Repository)
ctx.Data["commit_choice"] = util.Iif(commitFormOptions.CanCommitToBranch, editorCommitChoiceDirect, editorCommitChoiceNewBranch)
ctx.Data["new_branch_name"] = getUniquePatchBranchName(ctx, ctx.Doer.LowerName, commitFormOptions.TargetRepo)
ctx.Data["last_commit"] = ctx.Repo.CommitID
return commitFormOptions
}

func prepareTreePathFieldsAndPaths(ctx *context.Context, treePath string) {
// show the tree path fields in the "breadcrumb" and help users to edit the target tree path
ctx.Data["TreeNames"], ctx.Data["TreePaths"] = getParentTreeFields(treePath)
ctx.Data["TreeNames"], ctx.Data["TreePaths"] = getParentTreeFields(strings.TrimPrefix(treePath, "/"))
}

type parsedEditorCommitForm[T any] struct {
form T
commonForm *forms.CommitCommonForm
CommitFormBehaviors *context.CommitFormBehaviors
TargetBranchName string
GitCommitter *files_service.IdentityOptions
type preparedEditorCommitForm[T any] struct {
form T
commonForm *forms.CommitCommonForm
CommitFormOptions *context.CommitFormOptions
OldBranchName string
NewBranchName string
GitCommitter *files_service.IdentityOptions
}

func (f *parsedEditorCommitForm[T]) GetCommitMessage(defaultCommitMessage string) string {
func (f *preparedEditorCommitForm[T]) GetCommitMessage(defaultCommitMessage string) string {
commitMessage := util.IfZero(strings.TrimSpace(f.commonForm.CommitSummary), defaultCommitMessage)
if body := strings.TrimSpace(f.commonForm.CommitMessage); body != "" {
commitMessage += "\n\n" + body
}
return commitMessage
}

func parseEditorCommitSubmittedForm[T forms.CommitCommonFormInterface](ctx *context.Context) *parsedEditorCommitForm[T] {
func prepareEditorCommitSubmittedForm[T forms.CommitCommonFormInterface](ctx *context.Context) *preparedEditorCommitForm[T] {
form := web.GetForm(ctx).(T)
if ctx.HasError() {
ctx.JSONError(ctx.GetErrMsg())
Expand All @@ -105,15 +118,22 @@ func parseEditorCommitSubmittedForm[T forms.CommitCommonFormInterface](ctx *cont
commonForm := form.GetCommitCommonForm()
commonForm.TreePath = files_service.CleanGitTreePath(commonForm.TreePath)

commitFormBehaviors, err := ctx.Repo.PrepareCommitFormBehaviors(ctx, ctx.Doer)
commitFormOptions, err := context.PrepareCommitFormOptions(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.Permission, ctx.Repo.RefFullName)
if err != nil {
ctx.ServerError("PrepareCommitFormBehaviors", err)
ctx.ServerError("PrepareCommitFormOptions", err)
return nil
}
if commitFormOptions.NeedFork {
// It shouldn't happen, because we should have done the checks in the "GET" request. But just in case.
ctx.JSONError(ctx.Locale.TrString("error.not_found"))
return nil
}

// check commit behavior
targetBranchName := util.Iif(commonForm.CommitChoice == editorCommitChoiceNewBranch, commonForm.NewBranchName, ctx.Repo.BranchName)
if targetBranchName == ctx.Repo.BranchName && !commitFormBehaviors.CanCommitToBranch {
fromBaseBranch := ctx.FormString("from_base_branch")
commitToNewBranch := commonForm.CommitChoice == editorCommitChoiceNewBranch || fromBaseBranch != ""
targetBranchName := util.Iif(commitToNewBranch, commonForm.NewBranchName, ctx.Repo.BranchName)
if targetBranchName == ctx.Repo.BranchName && !commitFormOptions.CanCommitToBranch {
ctx.JSONError(ctx.Tr("repo.editor.cannot_commit_to_protected_branch", targetBranchName))
return nil
}
Expand All @@ -125,40 +145,73 @@ func parseEditorCommitSubmittedForm[T forms.CommitCommonFormInterface](ctx *cont
return nil
}

return &parsedEditorCommitForm[T]{
form: form,
commonForm: commonForm,
CommitFormBehaviors: commitFormBehaviors,
TargetBranchName: targetBranchName,
GitCommitter: gitCommitter,
if commitToNewBranch {
// if target branch exists, we should stop
targetBranchExists, err := git_model.IsBranchExist(ctx, commitFormOptions.TargetRepo.ID, targetBranchName)
if err != nil {
ctx.ServerError("IsBranchExist", err)
return nil
} else if targetBranchExists {
if fromBaseBranch != "" {
ctx.JSONError(ctx.Tr("repo.editor.fork_branch_exists", targetBranchName))
} else {
ctx.JSONError(ctx.Tr("repo.editor.branch_already_exists", targetBranchName))
}
return nil
}
}

oldBranchName := ctx.Repo.BranchName
if fromBaseBranch != "" {
err = editorPushBranchToForkedRepository(ctx, ctx.Doer, ctx.Repo.Repository.BaseRepo, fromBaseBranch, commitFormOptions.TargetRepo, targetBranchName)
if err != nil {
log.Error("Unable to editorPushBranchToForkedRepository: %v", err)
ctx.JSONError(ctx.Tr("repo.editor.fork_failed_to_push_branch", targetBranchName))
return nil
}
// we have pushed the base branch as the new branch, now we need to commit the changes directly to the new branch
oldBranchName = targetBranchName
}

return &preparedEditorCommitForm[T]{
form: form,
commonForm: commonForm,
CommitFormOptions: commitFormOptions,
OldBranchName: oldBranchName,
NewBranchName: targetBranchName,
GitCommitter: gitCommitter,
}
}

// redirectForCommitChoice redirects after committing the edit to a branch
func redirectForCommitChoice[T any](ctx *context.Context, parsed *parsedEditorCommitForm[T], treePath string) {
func redirectForCommitChoice[T any](ctx *context.Context, parsed *preparedEditorCommitForm[T], treePath string) {
// when editing a file in a PR, it should return to the origin location
if returnURI := ctx.FormString("return_uri"); returnURI != "" && httplib.IsCurrentGiteaSiteURL(ctx, returnURI) {
ctx.JSONRedirect(returnURI)
return
}

if parsed.commonForm.CommitChoice == editorCommitChoiceNewBranch {
// Redirect to a pull request when possible
redirectToPullRequest := false
repo, baseBranch, headBranch := ctx.Repo.Repository, ctx.Repo.BranchName, parsed.TargetBranchName
if repo.UnitEnabled(ctx, unit.TypePullRequests) {
redirectToPullRequest = true
} else if parsed.CommitFormBehaviors.CanCreateBasePullRequest {
repo, baseBranch, headBranch := ctx.Repo.Repository, parsed.OldBranchName, parsed.NewBranchName
if ctx.Repo.Repository.IsFork && parsed.CommitFormOptions.CanCreateBasePullRequest {
redirectToPullRequest = true
baseBranch = repo.BaseRepo.DefaultBranch
headBranch = repo.Owner.Name + "/" + repo.Name + ":" + headBranch
repo = repo.BaseRepo
} else if repo.UnitEnabled(ctx, unit.TypePullRequests) {
redirectToPullRequest = true
}
if redirectToPullRequest {
ctx.JSONRedirect(repo.Link() + "/compare/" + util.PathEscapeSegments(baseBranch) + "..." + util.PathEscapeSegments(headBranch))
return
}
}

returnURI := ctx.FormString("return_uri")
if returnURI == "" || !httplib.IsCurrentGiteaSiteURL(ctx, returnURI) {
returnURI = util.URLJoin(ctx.Repo.RepoLink, "src/branch", util.PathEscapeSegments(parsed.TargetBranchName), util.PathEscapeSegments(treePath))
}
ctx.JSONRedirect(returnURI)
// redirect to the newly updated file
redirectTo := util.URLJoin(ctx.Repo.RepoLink, "src/branch", util.PathEscapeSegments(parsed.NewBranchName), util.PathEscapeSegments(treePath))
ctx.JSONRedirect(redirectTo)
}

func editFileOpenExisting(ctx *context.Context) (prefetch []byte, dataRc io.ReadCloser, fInfo *fileInfo) {
Expand Down Expand Up @@ -268,7 +321,7 @@ func EditFile(ctx *context.Context) {
func EditFilePost(ctx *context.Context) {
editorAction := ctx.PathParam("editor_action")
isNewFile := editorAction == "_new"
parsed := parseEditorCommitSubmittedForm[*forms.EditRepoFileForm](ctx)
parsed := prepareEditorCommitSubmittedForm[*forms.EditRepoFileForm](ctx)
if ctx.Written() {
return
}
Expand All @@ -292,8 +345,8 @@ func EditFilePost(ctx *context.Context) {

_, err := files_service.ChangeRepoFiles(ctx, ctx.Repo.Repository, ctx.Doer, &files_service.ChangeRepoFilesOptions{
LastCommitID: parsed.form.LastCommit,
OldBranch: ctx.Repo.BranchName,
NewBranch: parsed.TargetBranchName,
OldBranch: parsed.OldBranchName,
NewBranch: parsed.NewBranchName,
Message: parsed.GetCommitMessage(defaultCommitMessage),
Files: []*files_service.ChangeRepoFile{
{
Expand All @@ -308,7 +361,7 @@ func EditFilePost(ctx *context.Context) {
Committer: parsed.GitCommitter,
})
if err != nil {
editorHandleFileOperationError(ctx, parsed.TargetBranchName, err)
editorHandleFileOperationError(ctx, parsed.NewBranchName, err)
return
}

Expand All @@ -327,16 +380,16 @@ func DeleteFile(ctx *context.Context) {

// DeleteFilePost response for deleting file
func DeleteFilePost(ctx *context.Context) {
parsed := parseEditorCommitSubmittedForm[*forms.DeleteRepoFileForm](ctx)
parsed := prepareEditorCommitSubmittedForm[*forms.DeleteRepoFileForm](ctx)
if ctx.Written() {
return
}

treePath := ctx.Repo.TreePath
_, err := files_service.ChangeRepoFiles(ctx, ctx.Repo.Repository, ctx.Doer, &files_service.ChangeRepoFilesOptions{
LastCommitID: parsed.form.LastCommit,
OldBranch: ctx.Repo.BranchName,
NewBranch: parsed.TargetBranchName,
OldBranch: parsed.OldBranchName,
NewBranch: parsed.NewBranchName,
Files: []*files_service.ChangeRepoFile{
{
Operation: "delete",
Expand All @@ -349,38 +402,38 @@ func DeleteFilePost(ctx *context.Context) {
Committer: parsed.GitCommitter,
})
if err != nil {
editorHandleFileOperationError(ctx, parsed.TargetBranchName, err)
editorHandleFileOperationError(ctx, parsed.NewBranchName, err)
return
}

ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", treePath))
redirectTreePath := getClosestParentWithFiles(ctx.Repo.GitRepo, parsed.TargetBranchName, treePath)
redirectTreePath := getClosestParentWithFiles(ctx.Repo.GitRepo, parsed.NewBranchName, treePath)
redirectForCommitChoice(ctx, parsed, redirectTreePath)
}

func UploadFile(ctx *context.Context) {
ctx.Data["PageIsUpload"] = true
upload.AddUploadContext(ctx, "repo")
prepareTreePathFieldsAndPaths(ctx, ctx.Repo.TreePath)

prepareEditorCommitFormOptions(ctx, "_upload")
opts := prepareEditorCommitFormOptions(ctx, "_upload")
if ctx.Written() {
return
}
upload.AddUploadContextForRepo(ctx, opts.TargetRepo)

ctx.HTML(http.StatusOK, tplUploadFile)
}

func UploadFilePost(ctx *context.Context) {
parsed := parseEditorCommitSubmittedForm[*forms.UploadRepoFileForm](ctx)
parsed := prepareEditorCommitSubmittedForm[*forms.UploadRepoFileForm](ctx)
if ctx.Written() {
return
}

defaultCommitMessage := ctx.Locale.TrString("repo.editor.upload_files_to_dir", util.IfZero(parsed.form.TreePath, "/"))
err := files_service.UploadRepoFiles(ctx, ctx.Repo.Repository, ctx.Doer, &files_service.UploadRepoFileOptions{
LastCommitID: parsed.form.LastCommit,
OldBranch: ctx.Repo.BranchName,
NewBranch: parsed.TargetBranchName,
OldBranch: parsed.OldBranchName,
NewBranch: parsed.NewBranchName,
TreePath: parsed.form.TreePath,
Message: parsed.GetCommitMessage(defaultCommitMessage),
Files: parsed.form.Files,
Expand All @@ -389,7 +442,7 @@ func UploadFilePost(ctx *context.Context) {
Committer: parsed.GitCommitter,
})
if err != nil {
editorHandleFileOperationError(ctx, parsed.TargetBranchName, err)
editorHandleFileOperationError(ctx, parsed.NewBranchName, err)
return
}
redirectForCommitChoice(ctx, parsed, parsed.form.TreePath)
Expand Down
8 changes: 4 additions & 4 deletions routers/web/repo/editor_apply_patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ func NewDiffPatch(ctx *context.Context) {

// NewDiffPatchPost response for sending patch page
func NewDiffPatchPost(ctx *context.Context) {
parsed := parseEditorCommitSubmittedForm[*forms.EditRepoFileForm](ctx)
parsed := prepareEditorCommitSubmittedForm[*forms.EditRepoFileForm](ctx)
if ctx.Written() {
return
}

defaultCommitMessage := ctx.Locale.TrString("repo.editor.patch")
_, err := files.ApplyDiffPatch(ctx, ctx.Repo.Repository, ctx.Doer, &files.ApplyDiffPatchOptions{
LastCommitID: parsed.form.LastCommit,
OldBranch: ctx.Repo.BranchName,
NewBranch: parsed.TargetBranchName,
OldBranch: parsed.OldBranchName,
NewBranch: parsed.NewBranchName,
Message: parsed.GetCommitMessage(defaultCommitMessage),
Content: strings.ReplaceAll(parsed.form.Content.Value(), "\r\n", "\n"),
Author: parsed.GitCommitter,
Expand All @@ -44,7 +44,7 @@ func NewDiffPatchPost(ctx *context.Context) {
err = util.ErrorWrapLocale(err, "repo.editor.fail_to_apply_patch")
}
if err != nil {
editorHandleFileOperationError(ctx, parsed.TargetBranchName, err)
editorHandleFileOperationError(ctx, parsed.NewBranchName, err)
return
}
redirectForCommitChoice(ctx, parsed, parsed.form.TreePath)
Expand Down
Loading