mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2024-11-14 06:39:40 +01:00
6433ba0ec3
Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
238 lines
7.9 KiB
Go
238 lines
7.9 KiB
Go
// Copyright 2020 The Gitea Authors. All rights reserved.
|
|
// Use of this source code is governed by a MIT-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package repo
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"code.gitea.io/gitea/models"
|
|
"code.gitea.io/gitea/modules/context"
|
|
"code.gitea.io/gitea/modules/convert"
|
|
auth "code.gitea.io/gitea/modules/forms"
|
|
"code.gitea.io/gitea/modules/graceful"
|
|
"code.gitea.io/gitea/modules/log"
|
|
"code.gitea.io/gitea/modules/migrations"
|
|
"code.gitea.io/gitea/modules/migrations/base"
|
|
"code.gitea.io/gitea/modules/notification"
|
|
repo_module "code.gitea.io/gitea/modules/repository"
|
|
"code.gitea.io/gitea/modules/setting"
|
|
api "code.gitea.io/gitea/modules/structs"
|
|
"code.gitea.io/gitea/modules/util"
|
|
"code.gitea.io/gitea/modules/web"
|
|
)
|
|
|
|
// Migrate migrate remote git repository to gitea
|
|
func Migrate(ctx *context.APIContext) {
|
|
// swagger:operation POST /repos/migrate repository repoMigrate
|
|
// ---
|
|
// summary: Migrate a remote git repository
|
|
// consumes:
|
|
// - application/json
|
|
// produces:
|
|
// - application/json
|
|
// parameters:
|
|
// - name: body
|
|
// in: body
|
|
// schema:
|
|
// "$ref": "#/definitions/MigrateRepoOptions"
|
|
// responses:
|
|
// "201":
|
|
// "$ref": "#/responses/Repository"
|
|
// "403":
|
|
// "$ref": "#/responses/forbidden"
|
|
// "422":
|
|
// "$ref": "#/responses/validationError"
|
|
|
|
form := web.GetForm(ctx).(*api.MigrateRepoOptions)
|
|
|
|
//get repoOwner
|
|
var (
|
|
repoOwner *models.User
|
|
err error
|
|
)
|
|
if len(form.RepoOwner) != 0 {
|
|
repoOwner, err = models.GetUserByName(form.RepoOwner)
|
|
} else if form.RepoOwnerID != 0 {
|
|
repoOwner, err = models.GetUserByID(form.RepoOwnerID)
|
|
} else {
|
|
repoOwner = ctx.User
|
|
}
|
|
if err != nil {
|
|
if models.IsErrUserNotExist(err) {
|
|
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
|
} else {
|
|
ctx.Error(http.StatusInternalServerError, "GetUser", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if ctx.HasError() {
|
|
ctx.Error(http.StatusUnprocessableEntity, "", ctx.GetErrMsg())
|
|
return
|
|
}
|
|
|
|
if !ctx.User.IsAdmin {
|
|
if !repoOwner.IsOrganization() && ctx.User.ID != repoOwner.ID {
|
|
ctx.Error(http.StatusForbidden, "", "Given user is not an organization.")
|
|
return
|
|
}
|
|
|
|
if repoOwner.IsOrganization() {
|
|
// Check ownership of organization.
|
|
isOwner, err := repoOwner.IsOwnedBy(ctx.User.ID)
|
|
if err != nil {
|
|
ctx.Error(http.StatusInternalServerError, "IsOwnedBy", err)
|
|
return
|
|
} else if !isOwner {
|
|
ctx.Error(http.StatusForbidden, "", "Given user is not owner of organization.")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
remoteAddr, err := auth.ParseRemoteAddr(form.CloneAddr, form.AuthUsername, form.AuthPassword, ctx.User)
|
|
if err != nil {
|
|
if models.IsErrInvalidCloneAddr(err) {
|
|
addrErr := err.(models.ErrInvalidCloneAddr)
|
|
switch {
|
|
case addrErr.IsURLError:
|
|
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
|
case addrErr.IsPermissionDenied:
|
|
ctx.Error(http.StatusUnprocessableEntity, "", "You are not allowed to import local repositories.")
|
|
case addrErr.IsInvalidPath:
|
|
ctx.Error(http.StatusUnprocessableEntity, "", "Invalid local path, it does not exist or not a directory.")
|
|
default:
|
|
ctx.Error(http.StatusInternalServerError, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
|
|
}
|
|
} else {
|
|
ctx.Error(http.StatusInternalServerError, "ParseRemoteAddr", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
gitServiceType := convert.ToGitServiceType(form.Service)
|
|
|
|
if form.Mirror && setting.Repository.DisableMirrors {
|
|
ctx.Error(http.StatusForbidden, "MirrorsGlobalDisabled", fmt.Errorf("the site administrator has disabled mirrors"))
|
|
return
|
|
}
|
|
|
|
if setting.Repository.DisableMigrations {
|
|
ctx.Error(http.StatusForbidden, "MigrationsGlobalDisabled", fmt.Errorf("the site administrator has disabled migrations"))
|
|
return
|
|
}
|
|
|
|
var opts = migrations.MigrateOptions{
|
|
CloneAddr: remoteAddr,
|
|
RepoName: form.RepoName,
|
|
Description: form.Description,
|
|
Private: form.Private || setting.Repository.ForcePrivate,
|
|
Mirror: form.Mirror,
|
|
AuthUsername: form.AuthUsername,
|
|
AuthPassword: form.AuthPassword,
|
|
AuthToken: form.AuthToken,
|
|
Wiki: form.Wiki,
|
|
Issues: form.Issues,
|
|
Milestones: form.Milestones,
|
|
Labels: form.Labels,
|
|
Comments: true,
|
|
PullRequests: form.PullRequests,
|
|
Releases: form.Releases,
|
|
GitServiceType: gitServiceType,
|
|
MirrorInterval: form.MirrorInterval,
|
|
}
|
|
if opts.Mirror {
|
|
opts.Issues = false
|
|
opts.Milestones = false
|
|
opts.Labels = false
|
|
opts.Comments = false
|
|
opts.PullRequests = false
|
|
opts.Releases = false
|
|
}
|
|
|
|
repo, err := repo_module.CreateRepository(ctx.User, repoOwner, models.CreateRepoOptions{
|
|
Name: opts.RepoName,
|
|
Description: opts.Description,
|
|
OriginalURL: form.CloneAddr,
|
|
GitServiceType: gitServiceType,
|
|
IsPrivate: opts.Private,
|
|
IsMirror: opts.Mirror,
|
|
Status: models.RepositoryBeingMigrated,
|
|
})
|
|
if err != nil {
|
|
handleMigrateError(ctx, repoOwner, remoteAddr, err)
|
|
return
|
|
}
|
|
|
|
opts.MigrateToRepoID = repo.ID
|
|
|
|
defer func() {
|
|
if e := recover(); e != nil {
|
|
var buf bytes.Buffer
|
|
fmt.Fprintf(&buf, "Handler crashed with error: %v", log.Stack(2))
|
|
|
|
err = errors.New(buf.String())
|
|
}
|
|
|
|
if err == nil {
|
|
notification.NotifyMigrateRepository(ctx.User, repoOwner, repo)
|
|
return
|
|
}
|
|
|
|
if repo != nil {
|
|
if errDelete := models.DeleteRepository(ctx.User, repoOwner.ID, repo.ID); errDelete != nil {
|
|
log.Error("DeleteRepository: %v", errDelete)
|
|
}
|
|
}
|
|
}()
|
|
|
|
if _, err = migrations.MigrateRepository(graceful.GetManager().HammerContext(), ctx.User, repoOwner.Name, opts); err != nil {
|
|
handleMigrateError(ctx, repoOwner, remoteAddr, err)
|
|
return
|
|
}
|
|
|
|
log.Trace("Repository migrated: %s/%s", repoOwner.Name, form.RepoName)
|
|
ctx.JSON(http.StatusCreated, convert.ToRepo(repo, models.AccessModeAdmin))
|
|
}
|
|
|
|
func handleMigrateError(ctx *context.APIContext, repoOwner *models.User, remoteAddr string, err error) {
|
|
switch {
|
|
case models.IsErrRepoAlreadyExist(err):
|
|
ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.")
|
|
case models.IsErrRepoFilesAlreadyExist(err):
|
|
ctx.Error(http.StatusConflict, "", "Files already exist for this repository. Adopt them or delete them.")
|
|
case migrations.IsRateLimitError(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", "Remote visit addressed rate limitation.")
|
|
case migrations.IsTwoFactorAuthError(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", "Remote visit required two factors authentication.")
|
|
case models.IsErrReachLimitOfRepo(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("You have already reached your limit of %d repositories.", repoOwner.MaxCreationLimit()))
|
|
case models.IsErrNameReserved(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("The username '%s' is reserved.", err.(models.ErrNameReserved).Name))
|
|
case models.IsErrNameCharsNotAllowed(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("The username '%s' contains invalid characters.", err.(models.ErrNameCharsNotAllowed).Name))
|
|
case models.IsErrNamePatternNotAllowed(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("The pattern '%s' is not allowed in a username.", err.(models.ErrNamePatternNotAllowed).Pattern))
|
|
case models.IsErrMigrationNotAllowed(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
|
case base.IsErrNotSupported(err):
|
|
ctx.Error(http.StatusUnprocessableEntity, "", err)
|
|
default:
|
|
err = util.URLSanitizedError(err, remoteAddr)
|
|
if strings.Contains(err.Error(), "Authentication failed") ||
|
|
strings.Contains(err.Error(), "Bad credentials") ||
|
|
strings.Contains(err.Error(), "could not read Username") {
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Authentication failed: %v.", err))
|
|
} else if strings.Contains(err.Error(), "fatal:") {
|
|
ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Migration failed: %v.", err))
|
|
} else {
|
|
ctx.Error(http.StatusInternalServerError, "MigrateRepository", err)
|
|
}
|
|
}
|
|
}
|