You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.2 KiB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package util
  5. import (
  6. "net/url"
  7. "path"
  8. "strings"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/setting"
  11. )
  12. // OptionalBool a boolean that can be "null"
  13. type OptionalBool byte
  14. const (
  15. // OptionalBoolNone a "null" boolean value
  16. OptionalBoolNone = iota
  17. // OptionalBoolTrue a "true" boolean value
  18. OptionalBoolTrue
  19. // OptionalBoolFalse a "false" boolean value
  20. OptionalBoolFalse
  21. )
  22. // IsTrue return true if equal to OptionalBoolTrue
  23. func (o OptionalBool) IsTrue() bool {
  24. return o == OptionalBoolTrue
  25. }
  26. // IsFalse return true if equal to OptionalBoolFalse
  27. func (o OptionalBool) IsFalse() bool {
  28. return o == OptionalBoolFalse
  29. }
  30. // IsNone return true if equal to OptionalBoolNone
  31. func (o OptionalBool) IsNone() bool {
  32. return o == OptionalBoolNone
  33. }
  34. // OptionalBoolOf get the corresponding OptionalBool of a bool
  35. func OptionalBoolOf(b bool) OptionalBool {
  36. if b {
  37. return OptionalBoolTrue
  38. }
  39. return OptionalBoolFalse
  40. }
  41. // Max max of two ints
  42. func Max(a, b int) int {
  43. if a < b {
  44. return b
  45. }
  46. return a
  47. }
  48. // URLJoin joins url components, like path.Join, but preserving contents
  49. func URLJoin(base string, elems ...string) string {
  50. if !strings.HasSuffix(base, "/") {
  51. base += "/"
  52. }
  53. baseURL, err := url.Parse(base)
  54. if err != nil {
  55. log.Error(4, "URLJoin: Invalid base URL %s", base)
  56. return ""
  57. }
  58. joinedPath := path.Join(elems...)
  59. argURL, err := url.Parse(joinedPath)
  60. if err != nil {
  61. log.Error(4, "URLJoin: Invalid arg %s", joinedPath)
  62. return ""
  63. }
  64. joinedURL := baseURL.ResolveReference(argURL).String()
  65. if !baseURL.IsAbs() && !strings.HasPrefix(base, "/") {
  66. return joinedURL[1:] // Removing leading '/' if needed
  67. }
  68. return joinedURL
  69. }
  70. // IsExternalURL checks if rawURL points to an external URL like http://example.com
  71. func IsExternalURL(rawURL string) bool {
  72. parsed, err := url.Parse(rawURL)
  73. if err != nil {
  74. return true
  75. }
  76. if len(parsed.Host) != 0 && strings.Replace(parsed.Host, "www.", "", 1) != strings.Replace(setting.Domain, "www.", "", 1) {
  77. return true
  78. }
  79. return false
  80. }
  81. // Min min of two ints
  82. func Min(a, b int) int {
  83. if a > b {
  84. return b
  85. }
  86. return a
  87. }