summaryrefslogtreecommitdiffstats
path: root/models/repo.go
blob: 0dc8ee5df33e72db60a0401f9e53b3a10efd0239 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package models

import (
	"context"
	"fmt"
	"strconv"

	_ "image/jpeg" // Needed for jpeg support

	asymkey_model "code.gitea.io/gitea/models/asymkey"
	"code.gitea.io/gitea/models/db"
	issues_model "code.gitea.io/gitea/models/issues"
	access_model "code.gitea.io/gitea/models/perm/access"
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/unit"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/log"
)

// Init initialize model
func Init(ctx context.Context) error {
	return unit.LoadUnitConfig()
}

type repoChecker struct {
	querySQL   func(ctx context.Context) ([]map[string][]byte, error)
	correctSQL func(ctx context.Context, id int64) error
	desc       string
}

func repoStatsCheck(ctx context.Context, checker *repoChecker) {
	results, err := checker.querySQL(ctx)
	if err != nil {
		log.Error("Select %s: %v", checker.desc, err)
		return
	}
	for _, result := range results {
		id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
		select {
		case <-ctx.Done():
			log.Warn("CheckRepoStats: Cancelled before checking %s for with id=%d", checker.desc, id)
			return
		default:
		}
		log.Trace("Updating %s: %d", checker.desc, id)
		err = checker.correctSQL(ctx, id)
		if err != nil {
			log.Error("Update %s[%d]: %v", checker.desc, id, err)
		}
	}
}

func StatsCorrectSQL(ctx context.Context, sql string, id int64) error {
	_, err := db.GetEngine(ctx).Exec(sql, id, id)
	return err
}

func repoStatsCorrectNumWatches(ctx context.Context, id int64) error {
	return StatsCorrectSQL(ctx, "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=? AND mode<>2) WHERE id=?", id)
}

func repoStatsCorrectNumStars(ctx context.Context, id int64) error {
	return StatsCorrectSQL(ctx, "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?", id)
}

func labelStatsCorrectNumIssues(ctx context.Context, id int64) error {
	return StatsCorrectSQL(ctx, "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?", id)
}

func labelStatsCorrectNumIssuesRepo(ctx context.Context, id int64) error {
	_, err := db.GetEngine(ctx).Exec("UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=id) WHERE repo_id=?", id)
	return err
}

func labelStatsCorrectNumClosedIssues(ctx context.Context, id int64) error {
	_, err := db.GetEngine(ctx).Exec("UPDATE `label` SET num_closed_issues=(SELECT COUNT(*) FROM `issue_label`,`issue` WHERE `issue_label`.label_id=`label`.id AND `issue_label`.issue_id=`issue`.id AND `issue`.is_closed=?) WHERE `label`.id=?", true, id)
	return err
}

func labelStatsCorrectNumClosedIssuesRepo(ctx context.Context, id int64) error {
	_, err := db.GetEngine(ctx).Exec("UPDATE `label` SET num_closed_issues=(SELECT COUNT(*) FROM `issue_label`,`issue` WHERE `issue_label`.label_id=`label`.id AND `issue_label`.issue_id=`issue`.id AND `issue`.is_closed=?) WHERE `label`.repo_id=?", true, id)
	return err
}

var milestoneStatsQueryNumIssues = "SELECT `milestone`.id FROM `milestone` WHERE `milestone`.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE `issue`.milestone_id=`milestone`.id AND `issue`.is_closed=?) OR `milestone`.num_issues!=(SELECT COUNT(*) FROM `issue` WHERE `issue`.milestone_id=`milestone`.id)"

func milestoneStatsCorrectNumIssuesRepo(ctx context.Context, id int64) error {
	e := db.GetEngine(ctx)
	results, err := e.Query(milestoneStatsQueryNumIssues+" AND `milestone`.repo_id = ?", true, id)
	if err != nil {
		return err
	}
	for _, result := range results {
		id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
		err = issues_model.UpdateMilestoneCounters(ctx, id)
		if err != nil {
			return err
		}
	}
	return nil
}

