gitea源码

helper.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package user
  4. import (
  5. "context"
  6. "slices"
  7. "strconv"
  8. "code.gitea.io/gitea/models/user"
  9. )
  10. func MakeSelfOnTop(doer *user.User, users []*user.User) []*user.User {
  11. if doer != nil {
  12. idx := slices.IndexFunc(users, func(u *user.User) bool {
  13. return u.ID == doer.ID
  14. })
  15. if idx > 0 {
  16. newUsers := make([]*user.User, len(users))
  17. newUsers[0] = users[idx]
  18. copy(newUsers[1:], users[:idx])
  19. copy(newUsers[idx+1:], users[idx+1:])
  20. return newUsers
  21. }
  22. }
  23. return users
  24. }
  25. // GetFilterUserIDByName tries to get the user ID from the given username.
  26. // Before, the "issue filter" passes user ID to query the list, but in many cases, it's impossible to pre-fetch the full user list.
  27. // So it's better to make it work like GitHub: users could input username directly.
  28. // Since it only converts the username to ID directly and is only used internally (to search issues), so no permission check is needed.
  29. // Return values:
  30. // * "": no filter
  31. // * "{the-id}": match the id
  32. // * "(none)": match no issue (due to the user doesn't exist)
  33. func GetFilterUserIDByName(ctx context.Context, name string) string {
  34. if name == "" {
  35. return ""
  36. }
  37. u, err := user.GetUserByName(ctx, name)
  38. if err != nil {
  39. if id, err := strconv.ParseInt(name, 10, 64); err == nil {
  40. return strconv.FormatInt(id, 10)
  41. }
  42. // The "(none)" is for internal usage only: when doer tries to search non-existing user, use "(none)" to return empty result.
  43. return "(none)"
  44. }
  45. return strconv.FormatInt(u.ID, 10)
  46. }