0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2025-02-14 10:08:30 -05:00

[gitea] week 2025-06 cherry pick (gitea/main -> forgejo) (#6763)

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/6763
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
This commit is contained in:
Earl Warren 2025-02-04 08:19:06 +00:00
commit 273bc9eb04
14 changed files with 277 additions and 9 deletions

View file

@ -38,14 +38,18 @@ func GenerateRandomAvatar(ctx context.Context, u *User) error {
u.Avatar = avatars.HashEmail(seed)
// Don't share the images so that we can delete them easily
if err := storage.SaveFrom(storage.Avatars, u.CustomAvatarRelativePath(), func(w io.Writer) error {
if err := png.Encode(w, img); err != nil {
log.Error("Encode: %v", err)
_, err = storage.Avatars.Stat(u.CustomAvatarRelativePath())
if err != nil {
// If unable to Stat the avatar file (usually it means non-existing), then try to save a new one
// Don't share the images so that we can delete them easily
if err := storage.SaveFrom(storage.Avatars, u.CustomAvatarRelativePath(), func(w io.Writer) error {
if err := png.Encode(w, img); err != nil {
log.Error("Encode: %v", err)
}
return nil
}); err != nil {
return fmt.Errorf("failed to save avatar %s: %w", u.CustomAvatarRelativePath(), err)
}
return err
}); err != nil {
return fmt.Errorf("Failed to create dir %s: %w", u.CustomAvatarRelativePath(), err)
}
if _, err := db.GetEngine(ctx).ID(u.ID).Cols("avatar").Update(u); err != nil {

View file

@ -0,0 +1,68 @@
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"context"
"io"
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUserAvatarLink(t *testing.T) {
defer test.MockVariableValue(&setting.AppURL, "https://localhost/")()
defer test.MockVariableValue(&setting.AppSubURL, "")()
u := &User{ID: 1, Avatar: "avatar.png"}
link := u.AvatarLink(db.DefaultContext)
assert.Equal(t, "https://localhost/avatars/avatar.png", link)
setting.AppURL = "https://localhost/sub-path/"
setting.AppSubURL = "/sub-path"
link = u.AvatarLink(db.DefaultContext)
assert.Equal(t, "https://localhost/sub-path/avatars/avatar.png", link)
}
func TestUserAvatarGenerate(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
var err error
tmpDir := t.TempDir()
storage.Avatars, err = storage.NewLocalStorage(context.Background(), &setting.Storage{Path: tmpDir})
require.NoError(t, err)
u := unittest.AssertExistsAndLoadBean(t, &User{ID: 2})
// there was no avatar, generate a new one
assert.Empty(t, u.Avatar)
err = GenerateRandomAvatar(db.DefaultContext, u)
require.NoError(t, err)
assert.NotEmpty(t, u.Avatar)
// make sure the generated one exists
oldAvatarPath := u.CustomAvatarRelativePath()
_, err = storage.Avatars.Stat(u.CustomAvatarRelativePath())
require.NoError(t, err)
// and try to change its content
_, err = storage.Avatars.Save(u.CustomAvatarRelativePath(), strings.NewReader("abcd"), 4)
require.NoError(t, err)
// try to generate again
err = GenerateRandomAvatar(db.DefaultContext, u)
require.NoError(t, err)
assert.Equal(t, oldAvatarPath, u.CustomAvatarRelativePath())
f, err := storage.Avatars.Open(u.CustomAvatarRelativePath())
require.NoError(t, err)
defer f.Close()
content, _ := io.ReadAll(f)
assert.Equal(t, "abcd", string(content))
}

View file

@ -72,10 +72,14 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin
url := fmt.Sprintf("%s/objects/batch", c.endpoint)
// Original: In some lfs server implementations, they require the ref attribute. #32838
// `ref` is an "optional object describing the server ref that the objects belong to"
// but some (incorrect) lfs servers require it, so maybe adding an empty ref here doesn't break the correct ones.
// but some (incorrect) lfs servers like aliyun require it, so maybe adding an empty ref here doesn't break the correct ones.
// https://github.com/git-lfs/git-lfs/blob/a32a02b44bf8a511aa14f047627c49e1a7fd5021/docs/api/batch.md?plain=1#L37
request := &BatchRequest{operation, c.transferNames(), &Reference{}, objects}
//
// UPDATE: it can't use "empty ref" here because it breaks others like https://github.com/go-gitea/gitea/issues/33453
request := &BatchRequest{operation, c.transferNames(), nil, objects}
payload := new(bytes.Buffer)
err := json.NewEncoder(payload).Encode(request)
if err != nil {

View file

@ -57,3 +57,12 @@ type EditOrgOption struct {
Visibility string `json:"visibility" binding:"In(,public,limited,private)"`
RepoAdminChangeTeamAccess *bool `json:"repo_admin_change_team_access"`
}
// RenameOrgOption options when renaming an organization
type RenameOrgOption struct {
// New username for this org. This name cannot be in use yet by any other user.
//
// required: true
// unique: true
NewName string `json:"new_name" binding:"Required"`
}

1
release-notes/6763.md Normal file
View file

@ -0,0 +1 @@
feat: [commit](https://codeberg.org/forgejo/forgejo/commit/689fb82a7043fdb2fee02195701b0bc728e99709) API endpoint to rename an organization

View file

@ -1505,6 +1505,7 @@ func Routes() *web.Route {
m.Combo("").Get(org.Get).
Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit).
Delete(reqToken(), reqOrgOwnership(), org.Delete)
m.Post("/rename", reqToken(), reqOrgOwnership(), bind(api.RenameOrgOption{}), org.Rename)
m.Combo("/repos").Get(user.ListOrgRepos).
Post(reqToken(), bind(api.CreateRepoOption{}), context.EnforceQuotaAPI(quota_model.LimitSubjectSizeReposAll, context.QuotaTargetOrg), repo.CreateOrgRepo)
m.Group("/members", func() {

View file

@ -320,6 +320,44 @@ func Get(ctx *context.APIContext) {
ctx.JSON(http.StatusOK, org)
}
func Rename(ctx *context.APIContext) {
// swagger:operation POST /orgs/{org}/rename organization renameOrg
// ---
// summary: Rename an organization
// produces:
// - application/json
// parameters:
// - name: org
// in: path
// description: existing org name
// type: string
// required: true
// - name: body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/RenameOrgOption"
// responses:
// "204":
// "$ref": "#/responses/empty"
// "403":
// "$ref": "#/responses/forbidden"
// "422":
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.RenameOrgOption)
orgUser := ctx.Org.Organization.AsUser()
if err := user_service.RenameUser(ctx, orgUser, form.NewName); err != nil {
if user_model.IsErrUserAlreadyExist(err) || db.IsErrNameReserved(err) || db.IsErrNamePatternNotAllowed(err) || db.IsErrNameCharsNotAllowed(err) {
ctx.Error(http.StatusUnprocessableEntity, "RenameOrg", err)
} else {
ctx.ServerError("RenameOrg", err)
}
return
}
ctx.Status(http.StatusNoContent)
}
// Edit change an organization's information
func Edit(ctx *context.APIContext) {
// swagger:operation PATCH /orgs/{org} organization orgEdit

View file

@ -216,6 +216,9 @@ type swaggerParameterBodies struct {
// in:body
CreateVariableOption api.CreateVariableOption
// in:body
RenameOrgOption api.RenameOrgOption
// in:body
UpdateVariableOption api.UpdateVariableOption

View file

@ -43,6 +43,7 @@ func ShowBranchFeed(ctx *context.Context, repo *repo.Repository, formatType stri
},
Description: commit.Message(),
Content: commit.Message(),
Created: commit.Committer.When,
})
}

View file

@ -55,6 +55,7 @@ func ShowFileFeed(ctx *context.Context, repo *repo.Repository, formatType string
},
Description: commit.Message(),
Content: commit.Message(),
Created: commit.Committer.When,
})
}

View file

@ -3772,6 +3772,46 @@
}
}
},
"/orgs/{org}/rename": {
"post": {
"produces": [
"application/json"
],
"tags": [
"organization"
],
"summary": "Rename an organization",
"operationId": "renameOrg",
"parameters": [
{
"type": "string",
"description": "existing org name",
"name": "org",
"in": "path",
"required": true
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/RenameOrgOption"
}
}
],
"responses": {
"204": {
"$ref": "#/responses/empty"
},
"403": {
"$ref": "#/responses/forbidden"
},
"422": {
"$ref": "#/responses/validationError"
}
}
}
},
"/orgs/{org}/repos": {
"get": {
"produces": [
@ -26634,6 +26674,22 @@
},
"x-go-package": "code.gitea.io/gitea/modules/structs"
},
"RenameOrgOption": {
"description": "RenameOrgOption options when renaming an organization",
"type": "object",
"required": [
"new_name"
],
"properties": {
"new_name": {
"description": "New username for this org. This name cannot be in use yet by any other user.",
"type": "string",
"uniqueItems": true,
"x-go-name": "NewName"
}
},
"x-go-package": "code.gitea.io/gitea/modules/structs"
},
"RenameUserOption": {
"description": "RenameUserOption options when renaming a user",
"type": "object",

View file

@ -99,6 +99,29 @@ func TestAPIOrgCreate(t *testing.T) {
assert.EqualValues(t, "user1", users[0].UserName)
}
func TestAPIOrgRename(t *testing.T) {
defer tests.PrepareTestEnv(t)()
token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteOrganization)
org := api.CreateOrgOption{
UserName: "user1_org",
FullName: "User1's organization",
Description: "This organization created by user1",
Website: "https://try.gitea.io",
Location: "Shanghai",
Visibility: "limited",
}
req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &org).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/user1_org/rename", &api.RenameOrgOption{
NewName: "renamed_org",
}).AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
unittest.AssertExistsAndLoadBean(t, &org_model.Organization{Name: "renamed_org"})
}
func TestAPIOrgEdit(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")

View file

@ -0,0 +1,36 @@
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
import (
"encoding/xml"
"net/http"
"testing"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFeedRepo(t *testing.T) {
t.Run("RSS", func(t *testing.T) {
defer tests.PrepareTestEnv(t)()
req := NewRequest(t, "GET", "/user2/repo1.rss")
resp := MakeRequest(t, req, http.StatusOK)
data := resp.Body.String()
assert.Contains(t, data, `<rss version="2.0"`)
var rss RSS
err := xml.Unmarshal(resp.Body.Bytes(), &rss)
require.NoError(t, err)
assert.Contains(t, rss.Channel.Link, "/user2/repo1")
assert.NotEmpty(t, rss.Channel.PubDate)
assert.Len(t, rss.Channel.Items, 1)
assert.EqualValues(t, "issue5", rss.Channel.Items[0].Description)
assert.NotEmpty(t, rss.Channel.Items[0].PubDate)
})
}

View file

@ -4,6 +4,7 @@
package integration
import (
"encoding/xml"
"net/http"
"testing"
@ -15,6 +16,22 @@ import (
"github.com/stretchr/testify/require"
)
// RSS is a struct to unmarshal RSS feeds test only
type RSS struct {
Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
Items []struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
} `xml:"item"`
} `xml:"channel"`
}
func TestFeed(t *testing.T) {
defer tests.AddFixtures("tests/integration/fixtures/TestFeed/")()
defer tests.PrepareTestEnv(t)()
@ -38,6 +55,12 @@ func TestFeed(t *testing.T) {
data := resp.Body.String()
assert.Contains(t, data, `<rss version="2.0"`)
var rss RSS
err := xml.Unmarshal(resp.Body.Bytes(), &rss)
require.NoError(t, err)
assert.Contains(t, rss.Channel.Link, "/user2")
assert.NotEmpty(t, rss.Channel.PubDate)
})
})