github.com/andrewhsu/cli/v2@v2.0.1-0.20210910131313-d4b4061f5b89/utils/utils.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"strings"
     7  	"time"
     8  )
     9  
    10  func Pluralize(num int, thing string) string {
    11  	if num == 1 {
    12  		return fmt.Sprintf("%d %s", num, thing)
    13  	}
    14  	return fmt.Sprintf("%d %ss", num, thing)
    15  }
    16  
    17  func fmtDuration(amount int, unit string) string {
    18  	return fmt.Sprintf("about %s ago", Pluralize(amount, unit))
    19  }
    20  
    21  func FuzzyAgo(ago time.Duration) string {
    22  	if ago < time.Minute {
    23  		return "less than a minute ago"
    24  	}
    25  	if ago < time.Hour {
    26  		return fmtDuration(int(ago.Minutes()), "minute")
    27  	}
    28  	if ago < 24*time.Hour {
    29  		return fmtDuration(int(ago.Hours()), "hour")
    30  	}
    31  	if ago < 30*24*time.Hour {
    32  		return fmtDuration(int(ago.Hours())/24, "day")
    33  	}
    34  	if ago < 365*24*time.Hour {
    35  		return fmtDuration(int(ago.Hours())/24/30, "month")
    36  	}
    37  
    38  	return fmtDuration(int(ago.Hours()/24/365), "year")
    39  }
    40  
    41  func FuzzyAgoAbbr(now time.Time, createdAt time.Time) string {
    42  	ago := now.Sub(createdAt)
    43  
    44  	if ago < time.Hour {
    45  		return fmt.Sprintf("%d%s", int(ago.Minutes()), "m")
    46  	}
    47  	if ago < 24*time.Hour {
    48  		return fmt.Sprintf("%d%s", int(ago.Hours()), "h")
    49  	}
    50  	if ago < 30*24*time.Hour {
    51  		return fmt.Sprintf("%d%s", int(ago.Hours())/24, "d")
    52  	}
    53  
    54  	return createdAt.Format("Jan _2, 2006")
    55  }
    56  
    57  func Humanize(s string) string {
    58  	// Replaces - and _ with spaces.
    59  	replace := "_-"
    60  	h := func(r rune) rune {
    61  		if strings.ContainsRune(replace, r) {
    62  			return ' '
    63  		}
    64  		return r
    65  	}
    66  
    67  	return strings.Map(h, s)
    68  }
    69  
    70  func IsURL(s string) bool {
    71  	return strings.HasPrefix(s, "http:/") || strings.HasPrefix(s, "https:/")
    72  }
    73  
    74  func DisplayURL(urlStr string) string {
    75  	u, err := url.Parse(urlStr)
    76  	if err != nil {
    77  		return urlStr
    78  	}
    79  	return u.Hostname() + u.Path
    80  }
    81  
    82  // Maximum length of a URL: 8192 bytes
    83  func ValidURL(urlStr string) bool {
    84  	return len(urlStr) < 8192
    85  }