chore: remove deadcode (#6743)

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/6743
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
This commit is contained in:
Earl Warren 2025-02-02 12:05:25 +00:00
commit 7579f25807
35 changed files with 30 additions and 797 deletions

View file

@ -10,20 +10,10 @@ code.gitea.io/gitea/cmd/forgejo
ContextSetStdin ContextSetStdin
code.gitea.io/gitea/models code.gitea.io/gitea/models
IsErrUpdateTaskNotExist
ErrUpdateTaskNotExist.Error
ErrUpdateTaskNotExist.Unwrap
IsErrSHANotFound IsErrSHANotFound
IsErrMergeDivergingFastForwardOnly IsErrMergeDivergingFastForwardOnly
code.gitea.io/gitea/models/actions
ScheduleList.GetUserIDs
ScheduleList.GetRepoIDs
ScheduleList.LoadTriggerUser
ScheduleList.LoadRepos
code.gitea.io/gitea/models/auth code.gitea.io/gitea/models/auth
GetSourceByName
WebAuthnCredentials WebAuthnCredentials
code.gitea.io/gitea/models/db code.gitea.io/gitea/models/db
@ -52,25 +42,12 @@ code.gitea.io/gitea/models/issues
IsErrIssueWasClosed IsErrIssueWasClosed
code.gitea.io/gitea/models/organization code.gitea.io/gitea/models/organization
GetTeamNamesByID
UpdateTeamUnits
SearchMembersOptions.ToConds SearchMembersOptions.ToConds
UsersInTeamsCount
code.gitea.io/gitea/models/perm/access code.gitea.io/gitea/models/perm/access
GetRepoWriters GetRepoWriters
code.gitea.io/gitea/models/project
UpdateColumnSorting
ChangeProjectStatus
code.gitea.io/gitea/models/repo code.gitea.io/gitea/models/repo
DeleteAttachmentsByIssue
FindReposMapByIDs
IsErrTopicNotExist
ErrTopicNotExist.Error
ErrTopicNotExist.Unwrap
GetTopicByName
WatchRepoMode WatchRepoMode
code.gitea.io/gitea/models/user code.gitea.io/gitea/models/user
@ -103,9 +80,6 @@ code.gitea.io/gitea/modules/cache
WithNoCacheContext WithNoCacheContext
RemoveContextData RemoveContextData
code.gitea.io/gitea/modules/charset
BreakWriter.Write
code.gitea.io/gitea/modules/emoji code.gitea.io/gitea/modules/emoji
ReplaceCodes ReplaceCodes
@ -127,10 +101,7 @@ code.gitea.io/gitea/modules/git
CommitChangesWithArgs CommitChangesWithArgs
SetUpdateHook SetUpdateHook
openRepositoryWithDefaultContext openRepositoryWithDefaultContext
IsTagExist
ToEntryMode ToEntryMode
LimitedReaderCloser.Read
LimitedReaderCloser.Close
code.gitea.io/gitea/modules/gitgraph code.gitea.io/gitea/modules/gitgraph
Parser.Reset Parser.Reset
@ -171,16 +142,8 @@ code.gitea.io/gitea/modules/markup/console
RenderString RenderString
code.gitea.io/gitea/modules/markup/markdown code.gitea.io/gitea/modules/markup/markdown
IsDetails
IsSummary
IsTaskCheckBoxListItem
IsIcon
RenderRawString RenderRawString
code.gitea.io/gitea/modules/markup/markdown/math
WithInlineDollarParser
WithBlockDollarParser
code.gitea.io/gitea/modules/markup/mdstripper code.gitea.io/gitea/modules/markup/mdstripper
stripRenderer.AddOptions stripRenderer.AddOptions
StripMarkdown StripMarkdown
@ -188,9 +151,6 @@ code.gitea.io/gitea/modules/markup/mdstripper
code.gitea.io/gitea/modules/markup/orgmode code.gitea.io/gitea/modules/markup/orgmode
RenderString RenderString
code.gitea.io/gitea/modules/private
ActionsRunnerRegister
code.gitea.io/gitea/modules/process code.gitea.io/gitea/modules/process
Manager.ExecTimeout Manager.ExecTimeout
@ -213,14 +173,6 @@ code.gitea.io/gitea/modules/setting
GitConfigType.GetOption GitConfigType.GetOption
InitLoggersForTest InitLoggersForTest
code.gitea.io/gitea/modules/storage
ErrInvalidConfiguration.Error
IsErrInvalidConfiguration
code.gitea.io/gitea/modules/structs
ParseCreateHook
ParsePushHook
code.gitea.io/gitea/modules/sync code.gitea.io/gitea/modules/sync
StatusTable.Start StatusTable.Start
StatusTable.IsRunning StatusTable.IsRunning
@ -252,9 +204,6 @@ code.gitea.io/gitea/modules/web
RouteMock RouteMock
RouteMockReset RouteMockReset
code.gitea.io/gitea/modules/web/middleware
DeleteLocaleCookie
code.gitea.io/gitea/modules/zstd code.gitea.io/gitea/modules/zstd
NewWriter NewWriter
Writer.Write Writer.Write
@ -269,23 +218,11 @@ code.gitea.io/gitea/routers/web/org
code.gitea.io/gitea/services/context code.gitea.io/gitea/services/context
GetPrivateContext GetPrivateContext
code.gitea.io/gitea/services/convert
ToSecret
code.gitea.io/gitea/services/forms
DeadlineForm.Validate
code.gitea.io/gitea/services/pull
IsCommitStatusContextSuccess
code.gitea.io/gitea/services/repository code.gitea.io/gitea/services/repository
IsErrForkAlreadyExist IsErrForkAlreadyExist
code.gitea.io/gitea/services/repository/files code.gitea.io/gitea/services/repository/files
ContentType.String ContentType.String
GetFileResponseFromCommit
TemporaryUploadRepository.GetLastCommit
TemporaryUploadRepository.GetLastCommitByRef
code.gitea.io/gitea/services/webhook code.gitea.io/gitea/services/webhook
NewNotifier NewNotifier

View file

@ -14,6 +14,8 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
webhook_module "code.gitea.io/gitea/modules/webhook" webhook_module "code.gitea.io/gitea/modules/webhook"
"xorm.io/builder"
) )
// ActionSchedule represents a schedule of a workflow file // ActionSchedule represents a schedule of a workflow file
@ -140,3 +142,25 @@ func CleanRepoScheduleTasks(ctx context.Context, repo *repo_model.Repository, ca
} }
return nil return nil
} }
type FindScheduleOptions struct {
db.ListOptions
RepoID int64
OwnerID int64
}
func (opts FindScheduleOptions) ToConds() builder.Cond {
cond := builder.NewCond()
if opts.RepoID > 0 {
cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
}
if opts.OwnerID > 0 {
cond = cond.And(builder.Eq{"owner_id": opts.OwnerID})
}
return cond
}
func (opts FindScheduleOptions) ToOrders() string {
return "`id` DESC"
}

