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

tool.go 15 kB

10 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
11 years ago
11 years ago
9 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. // Copyright 2014 The Gogs 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 base
  5. import (
  6. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "io"
  14. "math"
  15. "math/big"
  16. "net/http"
  17. "net/url"
  18. "path"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "unicode"
  23. "unicode/utf8"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/util"
  27. "github.com/Unknwon/com"
  28. "github.com/Unknwon/i18n"
  29. "github.com/gogits/chardet"
  30. )
  31. // EncodeMD5 encodes string to md5 hex value.
  32. func EncodeMD5(str string) string {
  33. m := md5.New()
  34. m.Write([]byte(str))
  35. return hex.EncodeToString(m.Sum(nil))
  36. }
  37. // EncodeSha1 string to sha1 hex value.
  38. func EncodeSha1(str string) string {
  39. h := sha1.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. // DetectEncoding detect the encoding of content
  49. func DetectEncoding(content []byte) (string, error) {
  50. if utf8.Valid(content) {
  51. log.Debug("Detected encoding: utf-8 (fast)")
  52. return "UTF-8", nil
  53. }
  54. result, err := chardet.NewTextDetector().DetectBest(content)
  55. if err != nil {
  56. return "", err
  57. }
  58. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  59. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  60. return setting.Repository.AnsiCharset, err
  61. }
  62. log.Debug("Detected encoding: %s", result.Charset)
  63. return result.Charset, err
  64. }
  65. // BasicAuthDecode decode basic auth string
  66. func BasicAuthDecode(encoded string) (string, string, error) {
  67. s, err := base64.StdEncoding.DecodeString(encoded)
  68. if err != nil {
  69. return "", "", err
  70. }
  71. auth := strings.SplitN(string(s), ":", 2)
  72. return auth[0], auth[1], nil
  73. }
  74. // BasicAuthEncode encode basic auth string
  75. func BasicAuthEncode(username, password string) string {
  76. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  77. }
  78. // GetRandomString generate random string by specify chars.
  79. func GetRandomString(n int) (string, error) {
  80. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  81. buffer := make([]byte, n)
  82. max := big.NewInt(int64(len(alphanum)))
  83. for i := 0; i < n; i++ {
  84. index, err := randomInt(max)
  85. if err != nil {
  86. return "", err
  87. }
  88. buffer[i] = alphanum[index]
  89. }
  90. return string(buffer), nil
  91. }
  92. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  93. func GetRandomBytesAsBase64(n int) string {
  94. bytes := make([]byte, 32)
  95. _, err := io.ReadFull(rand.Reader, bytes)
  96. if err != nil {
  97. log.Fatal(4, "Error reading random bytes: %v", err)
  98. }
  99. return base64.RawURLEncoding.EncodeToString(bytes)
  100. }
  101. func randomInt(max *big.Int) (int, error) {
  102. rand, err := rand.Int(rand.Reader, max)
  103. if err != nil {
  104. return 0, err
  105. }
  106. return int(rand.Int64()), nil
  107. }
  108. // VerifyTimeLimitCode verify time limit code
  109. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  110. if len(code) <= 18 {
  111. return false
  112. }
  113. // split code
  114. start := code[:12]
  115. lives := code[12:18]
  116. if d, err := com.StrTo(lives).Int(); err == nil {
  117. minutes = d
  118. }
  119. // right active code
  120. retCode := CreateTimeLimitCode(data, minutes, start)
  121. if retCode == code && minutes > 0 {
  122. // check time is expired or not
  123. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  124. now := time.Now()
  125. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  126. return true
  127. }
  128. }
  129. return false
  130. }
  131. // TimeLimitCodeLength default value for time limit code
  132. const TimeLimitCodeLength = 12 + 6 + 40
  133. // CreateTimeLimitCode create a time limit code
  134. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  135. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  136. format := "200601021504"
  137. var start, end time.Time
  138. var startStr, endStr string
  139. if startInf == nil {
  140. // Use now time create code
  141. start = time.Now()
  142. startStr = start.Format(format)
  143. } else {
  144. // use start string create code
  145. startStr = startInf.(string)
  146. start, _ = time.ParseInLocation(format, startStr, time.Local)
  147. startStr = start.Format(format)
  148. }
  149. end = start.Add(time.Minute * time.Duration(minutes))
  150. endStr = end.Format(format)
  151. // create sha1 encode string
  152. sh := sha1.New()
  153. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  154. encoded := hex.EncodeToString(sh.Sum(nil))
  155. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  156. return code
  157. }
  158. // HashEmail hashes email address to MD5 string.
  159. // https://en.gravatar.com/site/implement/hash/
  160. func HashEmail(email string) string {
  161. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  162. }
  163. // DefaultAvatarLink the default avatar link
  164. func DefaultAvatarLink() string {
  165. return setting.AppSubURL + "/img/avatar_default.png"
  166. }
  167. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  168. // determined by the avatar-hosting service.
  169. const DefaultAvatarSize = -1
  170. // libravatarURL returns the URL for the given email. This function should only
  171. // be called if a federated avatar service is enabled.
  172. func libravatarURL(email string) (*url.URL, error) {
  173. urlStr, err := setting.LibravatarService.FromEmail(email)
  174. if err != nil {
  175. log.Error(4, "LibravatarService.FromEmail(email=%s): error %v", email, err)
  176. return nil, err
  177. }
  178. u, err := url.Parse(urlStr)
  179. if err != nil {
  180. log.Error(4, "Failed to parse libravatar url(%s): error %v", urlStr, err)
  181. return nil, err
  182. }
  183. return u, nil
  184. }
  185. // SizedAvatarLink returns a sized link to the avatar for the given email
  186. // address.
  187. func SizedAvatarLink(email string, size int) string {
  188. var avatarURL *url.URL
  189. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  190. var err error
  191. avatarURL, err = libravatarURL(email)
  192. if err != nil {
  193. return DefaultAvatarLink()
  194. }
  195. } else if !setting.DisableGravatar {
  196. // copy GravatarSourceURL, because we will modify its Path.
  197. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  198. avatarURL = &copyOfGravatarSourceURL
  199. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  200. } else {
  201. return DefaultAvatarLink()
  202. }
  203. vals := avatarURL.Query()
  204. vals.Set("d", "identicon")
  205. if size != DefaultAvatarSize {
  206. vals.Set("s", strconv.Itoa(size))
  207. }
  208. avatarURL.RawQuery = vals.Encode()
  209. return avatarURL.String()
  210. }
  211. // AvatarLink returns relative avatar link to the site domain by given email,
  212. // which includes app sub-url as prefix. However, it is possible
  213. // to return full URL if user enables Gravatar-like service.
  214. func AvatarLink(email string) string {
  215. return SizedAvatarLink(email, DefaultAvatarSize)
  216. }
  217. // Seconds-based time units
  218. const (
  219. Minute = 60
  220. Hour = 60 * Minute
  221. Day = 24 * Hour
  222. Week = 7 * Day
  223. Month = 30 * Day
  224. Year = 12 * Month
  225. )
  226. func computeTimeDiff(diff int64, lang string) (int64, string) {
  227. diffStr := ""
  228. switch {
  229. case diff <= 0:
  230. diff = 0
  231. diffStr = i18n.Tr(lang, "tool.now")
  232. case diff < 2:
  233. diff = 0
  234. diffStr = i18n.Tr(lang, "tool.1s")
  235. case diff < 1*Minute:
  236. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  237. diff = 0
  238. case diff < 2*Minute:
  239. diff -= 1 * Minute
  240. diffStr = i18n.Tr(lang, "tool.1m")
  241. case diff < 1*Hour:
  242. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  243. diff -= diff / Minute * Minute
  244. case diff < 2*Hour:
  245. diff -= 1 * Hour
  246. diffStr = i18n.Tr(lang, "tool.1h")
  247. case diff < 1*Day:
  248. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  249. diff -= diff / Hour * Hour
  250. case diff < 2*Day:
  251. diff -= 1 * Day
  252. diffStr = i18n.Tr(lang, "tool.1d")
  253. case diff < 1*Week:
  254. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  255. diff -= diff / Day * Day
  256. case diff < 2*Week:
  257. diff -= 1 * Week
  258. diffStr = i18n.Tr(lang, "tool.1w")
  259. case diff < 1*Month:
  260. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  261. diff -= diff / Week * Week
  262. case diff < 2*Month:
  263. diff -= 1 * Month
  264. diffStr = i18n.Tr(lang, "tool.1mon")
  265. case diff < 1*Year:
  266. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  267. diff -= diff / Month * Month
  268. case diff < 2*Year:
  269. diff -= 1 * Year
  270. diffStr = i18n.Tr(lang, "tool.1y")
  271. default:
  272. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  273. diff -= (diff / Year) * Year
  274. }
  275. return diff, diffStr
  276. }
  277. // MinutesToFriendly returns a user friendly string with number of minutes
  278. // converted to hours and minutes.
  279. func MinutesToFriendly(minutes int, lang string) string {
  280. duration := time.Duration(minutes) * time.Minute
  281. return TimeSincePro(time.Now().Add(-duration), lang)
  282. }
  283. // TimeSincePro calculates the time interval and generate full user-friendly string.
  284. func TimeSincePro(then time.Time, lang string) string {
  285. return timeSincePro(then, time.Now(), lang)
  286. }
  287. func timeSincePro(then, now time.Time, lang string) string {
  288. diff := now.Unix() - then.Unix()
  289. if then.After(now) {
  290. return i18n.Tr(lang, "tool.future")
  291. }
  292. if diff == 0 {
  293. return i18n.Tr(lang, "tool.now")
  294. }
  295. var timeStr, diffStr string
  296. for {
  297. if diff == 0 {
  298. break
  299. }
  300. diff, diffStr = computeTimeDiff(diff, lang)
  301. timeStr += ", " + diffStr
  302. }
  303. return strings.TrimPrefix(timeStr, ", ")
  304. }
  305. func timeSince(then, now time.Time, lang string) string {
  306. return timeSinceUnix(then.Unix(), now.Unix(), lang)
  307. }
  308. func timeSinceUnix(then, now int64, lang string) string {
  309. lbl := "tool.ago"
  310. diff := now - then
  311. if then > now {
  312. lbl = "tool.from_now"
  313. diff = then - now
  314. }
  315. if diff <= 0 {
  316. return i18n.Tr(lang, "tool.now")
  317. }
  318. _, diffStr := computeTimeDiff(diff, lang)
  319. return i18n.Tr(lang, lbl, diffStr)
  320. }
  321. // RawTimeSince retrieves i18n key of time since t
  322. func RawTimeSince(t time.Time, lang string) string {
  323. return timeSince(t, time.Now(), lang)
  324. }
  325. // TimeSince calculates the time interval and generate user-friendly string.
  326. func TimeSince(then time.Time, lang string) template.HTML {
  327. return htmlTimeSince(then, time.Now(), lang)
  328. }
  329. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  330. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  331. then.Format(setting.TimeFormat),
  332. timeSince(then, now, lang)))
  333. }
  334. // TimeSinceUnix calculates the time interval and generate user-friendly string.
  335. func TimeSinceUnix(then util.TimeStamp, lang string) template.HTML {
  336. return htmlTimeSinceUnix(then, util.TimeStamp(time.Now().Unix()), lang)
  337. }
  338. func htmlTimeSinceUnix(then, now util.TimeStamp, lang string) template.HTML {
  339. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  340. then.Format(setting.TimeFormat),
  341. timeSinceUnix(int64(then), int64(now), lang)))
  342. }
  343. // Storage space size types
  344. const (
  345. Byte = 1
  346. KByte = Byte * 1024
  347. MByte = KByte * 1024
  348. GByte = MByte * 1024
  349. TByte = GByte * 1024
  350. PByte = TByte * 1024
  351. EByte = PByte * 1024
  352. )
  353. var bytesSizeTable = map[string]uint64{
  354. "b": Byte,
  355. "kb": KByte,
  356. "mb": MByte,
  357. "gb": GByte,
  358. "tb": TByte,
  359. "pb": PByte,
  360. "eb": EByte,
  361. }
  362. func logn(n, b float64) float64 {
  363. return math.Log(n) / math.Log(b)
  364. }
  365. func humanateBytes(s uint64, base float64, sizes []string) string {
  366. if s < 10 {
  367. return fmt.Sprintf("%dB", s)
  368. }
  369. e := math.Floor(logn(float64(s), base))
  370. suffix := sizes[int(e)]
  371. val := float64(s) / math.Pow(base, math.Floor(e))
  372. f := "%.0f"
  373. if val < 10 {
  374. f = "%.1f"
  375. }
  376. return fmt.Sprintf(f+"%s", val, suffix)
  377. }
  378. // FileSize calculates the file size and generate user-friendly string.
  379. func FileSize(s int64) string {
  380. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  381. return humanateBytes(uint64(s), 1024, sizes)
  382. }
  383. // Subtract deals with subtraction of all types of number.
  384. func Subtract(left interface{}, right interface{}) interface{} {
  385. var rleft, rright int64
  386. var fleft, fright float64
  387. var isInt = true
  388. switch left.(type) {
  389. case int:
  390. rleft = int64(left.(int))
  391. case int8:
  392. rleft = int64(left.(int8))
  393. case int16:
  394. rleft = int64(left.(int16))
  395. case int32:
  396. rleft = int64(left.(int32))
  397. case int64:
  398. rleft = left.(int64)
  399. case float32:
  400. fleft = float64(left.(float32))
  401. isInt = false
  402. case float64:
  403. fleft = left.(float64)
  404. isInt = false
  405. }
  406. switch right.(type) {
  407. case int:
  408. rright = int64(right.(int))
  409. case int8:
  410. rright = int64(right.(int8))
  411. case int16:
  412. rright = int64(right.(int16))
  413. case int32:
  414. rright = int64(right.(int32))
  415. case int64:
  416. rright = right.(int64)
  417. case float32:
  418. fright = float64(right.(float32))
  419. isInt = false
  420. case float64:
  421. fright = right.(float64)
  422. isInt = false
  423. }
  424. if isInt {
  425. return rleft - rright
  426. }
  427. return fleft + float64(rleft) - (fright + float64(rright))
  428. }
  429. // EllipsisString returns a truncated short string,
  430. // it appends '...' in the end of the length of string is too large.
  431. func EllipsisString(str string, length int) string {
  432. if length <= 3 {
  433. return "..."
  434. }
  435. if len(str) <= length {
  436. return str
  437. }
  438. return str[:length-3] + "..."
  439. }
  440. // TruncateString returns a truncated string with given limit,
  441. // it returns input string if length is not reached limit.
  442. func TruncateString(str string, limit int) string {
  443. if len(str) < limit {
  444. return str
  445. }
  446. return str[:limit]
  447. }
  448. // StringsToInt64s converts a slice of string to a slice of int64.
  449. func StringsToInt64s(strs []string) ([]int64, error) {
  450. ints := make([]int64, len(strs))
  451. for i := range strs {
  452. n, err := com.StrTo(strs[i]).Int64()
  453. if err != nil {
  454. return ints, err
  455. }
  456. ints[i] = n
  457. }
  458. return ints, nil
  459. }
  460. // Int64sToStrings converts a slice of int64 to a slice of string.
  461. func Int64sToStrings(ints []int64) []string {
  462. strs := make([]string, len(ints))
  463. for i := range ints {
  464. strs[i] = strconv.FormatInt(ints[i], 10)
  465. }
  466. return strs
  467. }
  468. // Int64sToMap converts a slice of int64 to a int64 map.
  469. func Int64sToMap(ints []int64) map[int64]bool {
  470. m := make(map[int64]bool)
  471. for _, i := range ints {
  472. m[i] = true
  473. }
  474. return m
  475. }
  476. // Int64sContains returns if a int64 in a slice of int64
  477. func Int64sContains(intsSlice []int64, a int64) bool {
  478. for _, c := range intsSlice {
  479. if c == a {
  480. return true
  481. }
  482. }
  483. return false
  484. }
  485. // IsLetter reports whether the rune is a letter (category L).
  486. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  487. func IsLetter(ch rune) bool {
  488. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  489. }
  490. // IsTextFile returns true if file content format is plain text or empty.
  491. func IsTextFile(data []byte) bool {
  492. if len(data) == 0 {
  493. return true
  494. }
  495. return strings.Index(http.DetectContentType(data), "text/") != -1
  496. }
  497. // IsImageFile detects if data is an image format
  498. func IsImageFile(data []byte) bool {
  499. return strings.Index(http.DetectContentType(data), "image/") != -1
  500. }
  501. // IsPDFFile detects if data is a pdf format
  502. func IsPDFFile(data []byte) bool {
  503. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  504. }
  505. // IsVideoFile detects if data is an video format
  506. func IsVideoFile(data []byte) bool {
  507. return strings.Index(http.DetectContentType(data), "video/") != -1
  508. }