file.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2017 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 tool
  5. import (
  6. "fmt"
  7. "math"
  8. "net/http"
  9. "strings"
  10. )
  11. // IsTextFile returns true if file content format is plain text or empty.
  12. func IsTextFile(data []byte) bool {
  13. if len(data) == 0 {
  14. return true
  15. }
  16. return strings.Contains(http.DetectContentType(data), "text/")
  17. }
  18. func IsAnnexedFile(data []byte) bool {
  19. const ANNEXSNIFFSIZE = 5000
  20. if len(data) == 0 {
  21. return true
  22. }
  23. if !(len(data) < ANNEXSNIFFSIZE) {
  24. data = data[:ANNEXSNIFFSIZE]
  25. }
  26. if strings.Contains(http.DetectContentType(data), "text/") {
  27. return strings.Contains(string(data), "annex")
  28. }
  29. return false
  30. }
  31. func IsImageFile(data []byte) bool {
  32. return strings.Contains(http.DetectContentType(data), "image/")
  33. }
  34. func IsPDFFile(data []byte) bool {
  35. return strings.Contains(http.DetectContentType(data), "application/pdf")
  36. }
  37. func IsVideoFile(data []byte) bool {
  38. return strings.Contains(http.DetectContentType(data), "video/")
  39. }
  40. const (
  41. Byte = 1
  42. KByte = Byte * 1024
  43. MByte = KByte * 1024
  44. GByte = MByte * 1024
  45. TByte = GByte * 1024
  46. PByte = TByte * 1024
  47. EByte = PByte * 1024
  48. )
  49. var bytesSizeTable = map[string]uint64{
  50. "b": Byte,
  51. "kb": KByte,
  52. "mb": MByte,
  53. "gb": GByte,
  54. "tb": TByte,
  55. "pb": PByte,
  56. "eb": EByte,
  57. }
  58. func logn(n, b float64) float64 {
  59. return math.Log(n) / math.Log(b)
  60. }
  61. func humanateBytes(s uint64, base float64, sizes []string) string {
  62. if s < 10 {
  63. return fmt.Sprintf("%d B", s)
  64. }
  65. e := math.Floor(logn(float64(s), base))
  66. suffix := sizes[int(e)]
  67. val := float64(s) / math.Pow(base, math.Floor(e))
  68. f := "%.0f"
  69. if val < 10 {
  70. f = "%.1f"
  71. }
  72. return fmt.Sprintf(f+" %s", val, suffix)
  73. }
  74. // FileSize calculates the file size and generate user-friendly string.
  75. func FileSize(s int64) string {
  76. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  77. return humanateBytes(uint64(s), 1024, sizes)
  78. }