-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
mgutil.go
75 lines (68 loc) · 1.56 KB
/
mgutil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Package mgutil is a collections of utility types and functions with no dependency on margo.sh/mg
package mgutil
import (
"strconv"
"strings"
)
// QuoteCmdArg uses strconv.Quote to quote the command arg s.
// NOTE: the result is for display only, and should not be used for shell security.
// e.g.
// `a b c` -> `"a b c"`
// `abc` -> `abc`
// `-abc=123` -> `-abc=123`
// `-abc=1 2 3` -> `-abc="1 2 3"`
func QuoteCmdArg(s string) string {
eqPos := strings.Index(s, "=")
switch {
case s == "":
return `""`
case !strings.Contains(s, " "):
return s
case strings.HasPrefix(s, "-") && eqPos > 0:
return s[:eqPos+1] + strconv.Quote(s[eqPos+1:])
default:
return strconv.Quote(s)
}
}
// QuoteCmd joins `name [args]` with name and each arg quoted with QuoteCmdArg
// NOTE: the result is for display only, and should not be used for shell security.
func QuoteCmd(name string, args ...string) string {
a := append([]string{name}, args...)
for i, s := range a {
a[i] = QuoteCmdArg(s)
}
return strings.Join(a, " ")
}
// Clamp limits n to the interval [ lo, hi ]
func Clamp(lo, hi int, n int) int {
switch {
case n <= lo:
return lo
case n >= hi:
return hi
default:
return n
}
}
// ClampPos limits pos to the interval [ 0, len(s) ]
func ClampPos(s []byte, pos int) int {
return Clamp(0, len(s), pos)
}
// Max returns the largest of p or q.
func Max(p int, q ...int) int {
for _, q := range q {
if q > p {
p = q
}
}
return p
}
// Min returns the smallest of p or q.
func Min(p int, q ...int) int {
for _, q := range q {
if q < p {
p = q
}
}
return p
}