github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/internal/text/text.go (about)

     1  package text
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"regexp"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/cli/go-gh/pkg/text"
    11  	"golang.org/x/text/cases"
    12  	"golang.org/x/text/language"
    13  )
    14  
    15  var whitespaceRE = regexp.MustCompile(`\s+`)
    16  
    17  func Indent(s, indent string) string {
    18  	return text.Indent(s, indent)
    19  }
    20  
    21  // Title returns a copy of the string s with all Unicode letters that begin words mapped to their Unicode title case.
    22  func Title(s string) string {
    23  	c := cases.Title(language.English)
    24  	return c.String(s)
    25  }
    26  
    27  // RemoveExcessiveWhitespace returns a copy of the string s with excessive whitespace removed.
    28  func RemoveExcessiveWhitespace(s string) string {
    29  	return whitespaceRE.ReplaceAllString(strings.TrimSpace(s), " ")
    30  }
    31  
    32  func DisplayWidth(s string) int {
    33  	return text.DisplayWidth(s)
    34  }
    35  
    36  func Truncate(maxWidth int, s string) string {
    37  	return text.Truncate(maxWidth, s)
    38  }
    39  
    40  func Pluralize(num int, thing string) string {
    41  	return text.Pluralize(num, thing)
    42  }
    43  
    44  func FuzzyAgo(a, b time.Time) string {
    45  	return text.RelativeTimeAgo(a, b)
    46  }
    47  
    48  // FuzzyAgoAbbr is an abbreviated version of FuzzyAgo. It returns a human readable string of the
    49  // time duration between a and b that is estimated to the nearest unit of time.
    50  func FuzzyAgoAbbr(a, b time.Time) string {
    51  	ago := a.Sub(b)
    52  
    53  	if ago < time.Hour {
    54  		return fmt.Sprintf("%d%s", int(ago.Minutes()), "m")
    55  	}
    56  	if ago < 24*time.Hour {
    57  		return fmt.Sprintf("%d%s", int(ago.Hours()), "h")
    58  	}
    59  	if ago < 30*24*time.Hour {
    60  		return fmt.Sprintf("%d%s", int(ago.Hours())/24, "d")
    61  	}
    62  
    63  	return b.Format("Jan _2, 2006")
    64  }
    65  
    66  // DisplayURL returns a copy of the string urlStr removing everything except the hostname and path.
    67  // If there is an error parsing urlStr then urlStr is returned without modification.
    68  func DisplayURL(urlStr string) string {
    69  	u, err := url.Parse(urlStr)
    70  	if err != nil {
    71  		return urlStr
    72  	}
    73  	return u.Hostname() + u.Path
    74  }