View file

@ -1,83 +0,0 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package actions
import (
"context"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/container"
"xorm.io/builder"
)
type ScheduleList []*ActionSchedule
// GetUserIDs returns a slice of user's id
func (schedules ScheduleList) GetUserIDs() []int64 {
return container.FilterSlice(schedules, func(schedule *ActionSchedule) (int64, bool) {
return schedule.TriggerUserID, true
})
}
func (schedules ScheduleList) GetRepoIDs() []int64 {
return container.FilterSlice(schedules, func(schedule *ActionSchedule) (int64, bool) {
return schedule.RepoID, true
})
}
func (schedules ScheduleList) LoadTriggerUser(ctx context.Context) error {
userIDs := schedules.GetUserIDs()
users := make(map[int64]*user_model.User, len(userIDs))
if err := db.GetEngine(ctx).In("id", userIDs).Find(&users); err != nil {
return err
}
for _, schedule := range schedules {
if schedule.TriggerUserID == user_model.ActionsUserID {
schedule.TriggerUser = user_model.NewActionsUser()
} else {
schedule.TriggerUser = users[schedule.TriggerUserID]
if schedule.TriggerUser == nil {
schedule.TriggerUser = user_model.NewGhostUser()
}
}
}
return nil
}
func (schedules ScheduleList) LoadRepos(ctx context.Context) error {
repoIDs := schedules.GetRepoIDs()
repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
if err != nil {
return err
}
for _, schedule := range schedules {
schedule.Repo = repos[schedule.RepoID]
}
return nil
}
type FindScheduleOptions struct {
db.ListOptions
RepoID int64
OwnerID int64
}
func (opts FindScheduleOptions) ToConds() builder.Cond {
cond := builder.NewCond()
if opts.RepoID > 0 {
cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
}
if opts.OwnerID > 0 {
cond = cond.And(builder.Eq{"owner_id": opts.OwnerID})
}
return cond
}
func (opts FindScheduleOptions) ToOrders() string {
return "`id` DESC"
}

View file

