file.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. func logn(n, b float64) float64 {
  28. return math.Log(n) / math.Log(b)
  29. }
  30. func humanateBytes(s uint64, base float64, sizes []string) string {
  31. if s < 10 {
  32. return fmt.Sprintf("%d B", s)
  33. }
  34. e := math.Floor(logn(float64(s), base))
  35. suffix := sizes[int(e)]
  36. val := float64(s) / math.Pow(base, math.Floor(e))
  37. f := "%.0f"
  38. if val < 10 {
  39. f = "%.1f"
  40. }
  41. return fmt.Sprintf(f+" %s", val, suffix)
  42. }
  43. // FileSize calculates the file size and generate user-friendly string.
  44. func FileSize(s int64) string {
  45. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  46. return humanateBytes(uint64(s), 1024, sizes)
  47. }