func userStatsCorrectNumRepos(ctx context.Context, id int64) error {
	return StatsCorrectSQL(ctx, "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?", id)
}

func repoStatsCorrectIssueNumComments(ctx context.Context, id int64) error {
	return StatsCorrectSQL(ctx, "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?", id)
}

func repoStatsCorrectNumIssues(ctx context.Context, id int64) error {
	return repo_model.UpdateRepoIssueNumbers(ctx, id, false, false)
}

func repoStatsCorrectNumPulls(ctx context.Context, id int64) error {
	return repo_model.UpdateRepoIssueNumbers(ctx, id, true, false)
}

func repoStatsCorrectNumClosedIssues(ctx context.Context, id int64) error {
	return repo_model.UpdateRepoIssueNumbers(ctx, id, false, true)
}

func repoStatsCorrectNumClosedPulls(ctx context.Context, id int64) error {
	return repo_model.UpdateRepoIssueNumbers(ctx, id, true, true)
}

func statsQuery(args ...any) func(context.Context) ([]map[string][]byte, error) {
	return func(ctx context.Context) ([]map[string][]byte, error) {
		return db.GetEngine(ctx).Query(args...)
	}
}

// CheckRepoStats checks the repository stats
func CheckRepoStats(ctx context.Context) error {
	log.Trace("Doing: CheckRepoStats")

	checkers := []*repoChecker{
		// Repository.NumWatches
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id AND mode<>2)"),
			repoStatsCorrectNumWatches,
			"repository count 'num_watches'",
		},
		// Repository.NumStars
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)"),
			repoStatsCorrectNumStars,
			"repository count 'num_stars'",
		},
		// Repository.NumIssues
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_pull=?)", false),
			repoStatsCorrectNumIssues,
			"repository count 'num_issues'",
		},
		// Repository.NumClosedIssues
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false),
			repoStatsCorrectNumClosedIssues,
			"repository count 'num_closed_issues'",
		},
		// Repository.NumPulls
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_pull=?)", true),
			repoStatsCorrectNumPulls,
			"repository count 'num_pulls'",
		},
		// Repository.NumClosedPulls
		{
			statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true),
			repoStatsCorrectNumClosedPulls,
			"repository count 'num_closed_pulls'",
		},
		// Label.NumIssues
		{
			statsQuery("SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)"),
			labelStatsCorrectNumIssues,
			"label count 'num_issues'",
		},
		// Label.NumClosedIssues
		{
			statsQuery("SELECT `label`.id FROM `label` WHERE `label`.num_closed_issues!=(SELECT COUNT(*) FROM `issue_label`,`issue` WHERE `issue_label`.label_id=`label`.id AND `issue_label`.issue_id=`issue`.id AND `issue`.is_closed=?)", true),
			labelStatsCorrectNumClosedIssues,
			"label count 'num_closed_issues'",
		},
		// Milestone.Num{,Closed}Issues
		{
			statsQuery(milestoneStatsQueryNumIssues, true),
			issues_model.UpdateMilestoneCounters,
			"milestone count 'num_closed_issues' and 'num_issues'",
		},
		// User.NumRepos
		{
			statsQuery("SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)"),
			userStatsCorrectNumRepos,
			"user count 'num_repos'",
		},
		// Issue.NumComments
		{
			statsQuery("SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)"),
			repoStatsCorrectIssueNumComments,
			"issue count 'num_comments'",
		},
	}
	for _, checker := range checkers {
		select {
		case <-ctx.Done():
			log.Warn("CheckRepoStats: Cancelled before %s", checker.desc)
			return db.ErrCancelledf("before checking %s", checker.desc)
		default:
			repoStatsCheck(ctx, checker)
		}
	}

	// FIXME: use checker when stop supporting old fork repo format.
	// ***** START: Repository.NumForks *****
	e := db.GetEngine(ctx)
	results, err := e.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
	if err != nil {
		log.Error("Select repository count 'num_forks': %v", err)
	} else {
		for _, result := range results {
			id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
			select {
			case <-ctx.Done():
				log.Warn("CheckRepoStats: Cancelled")
				return db.ErrCancelledf("during repository count 'num_fork' for repo ID %d", id)
			default:
			}
			log.Trace("Updating repository count 'num_forks': %d", id)

			repo, err := repo_model.GetRepositoryByID(ctx, id)
			if err != nil {
				log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err)
				continue
			}

			_, err = e.SQL("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID).Get(&repo.NumForks)
			if err != nil {
				log.Error("Select count of forks[%d]: %v", repo.ID, err)
				continue
			}

			if _, err = e.ID(repo.ID).Cols("num_forks").Update(repo); err != nil {
				log.Error("UpdateRepository[%d]: %v", id, err)
				continue
			}
		}
	}
	// ***** END: Repository.NumForks *****
	return nil
}