@ -299,17 +299,6 @@ func GetSourceByID(ctx context.Context, id int64) (*Source, error) {
return source, nil return source, nil
} }
func GetSourceByName(ctx context.Context, name string) (*Source, error) {
source := &Source{}
has, err := db.GetEngine(ctx).Where("name = ?", name).Get(source)
if err != nil {
return nil, err
} else if !has {
return nil, ErrSourceNotExist{}
}
return source, nil
}
// UpdateSource updates a Source record in DB. // UpdateSource updates a Source record in DB.
func UpdateSource(ctx context.Context, source *Source) error { func UpdateSource(ctx context.Context, source *Source) error {
var originalSource *Source var originalSource *Source

View file

@ -151,25 +151,6 @@ func (err *ErrInvalidCloneAddr) Unwrap() error {
return util.ErrInvalidArgument return util.ErrInvalidArgument
} }
// ErrUpdateTaskNotExist represents a "UpdateTaskNotExist" kind of error.
type ErrUpdateTaskNotExist struct {
UUID string
}
// IsErrUpdateTaskNotExist checks if an error is a ErrUpdateTaskNotExist.
func IsErrUpdateTaskNotExist(err error) bool {
_, ok := err.(ErrUpdateTaskNotExist)
return ok
}
func (err ErrUpdateTaskNotExist) Error() string {
return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID)
}
func (err ErrUpdateTaskNotExist) Unwrap() error {
return util.ErrNotExist
}
// ErrInvalidTagName represents a "InvalidTagName" kind of error. // ErrInvalidTagName represents a "InvalidTagName" kind of error.
type ErrInvalidTagName struct { type ErrInvalidTagName struct {
TagName string TagName string

View file

@ -247,22 +247,6 @@ func GetTeamByID(ctx context.Context, teamID int64) (*Team, error) {
return t, nil return t, nil
} }
// GetTeamNamesByID returns team's lower name from a list of team ids.
func GetTeamNamesByID(ctx context.Context, teamIDs []int64) ([]string, error) {
if len(teamIDs) == 0 {
return []string{}, nil
}
var teamNames []string
err := db.GetEngine(ctx).Table("team").
Select("lower_name").
In("id", teamIDs).
Asc("name").
Find(&teamNames)
return teamNames, err
}
// IncrTeamRepoNum increases the number of repos for the given team by 1 // IncrTeamRepoNum increases the number of repos for the given team by 1
func IncrTeamRepoNum(ctx context.Context, teamID int64) error { func IncrTeamRepoNum(ctx context.Context, teamID int64) error {
_, err := db.GetEngine(ctx).Incr("num_repos").ID(teamID).Update(new(Team)) _, err := db.GetEngine(ctx).Incr("num_repos").ID(teamID).Update(new(Team))

View file

@ -188,20 +188,6 @@ func TestHasTeamRepo(t *testing.T) {
test(2, 5, false) test(2, 5, false)
} }
func TestUsersInTeamsCount(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamIDs, userIDs []int64, expected int64) {
count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs)
require.NoError(t, err)
assert.Equal(t, expected, count)
}
test([]int64{2}, []int64{1, 2, 3, 4}, 1) // only userid 2
test([]int64{1, 2, 3, 4, 5}, []int64{2, 5}, 2) // userid 2,4
test([]int64{1, 2, 3, 4, 5}, []int64{2, 3, 5}, 3) // userid 2,4,5
}
func TestInconsistentOwnerTeam(t *testing.T) { func TestInconsistentOwnerTeam(t *testing.T) {
defer unittest.OverrideFixtures( defer unittest.OverrideFixtures(
unittest.FixturesOptions{ unittest.FixturesOptions{

View file

@ -28,24 +28,3 @@ func (t *TeamUnit) Unit() unit.Unit {
func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err error) { func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err error) {
return units, db.GetEngine(ctx).Where("team_id = ?", teamID).Find(&units) return units, db.GetEngine(ctx).Where("team_id = ?", teamID).Find(&units)
} }
// UpdateTeamUnits updates a teams's units
func UpdateTeamUnits(ctx context.Context, team *Team, units []TeamUnit) (err error) {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
if _, err = db.GetEngine(ctx).Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil {
return err
}
if len(units) > 0 {
if err = db.Insert(ctx, units); err != nil {
return err
}
}
return committer.Commit()
}

View file

@ -76,14 +76,3 @@ func GetTeamMembers(ctx context.Context, opts *SearchMembersOptions) ([]*user_mo
func IsUserInTeams(ctx context.Context, userID int64, teamIDs []int64) (bool, error) { func IsUserInTeams(ctx context.Context, userID int64, teamIDs []int64) (bool, error) {
return db.GetEngine(ctx).Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser)) return db.GetEngine(ctx).Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser))
} }
// UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
func UsersInTeamsCount(ctx context.Context, userIDs, teamIDs []int64) (int64, error) {
var ids []int64
if err := db.GetEngine(ctx).In("uid", userIDs).In("team_id", teamIDs).
Table("team_user").
Cols("uid").GroupBy("uid").Find(&ids); err != nil {
return 0, err
}
return int64(len(ids)), nil
}

View file

@ -305,20 +305,6 @@ func SetDefaultColumn(ctx context.Context, projectID, columnID int64) error {
}) })
} }
// UpdateColumnSorting update project column sorting
func UpdateColumnSorting(ctx context.Context, cl ColumnList) error {
return db.WithTx(ctx, func(ctx context.Context) error {
for i := range cl {
if _, err := db.GetEngine(ctx).ID(cl[i].ID).Cols(
"sorting",
).Update(cl[i]); err != nil {
return err
}
}
return nil
})
}
func GetColumnsByIDs(ctx context.Context, projectID int64, columnsIDs []int64) (ColumnList, error) { func GetColumnsByIDs(ctx context.Context, projectID int64, columnsIDs []int64) (ColumnList, error) {
columns := make([]*Column, 0, 5) columns := make([]*Column, 0, 5)
if err := db.GetEngine(ctx). if err := db.GetEngine(ctx).

View file

@ -368,21 +368,6 @@ func ChangeProjectStatusByRepoIDAndID(ctx context.Context, repoID, projectID int
return committer.Commit() return committer.Commit()
} }
// ChangeProjectStatus toggle a project between opened and closed
func ChangeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
if err := changeProjectStatus(ctx, p, isClosed); err != nil {
return err
}
return committer.Commit()
}
func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
p.IsClosed = isClosed p.IsClosed = isClosed
p.ClosedDateUnix = timeutil.TimeStampNow() p.ClosedDateUnix = timeutil.TimeStampNow()

View file

