This repository has been archived by the owner on Nov 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
124 lines (99 loc) · 2.35 KB
/
util.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package util
import (
"bytes"
"fmt"
"log"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
getopt "github.com/pborman/getopt/v2"
)
type PanicfWrapper func(panicfFormat string, panicfArgs ...interface{})
var InternalPanicf = func(format string, args ...interface{}) {
if len(args) > 0 {
log.Panicf(format, args)
}
log.Panic(format)
}
var CheckGoroutineCount bool
var ProfileStartStop func() func()
// FileHandleOptimizations is populated by individual OS-specific init()s
var ReadOptimizations []FileHandleOptimization
type FileHandleOptimization struct {
Name string
Action func(
file *os.File,
stat os.FileInfo,
) error
}
// This is a surprisingly cheap and reliable way to emulate a part of unsafe.*
// Use this for various syscalls, not to pull in unsafe and make folks go 😱🙀🤮
func _addressofref(val interface{}) uintptr {
a, _ := strconv.ParseInt(fmt.Sprintf("%p", val), 0, 64)
return uintptr(a)
}
func Commify(inVal int) []byte {
return Commify64(int64(inVal))
}
func Commify64(inVal int64) []byte {
inStr := strconv.FormatInt(inVal, 10)
outStr := make([]byte, 0, 20)
i := 1
if inVal < 0 {
outStr = append(outStr, '-')
i++
}
for i <= len(inStr) {
outStr = append(outStr, inStr[i-1])
if i < len(inStr) &&
((len(inStr)-i)%3) == 0 {
outStr = append(outStr, ',')
}
i++
}
return outStr
}
func AvailableMapKeys(m interface{}) string {
v := reflect.ValueOf(m)
if v.Kind() != reflect.Map {
log.Panicf("input type not a map: %v", v)
}
avail := make([]string, 0, v.Len())
for _, k := range v.MapKeys() {
avail = append(avail, "'"+k.String()+"'")
}
sort.Strings(avail)
return strings.Join(avail, ", ")
}
// ugly as sin due to lack of lookaheads :/
var indenter = regexp.MustCompile(`(?m)^([^\n])`)
var nonOptIndenter = regexp.MustCompile(`(?m)^\s{0,12}([^\s\n\-])`)
var dashStripper = regexp.MustCompile(`(?m)^(\s*)\-\-`)
func SubHelp(description string, optSet *getopt.Set) (sh []string) {
sh = append(
sh,
string(indenter.ReplaceAll(
[]byte(description),
[]byte(` $1`),
)),
)
if optSet == nil {
return sh
}
b := bytes.NewBuffer(make([]byte, 0, 1024))
optSet.PrintOptions(b)
sh = append(sh, " ::SubOptions::")
sh = append(sh,
string(dashStripper.ReplaceAll(
nonOptIndenter.ReplaceAll(
b.Bytes(),
[]byte(` $1`),
),
[]byte(`$1 `),
)),
)
return sh
}