forked from ooni/probe-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
82 lines (74 loc) · 2.22 KB
/
utils.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
package main
//
// Utility functions
//
import (
"errors"
"net/url"
"os"
"runtime"
"strings"
"github.com/ooni/probe-cli/v3/internal/runtimex"
)
// splitPair takes in input a string in the form KEY=VALUE and splits it. This
// function returns an error if it cannot find the = character to split the string.
func splitPair(s string) (string, string, error) {
v := strings.SplitN(s, "=", 2)
if len(v) != 2 {
return "", "", errors.New("invalid key-value pair")
}
return v[0], v[1], nil
}
// mustMakeMapStringString makes a map from string to string using as input a list
// of key-value pairs used to initialize the map, or panics on error
func mustMakeMapStringString(input []string) (output map[string]string) {
output = make(map[string]string)
for _, opt := range input {
key, value, err := splitPair(opt)
runtimex.PanicOnError(err, "cannot split key-value pair")
output[key] = value
}
return
}
// mustMakeMapStringAny makes a map from string to any using as input a list
// of key-value pairs used to initialize the map, or panics on error
func mustMakeMapStringAny(input []string) (output map[string]any) {
output = make(map[string]any)
for _, opt := range input {
key, value, err := splitPair(opt)
runtimex.PanicOnError(err, "cannot split key-value pair")
output[key] = value
}
return
}
// mustParseURL parses the given URL or panics
func mustParseURL(URL string) *url.URL {
rv, err := url.Parse(URL)
runtimex.PanicOnError(err, "cannot parse URL")
return rv
}
// gethomedir returns the home directory. If optionsHome is set, then we
// return that string as the home directory. Otherwise, we use typical
// platform-specific environment variables to determine the home. In case
// of failure to determine the home dir, we return an empty string.
func gethomedir(optionsHome string) string {
// See https://gist.github.com/miguelmota/f30a04a6d64bd52d7ab59ea8d95e54da
if optionsHome != "" {
return optionsHome
}
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
if runtime.GOOS == "linux" {
home := os.Getenv("XDG_CONFIG_HOME")
if home != "" {
return home
}
// fallthrough
}
return os.Getenv("HOME")
}