@ -75,7 +75,7 @@ func TestProject(t *testing.T) {
assert.Equal(t, project.Title, projectFromDB.Title) assert.Equal(t, project.Title, projectFromDB.Title)
require.NoError(t, ChangeProjectStatus(db.DefaultContext, project, true)) require.NoError(t, ChangeProjectStatusByRepoIDAndID(db.DefaultContext, project.RepoID, project.ID, true))
// Retrieve from DB afresh to check if it is truly closed // Retrieve from DB afresh to check if it is truly closed
projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID) projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID)

View file

@ -219,16 +219,6 @@ func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bo
return int(cnt), nil return int(cnt), nil
} }
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(ctx, issueID)
if err != nil {
return 0, err
}
return DeleteAttachments(ctx, attachments, remove)
}
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) { func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(ctx, commentID) attachments, err := GetAttachmentsByCommentID(ctx, commentID)

View file

@ -46,11 +46,7 @@ func TestGetByCommentOrIssueID(t *testing.T) {
func TestDeleteAttachments(t *testing.T) { func TestDeleteAttachments(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) count, err := repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false)
require.NoError(t, err)
assert.Equal(t, 2, count)
count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, 2, count) assert.Equal(t, 2, count)

View file

@ -21,11 +21,6 @@ import (
"xorm.io/builder" "xorm.io/builder"
) )
// FindReposMapByIDs find repos as map
func FindReposMapByIDs(ctx context.Context, repoIDs []int64, res map[int64]*Repository) error {
return db.GetEngine(ctx).In("id", repoIDs).Find(&res)
}
// RepositoryListDefaultPageSize is the default number of repositories // RepositoryListDefaultPageSize is the default number of repositories
// to load in memory when running administrative tasks on all (or almost // to load in memory when running administrative tasks on all (or almost
// all) of them. // all) of them.

View file

