mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-03 17:37:53 +02:00
feat: Merge the main branch
Signed-off-by: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
This commit is contained in:
@@ -17,13 +17,12 @@ import (
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
actions_module "code.gitea.io/gitea/modules/actions"
|
||||
"code.gitea.io/gitea/modules/actions/jobparser"
|
||||
"code.gitea.io/gitea/modules/commitstatus"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
webhook_module "code.gitea.io/gitea/modules/webhook"
|
||||
commitstatus_service "code.gitea.io/gitea/services/repository/commitstatus"
|
||||
|
||||
"github.com/nektos/act/pkg/jobparser"
|
||||
)
|
||||
|
||||
// CreateCommitStatusForRunJobs creates a commit status for the given job if it has a supported event and related commit.
|
||||
@@ -115,6 +114,21 @@ func getCommitStatusEventNameAndCommitID(run *actions_model.ActionRun) (event, c
|
||||
return "", "", errors.New("head of pull request is missing in event payload")
|
||||
}
|
||||
commitID = payload.PullRequest.Head.Sha
|
||||
case // pull_request_review events share the same PullRequestPayload as pull_request
|
||||
webhook_module.HookEventPullRequestReviewApproved,
|
||||
webhook_module.HookEventPullRequestReviewRejected,
|
||||
webhook_module.HookEventPullRequestReviewComment:
|
||||
event = run.TriggerEvent
|
||||
payload, err := run.GetPullRequestEventPayload()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("GetPullRequestEventPayload: %w", err)
|
||||
}
|
||||
if payload.PullRequest == nil {
|
||||
return "", "", errors.New("pull request is missing in event payload")
|
||||
} else if payload.PullRequest.Head == nil {
|
||||
return "", "", errors.New("head of pull request is missing in event payload")
|
||||
}
|
||||
commitID = payload.PullRequest.Head.Sha
|
||||
case webhook_module.HookEventRelease:
|
||||
event = string(run.Event)
|
||||
commitID = run.CommitSHA
|
||||
|
||||
@@ -8,10 +8,10 @@ import (
|
||||
"fmt"
|
||||
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
"code.gitea.io/gitea/modules/actions/jobparser"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
|
||||
"github.com/nektos/act/pkg/jobparser"
|
||||
act_model "github.com/nektos/act/pkg/model"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
@@ -20,16 +20,19 @@ import (
|
||||
// and fills the run's model fields with `concurrency.group` and `concurrency.cancel-in-progress`.
|
||||
// Workflow-level concurrency doesn't depend on the job outputs, so it can always be evaluated if there is no syntax error.
|
||||
// See https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#concurrency
|
||||
func EvaluateRunConcurrencyFillModel(ctx context.Context, run *actions_model.ActionRun, wfRawConcurrency *act_model.RawConcurrency, vars map[string]string) error {
|
||||
func EvaluateRunConcurrencyFillModel(ctx context.Context, run *actions_model.ActionRun, wfRawConcurrency *act_model.RawConcurrency, vars map[string]string, inputs map[string]any) error {
|
||||
if err := run.LoadAttributes(ctx); err != nil {
|
||||
return fmt.Errorf("run LoadAttributes: %w", err)
|
||||
}
|
||||
|
||||
actionsRunCtx := GenerateGiteaContext(run, nil)
|
||||
jobResults := map[string]*jobparser.JobResult{"": {}}
|
||||
inputs, err := getInputsFromRun(run)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get inputs: %w", err)
|
||||
if inputs == nil {
|
||||
var err error
|
||||
inputs, err = getInputsFromRun(run)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get inputs: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
rawConcurrency, err := yaml.Marshal(wfRawConcurrency)
|
||||
@@ -68,7 +71,7 @@ func findJobNeedsAndFillJobResults(ctx context.Context, job *actions_model.Actio
|
||||
// Job-level concurrency may depend on other job's outputs (via `needs`): `concurrency.group: my-group-${{ needs.job1.outputs.out1 }}`
|
||||
// If the needed jobs haven't been executed yet, this evaluation will also fail.
|
||||
// See https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idconcurrency
|
||||
func EvaluateJobConcurrencyFillModel(ctx context.Context, run *actions_model.ActionRun, actionRunJob *actions_model.ActionRunJob, vars map[string]string) error {
|
||||
func EvaluateJobConcurrencyFillModel(ctx context.Context, run *actions_model.ActionRun, actionRunJob *actions_model.ActionRunJob, vars map[string]string, inputs map[string]any) error {
|
||||
if err := actionRunJob.LoadAttributes(ctx); err != nil {
|
||||
return fmt.Errorf("job LoadAttributes: %w", err)
|
||||
}
|
||||
@@ -85,9 +88,12 @@ func EvaluateJobConcurrencyFillModel(ctx context.Context, run *actions_model.Act
|
||||
return fmt.Errorf("find job needs and fill job results: %w", err)
|
||||
}
|
||||
|
||||
inputs, err := getInputsFromRun(run)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get inputs: %w", err)
|
||||
if inputs == nil {
|
||||
var err error
|
||||
inputs, err = getInputsFromRun(run)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get inputs: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
workflowJob, err := actionRunJob.ParseJob()
|
||||
|
||||
@@ -104,7 +104,7 @@ type TaskNeed struct {
|
||||
// FindTaskNeeds finds the `needs` for the task by the task's job
|
||||
func FindTaskNeeds(ctx context.Context, job *actions_model.ActionRunJob) (map[string]*TaskNeed, error) {
|
||||
if len(job.Needs) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil when the job has no needs
|
||||
}
|
||||
needs := container.SetOf(job.Needs...)
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestInitToken(t *testing.T) {
|
||||
|
||||
@@ -124,7 +124,7 @@ func checkJobsByRunID(ctx context.Context, runID int64) error {
|
||||
// findBlockedRunByConcurrency finds the blocked concurrent run in a repo and returns `nil, nil` when there is no blocked run.
|
||||
func findBlockedRunByConcurrency(ctx context.Context, repoID int64, concurrencyGroup string) (*actions_model.ActionRun, error) {
|
||||
if concurrencyGroup == "" {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that no blocked run exists
|
||||
}
|
||||
cRuns, cJobs, err := actions_model.GetConcurrentRunsAndJobs(ctx, repoID, concurrencyGroup, []actions_model.Status{actions_model.StatusBlocked})
|
||||
if err != nil {
|
||||
@@ -444,7 +444,7 @@ func updateConcurrencyEvaluationForJobWithNeeds(ctx context.Context, actionRunJo
|
||||
return nil // for testing purpose only, no repo, no evaluation
|
||||
}
|
||||
|
||||
err := EvaluateJobConcurrencyFillModel(ctx, actionRunJob.Run, actionRunJob, vars)
|
||||
err := EvaluateJobConcurrencyFillModel(ctx, actionRunJob.Run, actionRunJob, vars, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ import (
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/actions/jobparser"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
notify_service "code.gitea.io/gitea/services/notify"
|
||||
|
||||
"github.com/nektos/act/pkg/jobparser"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -36,7 +36,7 @@ func PrepareRunAndInsert(ctx context.Context, content []byte, run *actions_model
|
||||
}
|
||||
|
||||
if wfRawConcurrency != nil {
|
||||
err = EvaluateRunConcurrencyFillModel(ctx, run, wfRawConcurrency, vars)
|
||||
err = EvaluateRunConcurrencyFillModel(ctx, run, wfRawConcurrency, vars, inputsWithDefaults)
|
||||
if err != nil {
|
||||
return fmt.Errorf("EvaluateRunConcurrencyFillModel: %w", err)
|
||||
}
|
||||
@@ -53,7 +53,7 @@ func PrepareRunAndInsert(ctx context.Context, content []byte, run *actions_model
|
||||
run.Title = jobs[0].RunName
|
||||
}
|
||||
|
||||
if err = InsertRun(ctx, run, jobs, vars, content); err != nil {
|
||||
if err = InsertRun(ctx, run, jobs, vars, inputsWithDefaults); err != nil {
|
||||
return fmt.Errorf("InsertRun: %w", err)
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ func PrepareRunAndInsert(ctx context.Context, content []byte, run *actions_model
|
||||
|
||||
// InsertRun inserts a run
|
||||
// The title will be cut off at 255 characters if it's longer than 255 characters.
|
||||
func InsertRun(ctx context.Context, run *actions_model.ActionRun, jobs []*jobparser.SingleWorkflow, vars map[string]string, workflowContent []byte) error {
|
||||
func InsertRun(ctx context.Context, run *actions_model.ActionRun, jobs []*jobparser.SingleWorkflow, vars map[string]string, inputs map[string]any) error {
|
||||
return db.WithTx(ctx, func(ctx context.Context) error {
|
||||
index, err := db.GetNextResourceIndex(ctx, "action_run_index", run.RepoID)
|
||||
if err != nil {
|
||||
@@ -154,7 +154,7 @@ func InsertRun(ctx context.Context, run *actions_model.ActionRun, jobs []*jobpar
|
||||
|
||||
// do not evaluate job concurrency when it requires `needs`, the jobs with `needs` will be evaluated later by job emitter
|
||||
if len(needs) == 0 {
|
||||
err = EvaluateJobConcurrencyFillModel(ctx, run, runJob, vars)
|
||||
err = EvaluateJobConcurrencyFillModel(ctx, run, runJob, vars, inputs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/actions"
|
||||
"code.gitea.io/gitea/modules/actions/jobparser"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/reqctx"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
@@ -21,7 +22,6 @@ import (
|
||||
"code.gitea.io/gitea/services/context"
|
||||
"code.gitea.io/gitea/services/convert"
|
||||
|
||||
"github.com/nektos/act/pkg/jobparser"
|
||||
"github.com/nektos/act/pkg/model"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -58,6 +58,10 @@ func UploadAttachmentGeneralSizeLimit(ctx context.Context, file *UploaderFile, a
|
||||
return uploadAttachment(ctx, file, allowedTypes, setting.Attachment.MaxSize<<20, attach)
|
||||
}
|
||||
|
||||
func UploadAttachmentReleaseSizeLimit(ctx context.Context, file *UploaderFile, allowedTypes string, attach *repo_model.Attachment) (*repo_model.Attachment, error) {
|
||||
return uploadAttachment(ctx, file, allowedTypes, setting.Repository.Release.FileMaxSize<<20, attach)
|
||||
}
|
||||
|
||||
func uploadAttachment(ctx context.Context, file *UploaderFile, allowedTypes string, maxFileSize int64, attach *repo_model.Attachment) (*repo_model.Attachment, error) {
|
||||
src := file.rd
|
||||
if file.size < 0 {
|
||||
|
||||
@@ -32,7 +32,7 @@ var (
|
||||
|
||||
func CheckAuthToken(ctx context.Context, value string) (*auth_model.AuthToken, error) {
|
||||
if len(value) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
parts := strings.SplitN(value, ":", 2)
|
||||
|
||||
@@ -121,7 +121,7 @@ func (b *Basic) VerifyAuthToken(req *http.Request, w http.ResponseWriter, store
|
||||
store.GetData()["LoginMethod"] = ActionTokenMethodName
|
||||
return user_model.NewActionsUserWithTaskID(task.ID), nil
|
||||
}
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
// Verify extracts and validates Basic data (username and password/token) from the
|
||||
@@ -132,7 +132,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
|
||||
parseBasicRet := b.parseAuthBasic(req)
|
||||
authToken, uname, passwd := parseBasicRet.authToken, parseBasicRet.uname, parseBasicRet.passwd
|
||||
if authToken == "" && uname == "" {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
u, err := b.VerifyAuthToken(req, w, store, sess, authToken)
|
||||
if u != nil || err != nil {
|
||||
@@ -140,7 +140,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
|
||||
}
|
||||
|
||||
if !setting.Service.EnableBasicAuth {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
log.Trace("Basic Authorization: Attempting SignIn for %s", uname)
|
||||
|
||||
@@ -42,7 +42,7 @@ func (h *HTTPSign) Name() string {
|
||||
func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
|
||||
sigHead := req.Header.Get("Signature")
|
||||
if len(sigHead) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -53,14 +53,14 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt
|
||||
if len(req.Header.Get("X-Ssh-Certificate")) != 0 {
|
||||
// Handle Signature signed by SSH certificates
|
||||
if len(setting.SSH.TrustedUserCAKeys) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
publicKey, err = VerifyCert(req)
|
||||
if err != nil {
|
||||
log.Debug("VerifyCert on request from %s: failed: %v", req.RemoteAddr, err)
|
||||
log.Warn("Failed authentication attempt from %s", req.RemoteAddr)
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
} else {
|
||||
// Handle Signature signed by Public Key
|
||||
@@ -68,7 +68,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt
|
||||
if err != nil {
|
||||
log.Debug("VerifyPubKey on request from %s: failed: %v", req.RemoteAddr, err)
|
||||
log.Warn("Failed authentication attempt from %s", req.RemoteAddr)
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -156,12 +156,12 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor
|
||||
detector := newAuthPathDetector(req)
|
||||
if !detector.isAPIPath() && !detector.isAttachmentDownload() && !detector.isAuthenticatedTokenRequest() &&
|
||||
!detector.isGitRawOrAttachPath() && !detector.isArchivePath() {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
token, ok := parseToken(req)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
user, err := o.userFromToken(req.Context(), token, store)
|
||||
|
||||
@@ -51,7 +51,7 @@ func (r *ReverseProxy) Name() string {
|
||||
func (r *ReverseProxy) getUserFromAuthUser(req *http.Request) (*user_model.User, error) {
|
||||
username := r.getUserName(req)
|
||||
if len(username) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
log.Trace("ReverseProxy Authorization: Found username: %s", username)
|
||||
|
||||
@@ -111,7 +111,7 @@ func (r *ReverseProxy) Verify(req *http.Request, w http.ResponseWriter, store Da
|
||||
if user == nil {
|
||||
user = r.getUserFromAuthEmail(req)
|
||||
if user == nil {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,19 +29,19 @@ func (s *Session) Name() string {
|
||||
// Returns nil if there is no user uid stored in the session.
|
||||
func (s *Session) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
|
||||
if sess == nil {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
// Get user ID
|
||||
uid := sess.Get("uid")
|
||||
if uid == nil {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
log.Trace("Session Authorization: Found user[%d]", uid)
|
||||
|
||||
id, ok := uid.(int64)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
// Get user object
|
||||
@@ -52,7 +52,7 @@ func (s *Session) Verify(req *http.Request, w http.ResponseWriter, store DataSto
|
||||
// Return the err as-is to keep current signed-in session, in case the err is something like context.Canceled. Otherwise non-existing user (nil, nil) will make the caller clear the signed-in session.
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
log.Trace("Session Authorization: Logged in user %-v", user)
|
||||
|
||||
@@ -19,11 +19,11 @@ func (p *fakeProvider) Name() string {
|
||||
func (p *fakeProvider) SetName(name string) {}
|
||||
|
||||
func (p *fakeProvider) BeginAuth(state string) (goth.Session, error) {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
func (p *fakeProvider) UnmarshalSession(string) (goth.Session, error) {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
func (p *fakeProvider) FetchUser(goth.Session) (goth.User, error) {
|
||||
|
||||
@@ -63,7 +63,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
|
||||
return nil, sspiAuthErrInit
|
||||
}
|
||||
if !s.shouldAuthenticate(req) {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
cfg, err := s.getConfig(req.Context())
|
||||
@@ -97,7 +97,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
|
||||
|
||||
username := sanitizeUsername(userInfo.Username, cfg)
|
||||
if len(username) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
log.Info("Authenticated as %s\n", username)
|
||||
|
||||
@@ -109,7 +109,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
|
||||
}
|
||||
if !cfg.AutoCreateUsers {
|
||||
log.Error("User '%s' not found", username)
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
user, err = s.newUser(req.Context(), username, cfg)
|
||||
if err != nil {
|
||||
|
||||
@@ -235,8 +235,6 @@ func APIContexter() func(http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{NoTransform: true})
|
||||
ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
|
||||
|
||||
next.ServeHTTP(ctx.Resp, ctx.Req)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -196,7 +196,10 @@ func Contexter() func(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{NoTransform: true})
|
||||
ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
|
||||
|
||||
if setting.Security.XFrameOptions != "unset" {
|
||||
ctx.Resp.Header().Set(`X-Frame-Options`, setting.Security.XFrameOptions)
|
||||
}
|
||||
|
||||
ctx.Data["SystemConfig"] = setting.Config()
|
||||
|
||||
|
||||
@@ -95,8 +95,8 @@ func AddUploadContext(ctx *context.Context, uploadType string) {
|
||||
ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/releases/attachments/remove"
|
||||
ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/releases/attachments"
|
||||
ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Repository.Release.AllowedTypes, "|", ",")
|
||||
ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles
|
||||
ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize
|
||||
ctx.Data["UploadMaxFiles"] = setting.Repository.Release.MaxFiles
|
||||
ctx.Data["UploadMaxSize"] = setting.Repository.Release.FileMaxSize
|
||||
case "comment":
|
||||
ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/issues/attachments"
|
||||
ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/issues/attachments/remove"
|
||||
|
||||
@@ -192,7 +192,7 @@ func LoadGitRepo(t *testing.T, ctx gocontext.Context) {
|
||||
type MockRender struct{}
|
||||
|
||||
func (tr *MockRender) TemplateLookup(tmpl string, _ gocontext.Context) (templates.TemplateExecutor, error) {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // mock implementation returns nil to indicate no template found
|
||||
}
|
||||
|
||||
func (tr *MockRender) HTML(w io.Writer, status int, _ templates.TplName, _ any, _ gocontext.Context) error {
|
||||
|
||||
@@ -193,7 +193,7 @@ func createCsvDiff(diffFile *DiffFile, baseReader, headReader *csv.Reader) ([]*T
|
||||
}
|
||||
if aRow == nil && bRow == nil {
|
||||
// No content
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the row has no content
|
||||
}
|
||||
|
||||
aIndex := 0 // tracks where we are in the a2bColMap
|
||||
|
||||
@@ -234,7 +234,7 @@ func TeamReviewRequest(ctx context.Context, issue *issues_model.Issue, doer *use
|
||||
}
|
||||
|
||||
if comment == nil || !isAdd {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil because no comment was created or it is a removal
|
||||
}
|
||||
|
||||
return comment, teamReviewRequestNotify(ctx, issue, doer, reviewer, isAdd, comment)
|
||||
|
||||
@@ -113,7 +113,7 @@ func getIssueFromRef(ctx context.Context, repo *repo_model.Repository, index int
|
||||
issue, err := issues_model.GetIssueByIndex(ctx, repo.ID, index)
|
||||
if err != nil {
|
||||
if issues_model.IsErrIssueNotExist(err) {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ func AddAssigneeIfNotAssigned(ctx context.Context, issue *issues_model.Issue, do
|
||||
}
|
||||
if isAssigned {
|
||||
// nothing to do
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil because the user is already assigned
|
||||
}
|
||||
|
||||
valid, err := access_model.CanBeAssigned(ctx, assignee, issue.Repo, issue.IsPull)
|
||||
|
||||
@@ -149,30 +149,31 @@ func composeAndSendActionsWorkflowRunStatusEmail(ctx context.Context, repo *repo
|
||||
return nil
|
||||
}
|
||||
|
||||
func MailActionsTrigger(ctx context.Context, sender *user_model.User, repo *repo_model.Repository, run *actions_model.ActionRun) error {
|
||||
func MailActionsTrigger(ctx context.Context, recipient *user_model.User, repo *repo_model.Repository, run *actions_model.ActionRun) error {
|
||||
if setting.MailService == nil {
|
||||
return nil
|
||||
}
|
||||
if !run.Status.IsDone() || run.Status.IsSkipped() {
|
||||
return nil
|
||||
}
|
||||
|
||||
recipients := make([]*user_model.User, 0)
|
||||
|
||||
if !sender.IsGiteaActions() && !sender.IsGhost() && sender.IsMailable() {
|
||||
notifyPref, err := user_model.GetUserSetting(ctx, sender.ID,
|
||||
user_model.SettingsKeyEmailNotificationGiteaActions, user_model.SettingEmailNotificationGiteaActionsFailureOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if notifyPref == user_model.SettingEmailNotificationGiteaActionsAll || !run.Status.IsSuccess() && notifyPref != user_model.SettingEmailNotificationGiteaActionsDisabled {
|
||||
recipients = append(recipients, sender)
|
||||
}
|
||||
if !recipient.IsMailable() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(recipients) > 0 {
|
||||
log.Debug("MailActionsTrigger: Initiate email composition")
|
||||
return composeAndSendActionsWorkflowRunStatusEmail(ctx, repo, run, sender, recipients)
|
||||
notifyPref, err := user_model.GetUserSetting(ctx, recipient.ID,
|
||||
user_model.SettingsKeyEmailNotificationGiteaActions, user_model.SettingEmailNotificationGiteaActionsFailureOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
// "disabled" never sends
|
||||
if notifyPref == user_model.SettingEmailNotificationGiteaActionsDisabled {
|
||||
return nil
|
||||
}
|
||||
// "failure-only" skips non-failure runs
|
||||
if notifyPref != user_model.SettingEmailNotificationGiteaActionsAll && !run.Status.IsFailure() {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Debug("MailActionsTrigger: Initiate email composition")
|
||||
return composeAndSendActionsWorkflowRunStatusEmail(ctx, repo, run, recipient, []*user_model.User{recipient})
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestRenderHelperIssueIconTitle(t *testing.T) {
|
||||
IssueIndex: 1,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<a href="/link"><span>octicon-issue-opened(16/text green)</span> issue1 (#1)</a>`, string(htm))
|
||||
assert.Equal(t, `<a href="/link"><span>octicon-issue-opened(16/tw-text-green)</span> issue1 (#1)</a>`, string(htm))
|
||||
|
||||
ctx, _ = contexttest.MockContext(t, "/", contexttest.MockContextOption{Render: templates.PageRenderer()})
|
||||
htm, err = renderRepoIssueIconTitle(ctx, markup.RenderIssueIconTitleOptions{
|
||||
@@ -36,7 +36,7 @@ func TestRenderHelperIssueIconTitle(t *testing.T) {
|
||||
IssueIndex: 1,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<a href="/link"><span>octicon-issue-opened(16/text green)</span> issue1 (user2/repo1#1)</a>`, string(htm))
|
||||
assert.Equal(t, `<a href="/link"><span>octicon-issue-opened(16/tw-text-green)</span> issue1 (user2/repo1#1)</a>`, string(htm))
|
||||
|
||||
ctx, _ = contexttest.MockContext(t, "/", contexttest.MockContextOption{Render: templates.PageRenderer()})
|
||||
_, err = renderRepoIssueIconTitle(ctx, markup.RenderIssueIconTitleOptions{
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/migrations"
|
||||
notify_service "code.gitea.io/gitea/services/notify"
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
)
|
||||
@@ -172,7 +173,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*repo_module.SyncResu
|
||||
if m.LFS && setting.LFS.StartServer {
|
||||
log.Trace("SyncMirrors [repo: %-v]: syncing LFS objects...", m.Repo)
|
||||
endpoint := lfs.DetermineEndpoint(remoteURL.String(), m.LFSEndpoint)
|
||||
lfsClient := lfs.NewClient(endpoint, nil)
|
||||
lfsClient := lfs.NewClient(endpoint, migrations.NewMigrationHTTPTransport())
|
||||
if err = repo_module.StoreMissingLfsObjectsInRepository(ctx, m.Repo, gitRepo, lfsClient); err != nil {
|
||||
log.Error("SyncMirrors [repo: %-v]: failed to synchronize LFS objects for repository: %v", m.Repo.FullName(), err)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/migrations"
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
)
|
||||
|
||||
@@ -144,7 +145,7 @@ func runPushSync(ctx context.Context, m *repo_model.PushMirror) error {
|
||||
defer gitRepo.Close()
|
||||
|
||||
endpoint := lfs.DetermineEndpoint(remoteURL.String(), "")
|
||||
lfsClient := lfs.NewClient(endpoint, nil)
|
||||
lfsClient := lfs.NewClient(endpoint, migrations.NewMigrationHTTPTransport())
|
||||
if err := pushAllLFSObjects(ctx, gitRepo, lfsClient); err != nil {
|
||||
return util.SanitizeErrorCredentialURLs(err)
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func CreateAuthorizationToken(u *user_model.User, packageScope auth_model.Access
|
||||
func ParseAuthorizationRequest(req *http.Request) (*PackageMeta, error) {
|
||||
h := req.Header.Get("Authorization")
|
||||
if h == "" {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // the auth method is not applicable
|
||||
}
|
||||
|
||||
parts := strings.SplitN(h, " ", 2)
|
||||
|
||||
@@ -152,7 +152,7 @@ func BuildPackageIndex(ctx context.Context, p *packages_model.Package) (*bytes.B
|
||||
return nil, fmt.Errorf("SearchVersions[%s]: %w", p.Name, err)
|
||||
}
|
||||
if len(pvs) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the package has no versions
|
||||
}
|
||||
|
||||
pds, err := packages_model.GetPackageDescriptors(ctx, pvs)
|
||||
|
||||
@@ -291,7 +291,7 @@ func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Com
|
||||
if err := gitrepo.RunCmdWithStderr(ctx, pr.BaseRepo, cmd); err != nil {
|
||||
if gitcmd.IsErrorExitCode(err, 1) {
|
||||
// prHeadRef is not an ancestor of the base branch
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the PR head is not merged
|
||||
}
|
||||
// Errors are signaled by a non-zero status that is not 1
|
||||
return nil, fmt.Errorf("%-v git merge-base --is-ancestor: %w", pr, err)
|
||||
|
||||
+57
-23
@@ -6,11 +6,13 @@ package pull
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
)
|
||||
|
||||
// getCommitIDsFromRepo get commit IDs from repo in between oldCommitID and newCommitID
|
||||
@@ -49,39 +51,71 @@ func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldC
|
||||
// CreatePushPullComment create push code to pull base comment
|
||||
func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *issues_model.PullRequest, oldCommitID, newCommitID string, isForcePush bool) (comment *issues_model.Comment, err error) {
|
||||
if pr.HasMerged || oldCommitID == "" || newCommitID == "" {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil because no comment needs to be created
|
||||
}
|
||||
|
||||
opts := &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
IsForcePush: isForcePush,
|
||||
Issue: pr.Issue,
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
Issue: pr.Issue,
|
||||
}
|
||||
|
||||
var data issues_model.PushActionContent
|
||||
if opts.IsForcePush {
|
||||
data.CommitIDs = []string{oldCommitID, newCommitID}
|
||||
data.IsForcePush = true
|
||||
} else {
|
||||
data.CommitIDs, err = getCommitIDsFromRepo(ctx, pr.BaseRepo, oldCommitID, newCommitID, pr.BaseBranch)
|
||||
if err != nil {
|
||||
data.CommitIDs, err = getCommitIDsFromRepo(ctx, pr.BaseRepo, oldCommitID, newCommitID, pr.BaseBranch)
|
||||
if err != nil {
|
||||
// For force-push events, a missing/unreachable old commit should not prevent
|
||||
// deleting stale push comments or creating the force-push timeline entry.
|
||||
if !isForcePush {
|
||||
return nil, err
|
||||
}
|
||||
// It maybe an empty pull request. Only non-empty pull request need to create push comment
|
||||
if len(data.CommitIDs) == 0 {
|
||||
return nil, nil
|
||||
log.Error("getCommitIDsFromRepo: %v", err)
|
||||
}
|
||||
// It maybe an empty pull request. Only non-empty pull request need to create push comment
|
||||
// for force push, we always need to delete the old push comment so don't return here.
|
||||
if len(data.CommitIDs) == 0 && !isForcePush {
|
||||
return nil, nil //nolint:nilnil // return nil because no comment needs to be created
|
||||
}
|
||||
|
||||
return db.WithTx2(ctx, func(ctx context.Context) (*issues_model.Comment, error) {
|
||||
if isForcePush {
|
||||
// Push commits comment should not have history, cross references, reactions and other
|
||||
// plain comment related records, so that we just need to delete the comment itself.
|
||||
if _, err := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
|
||||
And("type = ?", issues_model.CommentTypePullRequestPush).
|
||||
NoAutoCondition().
|
||||
Delete(new(issues_model.Comment)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dataJSON, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data.CommitIDs) > 0 {
|
||||
dataJSON, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.Content = string(dataJSON)
|
||||
comment, err = issues_model.CreateComment(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
opts.Content = string(dataJSON)
|
||||
comment, err = issues_model.CreateComment(ctx, opts)
|
||||
if isForcePush { // if it's a force push, we need to add a force push comment
|
||||
data.CommitIDs = []string{oldCommitID, newCommitID}
|
||||
data.IsForcePush = true
|
||||
dataJSON, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts.Content = string(dataJSON)
|
||||
opts.IsForcePush = true // FIXME: it seems the field is unnecessary any more because PushActionContent includes IsForcePush field
|
||||
comment, err = issues_model.CreateComment(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return comment, err
|
||||
return comment, err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package pull
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCreatePushPullCommentForcePushDeletesOldComments(t *testing.T) {
|
||||
t.Run("base-branch-only", func(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
|
||||
assert.NoError(t, pr.LoadIssue(t.Context()))
|
||||
assert.NoError(t, pr.LoadBaseRepo(t.Context()))
|
||||
|
||||
pusher := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
|
||||
_, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
Issue: pr.Issue,
|
||||
Content: "{}",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
_, err = issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
Issue: pr.Issue,
|
||||
Content: "{}",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
comments, err := issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{
|
||||
IssueID: pr.IssueID,
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, comments, 2)
|
||||
|
||||
gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo)
|
||||
assert.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
headCommit, err := gitRepo.GetBranchCommit(pr.BaseBranch)
|
||||
assert.NoError(t, err)
|
||||
oldCommit := headCommit
|
||||
if headCommit.ParentCount() > 0 {
|
||||
parentCommit, err := headCommit.Parent(0)
|
||||
assert.NoError(t, err)
|
||||
oldCommit = parentCommit
|
||||
}
|
||||
|
||||
comment, err := CreatePushPullComment(t.Context(), pusher, pr, oldCommit.ID.String(), headCommit.ID.String(), true)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, comment)
|
||||
var createdData issues_model.PushActionContent
|
||||
assert.NoError(t, json.Unmarshal([]byte(comment.Content), &createdData))
|
||||
assert.True(t, createdData.IsForcePush)
|
||||
|
||||
// When both commits are on the base branch, CommitsBetweenNotBase should
|
||||
// typically return no commits, so only the force-push comment is expected.
|
||||
commits, err := gitRepo.CommitsBetweenNotBase(headCommit, oldCommit, pr.BaseBranch)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, commits)
|
||||
|
||||
comments, err = issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{
|
||||
IssueID: pr.IssueID,
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, comments, 1)
|
||||
|
||||
forcePushCount := 0
|
||||
for _, comment := range comments {
|
||||
var pushData issues_model.PushActionContent
|
||||
assert.NoError(t, json.Unmarshal([]byte(comment.Content), &pushData))
|
||||
if pushData.IsForcePush {
|
||||
forcePushCount++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, forcePushCount)
|
||||
})
|
||||
|
||||
t.Run("head-vs-base-branch", func(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
|
||||
assert.NoError(t, pr.LoadIssue(t.Context()))
|
||||
assert.NoError(t, pr.LoadBaseRepo(t.Context()))
|
||||
|
||||
pusher := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
|
||||
_, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
Issue: pr.Issue,
|
||||
Content: "{}",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
_, err = issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
Doer: pusher,
|
||||
Repo: pr.BaseRepo,
|
||||
Issue: pr.Issue,
|
||||
Content: "{}",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
comments, err := issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{
|
||||
IssueID: pr.IssueID,
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, comments, 2)
|
||||
|
||||
gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo)
|
||||
assert.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
// In this subtest, use the head branch for the new commit and the base branch
|
||||
// for the old commit so that CommitsBetweenNotBase returns non-empty results.
|
||||
headCommit, err := gitRepo.GetBranchCommit(pr.HeadBranch)
|
||||
assert.NoError(t, err)
|
||||
|
||||
baseCommit, err := gitRepo.GetBranchCommit(pr.BaseBranch)
|
||||
assert.NoError(t, err)
|
||||
oldCommit := baseCommit
|
||||
|
||||
comment, err := CreatePushPullComment(t.Context(), pusher, pr, oldCommit.ID.String(), headCommit.ID.String(), true)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, comment)
|
||||
var createdData issues_model.PushActionContent
|
||||
assert.NoError(t, json.Unmarshal([]byte(comment.Content), &createdData))
|
||||
assert.True(t, createdData.IsForcePush)
|
||||
|
||||
commits, err := gitRepo.CommitsBetweenNotBase(headCommit, oldCommit, pr.BaseBranch)
|
||||
assert.NoError(t, err)
|
||||
// For this scenario we expect at least one commit between head and base
|
||||
// that is not on the base branch, so data.CommitIDs should be non-empty.
|
||||
assert.NotEmpty(t, commits)
|
||||
|
||||
comments, err = issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{
|
||||
IssueID: pr.IssueID,
|
||||
Type: issues_model.CommentTypePullRequestPush,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
// Two comments should exist now: one regular push comment and one force-push comment.
|
||||
assert.Len(t, comments, 2)
|
||||
|
||||
forcePushCount := 0
|
||||
for _, comment := range comments {
|
||||
var pushData issues_model.PushActionContent
|
||||
assert.NoError(t, json.Unmarshal([]byte(comment.Content), &pushData))
|
||||
if pushData.IsForcePush {
|
||||
forcePushCount++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, forcePushCount)
|
||||
})
|
||||
}
|
||||
@@ -465,7 +465,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string,
|
||||
}
|
||||
|
||||
if !isDismiss {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil because this is not a dismiss action
|
||||
}
|
||||
|
||||
if err := review.Issue.LoadAttributes(ctx); err != nil {
|
||||
|
||||
@@ -156,7 +156,7 @@ func doArchive(ctx context.Context, r *ArchiveRequest) (*repo_model.RepoArchiver
|
||||
// FIXME: If another process are generating it, we think it's not ready and just return
|
||||
// Or we should wait until the archive generated.
|
||||
if archiver.Status == repo_model.ArchiverGenerating {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil because the archive is still being generated
|
||||
}
|
||||
} else {
|
||||
archiver = &repo_model.RepoArchiver{
|
||||
|
||||
@@ -510,7 +510,7 @@ func modifyFile(ctx context.Context, t *TemporaryUploadRepository, file *ChangeR
|
||||
}
|
||||
|
||||
if writeObjectRet.LfsContent == nil {
|
||||
return nil, nil // No LFS pointer, so nothing to do
|
||||
return nil, nil //nolint:nilnil // No LFS pointer, so nothing to do
|
||||
}
|
||||
defer writeObjectRet.LfsContent.Close()
|
||||
|
||||
|
||||
@@ -16,10 +16,14 @@ import (
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
type themeCollection struct {
|
||||
themeList []*ThemeMetaInfo
|
||||
themeMap map[string]*ThemeMetaInfo
|
||||
}
|
||||
|
||||
var (
|
||||
availableThemes []*ThemeMetaInfo
|
||||
availableThemeMap map[string]*ThemeMetaInfo
|
||||
themeOnce sync.Once
|
||||
themeMu sync.RWMutex
|
||||
availableThemes *themeCollection
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -129,23 +133,13 @@ func parseThemeMetaInfo(fileName, cssContent string) *ThemeMetaInfo {
|
||||
return themeInfo
|
||||
}
|
||||
|
||||
func initThemes() {
|
||||
availableThemes = nil
|
||||
defer func() {
|
||||
availableThemeMap = map[string]*ThemeMetaInfo{}
|
||||
for _, theme := range availableThemes {
|
||||
availableThemeMap[theme.InternalName] = theme
|
||||
}
|
||||
if availableThemeMap[setting.UI.DefaultTheme] == nil {
|
||||
setting.LogStartupProblem(1, log.ERROR, "Default theme %q is not available, please correct the '[ui].DEFAULT_THEME' setting in the config file", setting.UI.DefaultTheme)
|
||||
}
|
||||
}()
|
||||
func loadThemesFromAssets() (themeList []*ThemeMetaInfo, themeMap map[string]*ThemeMetaInfo) {
|
||||
cssFiles, err := public.AssetFS().ListFiles("assets/css")
|
||||
if err != nil {
|
||||
log.Error("Failed to list themes: %v", err)
|
||||
availableThemes = []*ThemeMetaInfo{defaultThemeMetaInfoByInternalName(setting.UI.DefaultTheme)}
|
||||
return
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var foundThemes []*ThemeMetaInfo
|
||||
for _, fileName := range cssFiles {
|
||||
if strings.HasPrefix(fileName, fileNamePrefix) && strings.HasSuffix(fileName, fileNameSuffix) {
|
||||
@@ -157,39 +151,84 @@ func initThemes() {
|
||||
foundThemes = append(foundThemes, parseThemeMetaInfo(fileName, util.UnsafeBytesToString(content)))
|
||||
}
|
||||
}
|
||||
|
||||
themeList = foundThemes
|
||||
if len(setting.UI.Themes) > 0 {
|
||||
themeList = nil // only allow the themes specified in the setting
|
||||
allowedThemes := container.SetOf(setting.UI.Themes...)
|
||||
for _, theme := range foundThemes {
|
||||
if allowedThemes.Contains(theme.InternalName) {
|
||||
availableThemes = append(availableThemes, theme)
|
||||
themeList = append(themeList, theme)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
availableThemes = foundThemes
|
||||
}
|
||||
sort.Slice(availableThemes, func(i, j int) bool {
|
||||
if availableThemes[i].InternalName == setting.UI.DefaultTheme {
|
||||
|
||||
sort.Slice(themeList, func(i, j int) bool {
|
||||
if themeList[i].InternalName == setting.UI.DefaultTheme {
|
||||
return true
|
||||
}
|
||||
if availableThemes[i].ColorblindType != availableThemes[j].ColorblindType {
|
||||
return availableThemes[i].ColorblindType < availableThemes[j].ColorblindType
|
||||
if themeList[i].ColorblindType != themeList[j].ColorblindType {
|
||||
return themeList[i].ColorblindType < themeList[j].ColorblindType
|
||||
}
|
||||
return availableThemes[i].DisplayName < availableThemes[j].DisplayName
|
||||
return themeList[i].DisplayName < themeList[j].DisplayName
|
||||
})
|
||||
if len(availableThemes) == 0 {
|
||||
setting.LogStartupProblem(1, log.ERROR, "No theme candidate in asset files, but Gitea requires there should be at least one usable theme")
|
||||
availableThemes = []*ThemeMetaInfo{defaultThemeMetaInfoByInternalName(setting.UI.DefaultTheme)}
|
||||
|
||||
themeMap = map[string]*ThemeMetaInfo{}
|
||||
for _, theme := range themeList {
|
||||
themeMap[theme.InternalName] = theme
|
||||
}
|
||||
return themeList, themeMap
|
||||
}
|
||||
|
||||
func getAvailableThemes() (themeList []*ThemeMetaInfo, themeMap map[string]*ThemeMetaInfo) {
|
||||
themeMu.RLock()
|
||||
if availableThemes != nil {
|
||||
themeList, themeMap = availableThemes.themeList, availableThemes.themeMap
|
||||
}
|
||||
themeMu.RUnlock()
|
||||
if len(themeList) != 0 {
|
||||
return themeList, themeMap
|
||||
}
|
||||
|
||||
themeMu.Lock()
|
||||
defer themeMu.Unlock()
|
||||
// no need to double-check "availableThemes.themeList" since the loading isn't really slow, to keep code simple
|
||||
themeList, themeMap = loadThemesFromAssets()
|
||||
hasAvailableThemes := len(themeList) > 0
|
||||
if !hasAvailableThemes {
|
||||
defaultTheme := defaultThemeMetaInfoByInternalName(setting.UI.DefaultTheme)
|
||||
themeList = []*ThemeMetaInfo{defaultTheme}
|
||||
themeMap = map[string]*ThemeMetaInfo{setting.UI.DefaultTheme: defaultTheme}
|
||||
}
|
||||
|
||||
if setting.IsProd {
|
||||
if !hasAvailableThemes {
|
||||
setting.LogStartupProblem(1, log.ERROR, "No theme candidate in asset files, but Gitea requires there should be at least one usable theme")
|
||||
}
|
||||
if themeMap[setting.UI.DefaultTheme] == nil {
|
||||
setting.LogStartupProblem(1, log.ERROR, "Default theme %q is not available, please correct the '[ui].DEFAULT_THEME' setting in the config file", setting.UI.DefaultTheme)
|
||||
}
|
||||
availableThemes = &themeCollection{themeList, themeMap}
|
||||
return themeList, themeMap
|
||||
}
|
||||
|
||||
// In dev mode, only store the loaded themes if the list is not empty, in case the frontend is still being built.
|
||||
// TBH, there still could be a data-race that the themes are only partially built then the list is incomplete for first time loading.
|
||||
// Such edge case can be handled by checking whether the loaded themes are the same in a period or there is a flag file, but it is an over-kill, so, no.
|
||||
if hasAvailableThemes {
|
||||
availableThemes = &themeCollection{themeList, themeMap}
|
||||
}
|
||||
return themeList, themeMap
|
||||
}
|
||||
|
||||
func GetAvailableThemes() []*ThemeMetaInfo {
|
||||
themeOnce.Do(initThemes)
|
||||
return availableThemes
|
||||
themes, _ := getAvailableThemes()
|
||||
return themes
|
||||
}
|
||||
|
||||
func GetThemeMetaInfo(internalName string) *ThemeMetaInfo {
|
||||
themeOnce.Do(initThemes)
|
||||
return availableThemeMap[internalName]
|
||||
_, themeMap := getAvailableThemes()
|
||||
return themeMap[internalName]
|
||||
}
|
||||
|
||||
// GuaranteeGetThemeMetaInfo guarantees to return a non-nil ThemeMetaInfo,
|
||||
|
||||
Reference in New Issue
Block a user