enable staticcheck QFxxxx rules (#34064)

This commit is contained in:
TheFox0x7
2025-03-29 22:32:28 +01:00
committed by GitHub
parent 5564c39105
commit 2a59dfbd47
47 changed files with 179 additions and 143 deletions

View File

@ -86,13 +86,8 @@ linters:
- -ST1003 - -ST1003
- -ST1005 - -ST1005
- -QF1001 - -QF1001
- -QF1002
- -QF1003
- -QF1006 - -QF1006
- -QF1007
- -QF1008 - -QF1008
- -QF1009
- -QF1012
testifylint: testifylint:
disable: disable:
- go-require - go-require

View File

@ -144,11 +144,12 @@ func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr) setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
logFile := ctx.String("log-file") logFile := ctx.String("log-file")
if logFile == "" { switch logFile {
case "":
return // if no doctor log-file is set, do not show any log from default logger return // if no doctor log-file is set, do not show any log from default logger
} else if logFile == "-" { case "-":
setupConsoleLogger(log.TRACE, colorize, os.Stdout) setupConsoleLogger(log.TRACE, colorize, os.Stdout)
} else { default:
logFile, _ = filepath.Abs(logFile) logFile, _ = filepath.Abs(logFile)
writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}} writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
writer, err := log.NewEventWriter("console-to-file", "file", writeMode) writer, err := log.NewEventWriter("console-to-file", "file", writeMode)

View File

@ -86,9 +86,10 @@ func (r *ActionRunner) BelongsToOwnerType() types.OwnerType {
return types.OwnerTypeRepository return types.OwnerTypeRepository
} }
if r.OwnerID != 0 { if r.OwnerID != 0 {
if r.Owner.Type == user_model.UserTypeOrganization { switch r.Owner.Type {
case user_model.UserTypeOrganization:
return types.OwnerTypeOrganization return types.OwnerTypeOrganization
} else if r.Owner.Type == user_model.UserTypeIndividual { case user_model.UserTypeIndividual:
return types.OwnerTypeIndividual return types.OwnerTypeIndividual
} }
} }

View File

@ -42,9 +42,10 @@ func newXORMEngine() (*xorm.Engine, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if setting.Database.Type == "mysql" { switch setting.Database.Type {
case "mysql":
engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"}) engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
} else if setting.Database.Type == "mssql" { case "mssql":
engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"}) engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
} }
engine.SetSchema(setting.Database.Schema) engine.SetSchema(setting.Database.Schema)

View File

@ -425,32 +425,33 @@ func (repo *Repository) MustGetUnit(ctx context.Context, tp unit.Type) *RepoUnit
return ru return ru
} }
if tp == unit.TypeExternalWiki { switch tp {
case unit.TypeExternalWiki:
return &RepoUnit{ return &RepoUnit{
Type: tp, Type: tp,
Config: new(ExternalWikiConfig), Config: new(ExternalWikiConfig),
} }
} else if tp == unit.TypeExternalTracker { case unit.TypeExternalTracker:
return &RepoUnit{ return &RepoUnit{
Type: tp, Type: tp,
Config: new(ExternalTrackerConfig), Config: new(ExternalTrackerConfig),
} }
} else if tp == unit.TypePullRequests { case unit.TypePullRequests:
return &RepoUnit{ return &RepoUnit{
Type: tp, Type: tp,
Config: new(PullRequestsConfig), Config: new(PullRequestsConfig),
} }
} else if tp == unit.TypeIssues { case unit.TypeIssues:
return &RepoUnit{ return &RepoUnit{
Type: tp, Type: tp,
Config: new(IssuesConfig), Config: new(IssuesConfig),
} }
} else if tp == unit.TypeActions { case unit.TypeActions:
return &RepoUnit{ return &RepoUnit{
Type: tp, Type: tp,
Config: new(ActionsConfig), Config: new(ActionsConfig),
} }
} else if tp == unit.TypeProjects { case unit.TypeProjects:
cfg := new(ProjectsConfig) cfg := new(ProjectsConfig)
cfg.ProjectsMode = ProjectsModeNone cfg.ProjectsMode = ProjectsModeNone
return &RepoUnit{ return &RepoUnit{

View File

@ -28,7 +28,7 @@ func SyncFile(srcPath, destPath string) error {
} }
if src.Size() == dest.Size() && if src.Size() == dest.Size() &&
src.ModTime() == dest.ModTime() && src.ModTime().Equal(dest.ModTime()) &&
src.Mode() == dest.Mode() { src.Mode() == dest.Mode() {
return nil return nil
} }

View File

@ -45,13 +45,14 @@ func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Sess
var cond builder.Cond var cond builder.Cond
cond = builder.Eq{"type": opts.Type} cond = builder.Eq{"type": opts.Type}
if opts.IncludeReserved { if opts.IncludeReserved {
if opts.Type == UserTypeIndividual { switch opts.Type {
case UserTypeIndividual:
cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or( cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or(
builder.Eq{"type": UserTypeBot}, builder.Eq{"type": UserTypeBot},
).Or( ).Or(
builder.Eq{"type": UserTypeRemoteUser}, builder.Eq{"type": UserTypeRemoteUser},
) )
} else if opts.Type == UserTypeOrganization { case UserTypeOrganization:
cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved}) cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved})
} }
} }

View File

