file.go 1.9 KB

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