loading up the forgejo repo on tangled to test page performance
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

chore: remove deadcode (#6743)

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/6743
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>

+30 -797
-63
.deadcode-out
··· 10 10 ContextSetStdin 11 11 12 12 code.gitea.io/gitea/models 13 - IsErrUpdateTaskNotExist 14 - ErrUpdateTaskNotExist.Error 15 - ErrUpdateTaskNotExist.Unwrap 16 13 IsErrSHANotFound 17 14 IsErrMergeDivergingFastForwardOnly 18 15 19 - code.gitea.io/gitea/models/actions 20 - ScheduleList.GetUserIDs 21 - ScheduleList.GetRepoIDs 22 - ScheduleList.LoadTriggerUser 23 - ScheduleList.LoadRepos 24 - 25 16 code.gitea.io/gitea/models/auth 26 - GetSourceByName 27 17 WebAuthnCredentials 28 18 29 19 code.gitea.io/gitea/models/db ··· 52 42 IsErrIssueWasClosed 53 43 54 44 code.gitea.io/gitea/models/organization 55 - GetTeamNamesByID 56 - UpdateTeamUnits 57 45 SearchMembersOptions.ToConds 58 - UsersInTeamsCount 59 46 60 47 code.gitea.io/gitea/models/perm/access 61 48 GetRepoWriters 62 49 63 - code.gitea.io/gitea/models/project 64 - UpdateColumnSorting 65 - ChangeProjectStatus 66 - 67 50 code.gitea.io/gitea/models/repo 68 - DeleteAttachmentsByIssue 69 - FindReposMapByIDs 70 - IsErrTopicNotExist 71 - ErrTopicNotExist.Error 72 - ErrTopicNotExist.Unwrap 73 - GetTopicByName 74 51 WatchRepoMode 75 52 76 53 code.gitea.io/gitea/models/user ··· 103 80 WithNoCacheContext 104 81 RemoveContextData 105 82 106 - code.gitea.io/gitea/modules/charset 107 - BreakWriter.Write 108 - 109 83 code.gitea.io/gitea/modules/emoji 110 84 ReplaceCodes 111 85 ··· 127 101 CommitChangesWithArgs 128 102 SetUpdateHook 129 103 openRepositoryWithDefaultContext 130 - IsTagExist 131 104 ToEntryMode 132 - LimitedReaderCloser.Read 133 - LimitedReaderCloser.Close 134 105 135 106 code.gitea.io/gitea/modules/gitgraph 136 107 Parser.Reset ··· 171 142 RenderString 172 143 173 144 code.gitea.io/gitea/modules/markup/markdown 174 - IsDetails 175 - IsSummary 176 - IsTaskCheckBoxListItem 177 - IsIcon 178 145 RenderRawString 179 146 180 - code.gitea.io/gitea/modules/markup/markdown/math 181 - WithInlineDollarParser 182 - WithBlockDollarParser 183 - 184 147 code.gitea.io/gitea/modules/markup/mdstripper 185 148 stripRenderer.AddOptions 186 149 StripMarkdown 187 150 188 151 code.gitea.io/gitea/modules/markup/orgmode 189 152 RenderString 190 - 191 - code.gitea.io/gitea/modules/private 192 - ActionsRunnerRegister 193 153 194 154 code.gitea.io/gitea/modules/process 195 155 Manager.ExecTimeout ··· 212 172 NewConfigProviderFromData 213 173 GitConfigType.GetOption 214 174 InitLoggersForTest 215 - 216 - code.gitea.io/gitea/modules/storage 217 - ErrInvalidConfiguration.Error 218 - IsErrInvalidConfiguration 219 - 220 - code.gitea.io/gitea/modules/structs 221 - ParseCreateHook 222 - ParsePushHook 223 175 224 176 code.gitea.io/gitea/modules/sync 225 177 StatusTable.Start ··· 252 204 RouteMock 253 205 RouteMockReset 254 206 255 - code.gitea.io/gitea/modules/web/middleware 256 - DeleteLocaleCookie 257 - 258 207 code.gitea.io/gitea/modules/zstd 259 208 NewWriter 260 209 Writer.Write ··· 269 218 code.gitea.io/gitea/services/context 270 219 GetPrivateContext 271 220 272 - code.gitea.io/gitea/services/convert 273 - ToSecret 274 - 275 - code.gitea.io/gitea/services/forms 276 - DeadlineForm.Validate 277 - 278 - code.gitea.io/gitea/services/pull 279 - IsCommitStatusContextSuccess 280 - 281 221 code.gitea.io/gitea/services/repository 282 222 IsErrForkAlreadyExist 283 223 284 224 code.gitea.io/gitea/services/repository/files 285 225 ContentType.String 286 - GetFileResponseFromCommit 287 - TemporaryUploadRepository.GetLastCommit 288 - TemporaryUploadRepository.GetLastCommitByRef 289 226 290 227 code.gitea.io/gitea/services/webhook 291 228 NewNotifier
+24
models/actions/schedule.go
··· 14 14 "code.gitea.io/gitea/modules/timeutil" 15 15 "code.gitea.io/gitea/modules/util" 16 16 webhook_module "code.gitea.io/gitea/modules/webhook" 17 + 18 + "xorm.io/builder" 17 19 ) 18 20 19 21 // ActionSchedule represents a schedule of a workflow file ··· 140 142 } 141 143 return nil 142 144 } 145 + 146 + type FindScheduleOptions struct { 147 + db.ListOptions 148 + RepoID int64 149 + OwnerID int64 150 + } 151 + 152 + func (opts FindScheduleOptions) ToConds() builder.Cond { 153 + cond := builder.NewCond() 154 + if opts.RepoID > 0 { 155 + cond = cond.And(builder.Eq{"repo_id": opts.RepoID}) 156 + } 157 + if opts.OwnerID > 0 { 158 + cond = cond.And(builder.Eq{"owner_id": opts.OwnerID}) 159 + } 160 + 161 + return cond 162 + } 163 + 164 + func (opts FindScheduleOptions) ToOrders() string { 165 + return "`id` DESC" 166 + }
-83
models/actions/schedule_list.go
··· 1 - // Copyright 2023 The Gitea Authors. All rights reserved. 2 - // SPDX-License-Identifier: MIT 3 - 4 - package actions 5 - 6 - import ( 7 - "context" 8 - 9 - "code.gitea.io/gitea/models/db" 10 - repo_model "code.gitea.io/gitea/models/repo" 11 - user_model "code.gitea.io/gitea/models/user" 12 - "code.gitea.io/gitea/modules/container" 13 - 14 - "xorm.io/builder" 15 - ) 16 - 17 - type ScheduleList []*ActionSchedule 18 - 19 - // GetUserIDs returns a slice of user's id 20 - func (schedules ScheduleList) GetUserIDs() []int64 { 21 - return container.FilterSlice(schedules, func(schedule *ActionSchedule) (int64, bool) { 22 - return schedule.TriggerUserID, true 23 - }) 24 - } 25 - 26 - func (schedules ScheduleList) GetRepoIDs() []int64 { 27 - return container.FilterSlice(schedules, func(schedule *ActionSchedule) (int64, bool) { 28 - return schedule.RepoID, true 29 - }) 30 - } 31 - 32 - func (schedules ScheduleList) LoadTriggerUser(ctx context.Context) error { 33 - userIDs := schedules.GetUserIDs() 34 - users := make(map[int64]*user_model.User, len(userIDs)) 35 - if err := db.GetEngine(ctx).In("id", userIDs).Find(&users); err != nil { 36 - return err 37 - } 38 - for _, schedule := range schedules { 39 - if schedule.TriggerUserID == user_model.ActionsUserID { 40 - schedule.TriggerUser = user_model.NewActionsUser() 41 - } else { 42 - schedule.TriggerUser = users[schedule.TriggerUserID] 43 - if schedule.TriggerUser == nil { 44 - schedule.TriggerUser = user_model.NewGhostUser() 45 - } 46 - } 47 - } 48 - return nil 49 - } 50 - 51 - func (schedules ScheduleList) LoadRepos(ctx context.Context) error { 52 - repoIDs := schedules.GetRepoIDs() 53 - repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs) 54 - if err != nil { 55 - return err 56 - } 57 - for _, schedule := range schedules { 58 - schedule.Repo = repos[schedule.RepoID] 59 - } 60 - return nil 61 - } 62 - 63 - type FindScheduleOptions struct { 64 - db.ListOptions 65 - RepoID int64 66 - OwnerID int64 67 - } 68 - 69 - func (opts FindScheduleOptions) ToConds() builder.Cond { 70 - cond := builder.NewCond() 71 - if opts.RepoID > 0 { 72 - cond = cond.And(builder.Eq{"repo_id": opts.RepoID}) 73 - } 74 - if opts.OwnerID > 0 { 75 - cond = cond.And(builder.Eq{"owner_id": opts.OwnerID}) 76 - } 77 - 78 - return cond 79 - } 80 - 81 - func (opts FindScheduleOptions) ToOrders() string { 82 - return "`id` DESC" 83 - }
-11
models/auth/source.go
··· 299 299 return source, nil 300 300 } 301 301 302 - func GetSourceByName(ctx context.Context, name string) (*Source, error) { 303 - source := &Source{} 304 - has, err := db.GetEngine(ctx).Where("name = ?", name).Get(source) 305 - if err != nil { 306 - return nil, err 307 - } else if !has { 308 - return nil, ErrSourceNotExist{} 309 - } 310 - return source, nil 311 - } 312 - 313 302 // UpdateSource updates a Source record in DB. 314 303 func UpdateSource(ctx context.Context, source *Source) error { 315 304 var originalSource *Source
-19
models/error.go
··· 151 151 return util.ErrInvalidArgument 152 152 } 153 153 154 - // ErrUpdateTaskNotExist represents a "UpdateTaskNotExist" kind of error. 155 - type ErrUpdateTaskNotExist struct { 156 - UUID string 157 - } 158 - 159 - // IsErrUpdateTaskNotExist checks if an error is a ErrUpdateTaskNotExist. 160 - func IsErrUpdateTaskNotExist(err error) bool { 161 - _, ok := err.(ErrUpdateTaskNotExist) 162 - return ok 163 - } 164 - 165 - func (err ErrUpdateTaskNotExist) Error() string { 166 - return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID) 167 - } 168 - 169 - func (err ErrUpdateTaskNotExist) Unwrap() error { 170 - return util.ErrNotExist 171 - } 172 - 173 154 // ErrInvalidTagName represents a "InvalidTagName" kind of error. 174 155 type ErrInvalidTagName struct { 175 156 TagName string
-16
models/organization/team.go
··· 247 247 return t, nil 248 248 } 249 249 250 - // GetTeamNamesByID returns team's lower name from a list of team ids. 251 - func GetTeamNamesByID(ctx context.Context, teamIDs []int64) ([]string, error) { 252 - if len(teamIDs) == 0 { 253 - return []string{}, nil 254 - } 255 - 256 - var teamNames []string 257 - err := db.GetEngine(ctx).Table("team"). 258 - Select("lower_name"). 259 - In("id", teamIDs). 260 - Asc("name"). 261 - Find(&teamNames) 262 - 263 - return teamNames, err 264 - } 265 - 266 250 // IncrTeamRepoNum increases the number of repos for the given team by 1 267 251 func IncrTeamRepoNum(ctx context.Context, teamID int64) error { 268 252 _, err := db.GetEngine(ctx).Incr("num_repos").ID(teamID).Update(new(Team))
-14
models/organization/team_test.go
··· 188 188 test(2, 5, false) 189 189 } 190 190 191 - func TestUsersInTeamsCount(t *testing.T) { 192 - require.NoError(t, unittest.PrepareTestDatabase()) 193 - 194 - test := func(teamIDs, userIDs []int64, expected int64) { 195 - count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs) 196 - require.NoError(t, err) 197 - assert.Equal(t, expected, count) 198 - } 199 - 200 - test([]int64{2}, []int64{1, 2, 3, 4}, 1) // only userid 2 201 - test([]int64{1, 2, 3, 4, 5}, []int64{2, 5}, 2) // userid 2,4 202 - test([]int64{1, 2, 3, 4, 5}, []int64{2, 3, 5}, 3) // userid 2,4,5 203 - } 204 - 205 191 func TestInconsistentOwnerTeam(t *testing.T) { 206 192 defer unittest.OverrideFixtures( 207 193 unittest.FixturesOptions{
-21
models/organization/team_unit.go
··· 28 28 func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err error) { 29 29 return units, db.GetEngine(ctx).Where("team_id = ?", teamID).Find(&units) 30 30 } 31 - 32 - // UpdateTeamUnits updates a teams's units 33 - func UpdateTeamUnits(ctx context.Context, team *Team, units []TeamUnit) (err error) { 34 - ctx, committer, err := db.TxContext(ctx) 35 - if err != nil { 36 - return err 37 - } 38 - defer committer.Close() 39 - 40 - if _, err = db.GetEngine(ctx).Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil { 41 - return err 42 - } 43 - 44 - if len(units) > 0 { 45 - if err = db.Insert(ctx, units); err != nil { 46 - return err 47 - } 48 - } 49 - 50 - return committer.Commit() 51 - }
-11
models/organization/team_user.go
··· 76 76 func IsUserInTeams(ctx context.Context, userID int64, teamIDs []int64) (bool, error) { 77 77 return db.GetEngine(ctx).Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser)) 78 78 } 79 - 80 - // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs 81 - func UsersInTeamsCount(ctx context.Context, userIDs, teamIDs []int64) (int64, error) { 82 - var ids []int64 83 - if err := db.GetEngine(ctx).In("uid", userIDs).In("team_id", teamIDs). 84 - Table("team_user"). 85 - Cols("uid").GroupBy("uid").Find(&ids); err != nil { 86 - return 0, err 87 - } 88 - return int64(len(ids)), nil 89 - }
-14
models/project/column.go
··· 305 305 }) 306 306 } 307 307 308 - // UpdateColumnSorting update project column sorting 309 - func UpdateColumnSorting(ctx context.Context, cl ColumnList) error { 310 - return db.WithTx(ctx, func(ctx context.Context) error { 311 - for i := range cl { 312 - if _, err := db.GetEngine(ctx).ID(cl[i].ID).Cols( 313 - "sorting", 314 - ).Update(cl[i]); err != nil { 315 - return err 316 - } 317 - } 318 - return nil 319 - }) 320 - } 321 - 322 308 func GetColumnsByIDs(ctx context.Context, projectID int64, columnsIDs []int64) (ColumnList, error) { 323 309 columns := make([]*Column, 0, 5) 324 310 if err := db.GetEngine(ctx).
-15
models/project/project.go
··· 368 368 return committer.Commit() 369 369 } 370 370 371 - // ChangeProjectStatus toggle a project between opened and closed 372 - func ChangeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { 373 - ctx, committer, err := db.TxContext(ctx) 374 - if err != nil { 375 - return err 376 - } 377 - defer committer.Close() 378 - 379 - if err := changeProjectStatus(ctx, p, isClosed); err != nil { 380 - return err 381 - } 382 - 383 - return committer.Commit() 384 - } 385 - 386 371 func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { 387 372 p.IsClosed = isClosed 388 373 p.ClosedDateUnix = timeutil.TimeStampNow()
+1 -1
models/project/project_test.go
··· 75 75 76 76 assert.Equal(t, project.Title, projectFromDB.Title) 77 77 78 - require.NoError(t, ChangeProjectStatus(db.DefaultContext, project, true)) 78 + require.NoError(t, ChangeProjectStatusByRepoIDAndID(db.DefaultContext, project.RepoID, project.ID, true)) 79 79 80 80 // Retrieve from DB afresh to check if it is truly closed 81 81 projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID)
-10
models/repo/attachment.go
··· 219 219 return int(cnt), nil 220 220 } 221 221 222 - // DeleteAttachmentsByIssue deletes all attachments associated with the given issue. 223 - func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) { 224 - attachments, err := GetAttachmentsByIssueID(ctx, issueID) 225 - if err != nil { 226 - return 0, err 227 - } 228 - 229 - return DeleteAttachments(ctx, attachments, remove) 230 - } 231 - 232 222 // DeleteAttachmentsByComment deletes all attachments associated with the given comment. 233 223 func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) { 234 224 attachments, err := GetAttachmentsByCommentID(ctx, commentID)
+1 -5
models/repo/attachment_test.go
··· 46 46 func TestDeleteAttachments(t *testing.T) { 47 47 require.NoError(t, unittest.PrepareTestDatabase()) 48 48 49 - count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) 50 - require.NoError(t, err) 51 - assert.Equal(t, 2, count) 52 - 53 - count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) 49 + count, err := repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) 54 50 require.NoError(t, err) 55 51 assert.Equal(t, 2, count) 56 52
-5
models/repo/repo_list.go
··· 21 21 "xorm.io/builder" 22 22 ) 23 23 24 - // FindReposMapByIDs find repos as map 25 - func FindReposMapByIDs(ctx context.Context, repoIDs []int64, res map[int64]*Repository) error { 26 - return db.GetEngine(ctx).In("id", repoIDs).Find(&res) 27 - } 28 - 29 24 // RepositoryListDefaultPageSize is the default number of repositories 30 25 // to load in memory when running administrative tasks on all (or almost 31 26 // all) of them.
-33
models/repo/topic.go
··· 5 5 6 6 import ( 7 7 "context" 8 - "fmt" 9 8 "regexp" 10 9 "strings" 11 10 12 11 "code.gitea.io/gitea/models/db" 13 12 "code.gitea.io/gitea/modules/container" 14 13 "code.gitea.io/gitea/modules/timeutil" 15 - "code.gitea.io/gitea/modules/util" 16 14 17 15 "xorm.io/builder" 18 16 ) ··· 39 37 TopicID int64 `xorm:"pk"` 40 38 } 41 39 42 - // ErrTopicNotExist represents an error that a topic is not exist 43 - type ErrTopicNotExist struct { 44 - Name string 45 - } 46 - 47 - // IsErrTopicNotExist checks if an error is an ErrTopicNotExist. 48 - func IsErrTopicNotExist(err error) bool { 49 - _, ok := err.(ErrTopicNotExist) 50 - return ok 51 - } 52 - 53 - // Error implements error interface 54 - func (err ErrTopicNotExist) Error() string { 55 - return fmt.Sprintf("topic is not exist [name: %s]", err.Name) 56 - } 57 - 58 - func (err ErrTopicNotExist) Unwrap() error { 59 - return util.ErrNotExist 60 - } 61 - 62 40 // ValidateTopic checks a topic by length and match pattern rules 63 41 func ValidateTopic(topic string) bool { 64 42 return len(topic) <= 35 && topicPattern.MatchString(topic) ··· 89 67 } 90 68 91 69 return validTopics, invalidTopics 92 - } 93 - 94 - // GetTopicByName retrieves topic by name 95 - func GetTopicByName(ctx context.Context, name string) (*Topic, error) { 96 - var topic Topic 97 - if has, err := db.GetEngine(ctx).Where("name = ?", name).Get(&topic); err != nil { 98 - return nil, err 99 - } else if !has { 100 - return nil, ErrTopicNotExist{name} 101 - } 102 - return &topic, nil 103 70 } 104 71 105 72 // addTopicByNameToRepo adds a topic name to a repo and increments the topic count.
+1 -2
models/repo/topic_test.go
··· 52 52 require.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea")) 53 53 repo2NrOfTopics = 2 54 54 totalNrOfTopics++ 55 - topic, err := repo_model.GetTopicByName(db.DefaultContext, "gitea") 56 - require.NoError(t, err) 55 + topic := unittest.AssertExistsAndLoadBean(t, &repo_model.Topic{Name: "gitea"}) 57 56 assert.EqualValues(t, 1, topic.RepoCount) 58 57 59 58 topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{})
-43
modules/charset/breakwriter.go
··· 1 - // Copyright 2022 The Gitea Authors. All rights reserved. 2 - // SPDX-License-Identifier: MIT 3 - 4 - package charset 5 - 6 - import ( 7 - "bytes" 8 - "io" 9 - ) 10 - 11 - // BreakWriter wraps an io.Writer to always write '\n' as '<br>' 12 - type BreakWriter struct { 13 - io.Writer 14 - } 15 - 16 - // Write writes the provided byte slice transparently replacing '\n' with '<br>' 17 - func (b *BreakWriter) Write(bs []byte) (n int, err error) { 18 - pos := 0 19 - for pos < len(bs) { 20 - idx := bytes.IndexByte(bs[pos:], '\n') 21 - if idx < 0 { 22 - wn, err := b.Writer.Write(bs[pos:]) 23 - return n + wn, err 24 - } 25 - 26 - if idx > 0 { 27 - wn, err := b.Writer.Write(bs[pos : pos+idx]) 28 - n += wn 29 - if err != nil { 30 - return n, err 31 - } 32 - } 33 - 34 - if _, err = b.Writer.Write([]byte("<br>")); err != nil { 35 - return n, err 36 - } 37 - pos += idx + 1 38 - 39 - n++ 40 - } 41 - 42 - return n, err 43 - }
-68
modules/charset/breakwriter_test.go
··· 1 - // Copyright 2022 The Gitea Authors. All rights reserved. 2 - // SPDX-License-Identifier: MIT 3 - 4 - package charset 5 - 6 - import ( 7 - "strings" 8 - "testing" 9 - ) 10 - 11 - func TestBreakWriter_Write(t *testing.T) { 12 - tests := []struct { 13 - name string 14 - kase string 15 - expect string 16 - wantErr bool 17 - }{ 18 - { 19 - name: "noline", 20 - kase: "abcdefghijklmnopqrstuvwxyz", 21 - expect: "abcdefghijklmnopqrstuvwxyz", 22 - }, 23 - { 24 - name: "endline", 25 - kase: "abcdefghijklmnopqrstuvwxyz\n", 26 - expect: "abcdefghijklmnopqrstuvwxyz<br>", 27 - }, 28 - { 29 - name: "startline", 30 - kase: "\nabcdefghijklmnopqrstuvwxyz", 31 - expect: "<br>abcdefghijklmnopqrstuvwxyz", 32 - }, 33 - { 34 - name: "onlyline", 35 - kase: "\n\n\n", 36 - expect: "<br><br><br>", 37 - }, 38 - { 39 - name: "empty", 40 - kase: "", 41 - expect: "", 42 - }, 43 - { 44 - name: "midline", 45 - kase: "\nabc\ndefghijkl\nmnopqrstuvwxy\nz", 46 - expect: "<br>abc<br>defghijkl<br>mnopqrstuvwxy<br>z", 47 - }, 48 - } 49 - for _, tt := range tests { 50 - t.Run(tt.name, func(t *testing.T) { 51 - buf := &strings.Builder{} 52 - b := &BreakWriter{ 53 - Writer: buf, 54 - } 55 - n, err := b.Write([]byte(tt.kase)) 56 - if (err != nil) != tt.wantErr { 57 - t.Errorf("BreakWriter.Write() error = %v, wantErr %v", err, tt.wantErr) 58 - return 59 - } 60 - if n != len(tt.kase) { 61 - t.Errorf("BreakWriter.Write() = %v, want %v", n, len(tt.kase)) 62 - } 63 - if buf.String() != tt.expect { 64 - t.Errorf("BreakWriter.Write() wrote %q, want %v", buf.String(), tt.expect) 65 - } 66 - }) 67 - } 68 - }
-6
modules/git/repo_tag.go
··· 5 5 package git 6 6 7 7 import ( 8 - "context" 9 8 "errors" 10 9 "fmt" 11 10 "io" ··· 19 18 20 19 // TagPrefix tags prefix path on the repository 21 20 const TagPrefix = "refs/tags/" 22 - 23 - // IsTagExist returns true if given tag exists in the repository. 24 - func IsTagExist(ctx context.Context, repoPath, name string) bool { 25 - return IsReferenceExist(ctx, repoPath, TagPrefix+name) 26 - } 27 21 28 22 // CreateTag create one tag in the repository 29 23 func (repo *Repository) CreateTag(name, revision string) error {
-27
modules/git/utils.go
··· 7 7 "crypto/sha1" 8 8 "encoding/hex" 9 9 "fmt" 10 - "io" 11 10 "os" 12 11 "strconv" 13 12 "strings" ··· 103 102 return false, false 104 103 } 105 104 return intValue != 0, true 106 - } 107 - 108 - // LimitedReaderCloser is a limited reader closer 109 - type LimitedReaderCloser struct { 110 - R io.Reader 111 - C io.Closer 112 - N int64 113 - } 114 - 115 - // Read implements io.Reader 116 - func (l *LimitedReaderCloser) Read(p []byte) (n int, err error) { 117 - if l.N <= 0 { 118 - _ = l.C.Close() 119 - return 0, io.EOF 120 - } 121 - if int64(len(p)) > l.N { 122 - p = p[0:l.N] 123 - } 124 - n, err = l.R.Read(p) 125 - l.N -= int64(n) 126 - return n, err 127 - } 128 - 129 - // Close implements io.Closer 130 - func (l *LimitedReaderCloser) Close() error { 131 - return l.C.Close() 132 105 } 133 106 134 107 func HashFilePathForWebUI(s string) string {
-28
modules/markup/markdown/ast.go
··· 34 34 } 35 35 } 36 36 37 - // IsDetails returns true if the given node implements the Details interface, 38 - // otherwise false. 39 - func IsDetails(node ast.Node) bool { 40 - _, ok := node.(*Details) 41 - return ok 42 - } 43 - 44 37 // Summary is a block that contains the summary of details block 45 38 type Summary struct { 46 39 ast.BaseBlock ··· 64 57 return &Summary{ 65 58 BaseBlock: ast.BaseBlock{}, 66 59 } 67 - } 68 - 69 - // IsSummary returns true if the given node implements the Summary interface, 70 - // otherwise false. 71 - func IsSummary(node ast.Node) bool { 72 - _, ok := node.(*Summary) 73 - return ok 74 60 } 75 61 76 62 // TaskCheckBoxListItem is a block that represents a list item of a markdown block with a checkbox ··· 103 89 } 104 90 } 105 91 106 - // IsTaskCheckBoxListItem returns true if the given node implements the TaskCheckBoxListItem interface, 107 - // otherwise false. 108 - func IsTaskCheckBoxListItem(node ast.Node) bool { 109 - _, ok := node.(*TaskCheckBoxListItem) 110 - return ok 111 - } 112 - 113 92 // Icon is an inline for a fomantic icon 114 93 type Icon struct { 115 94 ast.BaseInline ··· 137 116 BaseInline: ast.BaseInline{}, 138 117 Name: []byte(name), 139 118 } 140 - } 141 - 142 - // IsIcon returns true if the given node implements the Icon interface, 143 - // otherwise false. 144 - func IsIcon(node ast.Node) bool { 145 - _, ok := node.(*Icon) 146 - return ok 147 119 } 148 120 149 121 // ColorPreview is an inline for a color preview
-22
modules/markup/markdown/math/math.go
··· 39 39 }) 40 40 } 41 41 42 - // WithInlineDollarParser enables or disables the parsing of $...$ 43 - func WithInlineDollarParser(enable ...bool) Option { 44 - value := true 45 - if len(enable) > 0 { 46 - value = enable[0] 47 - } 48 - return extensionFunc(func(e *Extension) { 49 - e.parseDollarInline = value 50 - }) 51 - } 52 - 53 - // WithBlockDollarParser enables or disables the parsing of $$...$$ 54 - func WithBlockDollarParser(enable ...bool) Option { 55 - value := true 56 - if len(enable) > 0 { 57 - value = enable[0] 58 - } 59 - return extensionFunc(func(e *Extension) { 60 - e.parseDollarBlock = value 61 - }) 62 - } 63 - 64 42 // Math represents a math extension with default rendered delimiters 65 43 var Math = &Extension{ 66 44 enabled: true,
-32
modules/private/forgejo_actions.go
··· 1 - // SPDX-License-Identifier: MIT 2 - 3 - package private 4 - 5 - import ( 6 - "context" 7 - 8 - "code.gitea.io/gitea/modules/setting" 9 - ) 10 - 11 - type ActionsRunnerRegisterRequest struct { 12 - Token string 13 - Scope string 14 - Labels []string 15 - Name string 16 - Version string 17 - } 18 - 19 - func ActionsRunnerRegister(ctx context.Context, token, scope string, labels []string, name, version string) (string, ResponseExtra) { 20 - reqURL := setting.LocalURL + "api/internal/actions/register" 21 - 22 - req := newInternalRequest(ctx, reqURL, "POST", ActionsRunnerRegisterRequest{ 23 - Token: token, 24 - Scope: scope, 25 - Labels: labels, 26 - Name: name, 27 - Version: version, 28 - }) 29 - 30 - resp, extra := requestJSONResp(req, &ResponseText{}) 31 - return resp.Text, extra 32 - }
+1 -2
modules/repository/collaborator_test.go
··· 272 272 273 273 // update team information and then check permission 274 274 team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}) 275 - err = organization.UpdateTeamUnits(db.DefaultContext, team, nil) 276 - require.NoError(t, err) 275 + unittest.AssertSuccessfulDelete(t, &organization.TeamUnit{TeamID: team.ID}) 277 276 perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) 278 277 require.NoError(t, err) 279 278 for _, unit := range repo.Units {
-19
modules/storage/storage.go
··· 18 18 // ErrURLNotSupported represents url is not supported 19 19 var ErrURLNotSupported = errors.New("url method not supported") 20 20 21 - // ErrInvalidConfiguration is called when there is invalid configuration for a storage 22 - type ErrInvalidConfiguration struct { 23 - cfg any 24 - err error 25 - } 26 - 27 - func (err ErrInvalidConfiguration) Error() string { 28 - if err.err != nil { 29 - return fmt.Sprintf("Invalid Configuration Argument: %v: Error: %v", err.cfg, err.err) 30 - } 31 - return fmt.Sprintf("Invalid Configuration Argument: %v", err.cfg) 32 - } 33 - 34 - // IsErrInvalidConfiguration checks if an error is an ErrInvalidConfiguration 35 - func IsErrInvalidConfiguration(err error) bool { 36 - _, ok := err.(ErrInvalidConfiguration) 37 - return ok 38 - } 39 - 40 21 type Type = setting.StorageType 41 22 42 23 // NewStorageFunc is a function that creates a storage
-36
modules/structs/hook.go
··· 141 141 return json.MarshalIndent(p, "", " ") 142 142 } 143 143 144 - // ParseCreateHook parses create event hook content. 145 - func ParseCreateHook(raw []byte) (*CreatePayload, error) { 146 - hook := new(CreatePayload) 147 - if err := json.Unmarshal(raw, hook); err != nil { 148 - return nil, err 149 - } 150 - 151 - // it is possible the JSON was parsed, however, 152 - // was not from Gogs (maybe was from Bitbucket) 153 - // So we'll check to be sure certain key fields 154 - // were populated 155 - switch { 156 - case hook.Repo == nil: 157 - return nil, ErrInvalidReceiveHook 158 - case len(hook.Ref) == 0: 159 - return nil, ErrInvalidReceiveHook 160 - } 161 - return hook, nil 162 - } 163 - 164 144 // ________ .__ __ 165 145 // \______ \ ____ | | _____/ |_ ____ 166 146 // | | \_/ __ \| | _/ __ \ __\/ __ \ ··· 290 270 // JSONPayload FIXME 291 271 func (p *PushPayload) JSONPayload() ([]byte, error) { 292 272 return json.MarshalIndent(p, "", " ") 293 - } 294 - 295 - // ParsePushHook parses push event hook content. 296 - func ParsePushHook(raw []byte) (*PushPayload, error) { 297 - hook := new(PushPayload) 298 - if err := json.Unmarshal(raw, hook); err != nil { 299 - return nil, err 300 - } 301 - 302 - switch { 303 - case hook.Repo == nil: 304 - return nil, ErrInvalidReceiveHook 305 - case len(hook.Ref) == 0: 306 - return nil, ErrInvalidReceiveHook 307 - } 308 - return hook, nil 309 273 } 310 274 311 275 // Branch returns branch name from a payload
-6
modules/web/middleware/locale.go
··· 53 53 func SetLocaleCookie(resp http.ResponseWriter, lang string, maxAge int) { 54 54 SetSiteCookie(resp, "lang", lang, maxAge) 55 55 } 56 - 57 - // DeleteLocaleCookie convenience function to delete the locale cookie consistently 58 - // Setting the lang cookie will trigger the middleware to reset the language to previous state. 59 - func DeleteLocaleCookie(resp http.ResponseWriter) { 60 - SetSiteCookie(resp, "lang", "", -1) 61 - }
-18
services/convert/secret.go
··· 1 - // Copyright 2023 The Gitea Authors. All rights reserved. 2 - // SPDX-License-Identifier: MIT 3 - 4 - package convert 5 - 6 - import ( 7 - secret_model "code.gitea.io/gitea/models/secret" 8 - api "code.gitea.io/gitea/modules/structs" 9 - ) 10 - 11 - // ToSecret converts Secret to API format 12 - func ToSecret(secret *secret_model.Secret) *api.Secret { 13 - result := &api.Secret{ 14 - Name: secret.Name, 15 - } 16 - 17 - return result 18 - }
-11
services/forms/repo_form.go
··· 740 740 Topics []string `binding:"topics;Required;"` 741 741 } 742 742 743 - // DeadlineForm hold the validation rules for deadlines 744 - type DeadlineForm struct { 745 - DateString string `form:"date" binding:"Required;Size(10)"` 746 - } 747 - 748 - // Validate validates the fields 749 - func (f *DeadlineForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { 750 - ctx := context.GetValidateContext(req) 751 - return middleware.Validate(errs, ctx.Data, f, ctx.Locale) 752 - } 753 - 754 743 type CommitNotesForm struct { 755 744 Notes string 756 745 }
-30
services/pull/commit_status.go
··· 71 71 return returnedStatus 72 72 } 73 73 74 - // IsCommitStatusContextSuccess returns true if all required status check contexts succeed. 75 - func IsCommitStatusContextSuccess(commitStatuses []*git_model.CommitStatus, requiredContexts []string) bool { 76 - // If no specific context is required, require that last commit status is a success 77 - if len(requiredContexts) == 0 { 78 - status := git_model.CalcCommitStatus(commitStatuses) 79 - if status == nil || status.State != structs.CommitStatusSuccess { 80 - return false 81 - } 82 - return true 83 - } 84 - 85 - for _, ctx := range requiredContexts { 86 - var found bool 87 - for _, commitStatus := range commitStatuses { 88 - if commitStatus.Context == ctx { 89 - if commitStatus.State != structs.CommitStatusSuccess { 90 - return false 91 - } 92 - 93 - found = true 94 - break 95 - } 96 - } 97 - if !found { 98 - return false 99 - } 100 - } 101 - return true 102 - } 103 - 104 74 // IsPullCommitStatusPass returns if all required status checks PASS 105 75 func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) (bool, error) { 106 76 pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)
-13
services/repository/files/file.go
··· 33 33 return filesResponse, nil 34 34 } 35 35 36 - // GetFileResponseFromCommit Constructs a FileResponse from a Commit object 37 - func GetFileResponseFromCommit(ctx context.Context, repo *repo_model.Repository, commit *git.Commit, branch, treeName string) (*api.FileResponse, error) { 38 - fileContents, _ := GetContents(ctx, repo, treeName, branch, false) // ok if fails, then will be nil 39 - fileCommitResponse, _ := GetFileCommitResponse(repo, commit) // ok if fails, then will be nil 40 - verification := GetPayloadCommitVerification(ctx, commit) 41 - fileResponse := &api.FileResponse{ 42 - Content: fileContents, 43 - Commit: fileCommitResponse, 44 - Verification: verification, 45 - } 46 - return fileResponse, nil 47 - } 48 - 49 36 // constructs a FileResponse with the file at the index from FilesResponse 50 37 func GetFileResponseFromFilesResponse(filesResponse *api.FilesResponse, index int) *api.FileResponse { 51 38 content := &api.ContentsResponse{}
-89
services/repository/files/file_test.go
··· 6 6 import ( 7 7 "testing" 8 8 9 - "code.gitea.io/gitea/models/db" 10 - repo_model "code.gitea.io/gitea/models/repo" 11 - "code.gitea.io/gitea/models/unittest" 12 - "code.gitea.io/gitea/modules/gitrepo" 13 - "code.gitea.io/gitea/modules/setting" 14 - api "code.gitea.io/gitea/modules/structs" 15 - 16 9 "github.com/stretchr/testify/assert" 17 - "github.com/stretchr/testify/require" 18 10 ) 19 11 20 12 func TestCleanUploadFileName(t *testing.T) { ··· 32 24 assert.EqualValues(t, expectedCleanName, cleanName) 33 25 }) 34 26 } 35 - 36 - func getExpectedFileResponse() *api.FileResponse { 37 - treePath := "README.md" 38 - sha := "4b4851ad51df6a7d9f25c979345979eaeb5b349f" 39 - encoding := "base64" 40 - content := "IyByZXBvMQoKRGVzY3JpcHRpb24gZm9yIHJlcG8x" 41 - selfURL := setting.AppURL + "api/v1/repos/user2/repo1/contents/" + treePath + "?ref=master" 42 - htmlURL := setting.AppURL + "user2/repo1/src/branch/master/" + treePath 43 - gitURL := setting.AppURL + "api/v1/repos/user2/repo1/git/blobs/" + sha 44 - downloadURL := setting.AppURL + "user2/repo1/raw/branch/master/" + treePath 45 - return &api.FileResponse{ 46 - Content: &api.ContentsResponse{ 47 - Name: treePath, 48 - Path: treePath, 49 - SHA: sha, 50 - LastCommitSHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d", 51 - Type: "file", 52 - Size: 30, 53 - Encoding: &encoding, 54 - Content: &content, 55 - URL: &selfURL, 56 - HTMLURL: &htmlURL, 57 - GitURL: &gitURL, 58 - DownloadURL: &downloadURL, 59 - Links: &api.FileLinksResponse{ 60 - Self: &selfURL, 61 - GitURL: &gitURL, 62 - HTMLURL: &htmlURL, 63 - }, 64 - }, 65 - Commit: &api.FileCommitResponse{ 66 - CommitMeta: api.CommitMeta{ 67 - URL: "https://try.gitea.io/api/v1/repos/user2/repo1/git/commits/65f1bf27bc3bf70f64657658635e66094edbcb4d", 68 - SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d", 69 - }, 70 - HTMLURL: "https://try.gitea.io/user2/repo1/commit/65f1bf27bc3bf70f64657658635e66094edbcb4d", 71 - Author: &api.CommitUser{ 72 - Identity: api.Identity{ 73 - Name: "user1", 74 - Email: "address1@example.com", 75 - }, 76 - Date: "2017-03-19T20:47:59Z", 77 - }, 78 - Committer: &api.CommitUser{ 79 - Identity: api.Identity{ 80 - Name: "Ethan Koenig", 81 - Email: "ethantkoenig@gmail.com", 82 - }, 83 - Date: "2017-03-19T20:47:59Z", 84 - }, 85 - Parents: []*api.CommitMeta{}, 86 - Message: "Initial commit\n", 87 - Tree: &api.CommitMeta{ 88 - URL: "https://try.gitea.io/api/v1/repos/user2/repo1/git/trees/2a2f1d4670728a2e10049e345bd7a276468beab6", 89 - SHA: "2a2f1d4670728a2e10049e345bd7a276468beab6", 90 - }, 91 - }, 92 - Verification: &api.PayloadCommitVerification{ 93 - Verified: false, 94 - Reason: "gpg.error.not_signed_commit", 95 - Signature: "", 96 - Payload: "", 97 - }, 98 - } 99 - } 100 - 101 - func TestGetFileResponseFromCommit(t *testing.T) { 102 - unittest.PrepareTestEnv(t) 103 - 104 - repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) 105 - branch := repo.DefaultBranch 106 - treePath := "README.md" 107 - gitRepo, _ := gitrepo.OpenRepository(db.DefaultContext, repo) 108 - defer gitRepo.Close() 109 - commit, _ := gitRepo.GetBranchCommit(branch) 110 - expectedFileResponse := getExpectedFileResponse() 111 - 112 - fileResponse, err := GetFileResponseFromCommit(db.DefaultContext, repo, commit, branch, treePath) 113 - require.NoError(t, err) 114 - assert.EqualValues(t, expectedFileResponse, fileResponse) 115 - }
-18
services/repository/files/temp_repo.go
··· 212 212 return strings.TrimSpace(stdout), nil 213 213 } 214 214 215 - // GetLastCommit gets the last commit ID SHA of the repo 216 - func (t *TemporaryUploadRepository) GetLastCommit() (string, error) { 217 - return t.GetLastCommitByRef("HEAD") 218 - } 219 - 220 - // GetLastCommitByRef gets the last commit ID SHA of the repo by ref 221 - func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, error) { 222 - if ref == "" { 223 - ref = "HEAD" 224 - } 225 - stdout, _, err := git.NewCommand(t.ctx, "rev-parse").AddDynamicArguments(ref).RunStdString(&git.RunOpts{Dir: t.basePath}) 226 - if err != nil { 227 - log.Error("Unable to get last ref for %s in temporary repo: %s(%s): Error: %v", ref, t.repo.FullName(), t.basePath, err) 228 - return "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %w", ref, t.repo.FullName(), err) 229 - } 230 - return strings.TrimSpace(stdout), nil 231 - } 232 - 233 215 // CommitTree creates a commit from a given tree for the user with provided message 234 216 func (t *TemporaryUploadRepository) CommitTree(parent string, author, committer *user_model.User, treeHash, message string, signoff bool) (string, error) { 235 217 return t.CommitTreeWithDate(parent, author, committer, treeHash, message, signoff, time.Now(), time.Now())
+2 -6
tests/integration/integration_test.go
··· 298 298 payload["_csrf"] = GetCSRF(t, session, "/admin/auths/new") 299 299 req := NewRequestWithValues(t, "POST", "/admin/auths/new", payload) 300 300 session.MakeRequest(t, req, http.StatusSeeOther) 301 - source, err := auth.GetSourceByName(context.Background(), payload["name"]) 302 - require.NoError(t, err) 303 - return source 301 + return unittest.AssertExistsAndLoadBean(t, &auth.Source{Name: payload["name"]}) 304 302 } 305 303 306 304 func authSourcePayloadOAuth2(name string) map[string]string { ··· 358 356 MatchingSource: matchingSource, 359 357 }, 360 358 })) 361 - source, err := auth.GetSourceByName(context.Background(), name) 362 - require.NoError(t, err) 363 - return source 359 + return unittest.AssertExistsAndLoadBean(t, &auth.Source{Name: name}) 364 360 } 365 361 366 362 func createUser(ctx context.Context, t testing.TB, user *user_model.User) func() {