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.

tool.go 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package base
  4. import (
  5. "crypto/md5"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "unicode"
  18. "unicode/utf8"
  19. "code.gitea.io/gitea/modules/git"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/setting"
  22. "github.com/dustin/go-humanize"
  23. "github.com/minio/sha256-simd"
  24. )
  25. // EncodeMD5 encodes string to md5 hex value.
  26. func EncodeMD5(str string) string {
  27. m := md5.New()
  28. _, _ = m.Write([]byte(str))
  29. return hex.EncodeToString(m.Sum(nil))
  30. }
  31. // EncodeSha1 string to sha1 hex value.
  32. func EncodeSha1(str string) string {
  33. h := sha1.New()
  34. _, _ = h.Write([]byte(str))
  35. return hex.EncodeToString(h.Sum(nil))
  36. }
  37. // EncodeSha256 string to sha256 hex value.
  38. func EncodeSha256(str string) string {
  39. h := sha256.New()
  40. _, _ = h.Write([]byte(str))
  41. return hex.EncodeToString(h.Sum(nil))
  42. }
  43. // ShortSha is basically just truncating.
  44. // It is DEPRECATED and will be removed in the future.
  45. func ShortSha(sha1 string) string {
  46. return TruncateString(sha1, 10)
  47. }
  48. // BasicAuthDecode decode basic auth string
  49. func BasicAuthDecode(encoded string) (string, string, error) {
  50. s, err := base64.StdEncoding.DecodeString(encoded)
  51. if err != nil {
  52. return "", "", err
  53. }
  54. auth := strings.SplitN(string(s), ":", 2)
  55. if len(auth) != 2 {
  56. return "", "", errors.New("invalid basic authentication")
  57. }
  58. return auth[0], auth[1], nil
  59. }
  60. // BasicAuthEncode encode basic auth string
  61. func BasicAuthEncode(username, password string) string {
  62. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  63. }
  64. // VerifyTimeLimitCode verify time limit code
  65. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  66. if len(code) <= 18 {
  67. return false
  68. }
  69. // split code
  70. start := code[:12]
  71. lives := code[12:18]
  72. if d, err := strconv.ParseInt(lives, 10, 0); err == nil {
  73. minutes = int(d)
  74. }
  75. // right active code
  76. retCode := CreateTimeLimitCode(data, minutes, start)
  77. if retCode == code && minutes > 0 {
  78. // check time is expired or not
  79. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  80. now := time.Now()
  81. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  82. return true
  83. }
  84. }
  85. return false
  86. }
  87. // TimeLimitCodeLength default value for time limit code
  88. const TimeLimitCodeLength = 12 + 6 + 40
  89. // CreateTimeLimitCode create a time limit code
  90. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  91. func CreateTimeLimitCode(data string, minutes int, startInf any) string {
  92. format := "200601021504"
  93. var start, end time.Time
  94. var startStr, endStr string
  95. if startInf == nil {
  96. // Use now time create code
  97. start = time.Now()
  98. startStr = start.Format(format)
  99. } else {
  100. // use start string create code
  101. startStr = startInf.(string)
  102. start, _ = time.ParseInLocation(format, startStr, time.Local)
  103. startStr = start.Format(format)
  104. }
  105. end = start.Add(time.Minute * time.Duration(minutes))
  106. endStr = end.Format(format)
  107. // create sha1 encode string
  108. sh := sha1.New()
  109. _, _ = sh.Write([]byte(fmt.Sprintf("%s%s%s%s%d", data, setting.SecretKey, startStr, endStr, minutes)))
  110. encoded := hex.EncodeToString(sh.Sum(nil))
  111. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  112. return code
  113. }
  114. // FileSize calculates the file size and generate user-friendly string.
  115. func FileSize(s int64) string {
  116. return humanize.IBytes(uint64(s))
  117. }
  118. // EllipsisString returns a truncated short string,
  119. // it appends '...' in the end of the length of string is too large.
  120. func EllipsisString(str string, length int) string {
  121. if length <= 3 {
  122. return "..."
  123. }
  124. if utf8.RuneCountInString(str) <= length {
  125. return str
  126. }
  127. return string([]rune(str)[:length-3]) + "..."
  128. }
  129. // TruncateString returns a truncated string with given limit,
  130. // it returns input string if length is not reached limit.
  131. func TruncateString(str string, limit int) string {
  132. if utf8.RuneCountInString(str) < limit {
  133. return str
  134. }
  135. return string([]rune(str)[:limit])
  136. }
  137. // StringsToInt64s converts a slice of string to a slice of int64.
  138. func StringsToInt64s(strs []string) ([]int64, error) {
  139. ints := make([]int64, len(strs))
  140. for i := range strs {
  141. n, err := strconv.ParseInt(strs[i], 10, 64)
  142. if err != nil {
  143. return ints, err
  144. }
  145. ints[i] = n
  146. }
  147. return ints, nil
  148. }
  149. // Int64sToStrings converts a slice of int64 to a slice of string.
  150. func Int64sToStrings(ints []int64) []string {
  151. strs := make([]string, len(ints))
  152. for i := range ints {
  153. strs[i] = strconv.FormatInt(ints[i], 10)
  154. }
  155. return strs
  156. }
  157. // Int64sContains returns if a int64 in a slice of int64
  158. func Int64sContains(intsSlice []int64, a int64) bool {
  159. for _, c := range intsSlice {
  160. if c == a {
  161. return true
  162. }
  163. }
  164. return false
  165. }
  166. // IsLetter reports whether the rune is a letter (category L).
  167. // https://github.com/golang/go/blob/c3b4918/src/go/scanner/scanner.go#L342
  168. func IsLetter(ch rune) bool {
  169. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  170. }
  171. // EntryIcon returns the octicon class for displaying files/directories
  172. func EntryIcon(entry *git.TreeEntry) string {
  173. switch {
  174. case entry.IsLink():
  175. te, err := entry.FollowLink()
  176. if err != nil {
  177. log.Debug(err.Error())
  178. return "file-symlink-file"
  179. }
  180. if te.IsDir() {
  181. return "file-directory-symlink"
  182. }
  183. return "file-symlink-file"
  184. case entry.IsDir():
  185. return "file-directory-fill"
  186. case entry.IsSubModule():
  187. return "file-submodule"
  188. }
  189. return "file"
  190. }
  191. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  192. func SetupGiteaRoot() string {
  193. giteaRoot := os.Getenv("GITEA_ROOT")
  194. if giteaRoot == "" {
  195. _, filename, _, _ := runtime.Caller(0)
  196. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  197. wd, err := os.Getwd()
  198. if err != nil {
  199. rel, err := filepath.Rel(giteaRoot, wd)
  200. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  201. giteaRoot = wd
  202. }
  203. }
  204. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  205. giteaRoot = ""
  206. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  207. giteaRoot = ""
  208. }
  209. }
  210. return giteaRoot
  211. }
  212. // FormatNumberSI format a number
  213. func FormatNumberSI(data any) string {
  214. var num int64
  215. if num1, ok := data.(int64); ok {
  216. num = num1
  217. } else if num1, ok := data.(int); ok {
  218. num = int64(num1)
  219. } else {
  220. return ""
  221. }
  222. if num < 1000 {
  223. return fmt.Sprintf("%d", num)
  224. } else if num < 1000000 {
  225. num2 := float32(num) / float32(1000.0)
  226. return fmt.Sprintf("%.1fk", num2)
  227. } else if num < 1000000000 {
  228. num2 := float32(num) / float32(1000000.0)
  229. return fmt.Sprintf("%.1fM", num2)
  230. }
  231. num2 := float32(num) / float32(1000000000.0)
  232. return fmt.Sprintf("%.1fG", num2)
  233. }