github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/formatters/bytes.go (about) 1 package formatters 2 3 import ( 4 "errors" 5 "fmt" 6 "regexp" 7 "strconv" 8 "strings" 9 10 . "code.cloudfoundry.org/cli/cf/i18n" 11 ) 12 13 const ( 14 BYTE = 1.0 15 KILOBYTE = 1024 * BYTE 16 MEGABYTE = 1024 * KILOBYTE 17 GIGABYTE = 1024 * MEGABYTE 18 TERABYTE = 1024 * GIGABYTE 19 ) 20 21 func ByteSize(bytes int64) string { 22 unit := "" 23 value := float32(bytes) 24 25 switch { 26 case bytes >= TERABYTE: 27 unit = "T" 28 value = value / TERABYTE 29 case bytes >= GIGABYTE: 30 unit = "G" 31 value = value / GIGABYTE 32 case bytes >= MEGABYTE: 33 unit = "M" 34 value = value / MEGABYTE 35 case bytes >= KILOBYTE: 36 unit = "K" 37 value = value / KILOBYTE 38 case bytes == 0: 39 return "0" 40 case bytes < KILOBYTE: 41 unit = "B" 42 } 43 44 stringValue := fmt.Sprintf("%.1f", value) 45 stringValue = strings.TrimSuffix(stringValue, ".0") 46 return fmt.Sprintf("%s%s", stringValue, unit) 47 } 48 49 func ToMegabytes(s string) (int64, error) { 50 parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s)) 51 if len(parts) < 3 { 52 return 0, invalidByteQuantityError() 53 } 54 55 value, err := strconv.ParseInt(parts[1], 10, 0) 56 if err != nil { 57 return 0, invalidByteQuantityError() 58 } 59 60 var bytes int64 61 unit := strings.ToUpper(parts[2]) 62 switch unit { 63 case "T": 64 bytes = value * TERABYTE 65 case "G": 66 bytes = value * GIGABYTE 67 case "M": 68 bytes = value * MEGABYTE 69 case "K": 70 bytes = value * KILOBYTE 71 } 72 73 return bytes / MEGABYTE, nil 74 } 75 76 var ( 77 bytesPattern = regexp.MustCompile(`(?i)^(-?\d+)([KMGT])B?$`) 78 ) 79 80 func invalidByteQuantityError() error { 81 return errors.New(T("Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB")) 82 }