@ -198,7 +198,8 @@ func MarkTaskDelivered(ctx context.Context, task *HookTask) (bool, error) {
func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error { func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error {
log.Trace("Doing: CleanupHookTaskTable") log.Trace("Doing: CleanupHookTaskTable")
if cleanupType == OlderThan { switch cleanupType {
case OlderThan:
deleteOlderThan := time.Now().Add(-olderThan).UnixNano() deleteOlderThan := time.Now().Add(-olderThan).UnixNano()
deletes, err := db.GetEngine(ctx). deletes, err := db.GetEngine(ctx).
Where("is_delivered = ? and delivered < ?", true, deleteOlderThan). Where("is_delivered = ? and delivered < ?", true, deleteOlderThan).
@ -207,7 +208,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType,
return err return err
} }
log.Trace("Deleted %d rows from hook_task", deletes) log.Trace("Deleted %d rows from hook_task", deletes)
} else if cleanupType == PerWebhook { case PerWebhook:
hookIDs := make([]int64, 0, 10) hookIDs := make([]int64, 0, 10)
err := db.GetEngine(ctx). err := db.GetEngine(ctx).
Table("webhook"). Table("webhook").

View File

@ -62,13 +62,14 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
var results []*GrepResult var results []*GrepResult
cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name") cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber)) cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber))
if opts.GrepMode == GrepModeExact { switch opts.GrepMode {
case GrepModeExact:
cmd.AddArguments("--fixed-strings") cmd.AddArguments("--fixed-strings")
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-")) cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
} else if opts.GrepMode == GrepModeRegexp { case GrepModeRegexp:
cmd.AddArguments("--perl-regexp") cmd.AddArguments("--perl-regexp")
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-")) cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
} else /* words */ { default: /* words */
words := strings.Fields(search) words := strings.Fields(search)
cmd.AddArguments("--fixed-strings", "--ignore-case") cmd.AddArguments("--fixed-strings", "--ignore-case")
for i, word := range words { for i, word := range words {

View File

@ -118,11 +118,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
g.buffull = false g.buffull = false
g.next, err = g.rd.ReadSlice('\x00') g.next, err = g.rd.ReadSlice('\x00')
if err != nil { if err != nil {
if err == bufio.ErrBufferFull { switch err {
case bufio.ErrBufferFull:
g.buffull = true g.buffull = true
} else if err == io.EOF { case io.EOF:
return nil, nil return nil, nil
} else { default:
return nil, err return nil, err
} }
} }
@ -132,11 +133,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
if bytes.Equal(g.next, []byte("commit\000")) { if bytes.Equal(g.next, []byte("commit\000")) {
g.next, err = g.rd.ReadSlice('\x00') g.next, err = g.rd.ReadSlice('\x00')
if err != nil { if err != nil {
if err == bufio.ErrBufferFull { switch err {
case bufio.ErrBufferFull:
g.buffull = true g.buffull = true
} else if err == io.EOF { case io.EOF:
return nil, nil return nil, nil
} else { default:
return nil, err return nil, err
} }
} }
@ -214,11 +216,12 @@ diffloop:
} }
g.next, err = g.rd.ReadSlice('\x00') g.next, err = g.rd.ReadSlice('\x00')
if err != nil { if err != nil {
if err == bufio.ErrBufferFull { switch err {
case bufio.ErrBufferFull:
g.buffull = true g.buffull = true
} else if err == io.EOF { case io.EOF:
return &ret, nil return &ret, nil
} else { default:
return nil, err return nil, err
} }
} }

View File

@ -19,11 +19,12 @@ func (repo *Repository) GetRefs() ([]*Reference, error) {
// refType should only be a literal "branch" or "tag" and nothing else // refType should only be a literal "branch" or "tag" and nothing else
func (repo *Repository) ListOccurrences(ctx context.Context, refType, commitSHA string) ([]string, error) { func (repo *Repository) ListOccurrences(ctx context.Context, refType, commitSHA string) ([]string, error) {
cmd := NewCommand() cmd := NewCommand()
if refType == "branch" { switch refType {
case "branch":
cmd.AddArguments("branch") cmd.AddArguments("branch")
} else if refType == "tag" { case "tag":
cmd.AddArguments("tag") cmd.AddArguments("tag")
} else { default:
return nil, util.NewInvalidArgumentErrorf(`can only use "branch" or "tag" for refType, but got %q`, refType) return nil, util.NewInvalidArgumentErrorf(`can only use "branch" or "tag" for refType, but got %q`, refType)
} }
stdout, _, err := cmd.AddArguments("--no-color", "--sort=-creatordate", "--contains").AddDynamicArguments(commitSHA).RunStdString(ctx, &RunOpts{Dir: repo.Path}) stdout, _, err := cmd.AddArguments("--no-color", "--sort=-creatordate", "--contains").AddDynamicArguments(commitSHA).RunStdString(ctx, &RunOpts{Dir: repo.Path})

View File

@ -133,12 +133,13 @@ func ParseRepositoryURL(ctx context.Context, repoURL string) (*RepositoryURL, er
} }
} }
if parsed.URL.Scheme == "http" || parsed.URL.Scheme == "https" { switch parsed.URL.Scheme {
case "http", "https":
if !httplib.IsCurrentGiteaSiteURL(ctx, repoURL) { if !httplib.IsCurrentGiteaSiteURL(ctx, repoURL) {
return ret, nil return ret, nil
} }
fillPathParts(strings.TrimPrefix(parsed.URL.Path, setting.AppSubURL)) fillPathParts(strings.TrimPrefix(parsed.URL.Path, setting.AppSubURL))
} else if parsed.URL.Scheme == "ssh" || parsed.URL.Scheme == "git+ssh" { case "ssh", "git+ssh":
domainSSH := setting.SSH.Domain domainSSH := setting.SSH.Domain
domainCur := httplib.GuessCurrentHostDomain(ctx) domainCur := httplib.GuessCurrentHostDomain(ctx)
urlDomain, _, _ := net.SplitHostPort(parsed.URL.Host) urlDomain, _, _ := net.SplitHostPort(parsed.URL.Host)
@ -166,9 +167,10 @@ func MakeRepositoryWebLink(repoURL *RepositoryURL) string {
// now, let's guess, for example: // now, let's guess, for example:
// * git@github.com:owner/submodule.git // * git@github.com:owner/submodule.git
// * https://github.com/example/submodule1.git // * https://github.com/example/submodule1.git
if repoURL.GitURL.Scheme == "http" || repoURL.GitURL.Scheme == "https" { switch repoURL.GitURL.Scheme {
case "http", "https":
return strings.TrimSuffix(repoURL.GitURL.String(), ".git") return strings.TrimSuffix(repoURL.GitURL.String(), ".git")
} else if repoURL.GitURL.Scheme == "ssh" || repoURL.GitURL.Scheme == "git+ssh" { case "ssh", "git+ssh":
hostname, _, _ := net.SplitHostPort(repoURL.GitURL.Host) hostname, _, _ := net.SplitHostPort(repoURL.GitURL.Host)
hostname = util.IfZero(hostname, repoURL.GitURL.Host) hostname = util.IfZero(hostname, repoURL.GitURL.Host)
urlPath := strings.TrimSuffix(repoURL.GitURL.Path, ".git") urlPath := strings.TrimSuffix(repoURL.GitURL.Path, ".git")

View File

@ -40,7 +40,7 @@ func (t *traceBuiltinSpan) toString(out *strings.Builder, indent int) {
if t.ts.endTime.IsZero() { if t.ts.endTime.IsZero() {
out.WriteString(" duration: (not ended)") out.WriteString(" duration: (not ended)")
} else { } else {
out.WriteString(fmt.Sprintf(" duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds())) fmt.Fprintf(out, " duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds())
} }
for _, a := range t.ts.attributes { for _, a := range t.ts.attributes {
out.WriteString(" ") out.WriteString(" ")

View File

@ -26,9 +26,10 @@ func indexSettingToGitGrepPathspecList() (list []string) {
func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int, err error) { func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int, err error) {
grepMode := git.GrepModeWords grepMode := git.GrepModeWords
if searchMode == indexer.SearchModeExact { switch searchMode {
case indexer.SearchModeExact:
grepMode = git.GrepModeExact grepMode = git.GrepModeExact
} else if searchMode == indexer.SearchModeRegexp { case indexer.SearchModeRegexp:
grepMode = git.GrepModeRegexp grepMode = git.GrepModeRegexp
} }
res, err := git.GrepSearch(ctx, gitRepo, keyword, git.GrepOptions{ res, err := git.GrepSearch(ctx, gitRepo, keyword, git.GrepOptions{

View File

@ -105,7 +105,7 @@ func (b *EventWriterBaseImpl) Run(ctx context.Context) {
case io.WriterTo: case io.WriterTo:
_, err = msg.WriteTo(b.OutputWriteCloser) _, err = msg.WriteTo(b.OutputWriteCloser)
default: default:
_, err = b.OutputWriteCloser.Write([]byte(fmt.Sprint(msg))) _, err = fmt.Fprint(b.OutputWriteCloser, msg)
} }
if err != nil { if err != nil {
FallbackErrorf("unable to write log message of %q (%v): %v", b.Name, err, event.Msg) FallbackErrorf("unable to write log message of %q (%v): %v", b.Name, err, event.Msg)

View File

@ -85,9 +85,10 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont
} else if lastChar == ')' { } else if lastChar == ')' {
closing := 0 closing := 0
for i := m[1] - 1; i >= m[0]; i-- { for i := m[1] - 1; i >= m[0]; i-- {
if line[i] == ')' { switch line[i] {
case ')':
closing++ closing++
} else if line[i] == '(' { case '(':
closing-- closing--
} }
} }

View File

@ -80,9 +80,10 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
// many places render non-comment contents with no mode=document, then these contents also use comment's hard line break setting // many places render non-comment contents with no mode=document, then these contents also use comment's hard line break setting
// especially in many tests. // especially in many tests.
markdownLineBreakStyle := ctx.RenderOptions.Metas["markdownLineBreakStyle"] markdownLineBreakStyle := ctx.RenderOptions.Metas["markdownLineBreakStyle"]
if markdownLineBreakStyle == "comment" { switch markdownLineBreakStyle {
case "comment":
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments) v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)
} else if markdownLineBreakStyle == "document" { case "document":
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments) v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)
} }
} }
@ -155,7 +156,7 @@ func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.
if entering { if entering {
_, err = w.WriteString("<div") _, err = w.WriteString("<div")
if err == nil { if err == nil {
_, err = w.WriteString(fmt.Sprintf(` lang=%q`, val)) _, err = fmt.Fprintf(w, ` lang=%q`, val)
} }
if err == nil { if err == nil {
_, err = w.WriteRune('>') _, err = w.WriteRune('>')

View File

@ -70,10 +70,11 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
startMarkLen = 1 startMarkLen = 1
stopMark = parser.endBytesSingleDollar stopMark = parser.endBytesSingleDollar
if len(line) > 1 { if len(line) > 1 {
if line[1] == '$' { switch line[1] {
case '$':
startMarkLen = 2 startMarkLen = 2
stopMark = parser.endBytesDoubleDollar stopMark = parser.endBytesDoubleDollar
} else if line[1] == '`' { case '`':
pos := 1 pos := 1
for ; pos < len(line) && line[pos] == '`'; pos++ { for ; pos < len(line) && line[pos] == '`'; pos++ {
} }
@ -121,9 +122,10 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
i++ i++
continue continue
} }
if line[i] == '{' { switch line[i] {
case '{':
depth++ depth++
} else if line[i] == '}' { case '}':
depth-- depth--
} }
} }

View File

@ -107,11 +107,12 @@ func (r *stripRenderer) processAutoLink(w io.Writer, link []byte) {
} }
var sep string var sep string
if parts[3] == "issues" { switch parts[3] {
case "issues":
sep = "#" sep = "#"
} else if parts[3] == "pulls" { case "pulls":
sep = "!" sep = "!"
} else { default:
// Process out of band // Process out of band
r.links = append(r.links, linkStr) r.links = append(r.links, linkStr)
return return

View File

@ -462,11 +462,12 @@ func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference
continue continue
} }
var sep string var sep string
if parts[3] == "issues" { switch parts[3] {
case "issues":
sep = "#" sep = "#"
} else if parts[3] == "pulls" { case "pulls":
sep = "!" sep = "!"
} else { default:
continue continue
} }
// Note: closing/reopening keywords not supported with URLs // Note: closing/reopening keywords not supported with URLs

View File

@ -210,8 +210,8 @@ func getStorageTargetSection(rootCfg ConfigProvider, name, typ string, sec Confi
targetSec, _ := rootCfg.GetSection(storageSectionName + "." + name) targetSec, _ := rootCfg.GetSection(storageSectionName + "." + name)
if targetSec != nil { if targetSec != nil {
targetType := targetSec.Key("STORAGE_TYPE").String() targetType := targetSec.Key("STORAGE_TYPE").String()
switch { switch targetType {
case targetType == "": case "":
if targetSec.Key("PATH").String() == "" { // both storage type and path are empty, use default if targetSec.Key("PATH").String() == "" { // both storage type and path are empty, use default
return getDefaultStorageSection(rootCfg), targetSecIsDefault, nil return getDefaultStorageSection(rootCfg), targetSecIsDefault, nil
} }

View File

@ -86,13 +86,14 @@ func NewMinioStorage(ctx context.Context, cfg *setting.Storage) (ObjectStorage,
log.Info("Creating Minio storage at %s:%s with base path %s", config.Endpoint, config.Bucket, config.BasePath) log.Info("Creating Minio storage at %s:%s with base path %s", config.Endpoint, config.Bucket, config.BasePath)
var lookup minio.BucketLookupType var lookup minio.BucketLookupType
if config.BucketLookUpType == "auto" || config.BucketLookUpType == "" { switch config.BucketLookUpType {
case "auto", "":
lookup = minio.BucketLookupAuto lookup = minio.BucketLookupAuto
} else if config.BucketLookUpType == "dns" { case "dns":
lookup = minio.BucketLookupDNS lookup = minio.BucketLookupDNS
} else if config.BucketLookUpType == "path" { case "path":
lookup = minio.BucketLookupPath lookup = minio.BucketLookupPath
} else { default:
return nil, fmt.Errorf("invalid minio bucket lookup type: %s", config.BucketLookUpType) return nil, fmt.Errorf("invalid minio bucket lookup type: %s", config.BucketLookUpType)
} }

View File

@ -38,10 +38,11 @@ func sortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML
} else { } else {
// if sort arg is in url test if it correlates with column header sort arguments // if sort arg is in url test if it correlates with column header sort arguments
// the direction of the arrow should indicate the "current sort order", up means ASC(normal), down means DESC(rev) // the direction of the arrow should indicate the "current sort order", up means ASC(normal), down means DESC(rev)
if urlSort == normSort { switch urlSort {
case normSort:
// the table is sorted with this header normal // the table is sorted with this header normal
return svg.RenderHTML("octicon-triangle-up", 16) return svg.RenderHTML("octicon-triangle-up", 16)
} else if urlSort == revSort { case revSort:
// the table is sorted with this header reverse // the table is sorted with this header reverse
return svg.RenderHTML("octicon-triangle-down", 16) return svg.RenderHTML("octicon-triangle-down", 16)
} }

View File

@ -36,9 +36,10 @@ func PathJoinRel(elem ...string) string {
elems[i] = path.Clean("/" + e) elems[i] = path.Clean("/" + e)
} }
p := path.Join(elems...) p := path.Join(elems...)
if p == "" { switch p {
case "":
return "" return ""
} else if p == "/" { case "/":
return "." return "."
} }
return p[1:] return p[1:]

View File

@ -162,8 +162,8 @@ func (r artifactV4Routes) buildSignature(endp, expires, artifactName string, tas
mac.Write([]byte(endp)) mac.Write([]byte(endp))
mac.Write([]byte(expires)) mac.Write([]byte(expires))
mac.Write([]byte(artifactName)) mac.Write([]byte(artifactName))
mac.Write([]byte(fmt.Sprint(taskID))) fmt.Fprint(mac, taskID)
mac.Write([]byte(fmt.Sprint(artifactID))) fmt.Fprint(mac, artifactID)
return mac.Sum(nil) return mac.Sum(nil)
} }

View File

@ -46,13 +46,14 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.Context) {
if ok { // it's a personal access token but not oauth2 token if ok { // it's a personal access token but not oauth2 token
scopeMatched := false scopeMatched := false
var err error var err error
if accessMode == perm.AccessModeRead { switch accessMode {
case perm.AccessModeRead:
scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeReadPackage) scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeReadPackage)
if err != nil { if err != nil {
ctx.HTTPError(http.StatusInternalServerError, "HasScope", err.Error()) ctx.HTTPError(http.StatusInternalServerError, "HasScope", err.Error())
return return
} }
} else if accessMode == perm.AccessModeWrite { case perm.AccessModeWrite:
scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeWritePackage) scopeMatched, err = scope.HasScope(auth_model.AccessTokenScopeWritePackage)
if err != nil { if err != nil {
ctx.HTTPError(http.StatusInternalServerError, "HasScope", err.Error()) ctx.HTTPError(http.StatusInternalServerError, "HasScope", err.Error())
@ -703,13 +704,14 @@ func ContainerRoutes() *web.Router {
g.MatchPath("POST", "/<image:*>/blobs/uploads", reqPackageAccess(perm.AccessModeWrite), container.VerifyImageName, container.InitiateUploadBlob) g.MatchPath("POST", "/<image:*>/blobs/uploads", reqPackageAccess(perm.AccessModeWrite), container.VerifyImageName, container.InitiateUploadBlob)
g.MatchPath("GET", "/<image:*>/tags/list", container.VerifyImageName, container.GetTagList) g.MatchPath("GET", "/<image:*>/tags/list", container.VerifyImageName, container.GetTagList)
g.MatchPath("GET,PATCH,PUT,DELETE", `/<image:*>/blobs/uploads/<uuid:[-.=\w]+>`, reqPackageAccess(perm.AccessModeWrite), container.VerifyImageName, func(ctx *context.Context) { g.MatchPath("GET,PATCH,PUT,DELETE", `/<image:*>/blobs/uploads/<uuid:[-.=\w]+>`, reqPackageAccess(perm.AccessModeWrite), container.VerifyImageName, func(ctx *context.Context) {
if ctx.Req.Method == http.MethodGet { switch ctx.Req.Method {
case http.MethodGet:
container.GetUploadBlob(ctx) container.GetUploadBlob(ctx)
} else if ctx.Req.Method == http.MethodPatch { case http.MethodPatch:
container.UploadBlob(ctx) container.UploadBlob(ctx)
} else if ctx.Req.Method == http.MethodPut { case http.MethodPut:
container.EndUploadBlob(ctx) container.EndUploadBlob(ctx)
} else /* DELETE */ { default: /* DELETE */
container.CancelUploadBlob(ctx) container.CancelUploadBlob(ctx)
} }
}) })

View File

@ -51,9 +51,10 @@ func ListHooks(ctx *context.APIContext) {
// for compatibility the default value is true // for compatibility the default value is true
isSystemWebhook := optional.Some(true) isSystemWebhook := optional.Some(true)
typeValue := ctx.FormString("type") typeValue := ctx.FormString("type")
if typeValue == "default" { switch typeValue {
case "default":
isSystemWebhook = optional.Some(false) isSystemWebhook = optional.Some(false)
} else if typeValue == "all" { case "all":
isSystemWebhook = optional.None[bool]() isSystemWebhook = optional.None[bool]()
} }

View File

@ -842,13 +842,13 @@ func verifyAuthWithOptions(options *common.VerifyOptions) func(ctx *context.APIC
func individualPermsChecker(ctx *context.APIContext) { func individualPermsChecker(ctx *context.APIContext) {
// org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked. // org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked.
if ctx.ContextUser.IsIndividual() { if ctx.ContextUser.IsIndividual() {
switch { switch ctx.ContextUser.Visibility {
case ctx.ContextUser.Visibility == api.VisibleTypePrivate: case api.VisibleTypePrivate:
if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) { if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) {
ctx.APIErrorNotFound("Visit Project", nil) ctx.APIErrorNotFound("Visit Project", nil)
return return
} }
case ctx.ContextUser.Visibility == api.VisibleTypeLimited: case api.VisibleTypeLimited:
if ctx.Doer == nil { if ctx.Doer == nil {
ctx.APIErrorNotFound("Visit Project", nil) ctx.APIErrorNotFound("Visit Project", nil)
return return

View File

@ -1103,8 +1103,8 @@ func DeleteArtifact(ctx *context.APIContext) {
func buildSignature(endp string, expires, artifactID int64) []byte { func buildSignature(endp string, expires, artifactID int64) []byte {
mac := hmac.New(sha256.New, setting.GetGeneralTokenSigningSecret()) mac := hmac.New(sha256.New, setting.GetGeneralTokenSigningSecret())
mac.Write([]byte(endp)) mac.Write([]byte(endp))
mac.Write([]byte(fmt.Sprint(expires))) fmt.Fprint(mac, expires)
mac.Write([]byte(fmt.Sprint(artifactID))) fmt.Fprint(mac, artifactID)
return mac.Sum(nil) return mac.Sum(nil)
} }

View File

@ -24,9 +24,10 @@ import (
// appendPrivateInformation appends the owner and key type information to api.PublicKey // appendPrivateInformation appends the owner and key type information to api.PublicKey
func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) { func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) {
if key.Type == asymkey_model.KeyTypeDeploy { switch key.Type {
case asymkey_model.KeyTypeDeploy:
apiKey.KeyType = "deploy" apiKey.KeyType = "deploy"
} else if key.Type == asymkey_model.KeyTypeUser { case asymkey_model.KeyTypeUser:
apiKey.KeyType = "user" apiKey.KeyType = "user"
if defaultUser.ID == key.OwnerID { if defaultUser.ID == key.OwnerID {
@ -38,7 +39,7 @@ func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *a
} }
apiKey.Owner = convert.ToUser(ctx, user, user) apiKey.Owner = convert.ToUser(ctx, user, user)
} }
} else { default:
apiKey.KeyType = "unknown" apiKey.KeyType = "unknown"
} }
apiKey.ReadOnly = key.Mode == perm.AccessModeRead apiKey.ReadOnly = key.Mode == perm.AccessModeRead

View File

@ -447,10 +447,7 @@ func preReceiveFor(ctx *preReceiveContext, refFullName git.RefName) {
baseBranchName := refFullName.ForBranchName() baseBranchName := refFullName.ForBranchName()
baseBranchExist := false baseBranchExist := gitrepo.IsBranchExist(ctx, ctx.Repo.Repository, baseBranchName)
if gitrepo.IsBranchExist(ctx, ctx.Repo.Repository, baseBranchName) {
baseBranchExist = true
}
if !baseBranchExist { if !baseBranchExist {
for p, v := range baseBranchName { for p, v := range baseBranchName {

View File

@ -534,7 +534,8 @@ func createUserInContext(ctx *context.Context, tpl templates.TplName, form any,
} }
if err := user_model.CreateUser(ctx, u, meta, overwrites); err != nil { if err := user_model.CreateUser(ctx, u, meta, overwrites); err != nil {
if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) { if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) {
if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingAuto { switch setting.OAuth2Client.AccountLinking {
case setting.OAuth2AccountLinkingAuto:
var user *user_model.User var user *user_model.User
user = &user_model.User{Name: u.Name} user = &user_model.User{Name: u.Name}
hasUser, err := user_model.GetUser(ctx, user) hasUser, err := user_model.GetUser(ctx, user)
@ -550,7 +551,7 @@ func createUserInContext(ctx *context.Context, tpl templates.TplName, form any,
// TODO: probably we should respect 'remember' user's choice... // TODO: probably we should respect 'remember' user's choice...
linkAccount(ctx, user, *gothUser, true) linkAccount(ctx, user, *gothUser, true)
return false // user is already created here, all redirects are handled return false // user is already created here, all redirects are handled
} else if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingLogin { case setting.OAuth2AccountLinkingLogin:
showLinkingLogin(ctx, *gothUser) showLinkingLogin(ctx, *gothUser)
return false // user will be created only after linking login return false // user will be created only after linking login
} }

View File

@ -155,9 +155,10 @@ func SignInOAuthCallback(ctx *context.Context) {
return return
} }
if uname == "" { if uname == "" {
if setting.OAuth2Client.Username == setting.OAuth2UsernameNickname { switch setting.OAuth2Client.Username {
case setting.OAuth2UsernameNickname:
missingFields = append(missingFields, "nickname") missingFields = append(missingFields, "nickname")
} else if setting.OAuth2Client.Username == setting.OAuth2UsernamePreferredUsername { case setting.OAuth2UsernamePreferredUsername:
missingFields = append(missingFields, "preferred_username") missingFields = append(missingFields, "preferred_username")
} // else: "UserID" and "Email" have been handled above separately } // else: "UserID" and "Email" have been handled above separately
} }

View File

@ -55,13 +55,14 @@ func Worktime(ctx *context.Context) {
var worktimeSumResult any var worktimeSumResult any
var err error var err error
if worktimeBy == "milestones" { switch worktimeBy {
case "milestones":
worktimeSumResult, err = organization.GetWorktimeByMilestones(ctx.Org.Organization, unixFrom, unixTo) worktimeSumResult, err = organization.GetWorktimeByMilestones(ctx.Org.Organization, unixFrom, unixTo)
ctx.Data["WorktimeByMilestones"] = true ctx.Data["WorktimeByMilestones"] = true
} else if worktimeBy == "members" { case "members":
worktimeSumResult, err = organization.GetWorktimeByMembers(ctx.Org.Organization, unixFrom, unixTo) worktimeSumResult, err = organization.GetWorktimeByMembers(ctx.Org.Organization, unixFrom, unixTo)
ctx.Data["WorktimeByMembers"] = true ctx.Data["WorktimeByMembers"] = true
} else /* by repos */ { default: /* by repos */
worktimeSumResult, err = organization.GetWorktimeByRepos(ctx.Org.Organization, unixFrom, unixTo) worktimeSumResult, err = organization.GetWorktimeByRepos(ctx.Org.Organization, unixFrom, unixTo)
ctx.Data["WorktimeByRepos"] = true ctx.Data["WorktimeByRepos"] = true
} }

View File

@ -938,9 +938,10 @@ func ExcerptBlob(ctx *context.Context) {
RightHunkSize: rightHunkSize, RightHunkSize: rightHunkSize,
}, },
} }
if direction == "up" { switch direction {
case "up":
section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...) section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...)
} else if direction == "down" { case "down":
section.Lines = append(section.Lines, lineSection) section.Lines = append(section.Lines, lineSection)
} }
} }

View File

@ -157,15 +157,16 @@ func GetContentHistoryDetail(ctx *context.Context) {
diffHTMLBuf := bytes.Buffer{} diffHTMLBuf := bytes.Buffer{}
diffHTMLBuf.WriteString("<pre class='chroma'>") diffHTMLBuf.WriteString("<pre class='chroma'>")
for _, it := range diff { for _, it := range diff {
if it.Type == diffmatchpatch.DiffInsert { switch it.Type {
case diffmatchpatch.DiffInsert:
diffHTMLBuf.WriteString("<span class='gi'>") diffHTMLBuf.WriteString("<span class='gi'>")
diffHTMLBuf.WriteString(html.EscapeString(it.Text)) diffHTMLBuf.WriteString(html.EscapeString(it.Text))
diffHTMLBuf.WriteString("</span>") diffHTMLBuf.WriteString("</span>")
} else if it.Type == diffmatchpatch.DiffDelete { case diffmatchpatch.DiffDelete:
diffHTMLBuf.WriteString("<span class='gd'>") diffHTMLBuf.WriteString("<span class='gd'>")
diffHTMLBuf.WriteString(html.EscapeString(it.Text)) diffHTMLBuf.WriteString(html.EscapeString(it.Text))
diffHTMLBuf.WriteString("</span>") diffHTMLBuf.WriteString("</span>")
} else { default:
diffHTMLBuf.WriteString(html.EscapeString(it.Text)) diffHTMLBuf.WriteString(html.EscapeString(it.Text))
} }
} }

View File

@ -696,9 +696,10 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption opt
return 0 return 0
} }
reviewTyp := issues_model.ReviewTypeApprove reviewTyp := issues_model.ReviewTypeApprove
if typ == "reject" { switch typ {
case "reject":
reviewTyp = issues_model.ReviewTypeReject reviewTyp = issues_model.ReviewTypeReject
} else if typ == "waiting" { case "waiting":
reviewTyp = issues_model.ReviewTypeRequest reviewTyp = issues_model.ReviewTypeRequest
} }
for _, count := range counts { for _, count := range counts {

View File

@ -209,11 +209,12 @@ func renderConversation(ctx *context.Context, comment *issues_model.Comment, ori
return user_service.CanBlockUser(ctx, ctx.Doer, blocker, blockee) return user_service.CanBlockUser(ctx, ctx.Doer, blocker, blockee)
} }
if origin == "diff" { switch origin {
case "diff":
ctx.HTML(http.StatusOK, tplDiffConversation) ctx.HTML(http.StatusOK, tplDiffConversation)
} else if origin == "timeline" { case "timeline":
ctx.HTML(http.StatusOK, tplTimelineConversation) ctx.HTML(http.StatusOK, tplTimelineConversation)
} else { default:
ctx.HTTPError(http.StatusBadRequest, "Unknown origin: "+origin) ctx.HTTPError(http.StatusBadRequest, "Unknown origin: "+origin)
} }
} }

View File

@ -617,9 +617,10 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
return 0 return 0
} }
reviewTyp := issues_model.ReviewTypeApprove reviewTyp := issues_model.ReviewTypeApprove
if typ == "reject" { switch typ {
case "reject":
reviewTyp = issues_model.ReviewTypeReject reviewTyp = issues_model.ReviewTypeReject
} else if typ == "waiting" { case "waiting":
reviewTyp = issues_model.ReviewTypeRequest reviewTyp = issues_model.ReviewTypeRequest
} }
for _, count := range counts { for _, count := range counts {

View File

@ -308,9 +308,10 @@ func NotificationSubscriptions(ctx *context.Context) {
return 0 return 0
} }
reviewTyp := issues_model.ReviewTypeApprove reviewTyp := issues_model.ReviewTypeApprove
if typ == "reject" { switch typ {
case "reject":
reviewTyp = issues_model.ReviewTypeReject reviewTyp = issues_model.ReviewTypeReject
} else if typ == "waiting" { case "waiting":
reviewTyp = issues_model.ReviewTypeRequest reviewTyp = issues_model.ReviewTypeRequest
} }
for _, count := range counts { for _, count := range counts {

View File

@ -854,13 +854,13 @@ func registerRoutes(m *web.Router) {
individualPermsChecker := func(ctx *context.Context) { individualPermsChecker := func(ctx *context.Context) {
// org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked. // org permissions have been checked in context.OrgAssignment(), but individual permissions haven't been checked.
if ctx.ContextUser.IsIndividual() { if ctx.ContextUser.IsIndividual() {
switch { switch ctx.ContextUser.Visibility {
case ctx.ContextUser.Visibility == structs.VisibleTypePrivate: case structs.VisibleTypePrivate:
if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) { if ctx.Doer == nil || (ctx.ContextUser.ID != ctx.Doer.ID && !ctx.Doer.IsAdmin) {
ctx.NotFound(nil) ctx.NotFound(nil)
return return
} }
case ctx.ContextUser.Visibility == structs.VisibleTypeLimited: case structs.VisibleTypeLimited:
if ctx.Doer == nil { if ctx.Doer == nil {
ctx.NotFound(nil) ctx.NotFound(nil)
return return

View File

@ -87,14 +87,15 @@ func Verify(buf []byte, fileName, allowedTypesStr string) error {
// AddUploadContext renders template values for dropzone // AddUploadContext renders template values for dropzone
func AddUploadContext(ctx *context.Context, uploadType string) { func AddUploadContext(ctx *context.Context, uploadType string) {
if uploadType == "release" { switch uploadType {
case "release":
ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/releases/attachments" ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/releases/attachments"
ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/releases/attachments/remove" ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/releases/attachments/remove"
ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/releases/attachments" ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/releases/attachments"
ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Repository.Release.AllowedTypes, "|", ",") ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Repository.Release.AllowedTypes, "|", ",")
ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles
ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize
} else if uploadType == "comment" { case "comment":
ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/issues/attachments" ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/issues/attachments"
ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/issues/attachments/remove" ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/issues/attachments/remove"
if len(ctx.PathParam("index")) > 0 { if len(ctx.PathParam("index")) > 0 {
@ -105,7 +106,7 @@ func AddUploadContext(ctx *context.Context, uploadType string) {
ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Attachment.AllowedTypes, "|", ",") ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Attachment.AllowedTypes, "|", ",")
ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles
ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize
} else if uploadType == "repo" { case "repo":
ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/upload-file" ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/upload-file"
ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/upload-remove" ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/upload-remove"
ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/upload-file" ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/upload-file"

View File

@ -14,13 +14,14 @@ import (
// token is a html tag or entity, eg: "<span ...>", "</span>", "&lt;" // token is a html tag or entity, eg: "<span ...>", "</span>", "&lt;"
func extractHTMLToken(s string) (before, token, after string, valid bool) { func extractHTMLToken(s string) (before, token, after string, valid bool) {
for pos1 := 0; pos1 < len(s); pos1++ { for pos1 := 0; pos1 < len(s); pos1++ {
if s[pos1] == '<' { switch s[pos1] {
case '<':
pos2 := strings.IndexByte(s[pos1:], '>') pos2 := strings.IndexByte(s[pos1:], '>')
if pos2 == -1 { if pos2 == -1 {
return "", "", s, false return "", "", s, false
} }
return s[:pos1], s[pos1 : pos1+pos2+1], s[pos1+pos2+1:], true return s[:pos1], s[pos1 : pos1+pos2+1], s[pos1+pos2+1:], true
} else if s[pos1] == '&' { case '&':
pos2 := strings.IndexByte(s[pos1:], ';') pos2 := strings.IndexByte(s[pos1:], ';')
if pos2 == -1 { if pos2 == -1 {
return "", "", s, false return "", "", s, false

View File

@ -164,11 +164,12 @@ func BatchHandler(ctx *context.Context) {
} }
var isUpload bool var isUpload bool
if br.Operation == "upload" { switch br.Operation {
case "upload":
isUpload = true isUpload = true
} else if br.Operation == "download" { case "download":
isUpload = false isUpload = false
} else { default:
log.Trace("Attempt to BATCH with invalid operation: %s", br.Operation) log.Trace("Attempt to BATCH with invalid operation: %s", br.Operation)
writeStatus(ctx, http.StatusBadRequest) writeStatus(ctx, http.StatusBadRequest)
return return

View File

@ -31,15 +31,16 @@ func (m *mailNotifier) CreateIssueComment(ctx context.Context, doer *user_model.
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
) { ) {
var act activities_model.ActionType var act activities_model.ActionType
if comment.Type == issues_model.CommentTypeClose { switch comment.Type {
case issues_model.CommentTypeClose:
act = activities_model.ActionCloseIssue act = activities_model.ActionCloseIssue
} else if comment.Type == issues_model.CommentTypeReopen { case issues_model.CommentTypeReopen:
act = activities_model.ActionReopenIssue act = activities_model.ActionReopenIssue
} else if comment.Type == issues_model.CommentTypeComment { case issues_model.CommentTypeComment:
act = activities_model.ActionCommentIssue act = activities_model.ActionCommentIssue
} else if comment.Type == issues_model.CommentTypeCode { case issues_model.CommentTypeCode:
act = activities_model.ActionCommentIssue act = activities_model.ActionCommentIssue
} else if comment.Type == issues_model.CommentTypePullRequestPush { case issues_model.CommentTypePullRequestPush:
act = 0 act = 0
} }
@ -95,11 +96,12 @@ func (m *mailNotifier) NewPullRequest(ctx context.Context, pr *issues_model.Pull
func (m *mailNotifier) PullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { func (m *mailNotifier) PullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) {
var act activities_model.ActionType var act activities_model.ActionType
if comment.Type == issues_model.CommentTypeClose { switch comment.Type {
case issues_model.CommentTypeClose:
act = activities_model.ActionCloseIssue act = activities_model.ActionCloseIssue
} else if comment.Type == issues_model.CommentTypeReopen { case issues_model.CommentTypeReopen:
act = activities_model.ActionReopenIssue act = activities_model.ActionReopenIssue
} else if comment.Type == issues_model.CommentTypeComment { case issues_model.CommentTypeComment:
act = activities_model.ActionCommentPull act = activities_model.ActionCommentPull
} }
if err := MailParticipantsComment(ctx, comment, act, pr.Issue, mentions); err != nil { if err := MailParticipantsComment(ctx, comment, act, pr.Issue, mentions); err != nil {

View File

@ -384,7 +384,8 @@ func CreateRepositoryByExample(ctx context.Context, doer, u *user_model.User, re
} }
units := make([]repo_model.RepoUnit, 0, len(defaultUnits)) units := make([]repo_model.RepoUnit, 0, len(defaultUnits))
for _, tp := range defaultUnits { for _, tp := range defaultUnits {
if tp == unit.TypeIssues { switch tp {
case unit.TypeIssues:
units = append(units, repo_model.RepoUnit{ units = append(units, repo_model.RepoUnit{
RepoID: repo.ID, RepoID: repo.ID,
Type: tp, Type: tp,
@ -394,7 +395,7 @@ func CreateRepositoryByExample(ctx context.Context, doer, u *user_model.User, re
EnableDependencies: setting.Service.DefaultEnableDependencies, EnableDependencies: setting.Service.DefaultEnableDependencies,
}, },
}) })
} else if tp == unit.TypePullRequests { case unit.TypePullRequests:
units = append(units, repo_model.RepoUnit{ units = append(units, repo_model.RepoUnit{
RepoID: repo.ID, RepoID: repo.ID,
Type: tp, Type: tp,
@ -404,13 +405,13 @@ func CreateRepositoryByExample(ctx context.Context, doer, u *user_model.User, re
AllowRebaseUpdate: true, AllowRebaseUpdate: true,
}, },
}) })
} else if tp == unit.TypeProjects { case unit.TypeProjects:
units = append(units, repo_model.RepoUnit{ units = append(units, repo_model.RepoUnit{
RepoID: repo.ID, RepoID: repo.ID,
Type: tp, Type: tp,
Config: &repo_model.ProjectsConfig{ProjectsMode: repo_model.ProjectsModeAll}, Config: &repo_model.ProjectsConfig{ProjectsMode: repo_model.ProjectsModeAll},
}) })
} else { default:
units = append(units, repo_model.RepoUnit{ units = append(units, repo_model.RepoUnit{
RepoID: repo.ID, RepoID: repo.ID,
Type: tp, Type: tp,

View File

@ -39,11 +39,12 @@ func getPullRequestInfo(p *api.PullRequestPayload) (title, link, by, operator, o
for i, user := range assignList { for i, user := range assignList {
assignStringList[i] = user.UserName assignStringList[i] = user.UserName
} }
if p.Action == api.HookIssueAssigned { switch p.Action {
case api.HookIssueAssigned:
operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName) operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName)
} else if p.Action == api.HookIssueUnassigned { case api.HookIssueUnassigned:
operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName) operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName)
} else if p.Action == api.HookIssueMilestoned { case api.HookIssueMilestoned:
operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.PullRequest.Milestone.ID) operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.PullRequest.Milestone.ID)
} }
link = p.PullRequest.HTMLURL link = p.PullRequest.HTMLURL
@ -64,11 +65,12 @@ func getIssuesInfo(p *api.IssuePayload) (issueTitle, link, by, operator, operate
for i, user := range assignList { for i, user := range assignList {
assignStringList[i] = user.UserName assignStringList[i] = user.UserName
} }
if p.Action == api.HookIssueAssigned { switch p.Action {
case api.HookIssueAssigned:
operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName) operateResult = fmt.Sprintf("%s assign this to %s", p.Sender.UserName, assignList[len(assignList)-1].UserName)
} else if p.Action == api.HookIssueUnassigned { case api.HookIssueUnassigned:
operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName) operateResult = fmt.Sprintf("%s unassigned this for someone", p.Sender.UserName)
} else if p.Action == api.HookIssueMilestoned { case api.HookIssueMilestoned:
operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.Issue.Milestone.ID) operateResult = fmt.Sprintf("%s/milestone/%d", p.Repository.HTMLURL, p.Issue.Milestone.ID)
} }
link = p.Issue.HTMLURL link = p.Issue.HTMLURL