@ -5,14 +5,12 @@ package repo
import ( import (
"context" "context"
"fmt"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/container"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
@ -39,26 +37,6 @@ type RepoTopic struct { //revive:disable-line:exported
TopicID int64 `xorm:"pk"` TopicID int64 `xorm:"pk"`
} }
// ErrTopicNotExist represents an error that a topic is not exist
type ErrTopicNotExist struct {
Name string
}
// IsErrTopicNotExist checks if an error is an ErrTopicNotExist.
func IsErrTopicNotExist(err error) bool {
_, ok := err.(ErrTopicNotExist)
return ok
}
// Error implements error interface
func (err ErrTopicNotExist) Error() string {
return fmt.Sprintf("topic is not exist [name: %s]", err.Name)
}
func (err ErrTopicNotExist) Unwrap() error {
return util.ErrNotExist
}
// ValidateTopic checks a topic by length and match pattern rules // ValidateTopic checks a topic by length and match pattern rules
func ValidateTopic(topic string) bool { func ValidateTopic(topic string) bool {
return len(topic) <= 35 && topicPattern.MatchString(topic) return len(topic) <= 35 && topicPattern.MatchString(topic)
@ -91,17 +69,6 @@ func SanitizeAndValidateTopics(topics []string) (validTopics, invalidTopics []st
return validTopics, invalidTopics return validTopics, invalidTopics
} }
// GetTopicByName retrieves topic by name
func GetTopicByName(ctx context.Context, name string) (*Topic, error) {
var topic Topic
if has, err := db.GetEngine(ctx).Where("name = ?", name).Get(&topic); err != nil {
return nil, err
} else if !has {
return nil, ErrTopicNotExist{name}
}
return &topic, nil
}
// addTopicByNameToRepo adds a topic name to a repo and increments the topic count. // addTopicByNameToRepo adds a topic name to a repo and increments the topic count.
// Returns topic after the addition // Returns topic after the addition
func addTopicByNameToRepo(ctx context.Context, repoID int64, topicName string) (*Topic, error) { func addTopicByNameToRepo(ctx context.Context, repoID int64, topicName string) (*Topic, error) {

View file

@ -52,8 +52,7 @@ func TestAddTopic(t *testing.T) {
require.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea")) require.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea"))
repo2NrOfTopics = 2 repo2NrOfTopics = 2
totalNrOfTopics++ totalNrOfTopics++
topic, err := repo_model.GetTopicByName(db.DefaultContext, "gitea") topic := unittest.AssertExistsAndLoadBean(t, &repo_model.Topic{Name: "gitea"})
require.NoError(t, err)
assert.EqualValues(t, 1, topic.RepoCount) assert.EqualValues(t, 1, topic.RepoCount)
topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{})

View file

@ -1,43 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package charset
import (
"bytes"
"io"
)
// BreakWriter wraps an io.Writer to always write '\n' as '<br>'
type BreakWriter struct {
io.Writer
}
// Write writes the provided byte slice transparently replacing '\n' with '<br>'
func (b *BreakWriter) Write(bs []byte) (n int, err error) {
pos := 0
for pos < len(bs) {
idx := bytes.IndexByte(bs[pos:], '\n')
if idx < 0 {
wn, err := b.Writer.Write(bs[pos:])
return n + wn, err
}
if idx > 0 {
wn, err := b.Writer.Write(bs[pos : pos+idx])
n += wn
if err != nil {
return n, err
}
}
if _, err = b.Writer.Write([]byte("<br>")); err != nil {
return n, err
}
pos += idx + 1
n++
}
return n, err
}

View file

@ -1,68 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package charset
import (
"strings"
"testing"
)
func TestBreakWriter_Write(t *testing.T) {
tests := []struct {
name string
kase string
expect string
wantErr bool
}{
{
name: "noline",
kase: "abcdefghijklmnopqrstuvwxyz",
expect: "abcdefghijklmnopqrstuvwxyz",
},
{
name: "endline",
kase: "abcdefghijklmnopqrstuvwxyz\n",
expect: "abcdefghijklmnopqrstuvwxyz<br>",
},
{
name: "startline",
kase: "\nabcdefghijklmnopqrstuvwxyz",
expect: "<br>abcdefghijklmnopqrstuvwxyz",
},
{
name: "onlyline",
kase: "\n\n\n",
expect: "<br><br><br>",
},
{
name: "empty",
kase: "",
expect: "",
},
{
name: "midline",
kase: "\nabc\ndefghijkl\nmnopqrstuvwxy\nz",
expect: "<br>abc<br>defghijkl<br>mnopqrstuvwxy<br>z",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
buf := &strings.Builder{}
b := &BreakWriter{
Writer: buf,
}
n, err := b.Write([]byte(tt.kase))
if (err != nil) != tt.wantErr {
t.Errorf("BreakWriter.Write() error = %v, wantErr %v", err, tt.wantErr)
return
}
if n != len(tt.kase) {
t.Errorf("BreakWriter.Write() = %v, want %v", n, len(tt.kase))
}
if buf.String() != tt.expect {
t.Errorf("BreakWriter.Write() wrote %q, want %v", buf.String(), tt.expect)
}
})
}
}

View file

@ -5,7 +5,6 @@
package git package git
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -20,11 +19,6 @@ import (
// TagPrefix tags prefix path on the repository // TagPrefix tags prefix path on the repository
const TagPrefix = "refs/tags/" const TagPrefix = "refs/tags/"
// IsTagExist returns true if given tag exists in the repository.
func IsTagExist(ctx context.Context, repoPath, name string) bool {
return IsReferenceExist(ctx, repoPath, TagPrefix+name)
}
// CreateTag create one tag in the repository // CreateTag create one tag in the repository
func (repo *Repository) CreateTag(name, revision string) error { func (repo *Repository) CreateTag(name, revision string) error {
_, _, err := NewCommand(repo.Ctx, "tag").AddDashesAndList(name, revision).RunStdString(&RunOpts{Dir: repo.Path}) _, _, err := NewCommand(repo.Ctx, "tag").AddDashesAndList(name, revision).RunStdString(&RunOpts{Dir: repo.Path})

View file

@ -7,7 +7,6 @@ import (
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -105,32 +104,6 @@ func ParseBool(value string) (result, valid bool) {
return intValue != 0, true return intValue != 0, true
} }
// LimitedReaderCloser is a limited reader closer
type LimitedReaderCloser struct {
R io.Reader
C io.Closer
N int64
}
// Read implements io.Reader
func (l *LimitedReaderCloser) Read(p []byte) (n int, err error) {
if l.N <= 0 {
_ = l.C.Close()
return 0, io.EOF
}
if int64(len(p)) > l.N {
p = p[0:l.N]
}
n, err = l.R.Read(p)
l.N -= int64(n)
return n, err
}
// Close implements io.Closer
func (l *LimitedReaderCloser) Close() error {
return l.C.Close()
}
func HashFilePathForWebUI(s string) string { func HashFilePathForWebUI(s string) string {
h := sha1.New() h := sha1.New()
_, _ = h.Write([]byte(s)) _, _ = h.Write([]byte(s))

View file

@ -34,13 +34,6 @@ func NewDetails() *Details {
} }
} }
// IsDetails returns true if the given node implements the Details interface,
// otherwise false.
func IsDetails(node ast.Node) bool {
_, ok := node.(*Details)
return ok
}
// Summary is a block that contains the summary of details block // Summary is a block that contains the summary of details block
type Summary struct { type Summary struct {
ast.BaseBlock ast.BaseBlock
@ -66,13 +59,6 @@ func NewSummary() *Summary {
} }
} }
// IsSummary returns true if the given node implements the Summary interface,
// otherwise false.
func IsSummary(node ast.Node) bool {
_, ok := node.(*Summary)
return ok
}
// TaskCheckBoxListItem is a block that represents a list item of a markdown block with a checkbox // TaskCheckBoxListItem is a block that represents a list item of a markdown block with a checkbox
type TaskCheckBoxListItem struct { type TaskCheckBoxListItem struct {
*ast.ListItem *ast.ListItem
@ -103,13 +89,6 @@ func NewTaskCheckBoxListItem(listItem *ast.ListItem) *TaskCheckBoxListItem {
} }
} }
// IsTaskCheckBoxListItem returns true if the given node implements the TaskCheckBoxListItem interface,
// otherwise false.
func IsTaskCheckBoxListItem(node ast.Node) bool {
_, ok := node.(*TaskCheckBoxListItem)
return ok
}
// Icon is an inline for a fomantic icon // Icon is an inline for a fomantic icon
type Icon struct { type Icon struct {
ast.BaseInline ast.BaseInline
@ -139,13 +118,6 @@ func NewIcon(name string) *Icon {
} }
} }
// IsIcon returns true if the given node implements the Icon interface,
// otherwise false.
func IsIcon(node ast.Node) bool {
_, ok := node.(*Icon)
return ok
}
// ColorPreview is an inline for a color preview // ColorPreview is an inline for a color preview
type ColorPreview struct { type ColorPreview struct {
ast.BaseInline ast.BaseInline

View file

@ -39,28 +39,6 @@ func Enabled(enable ...bool) Option {
}) })
} }
// WithInlineDollarParser enables or disables the parsing of $...$
func WithInlineDollarParser(enable ...bool) Option {
value := true
if len(enable) > 0 {
value = enable[0]
}
return extensionFunc(func(e *Extension) {
e.parseDollarInline = value
})
}
// WithBlockDollarParser enables or disables the parsing of $$...$$
func WithBlockDollarParser(enable ...bool) Option {
value := true
if len(enable) > 0 {
value = enable[0]
}
return extensionFunc(func(e *Extension) {
e.parseDollarBlock = value
})
}
// Math represents a math extension with default rendered delimiters // Math represents a math extension with default rendered delimiters
var Math = &Extension{ var Math = &Extension{
enabled: true, enabled: true,

View file

@ -1,32 +0,0 @@
// SPDX-License-Identifier: MIT
package private
import (
"context"
"code.gitea.io/gitea/modules/setting"
)
type ActionsRunnerRegisterRequest struct {
Token string
Scope string
Labels []string
Name string
Version string
}
func ActionsRunnerRegister(ctx context.Context, token, scope string, labels []string, name, version string) (string, ResponseExtra) {
reqURL := setting.LocalURL + "api/internal/actions/register"
req := newInternalRequest(ctx, reqURL, "POST", ActionsRunnerRegisterRequest{
Token: token,
Scope: scope,
Labels: labels,
Name: name,
Version: version,
})
resp, extra := requestJSONResp(req, &ResponseText{})
return resp.Text, extra
}

View file

@ -272,8 +272,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) {
// update team information and then check permission // update team information and then check permission
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5})
err = organization.UpdateTeamUnits(db.DefaultContext, team, nil) unittest.AssertSuccessfulDelete(t, &organization.TeamUnit{TeamID: team.ID})
require.NoError(t, err)
perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner)
require.NoError(t, err) require.NoError(t, err)
for _, unit := range repo.Units { for _, unit := range repo.Units {

View file

@ -18,25 +18,6 @@ import (
// ErrURLNotSupported represents url is not supported // ErrURLNotSupported represents url is not supported
var ErrURLNotSupported = errors.New("url method not supported") var ErrURLNotSupported = errors.New("url method not supported")
// ErrInvalidConfiguration is called when there is invalid configuration for a storage
type ErrInvalidConfiguration struct {
cfg any
err error
}
func (err ErrInvalidConfiguration) Error() string {
if err.err != nil {
return fmt.Sprintf("Invalid Configuration Argument: %v: Error: %v", err.cfg, err.err)
}
return fmt.Sprintf("Invalid Configuration Argument: %v", err.cfg)
}
// IsErrInvalidConfiguration checks if an error is an ErrInvalidConfiguration
func IsErrInvalidConfiguration(err error) bool {
_, ok := err.(ErrInvalidConfiguration)
return ok
}
type Type = setting.StorageType type Type = setting.StorageType
// NewStorageFunc is a function that creates a storage // NewStorageFunc is a function that creates a storage

View file

@ -141,26 +141,6 @@ func (p *CreatePayload) JSONPayload() ([]byte, error) {
return json.MarshalIndent(p, "", " ") return json.MarshalIndent(p, "", " ")
} }
// ParseCreateHook parses create event hook content.
func ParseCreateHook(raw []byte) (*CreatePayload, error) {
hook := new(CreatePayload)
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
// it is possible the JSON was parsed, however,
// was not from Gogs (maybe was from Bitbucket)
// So we'll check to be sure certain key fields
// were populated
switch {
case hook.Repo == nil:
return nil, ErrInvalidReceiveHook
case len(hook.Ref) == 0:
return nil, ErrInvalidReceiveHook
}
return hook, nil
}
// ________ .__ __ // ________ .__ __
// \______ \ ____ | | _____/ |_ ____ // \______ \ ____ | | _____/ |_ ____
// | | \_/ __ \| | _/ __ \ __\/ __ \ // | | \_/ __ \| | _/ __ \ __\/ __ \
@ -292,22 +272,6 @@ func (p *PushPayload) JSONPayload() ([]byte, error) {
return json.MarshalIndent(p, "", " ") return json.MarshalIndent(p, "", " ")
} }
// ParsePushHook parses push event hook content.
func ParsePushHook(raw []byte) (*PushPayload, error) {
hook := new(PushPayload)
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
switch {
case hook.Repo == nil:
return nil, ErrInvalidReceiveHook
case len(hook.Ref) == 0:
return nil, ErrInvalidReceiveHook
}
return hook, nil
}
// Branch returns branch name from a payload // Branch returns branch name from a payload
func (p *PushPayload) Branch() string { func (p *PushPayload) Branch() string {
return strings.ReplaceAll(p.Ref, "refs/heads/", "") return strings.ReplaceAll(p.Ref, "refs/heads/", "")

View file

@ -53,9 +53,3 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
func SetLocaleCookie(resp http.ResponseWriter, lang string, maxAge int) { func SetLocaleCookie(resp http.ResponseWriter, lang string, maxAge int) {
SetSiteCookie(resp, "lang", lang, maxAge) SetSiteCookie(resp, "lang", lang, maxAge)
} }
// DeleteLocaleCookie convenience function to delete the locale cookie consistently
// Setting the lang cookie will trigger the middleware to reset the language to previous state.
func DeleteLocaleCookie(resp http.ResponseWriter) {
SetSiteCookie(resp, "lang", "", -1)
}

View file

@ -1,18 +0,0 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package convert
import (
secret_model "code.gitea.io/gitea/models/secret"
api "code.gitea.io/gitea/modules/structs"
)
// ToSecret converts Secret to API format
func ToSecret(secret *secret_model.Secret) *api.Secret {
result := &api.Secret{
Name: secret.Name,
}
return result
}

View file

@ -740,17 +740,6 @@ type SaveTopicForm struct {
Topics []string `binding:"topics;Required;"` Topics []string `binding:"topics;Required;"`
} }
// DeadlineForm hold the validation rules for deadlines
type DeadlineForm struct {
DateString string `form:"date" binding:"Required;Size(10)"`
}
// Validate validates the fields
func (f *DeadlineForm) Validate(req *http.Request, errs binding.Errors) binding.Errors {
ctx := context.GetValidateContext(req)
return middleware.Validate(errs, ctx.Data, f, ctx.Locale)
}
type CommitNotesForm struct { type CommitNotesForm struct {
Notes string Notes string
} }

View file

@ -71,36 +71,6 @@ func MergeRequiredContextsCommitStatus(commitStatuses []*git_model.CommitStatus,
return returnedStatus return returnedStatus
} }
// IsCommitStatusContextSuccess returns true if all required status check contexts succeed.
func IsCommitStatusContextSuccess(commitStatuses []*git_model.CommitStatus, requiredContexts []string) bool {
// If no specific context is required, require that last commit status is a success
if len(requiredContexts) == 0 {
status := git_model.CalcCommitStatus(commitStatuses)
if status == nil || status.State != structs.CommitStatusSuccess {
return false
}
return true
}
for _, ctx := range requiredContexts {
var found bool
for _, commitStatus := range commitStatuses {
if commitStatus.Context == ctx {
if commitStatus.State != structs.CommitStatusSuccess {
return false
}
found = true
break
}
}
if !found {
return false
}
}
return true
}
// IsPullCommitStatusPass returns if all required status checks PASS // IsPullCommitStatusPass returns if all required status checks PASS
func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) (bool, error) { func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) (bool, error) {
pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch) pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)

