file.go 1.7 KB

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