Debian Codegraph @

lib/format/format.go

raw
1 package format
2
3 import (
4 "fmt"
5 "strings"
6 "time"
7 "unicode"
8
9 "github.com/emersion/go-message/mail"
10 )
11
12 const rfc5322specials string = `()<>[]:;@\,."`
13
14 // AddressForHumans formats the address.
15 // Meant for display purposes to the humans, not for sending over the wire.
16 func AddressForHumans(a *mail.Address) string {
17 if a.Name != "" {
18 if strings.ContainsAny(a.Name, rfc5322specials) {
19 return fmt.Sprintf("\"%s\" <%s>",
20 strings.ReplaceAll(a.Name, "\"", "'"), a.Address)
21 } else {
22 return fmt.Sprintf("%s <%s>", a.Name, a.Address)
23 }
24 } else {
25 return fmt.Sprintf("<%s>", a.Address)
26 }
27 }
28
29 // FormatAddresses formats a list of addresses into a human readable string
30 func FormatAddresses(l []*mail.Address) string {
31 formatted := make([]string, len(l))
32 for i, a := range l {
33 formatted[i] = strings.TrimSpace(AddressForHumans(a))
34 }
35 return strings.Join(formatted, ", ")
36 }
37
38 // CompactPath reduces a directory path into a compact form. The directory
39 // name will be split with the provided separator and each part will be reduced
40 // to the first letter in its name: INBOX/01_WORK/PROJECT will become
41 // I/W/PROJECT.
42 func CompactPath(name string, sep rune) (compact string) {
43 parts := strings.Split(name, string(sep))
44 for i, part := range parts {
45 if i == len(parts)-1 {
46 compact += part
47 } else {
48 if len(part) != 0 {
49 r := part[0]
50 for i := 0; i < len(part)-1; i++ {
51 if unicode.IsLetter(rune(part[i])) {
52 r = part[i]
53 break
54 }
55 }
56 compact += fmt.Sprintf("%c%c", r, sep)
57 } else {
58 compact += fmt.Sprintf("%c", sep)
59 }
60 }
61 }
62 return
63 }
64
65 func DummyIfZeroDate(date time.Time, format string, todayFormat string,
66 thisWeekFormat string, thisYearFormat string,
67 ) string {
68 if date.IsZero() {
69 return strings.Repeat("?", len(format))
70 }
71 year := date.Year()
72 day := date.YearDay()
73 now := time.Now()
74 thisYear := now.Year()
75 thisDay := now.YearDay()
76 if year == thisYear {
77 if day == thisDay && todayFormat != "" {
78 return date.Format(todayFormat)
79 }
80 if day > thisDay-7 && thisWeekFormat != "" {
81 return date.Format(thisWeekFormat)
82 }
83 if thisYearFormat != "" {
84 return date.Format(thisYearFormat)
85 }
86 }
87 return date.Format(format)
88 }