file.go 1.6 KB

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