func UpdateRepoStats(ctx context.Context, id int64) error {
	var err error

	for _, f := range []func(ctx context.Context, id int64) error{
		repoStatsCorrectNumWatches,
		repoStatsCorrectNumStars,
		repoStatsCorrectNumIssues,
		repoStatsCorrectNumPulls,
		repoStatsCorrectNumClosedIssues,
		repoStatsCorrectNumClosedPulls,
		labelStatsCorrectNumIssuesRepo,
		labelStatsCorrectNumClosedIssuesRepo,
		milestoneStatsCorrectNumIssuesRepo,
	} {
		err = f(ctx, id)
		if err != nil {
			return err
		}
	}
	return nil
}

func updateUserStarNumbers(ctx context.Context, users []user_model.User) error {
	ctx, committer, err := db.TxContext(ctx)
	if err != nil {
		return err
	}
	defer committer.Close()

	for _, user := range users {
		if _, err = db.Exec(ctx, "UPDATE `user` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE uid=?) WHERE id=?", user.ID, user.ID); err != nil {
			return err
		}
	}

	return committer.Commit()
}

// DoctorUserStarNum recalculate Stars number for all user
func DoctorUserStarNum(ctx context.Context) (err error) {
	const batchSize = 100

	for start := 0; ; start += batchSize {
		users := make([]user_model.User, 0, batchSize)
		if err = db.GetEngine(ctx).Limit(batchSize, start).Where("type = ?", 0).Cols("id").Find(&users); err != nil {
			return err
		}
		if len(users) == 0 {
			break
		}

		if err = updateUserStarNumbers(ctx, users); err != nil {
			return err
		}
	}

	log.Debug("recalculate Stars number for all user finished")

	return err
}

// DeleteDeployKey delete deploy keys
func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error {
	key, err := asymkey_model.GetDeployKeyByID(ctx, id)
	if err != nil {
		if asymkey_model.IsErrDeployKeyNotExist(err) {
			return nil
		}
		return fmt.Errorf("GetDeployKeyByID: %w", err)
	}

	// Check if user has access to delete this key.
	if !doer.IsAdmin {
		repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID)
		if err != nil {
			return fmt.Errorf("GetRepositoryByID: %w", err)
		}
		has, err := access_model.IsUserRepoAdmin(ctx, repo, doer)
		if err != nil {
			return fmt.Errorf("GetUserRepoPermission: %w", err)
		} else if !has {
			return asymkey_model.ErrKeyAccessDenied{
				UserID: doer.ID,
				KeyID:  key.ID,
				Note:   "deploy",
			}
		}
	}

	if _, err := db.DeleteByID[asymkey_model.DeployKey](ctx, key.ID); err != nil {
		return fmt.Errorf("delete deploy key [%d]: %w", key.ID, err)
	}

	// Check if this is the last reference to same key content.
	has, err := asymkey_model.IsDeployKeyExistByKeyID(ctx, key.KeyID)
	if err != nil {
		return err
	} else if !has {
		if _, err = db.DeleteByID[asymkey_model.PublicKey](ctx, key.KeyID); err != nil {
			return err
		}
	}

	return nil
}