file.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package tool
  7. import (
  8. "fmt"
  9. "math"
  10. "net/http"
  11. "strings"
  12. )
  13. // IsTextFile returns true if file content format is plain text or empty.
  14. func IsTextFile(data []byte) bool {
  15. if len(data) == 0 {
  16. return true
  17. }
  18. return strings.Contains(http.DetectContentType(data), "text/")
  19. }
  20. // IsImageFile detects if data is an image format
  21. func IsImageFile(data []byte) bool {
  22. return strings.Contains(http.DetectContentType(data), "image/")
  23. }
  24. // IsPDFFile detects if data is a pdf format
  25. func IsPDFFile(data []byte) bool {
  26. return strings.Contains(http.DetectContentType(data), "application/pdf")
  27. }
  28. // IsVideoFile detects if data is an video format
  29. func IsVideoFile(data []byte) bool {
  30. return strings.Contains(http.DetectContentType(data), "video/")
  31. }
  32. // hold memory types
  33. const (
  34. Byte = 1
  35. KByte = Byte * 1024
  36. MByte = KByte * 1024
  37. GByte = MByte * 1024
  38. TByte = GByte * 1024
  39. PByte = TByte * 1024
  40. EByte = PByte * 1024
  41. )
  42. var bytesSizeTable = map[string]uint64{
  43. "b": Byte,
  44. "kb": KByte,
  45. "mb": MByte,
  46. "gb": GByte,
  47. "tb": TByte,
  48. "pb": PByte,
  49. "eb": EByte,
  50. }
  51. func logn(n, b float64) float64 {
  52. return math.Log(n) / math.Log(b)
  53. }
  54. func humanateBytes(s uint64, base float64, sizes []string) string {
  55. if s < 10 {
  56. return fmt.Sprintf("%d B", s)
  57. }
  58. e := math.Floor(logn(float64(s), base))
  59. suffix := sizes[int(e)]
  60. val := float64(s) / math.Pow(base, math.Floor(e))
  61. f := "%.0f"
  62. if val < 10 {
  63. f = "%.1f"
  64. }
  65. return fmt.Sprintf(f+" %s", val, suffix)
  66. }
  67. // FileSize calculates the file size and generate user-friendly string.
  68. func FileSize(s int64) string {
  69. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  70. return humanateBytes(uint64(s), 1024, sizes)
  71. }