View file

@ -33,19 +33,6 @@ func GetFilesResponseFromCommit(ctx context.Context, repo *repo_model.Repository
return filesResponse, nil return filesResponse, nil
} }
// GetFileResponseFromCommit Constructs a FileResponse from a Commit object
func GetFileResponseFromCommit(ctx context.Context, repo *repo_model.Repository, commit *git.Commit, branch, treeName string) (*api.FileResponse, error) {
fileContents, _ := GetContents(ctx, repo, treeName, branch, false) // ok if fails, then will be nil
fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil
verification := GetPayloadCommitVerification(ctx, commit)
fileResponse := &api.FileResponse{
Content: fileContents,
Commit: fileCommitResponse,
Verification: verification,
}
return fileResponse, nil
}
// constructs a FileResponse with the file at the index from FilesResponse // constructs a FileResponse with the file at the index from FilesResponse
func GetFileResponseFromFilesResponse(filesResponse *api.FilesResponse, index int) *api.FileResponse { func GetFileResponseFromFilesResponse(filesResponse *api.FilesResponse, index int) *api.FileResponse {
content := &api.ContentsResponse{} content := &api.ContentsResponse{}

View file

@ -6,15 +6,7 @@ package files
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCleanUploadFileName(t *testing.T) { func TestCleanUploadFileName(t *testing.T) {
@ -32,84 +24,3 @@ func TestCleanUploadFileName(t *testing.T) {
assert.EqualValues(t, expectedCleanName, cleanName) assert.EqualValues(t, expectedCleanName, cleanName)
}) })
} }
func getExpectedFileResponse() *api.FileResponse {
treePath := "README.md"
sha := "4b4851ad51df6a7d9f25c979345979eaeb5b349f"
encoding := "base64"
content := "IyByZXBvMQoKRGVzY3JpcHRpb24gZm9yIHJlcG8x"
selfURL := setting.AppURL + "api/v1/repos/user2/repo1/contents/" + treePath + "?ref=master"
htmlURL := setting.AppURL + "user2/repo1/src/branch/master/" + treePath
gitURL := setting.AppURL + "api/v1/repos/user2/repo1/git/blobs/" + sha
downloadURL := setting.AppURL + "user2/repo1/raw/branch/master/" + treePath
return &api.FileResponse{
Content: &api.ContentsResponse{
Name: treePath,
Path: treePath,
SHA: sha,
LastCommitSHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
Type: "file",
Size: 30,
Encoding: &encoding,
Content: &content,
URL: &selfURL,
HTMLURL: &htmlURL,
GitURL: &gitURL,
DownloadURL: &downloadURL,
Links: &api.FileLinksResponse{
Self: &selfURL,
GitURL: &gitURL,
HTMLURL: &htmlURL,
},
},
Commit: &api.FileCommitResponse{
CommitMeta: api.CommitMeta{
URL: "https://try.gitea.io/api/v1/repos/user2/repo1/git/commits/65f1bf27bc3bf70f64657658635e66094edbcb4d",
SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
},
HTMLURL: "https://try.gitea.io/user2/repo1/commit/65f1bf27bc3bf70f64657658635e66094edbcb4d",
Author: &api.CommitUser{
Identity: api.Identity{
Name: "user1",
Email: "address1@example.com",
},
Date: "2017-03-19T20:47:59Z",
},
Committer: &api.CommitUser{
Identity: api.Identity{
Name: "Ethan Koenig",
Email: "ethantkoenig@gmail.com",
},
Date: "2017-03-19T20:47:59Z",
},
Parents: []*api.CommitMeta{},
Message: "Initial commit\n",
Tree: &api.CommitMeta{
URL: "https://try.gitea.io/api/v1/repos/user2/repo1/git/trees/2a2f1d4670728a2e10049e345bd7a276468beab6",
SHA: "2a2f1d4670728a2e10049e345bd7a276468beab6",
},
},
Verification: &api.PayloadCommitVerification{
Verified: false,
Reason: "gpg.error.not_signed_commit",
Signature: "",
Payload: "",
},
}
}
func TestGetFileResponseFromCommit(t *testing.T) {
unittest.PrepareTestEnv(t)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
branch := repo.DefaultBranch
treePath := "README.md"
gitRepo, _ := gitrepo.OpenRepository(db.DefaultContext, repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(branch)
expectedFileResponse := getExpectedFileResponse()
fileResponse, err := GetFileResponseFromCommit(db.DefaultContext, repo, commit, branch, treePath)
require.NoError(t, err)
assert.EqualValues(t, expectedFileResponse, fileResponse)
}

View file

@ -212,24 +212,6 @@ func (t *TemporaryUploadRepository) WriteTree() (string, error) {
return strings.TrimSpace(stdout), nil return strings.TrimSpace(stdout), nil
} }
// GetLastCommit gets the last commit ID SHA of the repo
func (t *TemporaryUploadRepository) GetLastCommit() (string, error) {
return t.GetLastCommitByRef("HEAD")
}
// GetLastCommitByRef gets the last commit ID SHA of the repo by ref
func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, error) {
if ref == "" {
ref = "HEAD"
}
stdout, _, err := git.NewCommand(t.ctx, "rev-parse").AddDynamicArguments(ref).RunStdString(&git.RunOpts{Dir: t.basePath})
if err != nil {
log.Error("Unable to get last ref for %s in temporary repo: %s(%s): Error: %v", ref, t.repo.FullName(), t.basePath, err)
return "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %w", ref, t.repo.FullName(), err)
}
return strings.TrimSpace(stdout), nil
}
// CommitTree creates a commit from a given tree for the user with provided message // CommitTree creates a commit from a given tree for the user with provided message
func (t *TemporaryUploadRepository) CommitTree(parent string, author, committer *user_model.User, treeHash, message string, signoff bool) (string, error) { func (t *TemporaryUploadRepository) CommitTree(parent string, author, committer *user_model.User, treeHash, message string, signoff bool) (string, error) {
return t.CommitTreeWithDate(parent, author, committer, treeHash, message, signoff, time.Now(), time.Now()) return t.CommitTreeWithDate(parent, author, committer, treeHash, message, signoff, time.Now(), time.Now())

View file

@ -298,9 +298,7 @@ func addAuthSource(t *testing.T, payload map[string]string) *auth.Source {
payload["_csrf"] = GetCSRF(t, session, "/admin/auths/new") payload["_csrf"] = GetCSRF(t, session, "/admin/auths/new")
req := NewRequestWithValues(t, "POST", "/admin/auths/new", payload) req := NewRequestWithValues(t, "POST", "/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusSeeOther) session.MakeRequest(t, req, http.StatusSeeOther)
source, err := auth.GetSourceByName(context.Background(), payload["name"]) return unittest.AssertExistsAndLoadBean(t, &auth.Source{Name: payload["name"]})
require.NoError(t, err)
return source
} }
func authSourcePayloadOAuth2(name string) map[string]string { func authSourcePayloadOAuth2(name string) map[string]string {
@ -358,9 +356,7 @@ func createRemoteAuthSource(t *testing.T, name, url, matchingSource string) *aut
MatchingSource: matchingSource, MatchingSource: matchingSource,
}, },
})) }))
source, err := auth.GetSourceByName(context.Background(), name) return unittest.AssertExistsAndLoadBean(t, &auth.Source{Name: name})
require.NoError(t, err)
return source
} }
func createUser(ctx context.Context, t testing.TB, user *user_model.User) func() { func createUser(ctx context.Context, t testing.TB, user *user_model.User) func() {