Debian Codegraph @

lib/lib.go

raw
1 // Package lib contains functions useful for most programs.
2 package lib
3
4 import (
5 "fmt"
6 "os"
7 "path/filepath"
8 "time"
9 )
10
11 var progname = filepath.Base(os.Args[0])
12
13 // ProgName returns what lib thinks the program name is, namely the
14 // basename of of argv0.
15 //
16 // It is similar to the Linux __progname function.
17 func ProgName() string {
18 return progname
19 }
20
21 // Warnx displays a formatted error message to standard error, à la
22 // warnx(3).
23 func Warnx(format string, a ...interface{}) (int, error) {
24 format = fmt.Sprintf("[%s] %s", progname, format)
25 format += "\n"
26 return fmt.Fprintf(os.Stderr, format, a...)
27 }
28
29 // Warn displays a formatted error message to standard output,
30 // appending the error string, à la warn(3).
31 func Warn(err error, format string, a ...interface{}) (int, error) {
32 format = fmt.Sprintf("[%s] %s", progname, format)
33 format += ": %v\n"
34 a = append(a, err)
35 return fmt.Fprintf(os.Stderr, format, a...)
36 }
37
38 // Errx displays a formatted error message to standard error and exits
39 // with the status code from `exit`, à la errx(3).
40 func Errx(exit int, format string, a ...interface{}) {
41 format = fmt.Sprintf("[%s] %s", progname, format)
42 format += "\n"
43 fmt.Fprintf(os.Stderr, format, a...)
44 os.Exit(exit)
45 }
46
47 // Err displays a formatting error message to standard error,
48 // appending the error string, and exits with the status code from
49 // `exit`, à la err(3).
50 func Err(exit int, err error, format string, a ...interface{}) {
51 format = fmt.Sprintf("[%s] %s", progname, format)
52 format += ": %v\n"
53 a = append(a, err)
54 fmt.Fprintf(os.Stderr, format, a...)
55 os.Exit(exit)
56 }
57
58 // Itoa provides cheap integer to fixed-width decimal ASCII. Give a
59 // negative width to avoid zero-padding. Adapted from the 'itoa'
60 // function in the log/log.go file in the standard library.
61 func Itoa(i int, wid int) string {
62 // Assemble decimal in reverse order.
63 var b [20]byte
64 bp := len(b) - 1
65 for i >= 10 || wid > 1 {
66 wid--
67 q := i / 10
68 b[bp] = byte('0' + i - q*10)
69 bp--
70 i = q
71 }
72 // i < 10
73 b[bp] = byte('0' + i)
74 return string(b[bp:])
75 }
76
77 var (
78 dayDuration = 24 * time.Hour
79 yearDuration = (365 * dayDuration) + (6 * time.Hour)
80 )
81
82 func Duration(d time.Duration) string {
83 var s string
84 if d >= yearDuration {
85 years := d / yearDuration
86 s += fmt.Sprintf("%dy", years)
87 d -= (years * yearDuration)
88 }
89
90 if d >= dayDuration {
91 days := d / dayDuration
92 s += fmt.Sprintf("%dd", days)
93 }
94
95 if s != "" {
96 return s
97 }
98
99 d %= 1 * time.Second
100 hours := d / time.Hour
101 d -= (hours * time.Hour)
102 s += fmt.Sprintf("%dh%s", hours, d)
103 return s
104 }