id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
15,700 | nbari/violetear | trie.go | Get | func (t *Trie) Get(path, version string) (*Trie, string, string, bool) {
key, path := t.SplitPath(path)
// search the key recursively on the tree
if node, ok := t.contains(key, version); ok {
if path == "" {
return node, key, path, true
}
return node.Get(path, version)
}
// if not fount check for catchall or regex
return t, key, path, false
} | go | func (t *Trie) Get(path, version string) (*Trie, string, string, bool) {
key, path := t.SplitPath(path)
// search the key recursively on the tree
if node, ok := t.contains(key, version); ok {
if path == "" {
return node, key, path, true
}
return node.Get(path, version)
}
// if not fount check for catchall or regex
return t, key, path, false
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"Get",
"(",
"path",
",",
"version",
"string",
")",
"(",
"*",
"Trie",
",",
"string",
",",
"string",
",",
"bool",
")",
"{",
"key",
",",
"path",
":=",
"t",
".",
"SplitPath",
"(",
"path",
")",
"\n",
"// search the key recursively on the tree",
"if",
"node",
",",
"ok",
":=",
"t",
".",
"contains",
"(",
"key",
",",
"version",
")",
";",
"ok",
"{",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"node",
",",
"key",
",",
"path",
",",
"true",
"\n",
"}",
"\n",
"return",
"node",
".",
"Get",
"(",
"path",
",",
"version",
")",
"\n",
"}",
"\n",
"// if not fount check for catchall or regex",
"return",
"t",
",",
"key",
",",
"path",
",",
"false",
"\n",
"}"
] | // Get returns a node | [
"Get",
"returns",
"a",
"node"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/trie.go#L83-L94 |
15,701 | nbari/violetear | trie.go | SplitPath | func (t *Trie) SplitPath(path string) (string, string) {
var key string
if path == "" {
return key, path
} else if path == "/" {
return path, ""
}
for i := 0; i < len(path); i++ {
if path[i] == '/' {
if i == 0 {
return t.SplitPath(path[1:])
}
if i > 0 {
key = path[:i]
path = path[i:]
if path == "/" {
return key, ""
}
return key, path
}
}
}
return path, ""
} | go | func (t *Trie) SplitPath(path string) (string, string) {
var key string
if path == "" {
return key, path
} else if path == "/" {
return path, ""
}
for i := 0; i < len(path); i++ {
if path[i] == '/' {
if i == 0 {
return t.SplitPath(path[1:])
}
if i > 0 {
key = path[:i]
path = path[i:]
if path == "/" {
return key, ""
}
return key, path
}
}
}
return path, ""
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"SplitPath",
"(",
"path",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"var",
"key",
"string",
"\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"key",
",",
"path",
"\n",
"}",
"else",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"path",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"path",
")",
";",
"i",
"++",
"{",
"if",
"path",
"[",
"i",
"]",
"==",
"'/'",
"{",
"if",
"i",
"==",
"0",
"{",
"return",
"t",
".",
"SplitPath",
"(",
"path",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"\n",
"if",
"i",
">",
"0",
"{",
"key",
"=",
"path",
"[",
":",
"i",
"]",
"\n",
"path",
"=",
"path",
"[",
"i",
":",
"]",
"\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"key",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"key",
",",
"path",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"path",
",",
"\"",
"\"",
"\n",
"}"
] | // SplitPath returns first element of path and remaining path | [
"SplitPath",
"returns",
"first",
"element",
"of",
"path",
"and",
"remaining",
"path"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/trie.go#L97-L120 |
15,702 | nbari/violetear | trie.go | Name | func (t *Trie) Name(name string) *Trie {
t.name = name
return t
} | go | func (t *Trie) Name(name string) *Trie {
t.name = name
return t
} | [
"func",
"(",
"t",
"*",
"Trie",
")",
"Name",
"(",
"name",
"string",
")",
"*",
"Trie",
"{",
"t",
".",
"name",
"=",
"name",
"\n",
"return",
"t",
"\n",
"}"
] | // Name add custom name to node | [
"Name",
"add",
"custom",
"name",
"to",
"node"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/trie.go#L123-L126 |
15,703 | nbari/violetear | logger.go | logger | func logger(ww *ResponseWriter, r *http.Request) {
log.Printf("%s [%s] %d %d %s %s",
r.RemoteAddr,
r.URL,
ww.Status(),
ww.Size(),
ww.RequestTime(),
ww.RequestID())
} | go | func logger(ww *ResponseWriter, r *http.Request) {
log.Printf("%s [%s] %d %d %s %s",
r.RemoteAddr,
r.URL,
ww.Status(),
ww.Size(),
ww.RequestTime(),
ww.RequestID())
} | [
"func",
"logger",
"(",
"ww",
"*",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"RemoteAddr",
",",
"r",
".",
"URL",
",",
"ww",
".",
"Status",
"(",
")",
",",
"ww",
".",
"Size",
"(",
")",
",",
"ww",
".",
"RequestTime",
"(",
")",
",",
"ww",
".",
"RequestID",
"(",
")",
")",
"\n",
"}"
] | // logger log values separated by space | [
"logger",
"log",
"values",
"separated",
"by",
"space"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/logger.go#L9-L17 |
15,704 | nbari/violetear | params.go | Add | func (p Params) Add(k, v string) {
if param, ok := p[k]; ok {
switch param.(type) {
case string:
param = []string{param.(string), v}
case []string:
param = append(param.([]string), v)
}
p[k] = param
} else {
p[k] = v
}
} | go | func (p Params) Add(k, v string) {
if param, ok := p[k]; ok {
switch param.(type) {
case string:
param = []string{param.(string), v}
case []string:
param = append(param.([]string), v)
}
p[k] = param
} else {
p[k] = v
}
} | [
"func",
"(",
"p",
"Params",
")",
"Add",
"(",
"k",
",",
"v",
"string",
")",
"{",
"if",
"param",
",",
"ok",
":=",
"p",
"[",
"k",
"]",
";",
"ok",
"{",
"switch",
"param",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"param",
"=",
"[",
"]",
"string",
"{",
"param",
".",
"(",
"string",
")",
",",
"v",
"}",
"\n",
"case",
"[",
"]",
"string",
":",
"param",
"=",
"append",
"(",
"param",
".",
"(",
"[",
"]",
"string",
")",
",",
"v",
")",
"\n",
"}",
"\n",
"p",
"[",
"k",
"]",
"=",
"param",
"\n",
"}",
"else",
"{",
"p",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}"
] | // Add param to Params | [
"Add",
"param",
"to",
"Params"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/params.go#L11-L23 |
15,705 | nbari/violetear | params.go | GetParam | func GetParam(name string, r *http.Request, index ...int) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if name != "*" {
name = ":" + name
}
if param := params[name]; param != nil {
switch param := param.(type) {
case []string:
if len(index) > 0 {
if index[0] < len(param) {
return param[index[0]]
}
return ""
}
return param[0]
default:
return param.(string)
}
}
}
return ""
} | go | func GetParam(name string, r *http.Request, index ...int) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if name != "*" {
name = ":" + name
}
if param := params[name]; param != nil {
switch param := param.(type) {
case []string:
if len(index) > 0 {
if index[0] < len(param) {
return param[index[0]]
}
return ""
}
return param[0]
default:
return param.(string)
}
}
}
return ""
} | [
"func",
"GetParam",
"(",
"name",
"string",
",",
"r",
"*",
"http",
".",
"Request",
",",
"index",
"...",
"int",
")",
"string",
"{",
"if",
"params",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ParamsKey",
")",
";",
"params",
"!=",
"nil",
"{",
"params",
":=",
"params",
".",
"(",
"Params",
")",
"\n",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"name",
"=",
"\"",
"\"",
"+",
"name",
"\n",
"}",
"\n",
"if",
"param",
":=",
"params",
"[",
"name",
"]",
";",
"param",
"!=",
"nil",
"{",
"switch",
"param",
":=",
"param",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"string",
":",
"if",
"len",
"(",
"index",
")",
">",
"0",
"{",
"if",
"index",
"[",
"0",
"]",
"<",
"len",
"(",
"param",
")",
"{",
"return",
"param",
"[",
"index",
"[",
"0",
"]",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"param",
"[",
"0",
"]",
"\n",
"default",
":",
"return",
"param",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // GetParam returns a value for the parameter set in path
// When having duplicate params pass the index as the last argument to
// retrieve the desired value. | [
"GetParam",
"returns",
"a",
"value",
"for",
"the",
"parameter",
"set",
"in",
"path",
"When",
"having",
"duplicate",
"params",
"pass",
"the",
"index",
"as",
"the",
"last",
"argument",
"to",
"retrieve",
"the",
"desired",
"value",
"."
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/params.go#L28-L50 |
15,706 | nbari/violetear | params.go | GetRouteName | func GetRouteName(r *http.Request) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if param := params["rname"]; param != nil {
return param.(string)
}
}
return ""
} | go | func GetRouteName(r *http.Request) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if param := params["rname"]; param != nil {
return param.(string)
}
}
return ""
} | [
"func",
"GetRouteName",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"if",
"params",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"ParamsKey",
")",
";",
"params",
"!=",
"nil",
"{",
"params",
":=",
"params",
".",
"(",
"Params",
")",
"\n",
"if",
"param",
":=",
"params",
"[",
"\"",
"\"",
"]",
";",
"param",
"!=",
"nil",
"{",
"return",
"param",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // GetRouteName return the name of the route | [
"GetRouteName",
"return",
"the",
"name",
"of",
"the",
"route"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/params.go#L72-L80 |
15,707 | nbari/violetear | responsewriter.go | NewResponseWriter | func NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
requestID: rid,
start: time.Now(),
status: http.StatusOK,
}
} | go | func NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
requestID: rid,
start: time.Now(),
status: http.StatusOK,
}
} | [
"func",
"NewResponseWriter",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"rid",
"string",
")",
"*",
"ResponseWriter",
"{",
"return",
"&",
"ResponseWriter",
"{",
"ResponseWriter",
":",
"w",
",",
"requestID",
":",
"rid",
",",
"start",
":",
"time",
".",
"Now",
"(",
")",
",",
"status",
":",
"http",
".",
"StatusOK",
",",
"}",
"\n",
"}"
] | // NewResponseWriter returns ResponseWriter | [
"NewResponseWriter",
"returns",
"ResponseWriter"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/responsewriter.go#L17-L24 |
15,708 | nbari/violetear | responsewriter.go | Write | func (w *ResponseWriter) Write(data []byte) (int, error) {
size, err := w.ResponseWriter.Write(data)
w.size += size
return size, err
} | go | func (w *ResponseWriter) Write(data []byte) (int, error) {
size, err := w.ResponseWriter.Write(data)
w.size += size
return size, err
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"Write",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"size",
",",
"err",
":=",
"w",
".",
"ResponseWriter",
".",
"Write",
"(",
"data",
")",
"\n",
"w",
".",
"size",
"+=",
"size",
"\n",
"return",
"size",
",",
"err",
"\n",
"}"
] | // Write satisfies the http.ResponseWriter interface and
// captures data written, in bytes | [
"Write",
"satisfies",
"the",
"http",
".",
"ResponseWriter",
"interface",
"and",
"captures",
"data",
"written",
"in",
"bytes"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/responsewriter.go#L48-L52 |
15,709 | nbari/violetear | responsewriter.go | WriteHeader | func (w *ResponseWriter) WriteHeader(statusCode int) {
w.status = statusCode
w.ResponseWriter.WriteHeader(statusCode)
} | go | func (w *ResponseWriter) WriteHeader(statusCode int) {
w.status = statusCode
w.ResponseWriter.WriteHeader(statusCode)
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"WriteHeader",
"(",
"statusCode",
"int",
")",
"{",
"w",
".",
"status",
"=",
"statusCode",
"\n",
"w",
".",
"ResponseWriter",
".",
"WriteHeader",
"(",
"statusCode",
")",
"\n",
"}"
] | // WriteHeader satisfies the http.ResponseWriter interface and
// allows us to catch the status code | [
"WriteHeader",
"satisfies",
"the",
"http",
".",
"ResponseWriter",
"interface",
"and",
"allows",
"us",
"to",
"catch",
"the",
"status",
"code"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/responsewriter.go#L56-L59 |
15,710 | nbari/violetear | violetear.go | New | func New() *Router {
return &Router{
dynamicRoutes: dynamicSet{},
routes: &Trie{},
Logger: logger,
Verbose: true,
}
} | go | func New() *Router {
return &Router{
dynamicRoutes: dynamicSet{},
routes: &Trie{},
Logger: logger,
Verbose: true,
}
} | [
"func",
"New",
"(",
")",
"*",
"Router",
"{",
"return",
"&",
"Router",
"{",
"dynamicRoutes",
":",
"dynamicSet",
"{",
"}",
",",
"routes",
":",
"&",
"Trie",
"{",
"}",
",",
"Logger",
":",
"logger",
",",
"Verbose",
":",
"true",
",",
"}",
"\n",
"}"
] | // New returns a new initialized router. | [
"New",
"returns",
"a",
"new",
"initialized",
"router",
"."
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/violetear.go#L102-L109 |
15,711 | nbari/violetear | violetear.go | MethodNotAllowed | func (r *Router) MethodNotAllowed() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
})
} | go | func (r *Router) MethodNotAllowed() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
})
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"MethodNotAllowed",
"(",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusMethodNotAllowed",
")",
",",
"http",
".",
"StatusMethodNotAllowed",
",",
")",
"\n",
"}",
")",
"\n",
"}"
] | // MethodNotAllowed default handler for 405 | [
"MethodNotAllowed",
"default",
"handler",
"for",
"405"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/violetear.go#L159-L166 |
15,712 | nbari/violetear | violetear.go | checkMethod | func (r *Router) checkMethod(node *Trie, method string) http.Handler {
for _, h := range node.Handler {
if h.Method == "ALL" {
return h.Handler
}
if h.Method == method {
return h.Handler
}
}
if r.NotAllowedHandler != nil {
return r.NotAllowedHandler
}
return r.MethodNotAllowed()
} | go | func (r *Router) checkMethod(node *Trie, method string) http.Handler {
for _, h := range node.Handler {
if h.Method == "ALL" {
return h.Handler
}
if h.Method == method {
return h.Handler
}
}
if r.NotAllowedHandler != nil {
return r.NotAllowedHandler
}
return r.MethodNotAllowed()
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"checkMethod",
"(",
"node",
"*",
"Trie",
",",
"method",
"string",
")",
"http",
".",
"Handler",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"node",
".",
"Handler",
"{",
"if",
"h",
".",
"Method",
"==",
"\"",
"\"",
"{",
"return",
"h",
".",
"Handler",
"\n",
"}",
"\n",
"if",
"h",
".",
"Method",
"==",
"method",
"{",
"return",
"h",
".",
"Handler",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"NotAllowedHandler",
"!=",
"nil",
"{",
"return",
"r",
".",
"NotAllowedHandler",
"\n",
"}",
"\n",
"return",
"r",
".",
"MethodNotAllowed",
"(",
")",
"\n",
"}"
] | // checkMethod check if request method is allowed or not | [
"checkMethod",
"check",
"if",
"request",
"method",
"is",
"allowed",
"or",
"not"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/violetear.go#L169-L182 |
15,713 | nbari/violetear | violetear.go | ServeHTTP | func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// panic handler
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %s", err)
if r.PanicHandler != nil {
r.PanicHandler(w, req)
} else {
http.Error(w, http.StatusText(500), http.StatusInternalServerError)
}
}
}()
// Request-ID
var rid string
if r.RequestID != "" {
if rid = req.Header.Get(r.RequestID); rid != "" {
w.Header().Set(r.RequestID, rid)
}
}
// wrap ResponseWriter
var ww *ResponseWriter
if r.LogRequests {
ww = NewResponseWriter(w, rid)
}
// set version based on the value of "Accept: application/vnd.*"
version := req.Header.Get("Accept")
if i := strings.LastIndex(version, versionHeader); i != -1 {
version = version[len(versionHeader)+i:]
} else {
version = ""
}
// query the path from left to right
node, key, path, leaf := r.routes.Get(req.URL.Path, version)
// dispatch the request
h, p := r.dispatch(node, key, path, req.Method, version, leaf, nil)
// dispatch request
if r.LogRequests {
if p == nil {
h.ServeHTTP(ww, req)
} else {
h.ServeHTTP(ww, req.WithContext(context.WithValue(req.Context(), ParamsKey, p)))
}
r.Logger(ww, req)
} else {
if p == nil {
h.ServeHTTP(w, req)
} else {
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), ParamsKey, p)))
}
}
} | go | func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// panic handler
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %s", err)
if r.PanicHandler != nil {
r.PanicHandler(w, req)
} else {
http.Error(w, http.StatusText(500), http.StatusInternalServerError)
}
}
}()
// Request-ID
var rid string
if r.RequestID != "" {
if rid = req.Header.Get(r.RequestID); rid != "" {
w.Header().Set(r.RequestID, rid)
}
}
// wrap ResponseWriter
var ww *ResponseWriter
if r.LogRequests {
ww = NewResponseWriter(w, rid)
}
// set version based on the value of "Accept: application/vnd.*"
version := req.Header.Get("Accept")
if i := strings.LastIndex(version, versionHeader); i != -1 {
version = version[len(versionHeader)+i:]
} else {
version = ""
}
// query the path from left to right
node, key, path, leaf := r.routes.Get(req.URL.Path, version)
// dispatch the request
h, p := r.dispatch(node, key, path, req.Method, version, leaf, nil)
// dispatch request
if r.LogRequests {
if p == nil {
h.ServeHTTP(ww, req)
} else {
h.ServeHTTP(ww, req.WithContext(context.WithValue(req.Context(), ParamsKey, p)))
}
r.Logger(ww, req)
} else {
if p == nil {
h.ServeHTTP(w, req)
} else {
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), ParamsKey, p)))
}
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// panic handler",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"if",
"r",
".",
"PanicHandler",
"!=",
"nil",
"{",
"r",
".",
"PanicHandler",
"(",
"w",
",",
"req",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"500",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Request-ID",
"var",
"rid",
"string",
"\n",
"if",
"r",
".",
"RequestID",
"!=",
"\"",
"\"",
"{",
"if",
"rid",
"=",
"req",
".",
"Header",
".",
"Get",
"(",
"r",
".",
"RequestID",
")",
";",
"rid",
"!=",
"\"",
"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"r",
".",
"RequestID",
",",
"rid",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// wrap ResponseWriter",
"var",
"ww",
"*",
"ResponseWriter",
"\n",
"if",
"r",
".",
"LogRequests",
"{",
"ww",
"=",
"NewResponseWriter",
"(",
"w",
",",
"rid",
")",
"\n",
"}",
"\n\n",
"// set version based on the value of \"Accept: application/vnd.*\"",
"version",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"LastIndex",
"(",
"version",
",",
"versionHeader",
")",
";",
"i",
"!=",
"-",
"1",
"{",
"version",
"=",
"version",
"[",
"len",
"(",
"versionHeader",
")",
"+",
"i",
":",
"]",
"\n",
"}",
"else",
"{",
"version",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// query the path from left to right",
"node",
",",
"key",
",",
"path",
",",
"leaf",
":=",
"r",
".",
"routes",
".",
"Get",
"(",
"req",
".",
"URL",
".",
"Path",
",",
"version",
")",
"\n\n",
"// dispatch the request",
"h",
",",
"p",
":=",
"r",
".",
"dispatch",
"(",
"node",
",",
"key",
",",
"path",
",",
"req",
".",
"Method",
",",
"version",
",",
"leaf",
",",
"nil",
")",
"\n\n",
"// dispatch request",
"if",
"r",
".",
"LogRequests",
"{",
"if",
"p",
"==",
"nil",
"{",
"h",
".",
"ServeHTTP",
"(",
"ww",
",",
"req",
")",
"\n",
"}",
"else",
"{",
"h",
".",
"ServeHTTP",
"(",
"ww",
",",
"req",
".",
"WithContext",
"(",
"context",
".",
"WithValue",
"(",
"req",
".",
"Context",
"(",
")",
",",
"ParamsKey",
",",
"p",
")",
")",
")",
"\n",
"}",
"\n",
"r",
".",
"Logger",
"(",
"ww",
",",
"req",
")",
"\n",
"}",
"else",
"{",
"if",
"p",
"==",
"nil",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
")",
"\n",
"}",
"else",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
".",
"WithContext",
"(",
"context",
".",
"WithValue",
"(",
"req",
".",
"Context",
"(",
")",
",",
"ParamsKey",
",",
"p",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ServeHTTP dispatches the handler registered in the matched path | [
"ServeHTTP",
"dispatches",
"the",
"handler",
"registered",
"in",
"the",
"matched",
"path"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/violetear.go#L239-L295 |
15,714 | nbari/violetear | violetear.go | splitPath | func (r *Router) splitPath(p string) []string {
pathParts := strings.FieldsFunc(p, func(c rune) bool {
return c == '/'
})
// root (empty slice)
if len(pathParts) == 0 {
return []string{"/"}
}
return pathParts
} | go | func (r *Router) splitPath(p string) []string {
pathParts := strings.FieldsFunc(p, func(c rune) bool {
return c == '/'
})
// root (empty slice)
if len(pathParts) == 0 {
return []string{"/"}
}
return pathParts
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"splitPath",
"(",
"p",
"string",
")",
"[",
"]",
"string",
"{",
"pathParts",
":=",
"strings",
".",
"FieldsFunc",
"(",
"p",
",",
"func",
"(",
"c",
"rune",
")",
"bool",
"{",
"return",
"c",
"==",
"'/'",
"\n",
"}",
")",
"\n",
"// root (empty slice)",
"if",
"len",
"(",
"pathParts",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"return",
"pathParts",
"\n",
"}"
] | // splitPath returns an slice of the path | [
"splitPath",
"returns",
"an",
"slice",
"of",
"the",
"path"
] | 971f3729520176a408b28de36d6f283f13b8e6d3 | https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/violetear.go#L298-L307 |
15,715 | dyatlov/go-opengraph | opengraph/opengraph.go | String | func (og *OpenGraph) String() string {
data, err := og.ToJSON()
if err != nil {
return err.Error()
}
return string(data[:])
} | go | func (og *OpenGraph) String() string {
data, err := og.ToJSON()
if err != nil {
return err.Error()
}
return string(data[:])
} | [
"func",
"(",
"og",
"*",
"OpenGraph",
")",
"String",
"(",
")",
"string",
"{",
"data",
",",
"err",
":=",
"og",
".",
"ToJSON",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"data",
"[",
":",
"]",
")",
"\n",
"}"
] | // String return json representation of structure, or error string | [
"String",
"return",
"json",
"representation",
"of",
"structure",
"or",
"error",
"string"
] | 816b6608b3c8c1e871bc9cf777f390e2532081fe | https://github.com/dyatlov/go-opengraph/blob/816b6608b3c8c1e871bc9cf777f390e2532081fe/opengraph/opengraph.go#L99-L107 |
15,716 | dyatlov/go-opengraph | opengraph/opengraph.go | ProcessHTML | func (og *OpenGraph) ProcessHTML(buffer io.Reader) error {
z := html.NewTokenizer(buffer)
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
if z.Err() == io.EOF {
return nil
}
return z.Err()
case html.StartTagToken, html.SelfClosingTagToken, html.EndTagToken:
name, hasAttr := z.TagName()
if atom.Lookup(name) == atom.Body {
return nil // OpenGraph is only in head, so we don't need body
}
if atom.Lookup(name) != atom.Meta || !hasAttr {
continue
}
m := make(map[string]string)
var key, val []byte
for hasAttr {
key, val, hasAttr = z.TagAttr()
m[atom.String(key)] = string(val)
}
og.ProcessMeta(m)
}
}
} | go | func (og *OpenGraph) ProcessHTML(buffer io.Reader) error {
z := html.NewTokenizer(buffer)
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
if z.Err() == io.EOF {
return nil
}
return z.Err()
case html.StartTagToken, html.SelfClosingTagToken, html.EndTagToken:
name, hasAttr := z.TagName()
if atom.Lookup(name) == atom.Body {
return nil // OpenGraph is only in head, so we don't need body
}
if atom.Lookup(name) != atom.Meta || !hasAttr {
continue
}
m := make(map[string]string)
var key, val []byte
for hasAttr {
key, val, hasAttr = z.TagAttr()
m[atom.String(key)] = string(val)
}
og.ProcessMeta(m)
}
}
} | [
"func",
"(",
"og",
"*",
"OpenGraph",
")",
"ProcessHTML",
"(",
"buffer",
"io",
".",
"Reader",
")",
"error",
"{",
"z",
":=",
"html",
".",
"NewTokenizer",
"(",
"buffer",
")",
"\n",
"for",
"{",
"tt",
":=",
"z",
".",
"Next",
"(",
")",
"\n",
"switch",
"tt",
"{",
"case",
"html",
".",
"ErrorToken",
":",
"if",
"z",
".",
"Err",
"(",
")",
"==",
"io",
".",
"EOF",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"z",
".",
"Err",
"(",
")",
"\n",
"case",
"html",
".",
"StartTagToken",
",",
"html",
".",
"SelfClosingTagToken",
",",
"html",
".",
"EndTagToken",
":",
"name",
",",
"hasAttr",
":=",
"z",
".",
"TagName",
"(",
")",
"\n",
"if",
"atom",
".",
"Lookup",
"(",
"name",
")",
"==",
"atom",
".",
"Body",
"{",
"return",
"nil",
"// OpenGraph is only in head, so we don't need body",
"\n",
"}",
"\n",
"if",
"atom",
".",
"Lookup",
"(",
"name",
")",
"!=",
"atom",
".",
"Meta",
"||",
"!",
"hasAttr",
"{",
"continue",
"\n",
"}",
"\n",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"key",
",",
"val",
"[",
"]",
"byte",
"\n",
"for",
"hasAttr",
"{",
"key",
",",
"val",
",",
"hasAttr",
"=",
"z",
".",
"TagAttr",
"(",
")",
"\n",
"m",
"[",
"atom",
".",
"String",
"(",
"key",
")",
"]",
"=",
"string",
"(",
"val",
")",
"\n",
"}",
"\n",
"og",
".",
"ProcessMeta",
"(",
"m",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ProcessHTML parses given html from Reader interface and fills up OpenGraph structure | [
"ProcessHTML",
"parses",
"given",
"html",
"from",
"Reader",
"interface",
"and",
"fills",
"up",
"OpenGraph",
"structure"
] | 816b6608b3c8c1e871bc9cf777f390e2532081fe | https://github.com/dyatlov/go-opengraph/blob/816b6608b3c8c1e871bc9cf777f390e2532081fe/opengraph/opengraph.go#L110-L137 |
15,717 | kelvins/sunrisesunset | sunrisesunset.go | GetSunriseSunset | func (p *Parameters) GetSunriseSunset() (time.Time, time.Time, error) {
return GetSunriseSunset(p.Latitude, p.Longitude, p.UtcOffset, p.Date)
} | go | func (p *Parameters) GetSunriseSunset() (time.Time, time.Time, error) {
return GetSunriseSunset(p.Latitude, p.Longitude, p.UtcOffset, p.Date)
} | [
"func",
"(",
"p",
"*",
"Parameters",
")",
"GetSunriseSunset",
"(",
")",
"(",
"time",
".",
"Time",
",",
"time",
".",
"Time",
",",
"error",
")",
"{",
"return",
"GetSunriseSunset",
"(",
"p",
".",
"Latitude",
",",
"p",
".",
"Longitude",
",",
"p",
".",
"UtcOffset",
",",
"p",
".",
"Date",
")",
"\n",
"}"
] | // Just call the 'general' GetSunriseSunset function and return the results | [
"Just",
"call",
"the",
"general",
"GetSunriseSunset",
"function",
"and",
"return",
"the",
"results"
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L22-L24 |
15,718 | kelvins/sunrisesunset | sunrisesunset.go | createSecondsNormalized | func createSecondsNormalized(seconds int) (vector []float64) {
for index := 0; index < seconds; index++ {
temp := float64(index) / float64(seconds-1)
vector = append(vector, temp)
}
return
} | go | func createSecondsNormalized(seconds int) (vector []float64) {
for index := 0; index < seconds; index++ {
temp := float64(index) / float64(seconds-1)
vector = append(vector, temp)
}
return
} | [
"func",
"createSecondsNormalized",
"(",
"seconds",
"int",
")",
"(",
"vector",
"[",
"]",
"float64",
")",
"{",
"for",
"index",
":=",
"0",
";",
"index",
"<",
"seconds",
";",
"index",
"++",
"{",
"temp",
":=",
"float64",
"(",
"index",
")",
"/",
"float64",
"(",
"seconds",
"-",
"1",
")",
"\n",
"vector",
"=",
"append",
"(",
"vector",
",",
"temp",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Creates a vector with the seconds normalized to the range 0~1.
// seconds - The number of seconds will be normalized to 1
// Return A vector with the seconds normalized to 0~1 | [
"Creates",
"a",
"vector",
"with",
"the",
"seconds",
"normalized",
"to",
"the",
"range",
"0~1",
".",
"seconds",
"-",
"The",
"number",
"of",
"seconds",
"will",
"be",
"normalized",
"to",
"1",
"Return",
"A",
"vector",
"with",
"the",
"seconds",
"normalized",
"to",
"0~1"
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L39-L45 |
15,719 | kelvins/sunrisesunset | sunrisesunset.go | checkDate | func checkDate(date time.Time) bool {
minDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
maxDate := time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC)
if date.Before(minDate) || date.After(maxDate) {
return false
}
return true
} | go | func checkDate(date time.Time) bool {
minDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
maxDate := time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC)
if date.Before(minDate) || date.After(maxDate) {
return false
}
return true
} | [
"func",
"checkDate",
"(",
"date",
"time",
".",
"Time",
")",
"bool",
"{",
"minDate",
":=",
"time",
".",
"Date",
"(",
"1900",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"time",
".",
"UTC",
")",
"\n",
"maxDate",
":=",
"time",
".",
"Date",
"(",
"2200",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"time",
".",
"UTC",
")",
"\n",
"if",
"date",
".",
"Before",
"(",
"minDate",
")",
"||",
"date",
".",
"After",
"(",
"maxDate",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Check if the date is valid. | [
"Check",
"if",
"the",
"date",
"is",
"valid",
"."
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L274-L281 |
15,720 | kelvins/sunrisesunset | sunrisesunset.go | diffDays | func diffDays(date1, date2 time.Time) int64 {
return int64(date2.Sub(date1) / (24 * time.Hour))
} | go | func diffDays(date1, date2 time.Time) int64 {
return int64(date2.Sub(date1) / (24 * time.Hour))
} | [
"func",
"diffDays",
"(",
"date1",
",",
"date2",
"time",
".",
"Time",
")",
"int64",
"{",
"return",
"int64",
"(",
"date2",
".",
"Sub",
"(",
"date1",
")",
"/",
"(",
"24",
"*",
"time",
".",
"Hour",
")",
")",
"\n",
"}"
] | // Compute the number of days between two dates | [
"Compute",
"the",
"number",
"of",
"days",
"between",
"two",
"dates"
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L284-L286 |
15,721 | kelvins/sunrisesunset | sunrisesunset.go | minIndex | func minIndex(slice []float64) int {
if len(slice) == 0 {
return -1
}
min := slice[0]
minIndex := 0
for index := 0; index < len(slice); index++ {
if slice[index] < min {
min = slice[index]
minIndex = index
}
}
return minIndex
} | go | func minIndex(slice []float64) int {
if len(slice) == 0 {
return -1
}
min := slice[0]
minIndex := 0
for index := 0; index < len(slice); index++ {
if slice[index] < min {
min = slice[index]
minIndex = index
}
}
return minIndex
} | [
"func",
"minIndex",
"(",
"slice",
"[",
"]",
"float64",
")",
"int",
"{",
"if",
"len",
"(",
"slice",
")",
"==",
"0",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"min",
":=",
"slice",
"[",
"0",
"]",
"\n",
"minIndex",
":=",
"0",
"\n",
"for",
"index",
":=",
"0",
";",
"index",
"<",
"len",
"(",
"slice",
")",
";",
"index",
"++",
"{",
"if",
"slice",
"[",
"index",
"]",
"<",
"min",
"{",
"min",
"=",
"slice",
"[",
"index",
"]",
"\n",
"minIndex",
"=",
"index",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"minIndex",
"\n",
"}"
] | // Find the index of the minimum value | [
"Find",
"the",
"index",
"of",
"the",
"minimum",
"value"
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L289-L302 |
15,722 | kelvins/sunrisesunset | sunrisesunset.go | abs | func abs(slice []float64) []float64 {
var newSlice []float64
for _, value := range slice {
if value < 0.0 {
value = math.Abs(value)
}
newSlice = append(newSlice, value)
}
return newSlice
} | go | func abs(slice []float64) []float64 {
var newSlice []float64
for _, value := range slice {
if value < 0.0 {
value = math.Abs(value)
}
newSlice = append(newSlice, value)
}
return newSlice
} | [
"func",
"abs",
"(",
"slice",
"[",
"]",
"float64",
")",
"[",
"]",
"float64",
"{",
"var",
"newSlice",
"[",
"]",
"float64",
"\n",
"for",
"_",
",",
"value",
":=",
"range",
"slice",
"{",
"if",
"value",
"<",
"0.0",
"{",
"value",
"=",
"math",
".",
"Abs",
"(",
"value",
")",
"\n",
"}",
"\n",
"newSlice",
"=",
"append",
"(",
"newSlice",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"newSlice",
"\n",
"}"
] | // Convert each value to the absolute value | [
"Convert",
"each",
"value",
"to",
"the",
"absolute",
"value"
] | 14f1915ad4b4fc68cdf3c144e39293993e21c67c | https://github.com/kelvins/sunrisesunset/blob/14f1915ad4b4fc68cdf3c144e39293993e21c67c/sunrisesunset.go#L305-L314 |
15,723 | uber-go/mapdecode | internal/mapstructure/mapstructure.go | Decode | func Decode(m interface{}, rawVal interface{}) error {
config := &DecoderConfig{
Metadata: nil,
Result: rawVal,
}
decoder, err := NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(m)
} | go | func Decode(m interface{}, rawVal interface{}) error {
config := &DecoderConfig{
Metadata: nil,
Result: rawVal,
}
decoder, err := NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(m)
} | [
"func",
"Decode",
"(",
"m",
"interface",
"{",
"}",
",",
"rawVal",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"&",
"DecoderConfig",
"{",
"Metadata",
":",
"nil",
",",
"Result",
":",
"rawVal",
",",
"}",
"\n\n",
"decoder",
",",
"err",
":=",
"NewDecoder",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"decoder",
".",
"Decode",
"(",
"m",
")",
"\n",
"}"
] | // Decode takes a map and uses reflection to convert it into the
// given Go native structure. val must be a pointer to a struct. | [
"Decode",
"takes",
"a",
"map",
"and",
"uses",
"reflection",
"to",
"convert",
"it",
"into",
"the",
"given",
"Go",
"native",
"structure",
".",
"val",
"must",
"be",
"a",
"pointer",
"to",
"a",
"struct",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/internal/mapstructure/mapstructure.go#L136-L148 |
15,724 | uber-go/mapdecode | internal/mapstructure/mapstructure.go | Decode | func (d *Decoder) Decode(raw interface{}) error {
return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem())
} | go | func (d *Decoder) Decode(raw interface{}) error {
return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem())
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"Decode",
"(",
"raw",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"d",
".",
"decode",
"(",
"\"",
"\"",
",",
"raw",
",",
"reflect",
".",
"ValueOf",
"(",
"d",
".",
"config",
".",
"Result",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"}"
] | // Decode decodes the given raw interface to the target pointer specified
// by the configuration. | [
"Decode",
"decodes",
"the",
"given",
"raw",
"interface",
"to",
"the",
"target",
"pointer",
"specified",
"by",
"the",
"configuration",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/internal/mapstructure/mapstructure.go#L204-L206 |
15,725 | uber-go/mapdecode | decode.go | FieldHook | func FieldHook(f FieldHookFunc) Option {
return func(o *options) {
o.FieldHooks = append(o.FieldHooks, f)
}
} | go | func FieldHook(f FieldHookFunc) Option {
return func(o *options) {
o.FieldHooks = append(o.FieldHooks, f)
}
} | [
"func",
"FieldHook",
"(",
"f",
"FieldHookFunc",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"options",
")",
"{",
"o",
".",
"FieldHooks",
"=",
"append",
"(",
"o",
".",
"FieldHooks",
",",
"f",
")",
"\n",
"}",
"\n",
"}"
] | // FieldHook registers a hook to be called when a struct field is being
// decoded by the system.
//
// This hook will be called with information about the target field of a
// struct and the source data that will fill it.
//
// Field hooks may return a value of the same type as the source data or the
// same type as the target. Other value decoding hooks will still be executed
// on this field.
//
// Multiple field hooks may be specified by providing this option multiple
// times. Hooks are exected in-order, feeding values from one hook to the
// next. | [
"FieldHook",
"registers",
"a",
"hook",
"to",
"be",
"called",
"when",
"a",
"struct",
"field",
"is",
"being",
"decoded",
"by",
"the",
"system",
".",
"This",
"hook",
"will",
"be",
"called",
"with",
"information",
"about",
"the",
"target",
"field",
"of",
"a",
"struct",
"and",
"the",
"source",
"data",
"that",
"will",
"fill",
"it",
".",
"Field",
"hooks",
"may",
"return",
"a",
"value",
"of",
"the",
"same",
"type",
"as",
"the",
"source",
"data",
"or",
"the",
"same",
"type",
"as",
"the",
"target",
".",
"Other",
"value",
"decoding",
"hooks",
"will",
"still",
"be",
"executed",
"on",
"this",
"field",
".",
"Multiple",
"field",
"hooks",
"may",
"be",
"specified",
"by",
"providing",
"this",
"option",
"multiple",
"times",
".",
"Hooks",
"are",
"exected",
"in",
"-",
"order",
"feeding",
"values",
"from",
"one",
"hook",
"to",
"the",
"next",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/decode.go#L92-L96 |
15,726 | uber-go/mapdecode | decode.go | DecodeHook | func DecodeHook(f DecodeHookFunc) Option {
return func(o *options) {
o.DecodeHooks = append(o.DecodeHooks, f)
}
} | go | func DecodeHook(f DecodeHookFunc) Option {
return func(o *options) {
o.DecodeHooks = append(o.DecodeHooks, f)
}
} | [
"func",
"DecodeHook",
"(",
"f",
"DecodeHookFunc",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"options",
")",
"{",
"o",
".",
"DecodeHooks",
"=",
"append",
"(",
"o",
".",
"DecodeHooks",
",",
"f",
")",
"\n",
"}",
"\n",
"}"
] | // DecodeHook registers a hook to be called before a value is decoded by the
// system.
//
// This hook will be called with information about the target type and the
// source data that will fill it.
//
// Multiple decode hooks may be specified by providing this option multiple
// times. Hooks are exected in-order, feeding values from one hook to the
// next. | [
"DecodeHook",
"registers",
"a",
"hook",
"to",
"be",
"called",
"before",
"a",
"value",
"is",
"decoded",
"by",
"the",
"system",
".",
"This",
"hook",
"will",
"be",
"called",
"with",
"information",
"about",
"the",
"target",
"type",
"and",
"the",
"source",
"data",
"that",
"will",
"fill",
"it",
".",
"Multiple",
"decode",
"hooks",
"may",
"be",
"specified",
"by",
"providing",
"this",
"option",
"multiple",
"times",
".",
"Hooks",
"are",
"exected",
"in",
"-",
"order",
"feeding",
"values",
"from",
"one",
"hook",
"to",
"the",
"next",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/decode.go#L107-L111 |
15,727 | uber-go/mapdecode | decode.go | decodeFrom | func decodeFrom(opts *options, src interface{}) Into {
return func(dest interface{}) error {
var fieldHooks FieldHookFunc
hooks := opts.DecodeHooks
// fieldHook goes first because it may replace the source data map.
if len(opts.FieldHooks) > 0 {
fieldHooks = composeFieldHooks(opts.FieldHooks)
}
hooks = append(
hooks,
unmarshalerHook(opts),
// durationHook must come before the strconvHook
// because the Kind of time.Duration is Int64.
durationHook,
strconvHook,
)
cfg := mapstructure.DecoderConfig{
ErrorUnused: !opts.IgnoreUnused,
Result: dest,
SquashEmbedded: true,
DecodeHook: fromDecodeHookFunc(
supportPointers(composeDecodeHooks(hooks)),
),
FieldHook: mapstructure.FieldHookFunc(fieldHooks),
TagName: opts.TagName,
}
decoder, err := mapstructure.NewDecoder(&cfg)
if err != nil {
return fmt.Errorf("failed to set up decoder: %v", err)
}
if err := decoder.Decode(src); err != nil {
if merr, ok := err.(*mapstructure.Error); ok {
return multierr.Combine(merr.WrappedErrors()...)
}
return err
}
return nil
}
} | go | func decodeFrom(opts *options, src interface{}) Into {
return func(dest interface{}) error {
var fieldHooks FieldHookFunc
hooks := opts.DecodeHooks
// fieldHook goes first because it may replace the source data map.
if len(opts.FieldHooks) > 0 {
fieldHooks = composeFieldHooks(opts.FieldHooks)
}
hooks = append(
hooks,
unmarshalerHook(opts),
// durationHook must come before the strconvHook
// because the Kind of time.Duration is Int64.
durationHook,
strconvHook,
)
cfg := mapstructure.DecoderConfig{
ErrorUnused: !opts.IgnoreUnused,
Result: dest,
SquashEmbedded: true,
DecodeHook: fromDecodeHookFunc(
supportPointers(composeDecodeHooks(hooks)),
),
FieldHook: mapstructure.FieldHookFunc(fieldHooks),
TagName: opts.TagName,
}
decoder, err := mapstructure.NewDecoder(&cfg)
if err != nil {
return fmt.Errorf("failed to set up decoder: %v", err)
}
if err := decoder.Decode(src); err != nil {
if merr, ok := err.(*mapstructure.Error); ok {
return multierr.Combine(merr.WrappedErrors()...)
}
return err
}
return nil
}
} | [
"func",
"decodeFrom",
"(",
"opts",
"*",
"options",
",",
"src",
"interface",
"{",
"}",
")",
"Into",
"{",
"return",
"func",
"(",
"dest",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"fieldHooks",
"FieldHookFunc",
"\n",
"hooks",
":=",
"opts",
".",
"DecodeHooks",
"\n\n",
"// fieldHook goes first because it may replace the source data map.",
"if",
"len",
"(",
"opts",
".",
"FieldHooks",
")",
">",
"0",
"{",
"fieldHooks",
"=",
"composeFieldHooks",
"(",
"opts",
".",
"FieldHooks",
")",
"\n",
"}",
"\n\n",
"hooks",
"=",
"append",
"(",
"hooks",
",",
"unmarshalerHook",
"(",
"opts",
")",
",",
"// durationHook must come before the strconvHook",
"// because the Kind of time.Duration is Int64.",
"durationHook",
",",
"strconvHook",
",",
")",
"\n\n",
"cfg",
":=",
"mapstructure",
".",
"DecoderConfig",
"{",
"ErrorUnused",
":",
"!",
"opts",
".",
"IgnoreUnused",
",",
"Result",
":",
"dest",
",",
"SquashEmbedded",
":",
"true",
",",
"DecodeHook",
":",
"fromDecodeHookFunc",
"(",
"supportPointers",
"(",
"composeDecodeHooks",
"(",
"hooks",
")",
")",
",",
")",
",",
"FieldHook",
":",
"mapstructure",
".",
"FieldHookFunc",
"(",
"fieldHooks",
")",
",",
"TagName",
":",
"opts",
".",
"TagName",
",",
"}",
"\n\n",
"decoder",
",",
"err",
":=",
"mapstructure",
".",
"NewDecoder",
"(",
"&",
"cfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"src",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"merr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"mapstructure",
".",
"Error",
")",
";",
"ok",
"{",
"return",
"multierr",
".",
"Combine",
"(",
"merr",
".",
"WrappedErrors",
"(",
")",
"...",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // decodeFrom builds a decode Into function that reads the given value into
// the destination. | [
"decodeFrom",
"builds",
"a",
"decode",
"Into",
"function",
"that",
"reads",
"the",
"given",
"value",
"into",
"the",
"destination",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/decode.go#L164-L208 |
15,728 | uber-go/mapdecode | hooks.go | composeDecodeHooks | func composeDecodeHooks(hooks []DecodeHookFunc) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
var err error
for _, hook := range hooks {
data, err = hook(from, to, data)
if err != nil {
return data, err
}
// Update the `from` type to reflect changes made by the hook.
from = data.Type()
}
return data, err
}
} | go | func composeDecodeHooks(hooks []DecodeHookFunc) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
var err error
for _, hook := range hooks {
data, err = hook(from, to, data)
if err != nil {
return data, err
}
// Update the `from` type to reflect changes made by the hook.
from = data.Type()
}
return data, err
}
} | [
"func",
"composeDecodeHooks",
"(",
"hooks",
"[",
"]",
"DecodeHookFunc",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"from",
",",
"to",
"reflect",
".",
"Type",
",",
"data",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"hook",
":=",
"range",
"hooks",
"{",
"data",
",",
"err",
"=",
"hook",
"(",
"from",
",",
"to",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"data",
",",
"err",
"\n",
"}",
"\n\n",
"// Update the `from` type to reflect changes made by the hook.",
"from",
"=",
"data",
".",
"Type",
"(",
")",
"\n",
"}",
"\n",
"return",
"data",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // Composes multiple DecodeHookFuncs into one. The hooks are applied in-order
// and values produced by a hook are fed into the next hook. | [
"Composes",
"multiple",
"DecodeHookFuncs",
"into",
"one",
".",
"The",
"hooks",
"are",
"applied",
"in",
"-",
"order",
"and",
"values",
"produced",
"by",
"a",
"hook",
"are",
"fed",
"into",
"the",
"next",
"hook",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/hooks.go#L80-L94 |
15,729 | uber-go/mapdecode | hooks.go | unmarshalerHook | func unmarshalerHook(opts *options) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from == to {
return data, nil
}
if !reflect.PtrTo(to).Implements(opts.Unmarshaler.Interface) {
return data, nil
}
// The following lines are roughly equivalent to,
// value := new(foo)
// err := value.Decode(...)
// return *value, err
value := reflect.New(to)
err := opts.Unmarshaler.Unmarshal(value, decodeFrom(opts, data.Interface()))
if err != nil {
err = fmt.Errorf("could not decode %v from %v: %v", to, from, err)
}
return value.Elem(), err
}
} | go | func unmarshalerHook(opts *options) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from == to {
return data, nil
}
if !reflect.PtrTo(to).Implements(opts.Unmarshaler.Interface) {
return data, nil
}
// The following lines are roughly equivalent to,
// value := new(foo)
// err := value.Decode(...)
// return *value, err
value := reflect.New(to)
err := opts.Unmarshaler.Unmarshal(value, decodeFrom(opts, data.Interface()))
if err != nil {
err = fmt.Errorf("could not decode %v from %v: %v", to, from, err)
}
return value.Elem(), err
}
} | [
"func",
"unmarshalerHook",
"(",
"opts",
"*",
"options",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"from",
",",
"to",
"reflect",
".",
"Type",
",",
"data",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"if",
"from",
"==",
"to",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"!",
"reflect",
".",
"PtrTo",
"(",
"to",
")",
".",
"Implements",
"(",
"opts",
".",
"Unmarshaler",
".",
"Interface",
")",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"// The following lines are roughly equivalent to,",
"// \tvalue := new(foo)",
"// \terr := value.Decode(...)",
"// \treturn *value, err",
"value",
":=",
"reflect",
".",
"New",
"(",
"to",
")",
"\n",
"err",
":=",
"opts",
".",
"Unmarshaler",
".",
"Unmarshal",
"(",
"value",
",",
"decodeFrom",
"(",
"opts",
",",
"data",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"to",
",",
"from",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"value",
".",
"Elem",
"(",
")",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // Builds a DecodeHookFunc which unmarshals types using the given unmarshaling
// scheme. See the unmarshaler type for more information. | [
"Builds",
"a",
"DecodeHookFunc",
"which",
"unmarshals",
"types",
"using",
"the",
"given",
"unmarshaling",
"scheme",
".",
"See",
"the",
"unmarshaler",
"type",
"for",
"more",
"information",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/hooks.go#L139-L160 |
15,730 | uber-go/mapdecode | hooks.go | durationHook | func durationHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String || to != _typeOfDuration {
return data, nil
}
d, err := time.ParseDuration(data.String())
return reflect.ValueOf(d), err
} | go | func durationHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String || to != _typeOfDuration {
return data, nil
}
d, err := time.ParseDuration(data.String())
return reflect.ValueOf(d), err
} | [
"func",
"durationHook",
"(",
"from",
",",
"to",
"reflect",
".",
"Type",
",",
"data",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"if",
"from",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"||",
"to",
"!=",
"_typeOfDuration",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"d",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"data",
".",
"String",
"(",
")",
")",
"\n",
"return",
"reflect",
".",
"ValueOf",
"(",
"d",
")",
",",
"err",
"\n",
"}"
] | // A DecodeHookFunc which decodes strings into time.Durations. | [
"A",
"DecodeHookFunc",
"which",
"decodes",
"strings",
"into",
"time",
".",
"Durations",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/hooks.go#L163-L170 |
15,731 | uber-go/mapdecode | hooks.go | strconvHook | func strconvHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String {
return data, nil
}
s := data.String()
switch to.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(s)
return reflect.ValueOf(b), err
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(s, to.Bits())
return reflect.ValueOf(f).Convert(to), err
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(s, 10, to.Bits())
return reflect.ValueOf(i).Convert(to), err
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(s, 10, to.Bits())
return reflect.ValueOf(u).Convert(to), err
}
return data, nil
} | go | func strconvHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String {
return data, nil
}
s := data.String()
switch to.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(s)
return reflect.ValueOf(b), err
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(s, to.Bits())
return reflect.ValueOf(f).Convert(to), err
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(s, 10, to.Bits())
return reflect.ValueOf(i).Convert(to), err
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(s, 10, to.Bits())
return reflect.ValueOf(u).Convert(to), err
}
return data, nil
} | [
"func",
"strconvHook",
"(",
"from",
",",
"to",
"reflect",
".",
"Type",
",",
"data",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"if",
"from",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"s",
":=",
"data",
".",
"String",
"(",
")",
"\n",
"switch",
"to",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Bool",
":",
"b",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"s",
")",
"\n",
"return",
"reflect",
".",
"ValueOf",
"(",
"b",
")",
",",
"err",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"f",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"s",
",",
"to",
".",
"Bits",
"(",
")",
")",
"\n",
"return",
"reflect",
".",
"ValueOf",
"(",
"f",
")",
".",
"Convert",
"(",
"to",
")",
",",
"err",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"s",
",",
"10",
",",
"to",
".",
"Bits",
"(",
")",
")",
"\n",
"return",
"reflect",
".",
"ValueOf",
"(",
"i",
")",
".",
"Convert",
"(",
"to",
")",
",",
"err",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"u",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"s",
",",
"10",
",",
"to",
".",
"Bits",
"(",
")",
")",
"\n",
"return",
"reflect",
".",
"ValueOf",
"(",
"u",
")",
".",
"Convert",
"(",
"to",
")",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // stringToPrimitivesHook is a DecodeHookFunc which decodes strings into
// primitives.
//
// Integers are parsed in base 10. | [
"stringToPrimitivesHook",
"is",
"a",
"DecodeHookFunc",
"which",
"decodes",
"strings",
"into",
"primitives",
".",
"Integers",
"are",
"parsed",
"in",
"base",
"10",
"."
] | 0cdb2a72cb565feae631bada7548587de7b1ce18 | https://github.com/uber-go/mapdecode/blob/0cdb2a72cb565feae631bada7548587de7b1ce18/hooks.go#L176-L198 |
15,732 | agext/levenshtein | levenshtein.go | Distance | func Distance(str1, str2 string, p *Params) int {
if p == nil {
p = defaultParams
}
dist, _, _ := Calculate([]rune(str1), []rune(str2), p.maxCost, p.insCost, p.subCost, p.delCost)
return dist
} | go | func Distance(str1, str2 string, p *Params) int {
if p == nil {
p = defaultParams
}
dist, _, _ := Calculate([]rune(str1), []rune(str2), p.maxCost, p.insCost, p.subCost, p.delCost)
return dist
} | [
"func",
"Distance",
"(",
"str1",
",",
"str2",
"string",
",",
"p",
"*",
"Params",
")",
"int",
"{",
"if",
"p",
"==",
"nil",
"{",
"p",
"=",
"defaultParams",
"\n",
"}",
"\n",
"dist",
",",
"_",
",",
"_",
":=",
"Calculate",
"(",
"[",
"]",
"rune",
"(",
"str1",
")",
",",
"[",
"]",
"rune",
"(",
"str2",
")",
",",
"p",
".",
"maxCost",
",",
"p",
".",
"insCost",
",",
"p",
".",
"subCost",
",",
"p",
".",
"delCost",
")",
"\n",
"return",
"dist",
"\n",
"}"
] | // Distance returns the Levenshtein distance between str1 and str2, using the
// default or provided cost values. Pass nil for the third argument to use the
// default cost of 1 for all three operations, with no maximum. | [
"Distance",
"returns",
"the",
"Levenshtein",
"distance",
"between",
"str1",
"and",
"str2",
"using",
"the",
"default",
"or",
"provided",
"cost",
"values",
".",
"Pass",
"nil",
"for",
"the",
"third",
"argument",
"to",
"use",
"the",
"default",
"cost",
"of",
"1",
"for",
"all",
"three",
"operations",
"with",
"no",
"maximum",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/levenshtein.go#L196-L202 |
15,733 | agext/levenshtein | levenshtein.go | Similarity | func Similarity(str1, str2 string, p *Params) float64 {
return Match(str1, str2, p.Clone().BonusThreshold(1.1)) // guaranteed no bonus
} | go | func Similarity(str1, str2 string, p *Params) float64 {
return Match(str1, str2, p.Clone().BonusThreshold(1.1)) // guaranteed no bonus
} | [
"func",
"Similarity",
"(",
"str1",
",",
"str2",
"string",
",",
"p",
"*",
"Params",
")",
"float64",
"{",
"return",
"Match",
"(",
"str1",
",",
"str2",
",",
"p",
".",
"Clone",
"(",
")",
".",
"BonusThreshold",
"(",
"1.1",
")",
")",
"// guaranteed no bonus",
"\n",
"}"
] | // Similarity returns a score in the range of 0..1 for how similar the two strings are.
// A score of 1 means the strings are identical, and 0 means they have nothing in common.
//
// A nil third argument uses the default cost of 1 for all three operations.
//
// If a non-zero MinScore value is provided in the parameters, scores lower than it
// will be returned as 0. | [
"Similarity",
"returns",
"a",
"score",
"in",
"the",
"range",
"of",
"0",
"..",
"1",
"for",
"how",
"similar",
"the",
"two",
"strings",
"are",
".",
"A",
"score",
"of",
"1",
"means",
"the",
"strings",
"are",
"identical",
"and",
"0",
"means",
"they",
"have",
"nothing",
"in",
"common",
".",
"A",
"nil",
"third",
"argument",
"uses",
"the",
"default",
"cost",
"of",
"1",
"for",
"all",
"three",
"operations",
".",
"If",
"a",
"non",
"-",
"zero",
"MinScore",
"value",
"is",
"provided",
"in",
"the",
"parameters",
"scores",
"lower",
"than",
"it",
"will",
"be",
"returned",
"as",
"0",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/levenshtein.go#L211-L213 |
15,734 | agext/levenshtein | levenshtein.go | Match | func Match(str1, str2 string, p *Params) float64 {
s1, s2 := []rune(str1), []rune(str2)
l1, l2 := len(s1), len(s2)
// two empty strings are identical; shortcut also avoids divByZero issues later on.
if l1 == 0 && l2 == 0 {
return 1
}
if p == nil {
p = defaultParams
}
// a min over 1 can never be satisfied, so the score is 0.
if p.minScore > 1 {
return 0
}
insCost, delCost, maxDist, max := p.insCost, p.delCost, 0, 0
if l1 > l2 {
l1, l2, insCost, delCost = l2, l1, delCost, insCost
}
if p.subCost < delCost+insCost {
maxDist = l1*p.subCost + (l2-l1)*insCost
} else {
maxDist = l1*delCost + l2*insCost
}
// a zero min is always satisfied, so no need to set a max cost.
if p.minScore > 0 {
// if p.minScore is lower than p.bonusThreshold, we can use a simplified formula
// for the max cost, because a sim score below min cannot receive a bonus.
if p.minScore < p.bonusThreshold {
// round down the max - a cost equal to a rounded up max would already be under min.
max = int((1 - p.minScore) * float64(maxDist))
} else {
// p.minScore <= sim + p.bonusPrefix*p.bonusScale*(1-sim)
// p.minScore <= (1-dist/maxDist) + p.bonusPrefix*p.bonusScale*(1-(1-dist/maxDist))
// p.minScore <= 1 - dist/maxDist + p.bonusPrefix*p.bonusScale*dist/maxDist
// 1 - p.minScore >= dist/maxDist - p.bonusPrefix*p.bonusScale*dist/maxDist
// (1-p.minScore)*maxDist/(1-p.bonusPrefix*p.bonusScale) >= dist
max = int((1 - p.minScore) * float64(maxDist) / (1 - float64(p.bonusPrefix)*p.bonusScale))
}
}
dist, pl, _ := Calculate(s1, s2, max, p.insCost, p.subCost, p.delCost)
if max > 0 && dist > max {
return 0
}
sim := 1 - float64(dist)/float64(maxDist)
if sim >= p.bonusThreshold && sim < 1 && p.bonusPrefix > 0 && p.bonusScale > 0 {
if pl > p.bonusPrefix {
pl = p.bonusPrefix
}
sim += float64(pl) * p.bonusScale * (1 - sim)
}
if sim < p.minScore {
return 0
}
return sim
} | go | func Match(str1, str2 string, p *Params) float64 {
s1, s2 := []rune(str1), []rune(str2)
l1, l2 := len(s1), len(s2)
// two empty strings are identical; shortcut also avoids divByZero issues later on.
if l1 == 0 && l2 == 0 {
return 1
}
if p == nil {
p = defaultParams
}
// a min over 1 can never be satisfied, so the score is 0.
if p.minScore > 1 {
return 0
}
insCost, delCost, maxDist, max := p.insCost, p.delCost, 0, 0
if l1 > l2 {
l1, l2, insCost, delCost = l2, l1, delCost, insCost
}
if p.subCost < delCost+insCost {
maxDist = l1*p.subCost + (l2-l1)*insCost
} else {
maxDist = l1*delCost + l2*insCost
}
// a zero min is always satisfied, so no need to set a max cost.
if p.minScore > 0 {
// if p.minScore is lower than p.bonusThreshold, we can use a simplified formula
// for the max cost, because a sim score below min cannot receive a bonus.
if p.minScore < p.bonusThreshold {
// round down the max - a cost equal to a rounded up max would already be under min.
max = int((1 - p.minScore) * float64(maxDist))
} else {
// p.minScore <= sim + p.bonusPrefix*p.bonusScale*(1-sim)
// p.minScore <= (1-dist/maxDist) + p.bonusPrefix*p.bonusScale*(1-(1-dist/maxDist))
// p.minScore <= 1 - dist/maxDist + p.bonusPrefix*p.bonusScale*dist/maxDist
// 1 - p.minScore >= dist/maxDist - p.bonusPrefix*p.bonusScale*dist/maxDist
// (1-p.minScore)*maxDist/(1-p.bonusPrefix*p.bonusScale) >= dist
max = int((1 - p.minScore) * float64(maxDist) / (1 - float64(p.bonusPrefix)*p.bonusScale))
}
}
dist, pl, _ := Calculate(s1, s2, max, p.insCost, p.subCost, p.delCost)
if max > 0 && dist > max {
return 0
}
sim := 1 - float64(dist)/float64(maxDist)
if sim >= p.bonusThreshold && sim < 1 && p.bonusPrefix > 0 && p.bonusScale > 0 {
if pl > p.bonusPrefix {
pl = p.bonusPrefix
}
sim += float64(pl) * p.bonusScale * (1 - sim)
}
if sim < p.minScore {
return 0
}
return sim
} | [
"func",
"Match",
"(",
"str1",
",",
"str2",
"string",
",",
"p",
"*",
"Params",
")",
"float64",
"{",
"s1",
",",
"s2",
":=",
"[",
"]",
"rune",
"(",
"str1",
")",
",",
"[",
"]",
"rune",
"(",
"str2",
")",
"\n",
"l1",
",",
"l2",
":=",
"len",
"(",
"s1",
")",
",",
"len",
"(",
"s2",
")",
"\n",
"// two empty strings are identical; shortcut also avoids divByZero issues later on.",
"if",
"l1",
"==",
"0",
"&&",
"l2",
"==",
"0",
"{",
"return",
"1",
"\n",
"}",
"\n\n",
"if",
"p",
"==",
"nil",
"{",
"p",
"=",
"defaultParams",
"\n",
"}",
"\n\n",
"// a min over 1 can never be satisfied, so the score is 0.",
"if",
"p",
".",
"minScore",
">",
"1",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"insCost",
",",
"delCost",
",",
"maxDist",
",",
"max",
":=",
"p",
".",
"insCost",
",",
"p",
".",
"delCost",
",",
"0",
",",
"0",
"\n",
"if",
"l1",
">",
"l2",
"{",
"l1",
",",
"l2",
",",
"insCost",
",",
"delCost",
"=",
"l2",
",",
"l1",
",",
"delCost",
",",
"insCost",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"subCost",
"<",
"delCost",
"+",
"insCost",
"{",
"maxDist",
"=",
"l1",
"*",
"p",
".",
"subCost",
"+",
"(",
"l2",
"-",
"l1",
")",
"*",
"insCost",
"\n",
"}",
"else",
"{",
"maxDist",
"=",
"l1",
"*",
"delCost",
"+",
"l2",
"*",
"insCost",
"\n",
"}",
"\n\n",
"// a zero min is always satisfied, so no need to set a max cost.",
"if",
"p",
".",
"minScore",
">",
"0",
"{",
"// if p.minScore is lower than p.bonusThreshold, we can use a simplified formula",
"// for the max cost, because a sim score below min cannot receive a bonus.",
"if",
"p",
".",
"minScore",
"<",
"p",
".",
"bonusThreshold",
"{",
"// round down the max - a cost equal to a rounded up max would already be under min.",
"max",
"=",
"int",
"(",
"(",
"1",
"-",
"p",
".",
"minScore",
")",
"*",
"float64",
"(",
"maxDist",
")",
")",
"\n",
"}",
"else",
"{",
"// p.minScore <= sim + p.bonusPrefix*p.bonusScale*(1-sim)",
"// p.minScore <= (1-dist/maxDist) + p.bonusPrefix*p.bonusScale*(1-(1-dist/maxDist))",
"// p.minScore <= 1 - dist/maxDist + p.bonusPrefix*p.bonusScale*dist/maxDist",
"// 1 - p.minScore >= dist/maxDist - p.bonusPrefix*p.bonusScale*dist/maxDist",
"// (1-p.minScore)*maxDist/(1-p.bonusPrefix*p.bonusScale) >= dist",
"max",
"=",
"int",
"(",
"(",
"1",
"-",
"p",
".",
"minScore",
")",
"*",
"float64",
"(",
"maxDist",
")",
"/",
"(",
"1",
"-",
"float64",
"(",
"p",
".",
"bonusPrefix",
")",
"*",
"p",
".",
"bonusScale",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"dist",
",",
"pl",
",",
"_",
":=",
"Calculate",
"(",
"s1",
",",
"s2",
",",
"max",
",",
"p",
".",
"insCost",
",",
"p",
".",
"subCost",
",",
"p",
".",
"delCost",
")",
"\n",
"if",
"max",
">",
"0",
"&&",
"dist",
">",
"max",
"{",
"return",
"0",
"\n",
"}",
"\n",
"sim",
":=",
"1",
"-",
"float64",
"(",
"dist",
")",
"/",
"float64",
"(",
"maxDist",
")",
"\n\n",
"if",
"sim",
">=",
"p",
".",
"bonusThreshold",
"&&",
"sim",
"<",
"1",
"&&",
"p",
".",
"bonusPrefix",
">",
"0",
"&&",
"p",
".",
"bonusScale",
">",
"0",
"{",
"if",
"pl",
">",
"p",
".",
"bonusPrefix",
"{",
"pl",
"=",
"p",
".",
"bonusPrefix",
"\n",
"}",
"\n",
"sim",
"+=",
"float64",
"(",
"pl",
")",
"*",
"p",
".",
"bonusScale",
"*",
"(",
"1",
"-",
"sim",
")",
"\n",
"}",
"\n\n",
"if",
"sim",
"<",
"p",
".",
"minScore",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"return",
"sim",
"\n",
"}"
] | // Match returns a similarity score adjusted by the same method as proposed by Winkler for
// the Jaro distance - giving a bonus to string pairs that share a common prefix, only if their
// similarity score is already over a threshold.
//
// The score is in the range of 0..1, with 1 meaning the strings are identical,
// and 0 meaning they have nothing in common.
//
// A nil third argument uses the default cost of 1 for all three operations, maximum length of
// common prefix to consider for bonus of 4, scaling factor of 0.1, and bonus threshold of 0.7.
//
// If a non-zero MinScore value is provided in the parameters, scores lower than it
// will be returned as 0. | [
"Match",
"returns",
"a",
"similarity",
"score",
"adjusted",
"by",
"the",
"same",
"method",
"as",
"proposed",
"by",
"Winkler",
"for",
"the",
"Jaro",
"distance",
"-",
"giving",
"a",
"bonus",
"to",
"string",
"pairs",
"that",
"share",
"a",
"common",
"prefix",
"only",
"if",
"their",
"similarity",
"score",
"is",
"already",
"over",
"a",
"threshold",
".",
"The",
"score",
"is",
"in",
"the",
"range",
"of",
"0",
"..",
"1",
"with",
"1",
"meaning",
"the",
"strings",
"are",
"identical",
"and",
"0",
"meaning",
"they",
"have",
"nothing",
"in",
"common",
".",
"A",
"nil",
"third",
"argument",
"uses",
"the",
"default",
"cost",
"of",
"1",
"for",
"all",
"three",
"operations",
"maximum",
"length",
"of",
"common",
"prefix",
"to",
"consider",
"for",
"bonus",
"of",
"4",
"scaling",
"factor",
"of",
"0",
".",
"1",
"and",
"bonus",
"threshold",
"of",
"0",
".",
"7",
".",
"If",
"a",
"non",
"-",
"zero",
"MinScore",
"value",
"is",
"provided",
"in",
"the",
"parameters",
"scores",
"lower",
"than",
"it",
"will",
"be",
"returned",
"as",
"0",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/levenshtein.go#L227-L290 |
15,735 | agext/levenshtein | params.go | NewParams | func NewParams() *Params {
return &Params{
insCost: 1,
subCost: 1,
delCost: 1,
maxCost: 0,
minScore: 0,
bonusPrefix: 4,
bonusScale: .1,
bonusThreshold: .7,
}
} | go | func NewParams() *Params {
return &Params{
insCost: 1,
subCost: 1,
delCost: 1,
maxCost: 0,
minScore: 0,
bonusPrefix: 4,
bonusScale: .1,
bonusThreshold: .7,
}
} | [
"func",
"NewParams",
"(",
")",
"*",
"Params",
"{",
"return",
"&",
"Params",
"{",
"insCost",
":",
"1",
",",
"subCost",
":",
"1",
",",
"delCost",
":",
"1",
",",
"maxCost",
":",
"0",
",",
"minScore",
":",
"0",
",",
"bonusPrefix",
":",
"4",
",",
"bonusScale",
":",
".1",
",",
"bonusThreshold",
":",
".7",
",",
"}",
"\n",
"}"
] | // NewParams creates a new set of parameters and initializes it with the default values. | [
"NewParams",
"creates",
"a",
"new",
"set",
"of",
"parameters",
"and",
"initializes",
"it",
"with",
"the",
"default",
"values",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/params.go#L35-L46 |
15,736 | agext/levenshtein | params.go | Clone | func (p *Params) Clone() *Params {
if p == nil {
return NewParams()
}
return &Params{
insCost: p.insCost,
subCost: p.subCost,
delCost: p.delCost,
maxCost: p.maxCost,
minScore: p.minScore,
bonusPrefix: p.bonusPrefix,
bonusScale: p.bonusScale,
bonusThreshold: p.bonusThreshold,
}
} | go | func (p *Params) Clone() *Params {
if p == nil {
return NewParams()
}
return &Params{
insCost: p.insCost,
subCost: p.subCost,
delCost: p.delCost,
maxCost: p.maxCost,
minScore: p.minScore,
bonusPrefix: p.bonusPrefix,
bonusScale: p.bonusScale,
bonusThreshold: p.bonusThreshold,
}
} | [
"func",
"(",
"p",
"*",
"Params",
")",
"Clone",
"(",
")",
"*",
"Params",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"NewParams",
"(",
")",
"\n",
"}",
"\n",
"return",
"&",
"Params",
"{",
"insCost",
":",
"p",
".",
"insCost",
",",
"subCost",
":",
"p",
".",
"subCost",
",",
"delCost",
":",
"p",
".",
"delCost",
",",
"maxCost",
":",
"p",
".",
"maxCost",
",",
"minScore",
":",
"p",
".",
"minScore",
",",
"bonusPrefix",
":",
"p",
".",
"bonusPrefix",
",",
"bonusScale",
":",
"p",
".",
"bonusScale",
",",
"bonusThreshold",
":",
"p",
".",
"bonusThreshold",
",",
"}",
"\n",
"}"
] | // Clone returns a pointer to a copy of the receiver parameter set, or of a new
// default parameter set if the receiver is nil. | [
"Clone",
"returns",
"a",
"pointer",
"to",
"a",
"copy",
"of",
"the",
"receiver",
"parameter",
"set",
"or",
"of",
"a",
"new",
"default",
"parameter",
"set",
"if",
"the",
"receiver",
"is",
"nil",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/params.go#L50-L64 |
15,737 | agext/levenshtein | params.go | InsCost | func (p *Params) InsCost(v int) *Params {
if v >= 0 {
p.insCost = v
}
return p
} | go | func (p *Params) InsCost(v int) *Params {
if v >= 0 {
p.insCost = v
}
return p
} | [
"func",
"(",
"p",
"*",
"Params",
")",
"InsCost",
"(",
"v",
"int",
")",
"*",
"Params",
"{",
"if",
"v",
">=",
"0",
"{",
"p",
".",
"insCost",
"=",
"v",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // InsCost overrides the default value of 1 for the cost of insertion.
// The new value must be zero or positive. | [
"InsCost",
"overrides",
"the",
"default",
"value",
"of",
"1",
"for",
"the",
"cost",
"of",
"insertion",
".",
"The",
"new",
"value",
"must",
"be",
"zero",
"or",
"positive",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/params.go#L68-L73 |
15,738 | agext/levenshtein | params.go | SubCost | func (p *Params) SubCost(v int) *Params {
if v >= 0 {
p.subCost = v
}
return p
} | go | func (p *Params) SubCost(v int) *Params {
if v >= 0 {
p.subCost = v
}
return p
} | [
"func",
"(",
"p",
"*",
"Params",
")",
"SubCost",
"(",
"v",
"int",
")",
"*",
"Params",
"{",
"if",
"v",
">=",
"0",
"{",
"p",
".",
"subCost",
"=",
"v",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // SubCost overrides the default value of 1 for the cost of substitution.
// The new value must be zero or positive. | [
"SubCost",
"overrides",
"the",
"default",
"value",
"of",
"1",
"for",
"the",
"cost",
"of",
"substitution",
".",
"The",
"new",
"value",
"must",
"be",
"zero",
"or",
"positive",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/params.go#L77-L82 |
15,739 | agext/levenshtein | params.go | DelCost | func (p *Params) DelCost(v int) *Params {
if v >= 0 {
p.delCost = v
}
return p
} | go | func (p *Params) DelCost(v int) *Params {
if v >= 0 {
p.delCost = v
}
return p
} | [
"func",
"(",
"p",
"*",
"Params",
")",
"DelCost",
"(",
"v",
"int",
")",
"*",
"Params",
"{",
"if",
"v",
">=",
"0",
"{",
"p",
".",
"delCost",
"=",
"v",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // DelCost overrides the default value of 1 for the cost of deletion.
// The new value must be zero or positive. | [
"DelCost",
"overrides",
"the",
"default",
"value",
"of",
"1",
"for",
"the",
"cost",
"of",
"deletion",
".",
"The",
"new",
"value",
"must",
"be",
"zero",
"or",
"positive",
"."
] | 0ded9c86537917af2ff89bc9c78de6bd58477894 | https://github.com/agext/levenshtein/blob/0ded9c86537917af2ff89bc9c78de6bd58477894/params.go#L86-L91 |
15,740 | mattn/go-jsonpointer | jsonpointer.go | Has | func Has(obj interface{}, pointer string) (rv bool) {
defer func() {
if e := recover(); e != nil {
rv = false
}
}()
tokens, err := parse(pointer)
if err != nil {
return false
}
i := 0
v := reflect.ValueOf(obj)
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
token := tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
return v.IsValid()
}
return false
} | go | func Has(obj interface{}, pointer string) (rv bool) {
defer func() {
if e := recover(); e != nil {
rv = false
}
}()
tokens, err := parse(pointer)
if err != nil {
return false
}
i := 0
v := reflect.ValueOf(obj)
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
token := tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
return v.IsValid()
}
return false
} | [
"func",
"Has",
"(",
"obj",
"interface",
"{",
"}",
",",
"pointer",
"string",
")",
"(",
"rv",
"bool",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
":=",
"recover",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"rv",
"=",
"false",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"tokens",
",",
"err",
":=",
"parse",
"(",
"pointer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
"\n",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
"&&",
"tokens",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"for",
"i",
"<",
"len",
"(",
"tokens",
")",
"{",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"token",
":=",
"tokens",
"[",
"i",
"]",
"\n\n",
"if",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"token",
")",
";",
"err",
"==",
"nil",
"&&",
"isIndexed",
"(",
"v",
")",
"{",
"v",
"=",
"v",
".",
"Index",
"(",
"n",
")",
"\n",
"}",
"else",
"{",
"v",
"=",
"v",
".",
"MapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"v",
".",
"IsValid",
"(",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Has return whether the obj has pointer. | [
"Has",
"return",
"whether",
"the",
"obj",
"has",
"pointer",
"."
] | 37667080efed1c5c793dc49809f8748f7c830432 | https://github.com/mattn/go-jsonpointer/blob/37667080efed1c5c793dc49809f8748f7c830432/jsonpointer.go#L28-L58 |
15,741 | mattn/go-jsonpointer | jsonpointer.go | Get | func Get(obj interface{}, pointer string) (rv interface{}, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return nil, err
}
i := 0
v := reflect.ValueOf(obj)
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
token := tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
}
return v.Interface(), nil
} | go | func Get(obj interface{}, pointer string) (rv interface{}, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return nil, err
}
i := 0
v := reflect.ValueOf(obj)
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
token := tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
}
return v.Interface(), nil
} | [
"func",
"Get",
"(",
"obj",
"interface",
"{",
"}",
",",
"pointer",
"string",
")",
"(",
"rv",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
":=",
"recover",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pointer",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"tokens",
",",
"err",
":=",
"parse",
"(",
"pointer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
"\n",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
"&&",
"tokens",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"for",
"i",
"<",
"len",
"(",
"tokens",
")",
"{",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"token",
":=",
"tokens",
"[",
"i",
"]",
"\n",
"if",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"token",
")",
";",
"err",
"==",
"nil",
"&&",
"isIndexed",
"(",
"v",
")",
"{",
"v",
"=",
"v",
".",
"Index",
"(",
"n",
")",
"\n",
"}",
"else",
"{",
"v",
"=",
"v",
".",
"MapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"v",
".",
"Interface",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Get return a value which is pointed with pointer on obj. | [
"Get",
"return",
"a",
"value",
"which",
"is",
"pointed",
"with",
"pointer",
"on",
"obj",
"."
] | 37667080efed1c5c793dc49809f8748f7c830432 | https://github.com/mattn/go-jsonpointer/blob/37667080efed1c5c793dc49809f8748f7c830432/jsonpointer.go#L61-L89 |
15,742 | mattn/go-jsonpointer | jsonpointer.go | Set | func Set(obj interface{}, pointer string, value interface{}) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return err
}
i := 0
v := reflect.ValueOf(obj)
var p reflect.Value
var token string
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
p = v
token = tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
if p.Kind() == reflect.Map {
p.SetMapIndex(reflect.ValueOf(token), reflect.ValueOf(value))
} else {
v.Set(reflect.ValueOf(value))
}
return nil
}
return fmt.Errorf("pointer should have element")
} | go | func Set(obj interface{}, pointer string, value interface{}) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return err
}
i := 0
v := reflect.ValueOf(obj)
var p reflect.Value
var token string
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
p = v
token = tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
if p.Kind() == reflect.Map {
p.SetMapIndex(reflect.ValueOf(token), reflect.ValueOf(value))
} else {
v.Set(reflect.ValueOf(value))
}
return nil
}
return fmt.Errorf("pointer should have element")
} | [
"func",
"Set",
"(",
"obj",
"interface",
"{",
"}",
",",
"pointer",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
":=",
"recover",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pointer",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"tokens",
",",
"err",
":=",
"parse",
"(",
"pointer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
"\n",
"var",
"p",
"reflect",
".",
"Value",
"\n",
"var",
"token",
"string",
"\n",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
"&&",
"tokens",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"for",
"i",
"<",
"len",
"(",
"tokens",
")",
"{",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"p",
"=",
"v",
"\n",
"token",
"=",
"tokens",
"[",
"i",
"]",
"\n",
"if",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"token",
")",
";",
"err",
"==",
"nil",
"&&",
"isIndexed",
"(",
"v",
")",
"{",
"v",
"=",
"v",
".",
"Index",
"(",
"n",
")",
"\n",
"}",
"else",
"{",
"v",
"=",
"v",
".",
"MapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"if",
"p",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Map",
"{",
"p",
".",
"SetMapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"token",
")",
",",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
")",
"\n",
"}",
"else",
"{",
"v",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Set set a value which is pointed with pointer on obj. | [
"Set",
"set",
"a",
"value",
"which",
"is",
"pointed",
"with",
"pointer",
"on",
"obj",
"."
] | 37667080efed1c5c793dc49809f8748f7c830432 | https://github.com/mattn/go-jsonpointer/blob/37667080efed1c5c793dc49809f8748f7c830432/jsonpointer.go#L92-L129 |
15,743 | mattn/go-jsonpointer | jsonpointer.go | Remove | func Remove(obj interface{}, pointer string) (rv interface{}, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return nil, err
}
i := 0
v := reflect.ValueOf(obj)
var p, pp reflect.Value
var token, ptoken string
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
pp = p
p = v
ptoken = token
token = tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
} else {
return nil, fmt.Errorf("pointer should have element")
}
var nv reflect.Value
if p.Kind() == reflect.Map {
nv = reflect.MakeMap(p.Type())
for _, mk := range p.MapKeys() {
if mk.String() != token {
nv.SetMapIndex(mk, p.MapIndex(mk))
}
}
} else {
nv = reflect.Zero(p.Type())
n, _ := strconv.Atoi(token)
for m := 0; m < p.Len(); m++ {
if n != m {
nv = reflect.Append(nv, p.Index(m))
}
}
}
if !pp.IsValid() {
obj = nv.Interface()
} else if pp.Kind() == reflect.Map {
pp.SetMapIndex(reflect.ValueOf(ptoken), nv)
} else {
p.Set(reflect.ValueOf(nv))
}
return obj, nil
} | go | func Remove(obj interface{}, pointer string) (rv interface{}, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("invalid JSON pointer: %q: %v", pointer, e)
}
}()
tokens, err := parse(pointer)
if err != nil {
return nil, err
}
i := 0
v := reflect.ValueOf(obj)
var p, pp reflect.Value
var token, ptoken string
if len(tokens) > 0 && tokens[0] != "" {
for i < len(tokens) {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
pp = p
p = v
ptoken = token
token = tokens[i]
if n, err := strconv.Atoi(token); err == nil && isIndexed(v) {
v = v.Index(n)
} else {
v = v.MapIndex(reflect.ValueOf(token))
}
i++
}
} else {
return nil, fmt.Errorf("pointer should have element")
}
var nv reflect.Value
if p.Kind() == reflect.Map {
nv = reflect.MakeMap(p.Type())
for _, mk := range p.MapKeys() {
if mk.String() != token {
nv.SetMapIndex(mk, p.MapIndex(mk))
}
}
} else {
nv = reflect.Zero(p.Type())
n, _ := strconv.Atoi(token)
for m := 0; m < p.Len(); m++ {
if n != m {
nv = reflect.Append(nv, p.Index(m))
}
}
}
if !pp.IsValid() {
obj = nv.Interface()
} else if pp.Kind() == reflect.Map {
pp.SetMapIndex(reflect.ValueOf(ptoken), nv)
} else {
p.Set(reflect.ValueOf(nv))
}
return obj, nil
} | [
"func",
"Remove",
"(",
"obj",
"interface",
"{",
"}",
",",
"pointer",
"string",
")",
"(",
"rv",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
":=",
"recover",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pointer",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"tokens",
",",
"err",
":=",
"parse",
"(",
"pointer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
"\n",
"var",
"p",
",",
"pp",
"reflect",
".",
"Value",
"\n",
"var",
"token",
",",
"ptoken",
"string",
"\n",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
"&&",
"tokens",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"for",
"i",
"<",
"len",
"(",
"tokens",
")",
"{",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"pp",
"=",
"p",
"\n",
"p",
"=",
"v",
"\n",
"ptoken",
"=",
"token",
"\n",
"token",
"=",
"tokens",
"[",
"i",
"]",
"\n",
"if",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"token",
")",
";",
"err",
"==",
"nil",
"&&",
"isIndexed",
"(",
"v",
")",
"{",
"v",
"=",
"v",
".",
"Index",
"(",
"n",
")",
"\n",
"}",
"else",
"{",
"v",
"=",
"v",
".",
"MapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"token",
")",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"nv",
"reflect",
".",
"Value",
"\n",
"if",
"p",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Map",
"{",
"nv",
"=",
"reflect",
".",
"MakeMap",
"(",
"p",
".",
"Type",
"(",
")",
")",
"\n",
"for",
"_",
",",
"mk",
":=",
"range",
"p",
".",
"MapKeys",
"(",
")",
"{",
"if",
"mk",
".",
"String",
"(",
")",
"!=",
"token",
"{",
"nv",
".",
"SetMapIndex",
"(",
"mk",
",",
"p",
".",
"MapIndex",
"(",
"mk",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"nv",
"=",
"reflect",
".",
"Zero",
"(",
"p",
".",
"Type",
"(",
")",
")",
"\n",
"n",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"token",
")",
"\n",
"for",
"m",
":=",
"0",
";",
"m",
"<",
"p",
".",
"Len",
"(",
")",
";",
"m",
"++",
"{",
"if",
"n",
"!=",
"m",
"{",
"nv",
"=",
"reflect",
".",
"Append",
"(",
"nv",
",",
"p",
".",
"Index",
"(",
"m",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"pp",
".",
"IsValid",
"(",
")",
"{",
"obj",
"=",
"nv",
".",
"Interface",
"(",
")",
"\n",
"}",
"else",
"if",
"pp",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Map",
"{",
"pp",
".",
"SetMapIndex",
"(",
"reflect",
".",
"ValueOf",
"(",
"ptoken",
")",
",",
"nv",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"nv",
")",
")",
"\n",
"}",
"\n",
"return",
"obj",
",",
"nil",
"\n",
"}"
] | // Remove remove a value which is pointed with pointer on obj. | [
"Remove",
"remove",
"a",
"value",
"which",
"is",
"pointed",
"with",
"pointer",
"on",
"obj",
"."
] | 37667080efed1c5c793dc49809f8748f7c830432 | https://github.com/mattn/go-jsonpointer/blob/37667080efed1c5c793dc49809f8748f7c830432/jsonpointer.go#L132-L193 |
15,744 | choria-io/go-choria | choria/ssl.go | TLSConfig | func (fw *Framework) TLSConfig() (tlsc *tls.Config, err error) {
return fw.security.TLSConfig()
} | go | func (fw *Framework) TLSConfig() (tlsc *tls.Config, err error) {
return fw.security.TLSConfig()
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"TLSConfig",
"(",
")",
"(",
"tlsc",
"*",
"tls",
".",
"Config",
",",
"err",
"error",
")",
"{",
"return",
"fw",
".",
"security",
".",
"TLSConfig",
"(",
")",
"\n",
"}"
] | // TLSConfig creates a TLS configuration for use by NATS, HTTPS etc | [
"TLSConfig",
"creates",
"a",
"TLS",
"configuration",
"for",
"use",
"by",
"NATS",
"HTTPS",
"etc"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/ssl.go#L15-L17 |
15,745 | choria-io/go-choria | choria/ssl.go | Enroll | func (fw *Framework) Enroll(ctx context.Context, wait time.Duration, cb func(int)) error {
return fw.security.Enroll(ctx, wait, cb)
} | go | func (fw *Framework) Enroll(ctx context.Context, wait time.Duration, cb func(int)) error {
return fw.security.Enroll(ctx, wait, cb)
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"Enroll",
"(",
"ctx",
"context",
".",
"Context",
",",
"wait",
"time",
".",
"Duration",
",",
"cb",
"func",
"(",
"int",
")",
")",
"error",
"{",
"return",
"fw",
".",
"security",
".",
"Enroll",
"(",
"ctx",
",",
"wait",
",",
"cb",
")",
"\n",
"}"
] | // Enroll performs the tasks needed to join the security system, like create
// a new certificate, csr etc | [
"Enroll",
"performs",
"the",
"tasks",
"needed",
"to",
"join",
"the",
"security",
"system",
"like",
"create",
"a",
"new",
"certificate",
"csr",
"etc"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/ssl.go#L21-L23 |
15,746 | choria-io/go-choria | choria/ssl.go | ValidateSecurity | func (fw *Framework) ValidateSecurity() (errors []string, ok bool) {
return fw.security.Validate()
} | go | func (fw *Framework) ValidateSecurity() (errors []string, ok bool) {
return fw.security.Validate()
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"ValidateSecurity",
"(",
")",
"(",
"errors",
"[",
"]",
"string",
",",
"ok",
"bool",
")",
"{",
"return",
"fw",
".",
"security",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // ValidateSecurity calls the security provider validation method and indicates
// if all dependencies are met for secure operation | [
"ValidateSecurity",
"calls",
"the",
"security",
"provider",
"validation",
"method",
"and",
"indicates",
"if",
"all",
"dependencies",
"are",
"met",
"for",
"secure",
"operation"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/ssl.go#L27-L29 |
15,747 | choria-io/go-choria | server/agents/server_info_source_mock.go | Metadata | func (m *MockAgent) Metadata() *Metadata {
ret := m.ctrl.Call(m, "Metadata")
ret0, _ := ret[0].(*Metadata)
return ret0
} | go | func (m *MockAgent) Metadata() *Metadata {
ret := m.ctrl.Call(m, "Metadata")
ret0, _ := ret[0].(*Metadata)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockAgent",
")",
"Metadata",
"(",
")",
"*",
"Metadata",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"*",
"Metadata",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // Metadata mocks base method | [
"Metadata",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L43-L47 |
15,748 | choria-io/go-choria | server/agents/server_info_source_mock.go | Metadata | func (mr *MockAgentMockRecorder) Metadata() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Metadata", reflect.TypeOf((*MockAgent)(nil).Metadata))
} | go | func (mr *MockAgentMockRecorder) Metadata() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Metadata", reflect.TypeOf((*MockAgent)(nil).Metadata))
} | [
"func",
"(",
"mr",
"*",
"MockAgentMockRecorder",
")",
"Metadata",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockAgent",
")",
"(",
"nil",
")",
".",
"Metadata",
")",
")",
"\n",
"}"
] | // Metadata indicates an expected call of Metadata | [
"Metadata",
"indicates",
"an",
"expected",
"call",
"of",
"Metadata"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L50-L52 |
15,749 | choria-io/go-choria | server/agents/server_info_source_mock.go | HandleMessage | func (mr *MockAgentMockRecorder) HandleMessage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleMessage", reflect.TypeOf((*MockAgent)(nil).HandleMessage), arg0, arg1, arg2, arg3, arg4)
} | go | func (mr *MockAgentMockRecorder) HandleMessage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleMessage", reflect.TypeOf((*MockAgent)(nil).HandleMessage), arg0, arg1, arg2, arg3, arg4)
} | [
"func",
"(",
"mr",
"*",
"MockAgentMockRecorder",
")",
"HandleMessage",
"(",
"arg0",
",",
"arg1",
",",
"arg2",
",",
"arg3",
",",
"arg4",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockAgent",
")",
"(",
"nil",
")",
".",
"HandleMessage",
")",
",",
"arg0",
",",
"arg1",
",",
"arg2",
",",
"arg3",
",",
"arg4",
")",
"\n",
"}"
] | // HandleMessage indicates an expected call of HandleMessage | [
"HandleMessage",
"indicates",
"an",
"expected",
"call",
"of",
"HandleMessage"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L72-L74 |
15,750 | choria-io/go-choria | server/agents/server_info_source_mock.go | SetServerInfo | func (m *MockAgent) SetServerInfo(arg0 ServerInfoSource) {
m.ctrl.Call(m, "SetServerInfo", arg0)
} | go | func (m *MockAgent) SetServerInfo(arg0 ServerInfoSource) {
m.ctrl.Call(m, "SetServerInfo", arg0)
} | [
"func",
"(",
"m",
"*",
"MockAgent",
")",
"SetServerInfo",
"(",
"arg0",
"ServerInfoSource",
")",
"{",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"}"
] | // SetServerInfo mocks base method | [
"SetServerInfo",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L77-L79 |
15,751 | choria-io/go-choria | server/agents/server_info_source_mock.go | NewMockServerInfoSource | func NewMockServerInfoSource(ctrl *gomock.Controller) *MockServerInfoSource {
mock := &MockServerInfoSource{ctrl: ctrl}
mock.recorder = &MockServerInfoSourceMockRecorder{mock}
return mock
} | go | func NewMockServerInfoSource(ctrl *gomock.Controller) *MockServerInfoSource {
mock := &MockServerInfoSource{ctrl: ctrl}
mock.recorder = &MockServerInfoSourceMockRecorder{mock}
return mock
} | [
"func",
"NewMockServerInfoSource",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockServerInfoSource",
"{",
"mock",
":=",
"&",
"MockServerInfoSource",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockServerInfoSourceMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockServerInfoSource creates a new mock instance | [
"NewMockServerInfoSource",
"creates",
"a",
"new",
"mock",
"instance"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L98-L102 |
15,752 | choria-io/go-choria | server/agents/server_info_source_mock.go | KnownAgents | func (m *MockServerInfoSource) KnownAgents() []string {
ret := m.ctrl.Call(m, "KnownAgents")
ret0, _ := ret[0].([]string)
return ret0
} | go | func (m *MockServerInfoSource) KnownAgents() []string {
ret := m.ctrl.Call(m, "KnownAgents")
ret0, _ := ret[0].([]string)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"KnownAgents",
"(",
")",
"[",
"]",
"string",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"string",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // KnownAgents mocks base method | [
"KnownAgents",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L110-L114 |
15,753 | choria-io/go-choria | server/agents/server_info_source_mock.go | AgentMetadata | func (m *MockServerInfoSource) AgentMetadata(arg0 string) (Metadata, bool) {
ret := m.ctrl.Call(m, "AgentMetadata", arg0)
ret0, _ := ret[0].(Metadata)
ret1, _ := ret[1].(bool)
return ret0, ret1
} | go | func (m *MockServerInfoSource) AgentMetadata(arg0 string) (Metadata, bool) {
ret := m.ctrl.Call(m, "AgentMetadata", arg0)
ret0, _ := ret[0].(Metadata)
ret1, _ := ret[1].(bool)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"AgentMetadata",
"(",
"arg0",
"string",
")",
"(",
"Metadata",
",",
"bool",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"Metadata",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"bool",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // AgentMetadata mocks base method | [
"AgentMetadata",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L122-L127 |
15,754 | choria-io/go-choria | server/agents/server_info_source_mock.go | AgentMetadata | func (mr *MockServerInfoSourceMockRecorder) AgentMetadata(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentMetadata", reflect.TypeOf((*MockServerInfoSource)(nil).AgentMetadata), arg0)
} | go | func (mr *MockServerInfoSourceMockRecorder) AgentMetadata(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentMetadata", reflect.TypeOf((*MockServerInfoSource)(nil).AgentMetadata), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockServerInfoSourceMockRecorder",
")",
"AgentMetadata",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServerInfoSource",
")",
"(",
"nil",
")",
".",
"AgentMetadata",
")",
",",
"arg0",
")",
"\n",
"}"
] | // AgentMetadata indicates an expected call of AgentMetadata | [
"AgentMetadata",
"indicates",
"an",
"expected",
"call",
"of",
"AgentMetadata"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L130-L132 |
15,755 | choria-io/go-choria | server/agents/server_info_source_mock.go | Facts | func (m *MockServerInfoSource) Facts() json.RawMessage {
ret := m.ctrl.Call(m, "Facts")
ret0, _ := ret[0].(json.RawMessage)
return ret0
} | go | func (m *MockServerInfoSource) Facts() json.RawMessage {
ret := m.ctrl.Call(m, "Facts")
ret0, _ := ret[0].(json.RawMessage)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"Facts",
"(",
")",
"json",
".",
"RawMessage",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"json",
".",
"RawMessage",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // Facts mocks base method | [
"Facts",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L159-L163 |
15,756 | choria-io/go-choria | server/agents/server_info_source_mock.go | StartTime | func (m *MockServerInfoSource) StartTime() time.Time {
ret := m.ctrl.Call(m, "StartTime")
ret0, _ := ret[0].(time.Time)
return ret0
} | go | func (m *MockServerInfoSource) StartTime() time.Time {
ret := m.ctrl.Call(m, "StartTime")
ret0, _ := ret[0].(time.Time)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"StartTime",
"(",
")",
"time",
".",
"Time",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // StartTime mocks base method | [
"StartTime",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L171-L175 |
15,757 | choria-io/go-choria | server/agents/server_info_source_mock.go | NewEvent | func (m *MockServerInfoSource) NewEvent(t go_lifecycle.Type, opts ...go_lifecycle.Option) error {
varargs := []interface{}{t}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "NewEvent", varargs...)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockServerInfoSource) NewEvent(t go_lifecycle.Type, opts ...go_lifecycle.Option) error {
varargs := []interface{}{t}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "NewEvent", varargs...)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"NewEvent",
"(",
"t",
"go_lifecycle",
".",
"Type",
",",
"opts",
"...",
"go_lifecycle",
".",
"Option",
")",
"error",
"{",
"varargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"t",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"opts",
"{",
"varargs",
"=",
"append",
"(",
"varargs",
",",
"a",
")",
"\n",
"}",
"\n",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"varargs",
"...",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // NewEvent mocks base method | [
"NewEvent",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L195-L203 |
15,758 | choria-io/go-choria | server/agents/server_info_source_mock.go | NewEvent | func (mr *MockServerInfoSourceMockRecorder) NewEvent(t interface{}, opts ...interface{}) *gomock.Call {
varargs := append([]interface{}{t}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewEvent", reflect.TypeOf((*MockServerInfoSource)(nil).NewEvent), varargs...)
} | go | func (mr *MockServerInfoSourceMockRecorder) NewEvent(t interface{}, opts ...interface{}) *gomock.Call {
varargs := append([]interface{}{t}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewEvent", reflect.TypeOf((*MockServerInfoSource)(nil).NewEvent), varargs...)
} | [
"func",
"(",
"mr",
"*",
"MockServerInfoSourceMockRecorder",
")",
"NewEvent",
"(",
"t",
"interface",
"{",
"}",
",",
"opts",
"...",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"varargs",
":=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"t",
"}",
",",
"opts",
"...",
")",
"\n",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServerInfoSource",
")",
"(",
"nil",
")",
".",
"NewEvent",
")",
",",
"varargs",
"...",
")",
"\n",
"}"
] | // NewEvent indicates an expected call of NewEvent | [
"NewEvent",
"indicates",
"an",
"expected",
"call",
"of",
"NewEvent"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L206-L209 |
15,759 | choria-io/go-choria | server/agents/server_info_source_mock.go | MachinesStatus | func (m *MockServerInfoSource) MachinesStatus() ([]aagent.MachineState, error) {
ret := m.ctrl.Call(m, "MachinesStatus")
ret0, _ := ret[0].([]aagent.MachineState)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockServerInfoSource) MachinesStatus() ([]aagent.MachineState, error) {
ret := m.ctrl.Call(m, "MachinesStatus")
ret0, _ := ret[0].([]aagent.MachineState)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"MachinesStatus",
"(",
")",
"(",
"[",
"]",
"aagent",
".",
"MachineState",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"aagent",
".",
"MachineState",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // MachinesStatus mocks base method | [
"MachinesStatus",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L212-L217 |
15,760 | choria-io/go-choria | server/agents/server_info_source_mock.go | MachinesStatus | func (mr *MockServerInfoSourceMockRecorder) MachinesStatus() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MachinesStatus", reflect.TypeOf((*MockServerInfoSource)(nil).MachinesStatus))
} | go | func (mr *MockServerInfoSourceMockRecorder) MachinesStatus() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MachinesStatus", reflect.TypeOf((*MockServerInfoSource)(nil).MachinesStatus))
} | [
"func",
"(",
"mr",
"*",
"MockServerInfoSourceMockRecorder",
")",
"MachinesStatus",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServerInfoSource",
")",
"(",
"nil",
")",
".",
"MachinesStatus",
")",
")",
"\n",
"}"
] | // MachinesStatus indicates an expected call of MachinesStatus | [
"MachinesStatus",
"indicates",
"an",
"expected",
"call",
"of",
"MachinesStatus"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L220-L222 |
15,761 | choria-io/go-choria | server/agents/server_info_source_mock.go | MachineTransition | func (m *MockServerInfoSource) MachineTransition(name, version, path, id, transition string) error {
ret := m.ctrl.Call(m, "MachineTransition", name, version, path, id, transition)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockServerInfoSource) MachineTransition(name, version, path, id, transition string) error {
ret := m.ctrl.Call(m, "MachineTransition", name, version, path, id, transition)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockServerInfoSource",
")",
"MachineTransition",
"(",
"name",
",",
"version",
",",
"path",
",",
"id",
",",
"transition",
"string",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"name",
",",
"version",
",",
"path",
",",
"id",
",",
"transition",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // MachineTransition mocks base method | [
"MachineTransition",
"mocks",
"base",
"method"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L225-L229 |
15,762 | choria-io/go-choria | server/agents/server_info_source_mock.go | MachineTransition | func (mr *MockServerInfoSourceMockRecorder) MachineTransition(name, version, path, id, transition interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MachineTransition", reflect.TypeOf((*MockServerInfoSource)(nil).MachineTransition), name, version, path, id, transition)
} | go | func (mr *MockServerInfoSourceMockRecorder) MachineTransition(name, version, path, id, transition interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MachineTransition", reflect.TypeOf((*MockServerInfoSource)(nil).MachineTransition), name, version, path, id, transition)
} | [
"func",
"(",
"mr",
"*",
"MockServerInfoSourceMockRecorder",
")",
"MachineTransition",
"(",
"name",
",",
"version",
",",
"path",
",",
"id",
",",
"transition",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServerInfoSource",
")",
"(",
"nil",
")",
".",
"MachineTransition",
")",
",",
"name",
",",
"version",
",",
"path",
",",
"id",
",",
"transition",
")",
"\n",
"}"
] | // MachineTransition indicates an expected call of MachineTransition | [
"MachineTransition",
"indicates",
"an",
"expected",
"call",
"of",
"MachineTransition"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/agents/server_info_source_mock.go#L232-L234 |
15,763 | choria-io/go-choria | aagent/watchers/watcherdef.go | ParseAnnounceInterval | func (w *WatcherDef) ParseAnnounceInterval() (err error) {
if w.AnnounceInterval != "" {
w.announceDuration, err = time.ParseDuration(w.AnnounceInterval)
if err != nil {
return errors.Wrapf(err, "unknown announce interval for watcher %s", w.Name)
}
if w.announceDuration < time.Minute {
return errors.Errorf("announce interval %v is too small for watcher %s", w.announceDuration, w.Name)
}
}
return nil
} | go | func (w *WatcherDef) ParseAnnounceInterval() (err error) {
if w.AnnounceInterval != "" {
w.announceDuration, err = time.ParseDuration(w.AnnounceInterval)
if err != nil {
return errors.Wrapf(err, "unknown announce interval for watcher %s", w.Name)
}
if w.announceDuration < time.Minute {
return errors.Errorf("announce interval %v is too small for watcher %s", w.announceDuration, w.Name)
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"WatcherDef",
")",
"ParseAnnounceInterval",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"w",
".",
"AnnounceInterval",
"!=",
"\"",
"\"",
"{",
"w",
".",
"announceDuration",
",",
"err",
"=",
"time",
".",
"ParseDuration",
"(",
"w",
".",
"AnnounceInterval",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"w",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"if",
"w",
".",
"announceDuration",
"<",
"time",
".",
"Minute",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"w",
".",
"announceDuration",
",",
"w",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ParseAnnounceInterval parses the announce interval and ensures its not too small | [
"ParseAnnounceInterval",
"parses",
"the",
"announce",
"interval",
"and",
"ensures",
"its",
"not",
"too",
"small"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/aagent/watchers/watcherdef.go#L25-L38 |
15,764 | choria-io/go-choria | config/mutators.go | RegisterMutator | func RegisterMutator(name string, m Mutator) {
mu.Lock()
defer mu.Unlock()
mutators = append(mutators, m)
mutatorNames = append(mutatorNames, name)
} | go | func RegisterMutator(name string, m Mutator) {
mu.Lock()
defer mu.Unlock()
mutators = append(mutators, m)
mutatorNames = append(mutatorNames, name)
} | [
"func",
"RegisterMutator",
"(",
"name",
"string",
",",
"m",
"Mutator",
")",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"mutators",
"=",
"append",
"(",
"mutators",
",",
"m",
")",
"\n",
"mutatorNames",
"=",
"append",
"(",
"mutatorNames",
",",
"name",
")",
"\n",
"}"
] | // RegisterMutator registers a new configuration mutator | [
"RegisterMutator",
"registers",
"a",
"new",
"configuration",
"mutator"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/config/mutators.go#L19-L25 |
15,765 | choria-io/go-choria | config/mutators.go | Mutate | func Mutate(c *Config, log *logrus.Entry) {
mu.Lock()
defer mu.Unlock()
for _, mutator := range mutators {
mutator.Mutate(c, log)
}
} | go | func Mutate(c *Config, log *logrus.Entry) {
mu.Lock()
defer mu.Unlock()
for _, mutator := range mutators {
mutator.Mutate(c, log)
}
} | [
"func",
"Mutate",
"(",
"c",
"*",
"Config",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"mutator",
":=",
"range",
"mutators",
"{",
"mutator",
".",
"Mutate",
"(",
"c",
",",
"log",
")",
"\n",
"}",
"\n",
"}"
] | // Mutate calls all registered mutators on the given configuration | [
"Mutate",
"calls",
"all",
"registered",
"mutators",
"on",
"the",
"given",
"configuration"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/config/mutators.go#L33-L40 |
15,766 | choria-io/go-choria | server/registration/registration.go | New | func New(c *choria.Framework, conn choria.PublishableConnector, logger *logrus.Entry) *Manager {
r := &Manager{
log: logger.WithFields(logrus.Fields{"subsystem": "registration"}),
choria: c,
cfg: c.Config,
connector: conn,
datac: make(chan *data.RegistrationItem, 1),
}
return r
} | go | func New(c *choria.Framework, conn choria.PublishableConnector, logger *logrus.Entry) *Manager {
r := &Manager{
log: logger.WithFields(logrus.Fields{"subsystem": "registration"}),
choria: c,
cfg: c.Config,
connector: conn,
datac: make(chan *data.RegistrationItem, 1),
}
return r
} | [
"func",
"New",
"(",
"c",
"*",
"choria",
".",
"Framework",
",",
"conn",
"choria",
".",
"PublishableConnector",
",",
"logger",
"*",
"logrus",
".",
"Entry",
")",
"*",
"Manager",
"{",
"r",
":=",
"&",
"Manager",
"{",
"log",
":",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
",",
"choria",
":",
"c",
",",
"cfg",
":",
"c",
".",
"Config",
",",
"connector",
":",
"conn",
",",
"datac",
":",
"make",
"(",
"chan",
"*",
"data",
".",
"RegistrationItem",
",",
"1",
")",
",",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] | // New creates a new instance of the registration subsystem manager | [
"New",
"creates",
"a",
"new",
"instance",
"of",
"the",
"registration",
"subsystem",
"manager"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/registration/registration.go#L41-L51 |
15,767 | choria-io/go-choria | server/registration/registration.go | Start | func (reg *Manager) Start(ctx context.Context, wg *sync.WaitGroup) error {
defer wg.Done()
if reg.cfg.RegistrationCollective == "" {
reg.cfg.RegistrationCollective = reg.cfg.MainCollective
}
var err error
var registrator Registrator
for _, rtype := range reg.cfg.Registration {
switch rtype {
case "":
return nil
case "file_content":
registrator, err = registration.NewFileContent(reg.cfg, reg.log)
if err != nil {
return fmt.Errorf("Cannot start File Content Registrator: %s", err)
}
default:
return fmt.Errorf("Unknown registration plugin: %s", reg.cfg.Registration)
}
reg.log.Infof("Starting registration worker for %s", rtype)
reg.RegisterProvider(ctx, wg, registrator)
}
return nil
} | go | func (reg *Manager) Start(ctx context.Context, wg *sync.WaitGroup) error {
defer wg.Done()
if reg.cfg.RegistrationCollective == "" {
reg.cfg.RegistrationCollective = reg.cfg.MainCollective
}
var err error
var registrator Registrator
for _, rtype := range reg.cfg.Registration {
switch rtype {
case "":
return nil
case "file_content":
registrator, err = registration.NewFileContent(reg.cfg, reg.log)
if err != nil {
return fmt.Errorf("Cannot start File Content Registrator: %s", err)
}
default:
return fmt.Errorf("Unknown registration plugin: %s", reg.cfg.Registration)
}
reg.log.Infof("Starting registration worker for %s", rtype)
reg.RegisterProvider(ctx, wg, registrator)
}
return nil
} | [
"func",
"(",
"reg",
"*",
"Manager",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"error",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"if",
"reg",
".",
"cfg",
".",
"RegistrationCollective",
"==",
"\"",
"\"",
"{",
"reg",
".",
"cfg",
".",
"RegistrationCollective",
"=",
"reg",
".",
"cfg",
".",
"MainCollective",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"var",
"registrator",
"Registrator",
"\n\n",
"for",
"_",
",",
"rtype",
":=",
"range",
"reg",
".",
"cfg",
".",
"Registration",
"{",
"switch",
"rtype",
"{",
"case",
"\"",
"\"",
":",
"return",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"registrator",
",",
"err",
"=",
"registration",
".",
"NewFileContent",
"(",
"reg",
".",
"cfg",
",",
"reg",
".",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reg",
".",
"cfg",
".",
"Registration",
")",
"\n",
"}",
"\n\n",
"reg",
".",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"rtype",
")",
"\n",
"reg",
".",
"RegisterProvider",
"(",
"ctx",
",",
"wg",
",",
"registrator",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Start initializes the fully managed registration plugins and start publishing
// their data | [
"Start",
"initializes",
"the",
"fully",
"managed",
"registration",
"plugins",
"and",
"start",
"publishing",
"their",
"data"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/registration/registration.go#L55-L83 |
15,768 | choria-io/go-choria | server/registration/registration.go | RegisterProvider | func (reg *Manager) RegisterProvider(ctx context.Context, wg *sync.WaitGroup, provider RegistrationDataProvider) error {
wg.Add(1)
go reg.registrationWorker(ctx, wg, provider)
return nil
} | go | func (reg *Manager) RegisterProvider(ctx context.Context, wg *sync.WaitGroup, provider RegistrationDataProvider) error {
wg.Add(1)
go reg.registrationWorker(ctx, wg, provider)
return nil
} | [
"func",
"(",
"reg",
"*",
"Manager",
")",
"RegisterProvider",
"(",
"ctx",
"context",
".",
"Context",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
",",
"provider",
"RegistrationDataProvider",
")",
"error",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"reg",
".",
"registrationWorker",
"(",
"ctx",
",",
"wg",
",",
"provider",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // RegisterProvider creates a publisher for a new provider | [
"RegisterProvider",
"creates",
"a",
"publisher",
"for",
"a",
"new",
"provider"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/registration/registration.go#L86-L91 |
15,769 | choria-io/go-choria | server/machine.go | StartMachine | func (srv *Instance) StartMachine(ctx context.Context, wg *sync.WaitGroup) (err error) {
if srv.cfg.Choria.MachineSourceDir == "" {
return fmt.Errorf("Choria Autonomous Agent source directory not configured, skipping initialization")
}
srv.machines, err = aagent.New(srv.cfg.Choria.MachineSourceDir, srv)
if err != nil {
return err
}
return srv.machines.ManageMachines(ctx, wg)
} | go | func (srv *Instance) StartMachine(ctx context.Context, wg *sync.WaitGroup) (err error) {
if srv.cfg.Choria.MachineSourceDir == "" {
return fmt.Errorf("Choria Autonomous Agent source directory not configured, skipping initialization")
}
srv.machines, err = aagent.New(srv.cfg.Choria.MachineSourceDir, srv)
if err != nil {
return err
}
return srv.machines.ManageMachines(ctx, wg)
} | [
"func",
"(",
"srv",
"*",
"Instance",
")",
"StartMachine",
"(",
"ctx",
"context",
".",
"Context",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"(",
"err",
"error",
")",
"{",
"if",
"srv",
".",
"cfg",
".",
"Choria",
".",
"MachineSourceDir",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"srv",
".",
"machines",
",",
"err",
"=",
"aagent",
".",
"New",
"(",
"srv",
".",
"cfg",
".",
"Choria",
".",
"MachineSourceDir",
",",
"srv",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"srv",
".",
"machines",
".",
"ManageMachines",
"(",
"ctx",
",",
"wg",
")",
"\n",
"}"
] | // StartMachine starts the choria machine instances | [
"StartMachine",
"starts",
"the",
"choria",
"machine",
"instances"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/machine.go#L12-L23 |
15,770 | choria-io/go-choria | registration/file_content.go | NewFileContent | func NewFileContent(c *config.Config, logger *logrus.Entry) (*FileContent, error) {
if c.Choria.FileContentRegistrationData == "" {
return nil, fmt.Errorf("File Content Registration is enabled but no source data is configured, please set plugin.choria.registration.file_content.data")
}
reg := &FileContent{}
reg.Init(c, logger)
return reg, nil
} | go | func NewFileContent(c *config.Config, logger *logrus.Entry) (*FileContent, error) {
if c.Choria.FileContentRegistrationData == "" {
return nil, fmt.Errorf("File Content Registration is enabled but no source data is configured, please set plugin.choria.registration.file_content.data")
}
reg := &FileContent{}
reg.Init(c, logger)
return reg, nil
} | [
"func",
"NewFileContent",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"logger",
"*",
"logrus",
".",
"Entry",
")",
"(",
"*",
"FileContent",
",",
"error",
")",
"{",
"if",
"c",
".",
"Choria",
".",
"FileContentRegistrationData",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"reg",
":=",
"&",
"FileContent",
"{",
"}",
"\n",
"reg",
".",
"Init",
"(",
"c",
",",
"logger",
")",
"\n\n",
"return",
"reg",
",",
"nil",
"\n",
"}"
] | // NewFileContent creates a new fully managed registration plugin instance | [
"NewFileContent",
"creates",
"a",
"new",
"fully",
"managed",
"registration",
"plugin",
"instance"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/registration/file_content.go#L41-L50 |
15,771 | choria-io/go-choria | registration/file_content.go | Init | func (fc *FileContent) Init(c *config.Config, logger *logrus.Entry) {
fc.c = c
fc.dataFile = c.Choria.FileContentRegistrationData
fc.log = logger.WithFields(logrus.Fields{"registration": "file_content", "source": fc.dataFile})
fc.log.Infof("Configured File Content Registration with source '%s' and target '%s'", fc.dataFile, c.Choria.FileContentRegistrationTarget)
} | go | func (fc *FileContent) Init(c *config.Config, logger *logrus.Entry) {
fc.c = c
fc.dataFile = c.Choria.FileContentRegistrationData
fc.log = logger.WithFields(logrus.Fields{"registration": "file_content", "source": fc.dataFile})
fc.log.Infof("Configured File Content Registration with source '%s' and target '%s'", fc.dataFile, c.Choria.FileContentRegistrationTarget)
} | [
"func",
"(",
"fc",
"*",
"FileContent",
")",
"Init",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"logger",
"*",
"logrus",
".",
"Entry",
")",
"{",
"fc",
".",
"c",
"=",
"c",
"\n",
"fc",
".",
"dataFile",
"=",
"c",
".",
"Choria",
".",
"FileContentRegistrationData",
"\n",
"fc",
".",
"log",
"=",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"fc",
".",
"dataFile",
"}",
")",
"\n\n",
"fc",
".",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"fc",
".",
"dataFile",
",",
"c",
".",
"Choria",
".",
"FileContentRegistrationTarget",
")",
"\n",
"}"
] | // Init sets up the plugin | [
"Init",
"sets",
"up",
"the",
"plugin"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/registration/file_content.go#L53-L59 |
15,772 | choria-io/go-choria | registration/file_content.go | StartRegistration | func (fc *FileContent) StartRegistration(ctx context.Context, wg *sync.WaitGroup, interval int, output chan *data.RegistrationItem) {
defer wg.Done()
err := fc.publish(output)
if err != nil {
fc.log.Errorf("Could not create registration data: %s", err)
}
for {
select {
case <-time.Tick(time.Duration(interval) * time.Second):
err = fc.publish(output)
if err != nil {
fc.log.Errorf("Could not create registration data: %s", err)
}
case <-ctx.Done():
return
}
}
} | go | func (fc *FileContent) StartRegistration(ctx context.Context, wg *sync.WaitGroup, interval int, output chan *data.RegistrationItem) {
defer wg.Done()
err := fc.publish(output)
if err != nil {
fc.log.Errorf("Could not create registration data: %s", err)
}
for {
select {
case <-time.Tick(time.Duration(interval) * time.Second):
err = fc.publish(output)
if err != nil {
fc.log.Errorf("Could not create registration data: %s", err)
}
case <-ctx.Done():
return
}
}
} | [
"func",
"(",
"fc",
"*",
"FileContent",
")",
"StartRegistration",
"(",
"ctx",
"context",
".",
"Context",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
",",
"interval",
"int",
",",
"output",
"chan",
"*",
"data",
".",
"RegistrationItem",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"err",
":=",
"fc",
".",
"publish",
"(",
"output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fc",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"Tick",
"(",
"time",
".",
"Duration",
"(",
"interval",
")",
"*",
"time",
".",
"Second",
")",
":",
"err",
"=",
"fc",
".",
"publish",
"(",
"output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fc",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // StartRegistration starts stats a publishing loop | [
"StartRegistration",
"starts",
"stats",
"a",
"publishing",
"loop"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/registration/file_content.go#L62-L82 |
15,773 | choria-io/go-choria | plugin/plugin.go | Register | func Register(name string, plugin Pluggable) error {
var err error
switch Type(plugin.PluginType()) {
case AgentProviderPlugin:
err = registerAgentProviderPlugin(name, plugin)
case AgentPlugin:
err = registerAgentPlugin(name, plugin)
case ProvisionTargetResolverPlugin:
err = registerProvisionTargetResolverPlugin(name, plugin)
case ConfigMutatorPlugin:
err = registerConfigMutator(name, plugin)
default:
err = fmt.Errorf("unknown plugin type %d from %s", plugin.PluginType(), name)
}
return err
} | go | func Register(name string, plugin Pluggable) error {
var err error
switch Type(plugin.PluginType()) {
case AgentProviderPlugin:
err = registerAgentProviderPlugin(name, plugin)
case AgentPlugin:
err = registerAgentPlugin(name, plugin)
case ProvisionTargetResolverPlugin:
err = registerProvisionTargetResolverPlugin(name, plugin)
case ConfigMutatorPlugin:
err = registerConfigMutator(name, plugin)
default:
err = fmt.Errorf("unknown plugin type %d from %s", plugin.PluginType(), name)
}
return err
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"plugin",
"Pluggable",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"switch",
"Type",
"(",
"plugin",
".",
"PluginType",
"(",
")",
")",
"{",
"case",
"AgentProviderPlugin",
":",
"err",
"=",
"registerAgentProviderPlugin",
"(",
"name",
",",
"plugin",
")",
"\n\n",
"case",
"AgentPlugin",
":",
"err",
"=",
"registerAgentPlugin",
"(",
"name",
",",
"plugin",
")",
"\n\n",
"case",
"ProvisionTargetResolverPlugin",
":",
"err",
"=",
"registerProvisionTargetResolverPlugin",
"(",
"name",
",",
"plugin",
")",
"\n\n",
"case",
"ConfigMutatorPlugin",
":",
"err",
"=",
"registerConfigMutator",
"(",
"name",
",",
"plugin",
")",
"\n\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"plugin",
".",
"PluginType",
"(",
")",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Register registers a type of plugin into the choria server | [
"Register",
"registers",
"a",
"type",
"of",
"plugin",
"into",
"the",
"choria",
"server"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/plugin/plugin.go#L62-L83 |
15,774 | choria-io/go-choria | plugin/plugin.go | Load | func Load(file string) (*List, error) {
rawdat := make(map[string]string)
input, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(input, &rawdat)
if err != nil {
return nil, fmt.Errorf("could not parse yaml: %s", err)
}
list := &List{Plugins: []*Plugin{}}
for k, v := range rawdat {
list.Plugins = append(list.Plugins, &Plugin{Name: k, Repo: v})
}
return list, err
} | go | func Load(file string) (*List, error) {
rawdat := make(map[string]string)
input, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(input, &rawdat)
if err != nil {
return nil, fmt.Errorf("could not parse yaml: %s", err)
}
list := &List{Plugins: []*Plugin{}}
for k, v := range rawdat {
list.Plugins = append(list.Plugins, &Plugin{Name: k, Repo: v})
}
return list, err
} | [
"func",
"Load",
"(",
"file",
"string",
")",
"(",
"*",
"List",
",",
"error",
")",
"{",
"rawdat",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"input",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"yaml",
".",
"Unmarshal",
"(",
"input",
",",
"&",
"rawdat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"list",
":=",
"&",
"List",
"{",
"Plugins",
":",
"[",
"]",
"*",
"Plugin",
"{",
"}",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"rawdat",
"{",
"list",
".",
"Plugins",
"=",
"append",
"(",
"list",
".",
"Plugins",
",",
"&",
"Plugin",
"{",
"Name",
":",
"k",
",",
"Repo",
":",
"v",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"list",
",",
"err",
"\n",
"}"
] | // Load loads a plugin list from file | [
"Load",
"loads",
"a",
"plugin",
"list",
"from",
"file"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/plugin/plugin.go#L86-L104 |
15,775 | choria-io/go-choria | plugin/plugin.go | Loader | func (p *Plugin) Loader() (string, error) {
templ := template.Must(template.New("provider").Parse(ftempl))
var b bytes.Buffer
writer := bufio.NewWriter(&b)
err := templ.Execute(writer, p)
writer.Flush()
return string(b.Bytes()), err
} | go | func (p *Plugin) Loader() (string, error) {
templ := template.Must(template.New("provider").Parse(ftempl))
var b bytes.Buffer
writer := bufio.NewWriter(&b)
err := templ.Execute(writer, p)
writer.Flush()
return string(b.Bytes()), err
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Loader",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"templ",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"ftempl",
")",
")",
"\n\n",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"writer",
":=",
"bufio",
".",
"NewWriter",
"(",
"&",
"b",
")",
"\n\n",
"err",
":=",
"templ",
".",
"Execute",
"(",
"writer",
",",
"p",
")",
"\n",
"writer",
".",
"Flush",
"(",
")",
"\n\n",
"return",
"string",
"(",
"b",
".",
"Bytes",
"(",
")",
")",
",",
"err",
"\n",
"}"
] | // Loader is the loader go code | [
"Loader",
"is",
"the",
"loader",
"go",
"code"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/plugin/plugin.go#L112-L122 |
15,776 | choria-io/go-choria | puppet/puppet.go | FacterStringFact | func FacterStringFact(fact string) (string, error) {
mu.Lock()
defer mu.Unlock()
value, ok := cache[fact]
if ok {
return value, nil
}
cmd := FacterCmd()
if cmd == "" {
return "", errors.New("could not find your facter command")
}
out, err := exec.Command(cmd, fact).Output()
if err != nil {
return "", err
}
value = strings.Replace(string(out), "\n", "", -1)
cache[fact] = value
return value, nil
} | go | func FacterStringFact(fact string) (string, error) {
mu.Lock()
defer mu.Unlock()
value, ok := cache[fact]
if ok {
return value, nil
}
cmd := FacterCmd()
if cmd == "" {
return "", errors.New("could not find your facter command")
}
out, err := exec.Command(cmd, fact).Output()
if err != nil {
return "", err
}
value = strings.Replace(string(out), "\n", "", -1)
cache[fact] = value
return value, nil
} | [
"func",
"FacterStringFact",
"(",
"fact",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"value",
",",
"ok",
":=",
"cache",
"[",
"fact",
"]",
"\n",
"if",
"ok",
"{",
"return",
"value",
",",
"nil",
"\n",
"}",
"\n\n",
"cmd",
":=",
"FacterCmd",
"(",
")",
"\n\n",
"if",
"cmd",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"out",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"cmd",
",",
"fact",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"value",
"=",
"strings",
".",
"Replace",
"(",
"string",
"(",
"out",
")",
",",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"cache",
"[",
"fact",
"]",
"=",
"value",
"\n\n",
"return",
"value",
",",
"nil",
"\n",
"}"
] | // FacterStringFact looks up a facter fact, returns "" when unknown | [
"FacterStringFact",
"looks",
"up",
"a",
"facter",
"fact",
"returns",
"when",
"unknown"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/puppet/puppet.go#L18-L42 |
15,777 | choria-io/go-choria | puppet/puppet.go | AIOCmd | func AIOCmd(command string, def string) string {
aioPath := filepath.Join("/opt/puppetlabs/bin", command)
if runtime.GOOS == "windows" {
aioPath = filepath.FromSlash(filepath.Join("C:/Program Files/Puppet Labs/Puppet/bin", fmt.Sprintf("%s.bat", command)))
}
if _, err := os.Stat(aioPath); err == nil {
return aioPath
}
path, err := exec.LookPath(command)
if err != nil {
return def
}
return path
} | go | func AIOCmd(command string, def string) string {
aioPath := filepath.Join("/opt/puppetlabs/bin", command)
if runtime.GOOS == "windows" {
aioPath = filepath.FromSlash(filepath.Join("C:/Program Files/Puppet Labs/Puppet/bin", fmt.Sprintf("%s.bat", command)))
}
if _, err := os.Stat(aioPath); err == nil {
return aioPath
}
path, err := exec.LookPath(command)
if err != nil {
return def
}
return path
} | [
"func",
"AIOCmd",
"(",
"command",
"string",
",",
"def",
"string",
")",
"string",
"{",
"aioPath",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"command",
")",
"\n\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"aioPath",
"=",
"filepath",
".",
"FromSlash",
"(",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"command",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"aioPath",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"aioPath",
"\n",
"}",
"\n\n",
"path",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"command",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"def",
"\n",
"}",
"\n\n",
"return",
"path",
"\n",
"}"
] | // AIOCmd looks up a command in the AIO paths, if it's not there
// it will try PATH and finally return a default if not in PATH | [
"AIOCmd",
"looks",
"up",
"a",
"command",
"in",
"the",
"AIO",
"paths",
"if",
"it",
"s",
"not",
"there",
"it",
"will",
"try",
"PATH",
"and",
"finally",
"return",
"a",
"default",
"if",
"not",
"in",
"PATH"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/puppet/puppet.go#L61-L78 |
15,778 | choria-io/go-choria | choria/framework.go | New | func New(path string) (*Framework, error) {
conf, err := config.NewConfig(path)
if err != nil {
return nil, err
}
return NewWithConfig(conf)
} | go | func New(path string) (*Framework, error) {
conf, err := config.NewConfig(path)
if err != nil {
return nil, err
}
return NewWithConfig(conf)
} | [
"func",
"New",
"(",
"path",
"string",
")",
"(",
"*",
"Framework",
",",
"error",
")",
"{",
"conf",
",",
"err",
":=",
"config",
".",
"NewConfig",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewWithConfig",
"(",
"conf",
")",
"\n",
"}"
] | // New sets up a Choria with all its config loaded and so forth | [
"New",
"sets",
"up",
"a",
"Choria",
"with",
"all",
"its",
"config",
"loaded",
"and",
"so",
"forth"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L40-L47 |
15,779 | choria-io/go-choria | choria/framework.go | NewWithConfig | func NewWithConfig(cfg *config.Config) (*Framework, error) {
c := Framework{
Config: cfg,
mu: &sync.Mutex{},
}
if c.ProvisionMode() {
c.ConfigureProvisioning()
}
err := c.SetupLogging(false)
if err != nil {
return &c, fmt.Errorf("could not set up logging: %s", err)
}
err = c.setupSecurity()
if err != nil {
return &c, fmt.Errorf("could not set up security framework: %s", err)
}
config.Mutate(cfg, c.Logger("config"))
return &c, nil
} | go | func NewWithConfig(cfg *config.Config) (*Framework, error) {
c := Framework{
Config: cfg,
mu: &sync.Mutex{},
}
if c.ProvisionMode() {
c.ConfigureProvisioning()
}
err := c.SetupLogging(false)
if err != nil {
return &c, fmt.Errorf("could not set up logging: %s", err)
}
err = c.setupSecurity()
if err != nil {
return &c, fmt.Errorf("could not set up security framework: %s", err)
}
config.Mutate(cfg, c.Logger("config"))
return &c, nil
} | [
"func",
"NewWithConfig",
"(",
"cfg",
"*",
"config",
".",
"Config",
")",
"(",
"*",
"Framework",
",",
"error",
")",
"{",
"c",
":=",
"Framework",
"{",
"Config",
":",
"cfg",
",",
"mu",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n\n",
"if",
"c",
".",
"ProvisionMode",
"(",
")",
"{",
"c",
".",
"ConfigureProvisioning",
"(",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"c",
".",
"SetupLogging",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"c",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"c",
".",
"setupSecurity",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"c",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"config",
".",
"Mutate",
"(",
"cfg",
",",
"c",
".",
"Logger",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"return",
"&",
"c",
",",
"nil",
"\n",
"}"
] | // NewWithConfig creates a new instance of the framework with the supplied config instance | [
"NewWithConfig",
"creates",
"a",
"new",
"instance",
"of",
"the",
"framework",
"with",
"the",
"supplied",
"config",
"instance"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L50-L73 |
15,780 | choria-io/go-choria | choria/framework.go | ProvisionMode | func (fw *Framework) ProvisionMode() bool {
if !fw.Config.InitiatedByServer || build.ProvisionBrokerURLs == "" {
return false
}
if fw.Config.HasOption("plugin.choria.server.provision") {
return fw.Config.Choria.Provision
}
return build.ProvisionDefault()
} | go | func (fw *Framework) ProvisionMode() bool {
if !fw.Config.InitiatedByServer || build.ProvisionBrokerURLs == "" {
return false
}
if fw.Config.HasOption("plugin.choria.server.provision") {
return fw.Config.Choria.Provision
}
return build.ProvisionDefault()
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"ProvisionMode",
"(",
")",
"bool",
"{",
"if",
"!",
"fw",
".",
"Config",
".",
"InitiatedByServer",
"||",
"build",
".",
"ProvisionBrokerURLs",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"fw",
".",
"Config",
".",
"HasOption",
"(",
"\"",
"\"",
")",
"{",
"return",
"fw",
".",
"Config",
".",
"Choria",
".",
"Provision",
"\n",
"}",
"\n\n",
"return",
"build",
".",
"ProvisionDefault",
"(",
")",
"\n",
"}"
] | // ProvisionMode determines if this instance is in provisioning mode
// if the setting `plugin.choria.server.provision` is set at all then
// the value of that is returned, else it the build time property
// ProvisionDefault is consulted | [
"ProvisionMode",
"determines",
"if",
"this",
"instance",
"is",
"in",
"provisioning",
"mode",
"if",
"the",
"setting",
"plugin",
".",
"choria",
".",
"server",
".",
"provision",
"is",
"set",
"at",
"all",
"then",
"the",
"value",
"of",
"that",
"is",
"returned",
"else",
"it",
"the",
"build",
"time",
"property",
"ProvisionDefault",
"is",
"consulted"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L105-L115 |
15,781 | choria-io/go-choria | choria/framework.go | ConfigureProvisioning | func (fw *Framework) ConfigureProvisioning() {
fw.Config.Choria.FederationCollectives = []string{}
fw.Config.Collectives = []string{"provisioning"}
fw.Config.MainCollective = "provisioning"
fw.Config.Registration = []string{}
fw.Config.FactSourceFile = build.ProvisionFacts
if build.ProvisionStatusFile != "" {
fw.Config.Choria.StatusFilePath = build.ProvisionStatusFile
fw.Config.Choria.StatusUpdateSeconds = 10
}
if build.ProvisionRegistrationData != "" {
fw.Config.RegistrationCollective = "provisioning"
fw.Config.Registration = []string{"file_content"}
fw.Config.RegisterInterval = 120
fw.Config.RegistrationSplay = false
fw.Config.Choria.FileContentRegistrationTarget = "choria.provisioning_data"
fw.Config.Choria.FileContentRegistrationData = build.ProvisionRegistrationData
}
if !build.ProvisionSecurity() {
protocol.Secure = "false"
fw.Config.Choria.SecurityProvider = "file"
fw.Config.DisableTLS = true
}
} | go | func (fw *Framework) ConfigureProvisioning() {
fw.Config.Choria.FederationCollectives = []string{}
fw.Config.Collectives = []string{"provisioning"}
fw.Config.MainCollective = "provisioning"
fw.Config.Registration = []string{}
fw.Config.FactSourceFile = build.ProvisionFacts
if build.ProvisionStatusFile != "" {
fw.Config.Choria.StatusFilePath = build.ProvisionStatusFile
fw.Config.Choria.StatusUpdateSeconds = 10
}
if build.ProvisionRegistrationData != "" {
fw.Config.RegistrationCollective = "provisioning"
fw.Config.Registration = []string{"file_content"}
fw.Config.RegisterInterval = 120
fw.Config.RegistrationSplay = false
fw.Config.Choria.FileContentRegistrationTarget = "choria.provisioning_data"
fw.Config.Choria.FileContentRegistrationData = build.ProvisionRegistrationData
}
if !build.ProvisionSecurity() {
protocol.Secure = "false"
fw.Config.Choria.SecurityProvider = "file"
fw.Config.DisableTLS = true
}
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"ConfigureProvisioning",
"(",
")",
"{",
"fw",
".",
"Config",
".",
"Choria",
".",
"FederationCollectives",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"fw",
".",
"Config",
".",
"Collectives",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"\n",
"fw",
".",
"Config",
".",
"MainCollective",
"=",
"\"",
"\"",
"\n",
"fw",
".",
"Config",
".",
"Registration",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"fw",
".",
"Config",
".",
"FactSourceFile",
"=",
"build",
".",
"ProvisionFacts",
"\n\n",
"if",
"build",
".",
"ProvisionStatusFile",
"!=",
"\"",
"\"",
"{",
"fw",
".",
"Config",
".",
"Choria",
".",
"StatusFilePath",
"=",
"build",
".",
"ProvisionStatusFile",
"\n",
"fw",
".",
"Config",
".",
"Choria",
".",
"StatusUpdateSeconds",
"=",
"10",
"\n",
"}",
"\n\n",
"if",
"build",
".",
"ProvisionRegistrationData",
"!=",
"\"",
"\"",
"{",
"fw",
".",
"Config",
".",
"RegistrationCollective",
"=",
"\"",
"\"",
"\n",
"fw",
".",
"Config",
".",
"Registration",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"\n",
"fw",
".",
"Config",
".",
"RegisterInterval",
"=",
"120",
"\n",
"fw",
".",
"Config",
".",
"RegistrationSplay",
"=",
"false",
"\n",
"fw",
".",
"Config",
".",
"Choria",
".",
"FileContentRegistrationTarget",
"=",
"\"",
"\"",
"\n",
"fw",
".",
"Config",
".",
"Choria",
".",
"FileContentRegistrationData",
"=",
"build",
".",
"ProvisionRegistrationData",
"\n",
"}",
"\n\n",
"if",
"!",
"build",
".",
"ProvisionSecurity",
"(",
")",
"{",
"protocol",
".",
"Secure",
"=",
"\"",
"\"",
"\n",
"fw",
".",
"Config",
".",
"Choria",
".",
"SecurityProvider",
"=",
"\"",
"\"",
"\n",
"fw",
".",
"Config",
".",
"DisableTLS",
"=",
"true",
"\n",
"}",
"\n",
"}"
] | // ConfigureProvisioning adjusts the active configuration to match the
// provisioning profile | [
"ConfigureProvisioning",
"adjusts",
"the",
"active",
"configuration",
"to",
"match",
"the",
"provisioning",
"profile"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L119-L145 |
15,782 | choria-io/go-choria | choria/framework.go | IsFederated | func (fw *Framework) IsFederated() (result bool) {
if len(fw.FederationCollectives()) == 0 {
return false
}
return true
} | go | func (fw *Framework) IsFederated() (result bool) {
if len(fw.FederationCollectives()) == 0 {
return false
}
return true
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"IsFederated",
"(",
")",
"(",
"result",
"bool",
")",
"{",
"if",
"len",
"(",
"fw",
".",
"FederationCollectives",
"(",
")",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // IsFederated determiens if the configuration is setting up any Federation collectives | [
"IsFederated",
"determiens",
"if",
"the",
"configuration",
"is",
"setting",
"up",
"any",
"Federation",
"collectives"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L148-L154 |
15,783 | choria-io/go-choria | choria/framework.go | Logger | func (fw *Framework) Logger(component string) *log.Entry {
return fw.log.WithFields(log.Fields{"component": component})
} | go | func (fw *Framework) Logger(component string) *log.Entry {
return fw.log.WithFields(log.Fields{"component": component})
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"Logger",
"(",
"component",
"string",
")",
"*",
"log",
".",
"Entry",
"{",
"return",
"fw",
".",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"component",
"}",
")",
"\n",
"}"
] | // Logger creates a new logrus entry | [
"Logger",
"creates",
"a",
"new",
"logrus",
"entry"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L157-L159 |
15,784 | choria-io/go-choria | choria/framework.go | FederationCollectives | func (fw *Framework) FederationCollectives() (collectives []string) {
var found []string
env := os.Getenv("CHORIA_FED_COLLECTIVE")
if env != "" {
found = strings.Split(env, ",")
}
if len(found) == 0 {
found = fw.Config.Choria.FederationCollectives
}
for _, collective := range found {
collectives = append(collectives, strings.TrimSpace(collective))
}
return
} | go | func (fw *Framework) FederationCollectives() (collectives []string) {
var found []string
env := os.Getenv("CHORIA_FED_COLLECTIVE")
if env != "" {
found = strings.Split(env, ",")
}
if len(found) == 0 {
found = fw.Config.Choria.FederationCollectives
}
for _, collective := range found {
collectives = append(collectives, strings.TrimSpace(collective))
}
return
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"FederationCollectives",
"(",
")",
"(",
"collectives",
"[",
"]",
"string",
")",
"{",
"var",
"found",
"[",
"]",
"string",
"\n\n",
"env",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"env",
"!=",
"\"",
"\"",
"{",
"found",
"=",
"strings",
".",
"Split",
"(",
"env",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"found",
")",
"==",
"0",
"{",
"found",
"=",
"fw",
".",
"Config",
".",
"Choria",
".",
"FederationCollectives",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"collective",
":=",
"range",
"found",
"{",
"collectives",
"=",
"append",
"(",
"collectives",
",",
"strings",
".",
"TrimSpace",
"(",
"collective",
")",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // FederationCollectives determines the known Federation Member
// Collectives based on the CHORIA_FED_COLLECTIVE environment
// variable or the choria.federation.collectives config item | [
"FederationCollectives",
"determines",
"the",
"known",
"Federation",
"Member",
"Collectives",
"based",
"on",
"the",
"CHORIA_FED_COLLECTIVE",
"environment",
"variable",
"or",
"the",
"choria",
".",
"federation",
".",
"collectives",
"config",
"item"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L164-L182 |
15,785 | choria-io/go-choria | choria/framework.go | ProvisioningServers | func (fw *Framework) ProvisioningServers(ctx context.Context) ([]srvcache.Server, error) {
return provtarget.Targets(ctx, fw.Logger("provtarget"))
} | go | func (fw *Framework) ProvisioningServers(ctx context.Context) ([]srvcache.Server, error) {
return provtarget.Targets(ctx, fw.Logger("provtarget"))
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"ProvisioningServers",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"srvcache",
".",
"Server",
",",
"error",
")",
"{",
"return",
"provtarget",
".",
"Targets",
"(",
"ctx",
",",
"fw",
".",
"Logger",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // ProvisioningServers determines the build time provisioning servers
// when it's unset or results in an empty server list this will return
// an error | [
"ProvisioningServers",
"determines",
"the",
"build",
"time",
"provisioning",
"servers",
"when",
"it",
"s",
"unset",
"or",
"results",
"in",
"an",
"empty",
"server",
"list",
"this",
"will",
"return",
"an",
"error"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L220-L222 |
15,786 | choria-io/go-choria | choria/framework.go | SetupLogging | func (fw *Framework) SetupLogging(debug bool) (err error) {
fw.log = log.New()
fw.log.Out = os.Stdout
if fw.Config.LogFile != "" {
fw.log.Formatter = &log.JSONFormatter{}
file, err := os.OpenFile(fw.Config.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("Could not set up logging: %s", err)
}
fw.log.Out = file
}
switch fw.Config.LogLevel {
case "debug":
fw.log.SetLevel(log.DebugLevel)
case "info":
fw.log.SetLevel(log.InfoLevel)
case "warn":
fw.log.SetLevel(log.WarnLevel)
case "error":
fw.log.SetLevel(log.ErrorLevel)
case "fatal":
fw.log.SetLevel(log.FatalLevel)
default:
fw.log.SetLevel(log.WarnLevel)
}
if debug {
fw.log.SetLevel(log.DebugLevel)
}
log.SetFormatter(fw.log.Formatter)
log.SetLevel(fw.log.Level)
log.SetOutput(fw.log.Out)
return
} | go | func (fw *Framework) SetupLogging(debug bool) (err error) {
fw.log = log.New()
fw.log.Out = os.Stdout
if fw.Config.LogFile != "" {
fw.log.Formatter = &log.JSONFormatter{}
file, err := os.OpenFile(fw.Config.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("Could not set up logging: %s", err)
}
fw.log.Out = file
}
switch fw.Config.LogLevel {
case "debug":
fw.log.SetLevel(log.DebugLevel)
case "info":
fw.log.SetLevel(log.InfoLevel)
case "warn":
fw.log.SetLevel(log.WarnLevel)
case "error":
fw.log.SetLevel(log.ErrorLevel)
case "fatal":
fw.log.SetLevel(log.FatalLevel)
default:
fw.log.SetLevel(log.WarnLevel)
}
if debug {
fw.log.SetLevel(log.DebugLevel)
}
log.SetFormatter(fw.log.Formatter)
log.SetLevel(fw.log.Level)
log.SetOutput(fw.log.Out)
return
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"SetupLogging",
"(",
"debug",
"bool",
")",
"(",
"err",
"error",
")",
"{",
"fw",
".",
"log",
"=",
"log",
".",
"New",
"(",
")",
"\n\n",
"fw",
".",
"log",
".",
"Out",
"=",
"os",
".",
"Stdout",
"\n\n",
"if",
"fw",
".",
"Config",
".",
"LogFile",
"!=",
"\"",
"\"",
"{",
"fw",
".",
"log",
".",
"Formatter",
"=",
"&",
"log",
".",
"JSONFormatter",
"{",
"}",
"\n\n",
"file",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"fw",
".",
"Config",
".",
"LogFile",
",",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_WRONLY",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"fw",
".",
"log",
".",
"Out",
"=",
"file",
"\n",
"}",
"\n\n",
"switch",
"fw",
".",
"Config",
".",
"LogLevel",
"{",
"case",
"\"",
"\"",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"DebugLevel",
")",
"\n",
"case",
"\"",
"\"",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"InfoLevel",
")",
"\n",
"case",
"\"",
"\"",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"WarnLevel",
")",
"\n",
"case",
"\"",
"\"",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"ErrorLevel",
")",
"\n",
"case",
"\"",
"\"",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"FatalLevel",
")",
"\n",
"default",
":",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"WarnLevel",
")",
"\n",
"}",
"\n\n",
"if",
"debug",
"{",
"fw",
".",
"log",
".",
"SetLevel",
"(",
"log",
".",
"DebugLevel",
")",
"\n",
"}",
"\n\n",
"log",
".",
"SetFormatter",
"(",
"fw",
".",
"log",
".",
"Formatter",
")",
"\n",
"log",
".",
"SetLevel",
"(",
"fw",
".",
"log",
".",
"Level",
")",
"\n",
"log",
".",
"SetOutput",
"(",
"fw",
".",
"log",
".",
"Out",
")",
"\n\n",
"return",
"\n",
"}"
] | // SetupLogging configures logging based on choria config directives
// currently only file and console behaviours are supported | [
"SetupLogging",
"configures",
"logging",
"based",
"on",
"choria",
"config",
"directives",
"currently",
"only",
"file",
"and",
"console",
"behaviours",
"are",
"supported"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L268-L308 |
15,787 | choria-io/go-choria | choria/framework.go | TrySrvLookup | func (fw *Framework) TrySrvLookup(names []string, defaultSrv srvcache.Server) (srvcache.Server, error) {
if !fw.Config.Choria.UseSRVRecords {
return defaultSrv, nil
}
for _, q := range names {
a, err := fw.QuerySrvRecords([]string{q})
if err == nil {
log.Infof("Found %s:%d from %s SRV lookups", a[0].Host, a[0].Port, strings.Join(names, ", "))
return a[0], nil
}
}
log.Debugf("Could not find SRV records for %s, returning defaults %s:%d", strings.Join(names, ", "), defaultSrv.Host, defaultSrv.Port)
return defaultSrv, nil
} | go | func (fw *Framework) TrySrvLookup(names []string, defaultSrv srvcache.Server) (srvcache.Server, error) {
if !fw.Config.Choria.UseSRVRecords {
return defaultSrv, nil
}
for _, q := range names {
a, err := fw.QuerySrvRecords([]string{q})
if err == nil {
log.Infof("Found %s:%d from %s SRV lookups", a[0].Host, a[0].Port, strings.Join(names, ", "))
return a[0], nil
}
}
log.Debugf("Could not find SRV records for %s, returning defaults %s:%d", strings.Join(names, ", "), defaultSrv.Host, defaultSrv.Port)
return defaultSrv, nil
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"TrySrvLookup",
"(",
"names",
"[",
"]",
"string",
",",
"defaultSrv",
"srvcache",
".",
"Server",
")",
"(",
"srvcache",
".",
"Server",
",",
"error",
")",
"{",
"if",
"!",
"fw",
".",
"Config",
".",
"Choria",
".",
"UseSRVRecords",
"{",
"return",
"defaultSrv",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"q",
":=",
"range",
"names",
"{",
"a",
",",
"err",
":=",
"fw",
".",
"QuerySrvRecords",
"(",
"[",
"]",
"string",
"{",
"q",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"a",
"[",
"0",
"]",
".",
"Host",
",",
"a",
"[",
"0",
"]",
".",
"Port",
",",
"strings",
".",
"Join",
"(",
"names",
",",
"\"",
"\"",
")",
")",
"\n\n",
"return",
"a",
"[",
"0",
"]",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"names",
",",
"\"",
"\"",
")",
",",
"defaultSrv",
".",
"Host",
",",
"defaultSrv",
".",
"Port",
")",
"\n\n",
"return",
"defaultSrv",
",",
"nil",
"\n",
"}"
] | // TrySrvLookup will attempt to lookup a series of names returning the first found
// if SRV lookups are disabled or nothing is found the default will be returned | [
"TrySrvLookup",
"will",
"attempt",
"to",
"lookup",
"a",
"series",
"of",
"names",
"returning",
"the",
"first",
"found",
"if",
"SRV",
"lookups",
"are",
"disabled",
"or",
"nothing",
"is",
"found",
"the",
"default",
"will",
"be",
"returned"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L312-L329 |
15,788 | choria-io/go-choria | choria/framework.go | QuerySrvRecords | func (fw *Framework) QuerySrvRecords(records []string) ([]srvcache.Server, error) {
servers := []srvcache.Server{}
if !fw.Config.Choria.UseSRVRecords {
return servers, errors.New("SRV lookups are disabled in the configuration file")
}
domain := fw.Config.Choria.SRVDomain
var err error
if fw.Config.Choria.SRVDomain == "" {
domain, err = fw.FacterDomain()
if err != nil {
return servers, err
}
// cache the result to speed things up
fw.Config.Choria.SRVDomain = domain
}
for _, q := range records {
record := q + "." + domain
log.Debugf("Attempting SRV lookup for %s", record)
cname, addrs, err := srvcache.LookupSRV("", "", record, net.LookupSRV)
if err != nil {
log.Debugf("Failed to resolve %s: %s", record, err)
continue
}
log.Debugf("Found %d SRV records for %s", len(addrs), cname)
for _, a := range addrs {
servers = append(servers, srvcache.Server{Host: strings.TrimRight(a.Target, "."), Port: int(a.Port)})
}
}
return servers, nil
} | go | func (fw *Framework) QuerySrvRecords(records []string) ([]srvcache.Server, error) {
servers := []srvcache.Server{}
if !fw.Config.Choria.UseSRVRecords {
return servers, errors.New("SRV lookups are disabled in the configuration file")
}
domain := fw.Config.Choria.SRVDomain
var err error
if fw.Config.Choria.SRVDomain == "" {
domain, err = fw.FacterDomain()
if err != nil {
return servers, err
}
// cache the result to speed things up
fw.Config.Choria.SRVDomain = domain
}
for _, q := range records {
record := q + "." + domain
log.Debugf("Attempting SRV lookup for %s", record)
cname, addrs, err := srvcache.LookupSRV("", "", record, net.LookupSRV)
if err != nil {
log.Debugf("Failed to resolve %s: %s", record, err)
continue
}
log.Debugf("Found %d SRV records for %s", len(addrs), cname)
for _, a := range addrs {
servers = append(servers, srvcache.Server{Host: strings.TrimRight(a.Target, "."), Port: int(a.Port)})
}
}
return servers, nil
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"QuerySrvRecords",
"(",
"records",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"srvcache",
".",
"Server",
",",
"error",
")",
"{",
"servers",
":=",
"[",
"]",
"srvcache",
".",
"Server",
"{",
"}",
"\n\n",
"if",
"!",
"fw",
".",
"Config",
".",
"Choria",
".",
"UseSRVRecords",
"{",
"return",
"servers",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"domain",
":=",
"fw",
".",
"Config",
".",
"Choria",
".",
"SRVDomain",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
"fw",
".",
"Config",
".",
"Choria",
".",
"SRVDomain",
"==",
"\"",
"\"",
"{",
"domain",
",",
"err",
"=",
"fw",
".",
"FacterDomain",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"servers",
",",
"err",
"\n",
"}",
"\n\n",
"// cache the result to speed things up",
"fw",
".",
"Config",
".",
"Choria",
".",
"SRVDomain",
"=",
"domain",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"q",
":=",
"range",
"records",
"{",
"record",
":=",
"q",
"+",
"\"",
"\"",
"+",
"domain",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"record",
")",
"\n\n",
"cname",
",",
"addrs",
",",
"err",
":=",
"srvcache",
".",
"LookupSRV",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"record",
",",
"net",
".",
"LookupSRV",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"record",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"addrs",
")",
",",
"cname",
")",
"\n\n",
"for",
"_",
",",
"a",
":=",
"range",
"addrs",
"{",
"servers",
"=",
"append",
"(",
"servers",
",",
"srvcache",
".",
"Server",
"{",
"Host",
":",
"strings",
".",
"TrimRight",
"(",
"a",
".",
"Target",
",",
"\"",
"\"",
")",
",",
"Port",
":",
"int",
"(",
"a",
".",
"Port",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"servers",
",",
"nil",
"\n",
"}"
] | // QuerySrvRecords looks for SRV records within the right domain either
// thanks to facter domain or the configured domain.
//
// If the config disables SRV then a error is returned. | [
"QuerySrvRecords",
"looks",
"for",
"SRV",
"records",
"within",
"the",
"right",
"domain",
"either",
"thanks",
"to",
"facter",
"domain",
"or",
"the",
"configured",
"domain",
".",
"If",
"the",
"config",
"disables",
"SRV",
"then",
"a",
"error",
"is",
"returned",
"."
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L335-L373 |
15,789 | choria-io/go-choria | choria/framework.go | NetworkBrokerPeers | func (fw *Framework) NetworkBrokerPeers() (servers []srvcache.Server, err error) {
servers, err = fw.QuerySrvRecords([]string{"_mcollective-broker._tcp"})
if err != nil {
log.Errorf("SRV lookup for _mcollective-broker._tcp failed: %s", err)
err = nil
}
if len(servers) == 0 {
for _, server := range fw.Config.Choria.NetworkPeers {
parsed, err := url.Parse(server)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
host, sport, err := net.SplitHostPort(parsed.Host)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
port, err := strconv.Atoi(sport)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
s := srvcache.Server{
Host: host,
Port: port,
Scheme: parsed.Scheme,
}
servers = append(servers, s)
}
}
for i, s := range servers {
s.Scheme = "nats"
servers[i] = s
}
return
} | go | func (fw *Framework) NetworkBrokerPeers() (servers []srvcache.Server, err error) {
servers, err = fw.QuerySrvRecords([]string{"_mcollective-broker._tcp"})
if err != nil {
log.Errorf("SRV lookup for _mcollective-broker._tcp failed: %s", err)
err = nil
}
if len(servers) == 0 {
for _, server := range fw.Config.Choria.NetworkPeers {
parsed, err := url.Parse(server)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
host, sport, err := net.SplitHostPort(parsed.Host)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
port, err := strconv.Atoi(sport)
if err != nil {
return servers, fmt.Errorf("Could not parse network peer %s: %s", server, err)
}
s := srvcache.Server{
Host: host,
Port: port,
Scheme: parsed.Scheme,
}
servers = append(servers, s)
}
}
for i, s := range servers {
s.Scheme = "nats"
servers[i] = s
}
return
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"NetworkBrokerPeers",
"(",
")",
"(",
"servers",
"[",
"]",
"srvcache",
".",
"Server",
",",
"err",
"error",
")",
"{",
"servers",
",",
"err",
"=",
"fw",
".",
"QuerySrvRecords",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"err",
"=",
"nil",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"servers",
")",
"==",
"0",
"{",
"for",
"_",
",",
"server",
":=",
"range",
"fw",
".",
"Config",
".",
"Choria",
".",
"NetworkPeers",
"{",
"parsed",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"server",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"servers",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"server",
",",
"err",
")",
"\n",
"}",
"\n\n",
"host",
",",
"sport",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"parsed",
".",
"Host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"servers",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"server",
",",
"err",
")",
"\n",
"}",
"\n\n",
"port",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"sport",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"servers",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"server",
",",
"err",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"srvcache",
".",
"Server",
"{",
"Host",
":",
"host",
",",
"Port",
":",
"port",
",",
"Scheme",
":",
"parsed",
".",
"Scheme",
",",
"}",
"\n\n",
"servers",
"=",
"append",
"(",
"servers",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"s",
":=",
"range",
"servers",
"{",
"s",
".",
"Scheme",
"=",
"\"",
"\"",
"\n",
"servers",
"[",
"i",
"]",
"=",
"s",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // NetworkBrokerPeers are peers in the broker cluster resolved from
// _mcollective-broker._tcp or from the plugin config | [
"NetworkBrokerPeers",
"are",
"peers",
"in",
"the",
"broker",
"cluster",
"resolved",
"from",
"_mcollective",
"-",
"broker",
".",
"_tcp",
"or",
"from",
"the",
"plugin",
"config"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L377-L417 |
15,790 | choria-io/go-choria | choria/framework.go | DiscoveryServer | func (fw *Framework) DiscoveryServer() (srvcache.Server, error) {
s := srvcache.Server{
Host: fw.Config.Choria.DiscoveryHost,
Port: fw.Config.Choria.DiscoveryPort,
}
if !fw.ProxiedDiscovery() {
return s, errors.New("Proxy discovery is not enabled")
}
result, err := fw.TrySrvLookup([]string{"_mcollective-discovery._tcp"}, s)
return result, err
} | go | func (fw *Framework) DiscoveryServer() (srvcache.Server, error) {
s := srvcache.Server{
Host: fw.Config.Choria.DiscoveryHost,
Port: fw.Config.Choria.DiscoveryPort,
}
if !fw.ProxiedDiscovery() {
return s, errors.New("Proxy discovery is not enabled")
}
result, err := fw.TrySrvLookup([]string{"_mcollective-discovery._tcp"}, s)
return result, err
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"DiscoveryServer",
"(",
")",
"(",
"srvcache",
".",
"Server",
",",
"error",
")",
"{",
"s",
":=",
"srvcache",
".",
"Server",
"{",
"Host",
":",
"fw",
".",
"Config",
".",
"Choria",
".",
"DiscoveryHost",
",",
"Port",
":",
"fw",
".",
"Config",
".",
"Choria",
".",
"DiscoveryPort",
",",
"}",
"\n\n",
"if",
"!",
"fw",
".",
"ProxiedDiscovery",
"(",
")",
"{",
"return",
"s",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"fw",
".",
"TrySrvLookup",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"s",
")",
"\n\n",
"return",
"result",
",",
"err",
"\n",
"}"
] | // DiscoveryServer is the server configured as a discovery proxy | [
"DiscoveryServer",
"is",
"the",
"server",
"configured",
"as",
"a",
"discovery",
"proxy"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L420-L433 |
15,791 | choria-io/go-choria | choria/framework.go | ProxiedDiscovery | func (fw *Framework) ProxiedDiscovery() bool {
if fw.Config.HasOption("plugin.choria.discovery_host") || fw.Config.HasOption("plugin.choria.discovery_port") {
return true
}
return fw.Config.Choria.DiscoveryProxy
} | go | func (fw *Framework) ProxiedDiscovery() bool {
if fw.Config.HasOption("plugin.choria.discovery_host") || fw.Config.HasOption("plugin.choria.discovery_port") {
return true
}
return fw.Config.Choria.DiscoveryProxy
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"ProxiedDiscovery",
"(",
")",
"bool",
"{",
"if",
"fw",
".",
"Config",
".",
"HasOption",
"(",
"\"",
"\"",
")",
"||",
"fw",
".",
"Config",
".",
"HasOption",
"(",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"fw",
".",
"Config",
".",
"Choria",
".",
"DiscoveryProxy",
"\n",
"}"
] | // ProxiedDiscovery determines if a client is configured for proxied discover | [
"ProxiedDiscovery",
"determines",
"if",
"a",
"client",
"is",
"configured",
"for",
"proxied",
"discover"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L436-L442 |
15,792 | choria-io/go-choria | choria/framework.go | PuppetAIOCmd | func (fw *Framework) PuppetAIOCmd(command string, def string) string {
return PuppetAIOCmd(command, def)
} | go | func (fw *Framework) PuppetAIOCmd(command string, def string) string {
return PuppetAIOCmd(command, def)
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"PuppetAIOCmd",
"(",
"command",
"string",
",",
"def",
"string",
")",
"string",
"{",
"return",
"PuppetAIOCmd",
"(",
"command",
",",
"def",
")",
"\n",
"}"
] | // PuppetAIOCmd looks up a command in the AIO paths, if it's not there
// it will try PATH and finally return a default if not in PATH | [
"PuppetAIOCmd",
"looks",
"up",
"a",
"command",
"in",
"the",
"AIO",
"paths",
"if",
"it",
"s",
"not",
"there",
"it",
"will",
"try",
"PATH",
"and",
"finally",
"return",
"a",
"default",
"if",
"not",
"in",
"PATH"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L476-L478 |
15,793 | choria-io/go-choria | choria/framework.go | HasCollective | func (fw *Framework) HasCollective(collective string) bool {
for _, c := range fw.Config.Collectives {
if c == collective {
return true
}
}
return false
} | go | func (fw *Framework) HasCollective(collective string) bool {
for _, c := range fw.Config.Collectives {
if c == collective {
return true
}
}
return false
} | [
"func",
"(",
"fw",
"*",
"Framework",
")",
"HasCollective",
"(",
"collective",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"fw",
".",
"Config",
".",
"Collectives",
"{",
"if",
"c",
"==",
"collective",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // HasCollective determines if a collective is known in the configuration | [
"HasCollective",
"determines",
"if",
"a",
"collective",
"is",
"known",
"in",
"the",
"configuration"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/choria/framework.go#L491-L499 |
15,794 | choria-io/go-choria | server/discovery/facts/facts.go | Match | func Match(filters [][3]string, fw *choria.Framework, log *logrus.Entry) bool {
matched := false
var err error
for _, filter := range filters {
matched, err = HasFact(filter[0], filter[1], filter[2], fw.Config.FactSourceFile, log)
if err != nil {
log.Warnf("Failed to match fact '%#v': %s", filter, err)
return false
}
if matched == false {
log.Debugf("Failed to match fact filter '%#v'", filter)
break
}
}
return matched
} | go | func Match(filters [][3]string, fw *choria.Framework, log *logrus.Entry) bool {
matched := false
var err error
for _, filter := range filters {
matched, err = HasFact(filter[0], filter[1], filter[2], fw.Config.FactSourceFile, log)
if err != nil {
log.Warnf("Failed to match fact '%#v': %s", filter, err)
return false
}
if matched == false {
log.Debugf("Failed to match fact filter '%#v'", filter)
break
}
}
return matched
} | [
"func",
"Match",
"(",
"filters",
"[",
"]",
"[",
"3",
"]",
"string",
",",
"fw",
"*",
"choria",
".",
"Framework",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"bool",
"{",
"matched",
":=",
"false",
"\n",
"var",
"err",
"error",
"\n\n",
"for",
"_",
",",
"filter",
":=",
"range",
"filters",
"{",
"matched",
",",
"err",
"=",
"HasFact",
"(",
"filter",
"[",
"0",
"]",
",",
"filter",
"[",
"1",
"]",
",",
"filter",
"[",
"2",
"]",
",",
"fw",
".",
"Config",
".",
"FactSourceFile",
",",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"filter",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"matched",
"==",
"false",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"filter",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"matched",
"\n",
"}"
] | // Match match fact filters in a OR manner, only nodes that have all
// the matching facts will be true here | [
"Match",
"match",
"fact",
"filters",
"in",
"a",
"OR",
"manner",
"only",
"nodes",
"that",
"have",
"all",
"the",
"matching",
"facts",
"will",
"be",
"true",
"here"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/discovery/facts/facts.go#L19-L37 |
15,795 | choria-io/go-choria | server/discovery/facts/facts.go | JSON | func JSON(file string, log *logrus.Entry) (json.RawMessage, error) {
out := make(map[string]interface{})
for _, f := range strings.Split(file, string(os.PathListSeparator)) {
if f == "" {
continue
}
if _, err := os.Stat(f); os.IsNotExist(err) {
log.Warnf("Fact file %s does not exist", f)
continue
}
j, err := ioutil.ReadFile(f)
if err != nil {
log.Errorf("Could not read fact file %s: %s", f, err)
continue
}
if strings.HasSuffix(f, "yaml") {
j, err = yaml.YAMLToJSON(j)
if err != nil {
log.Errorf("Could not parse facts file %s as YAML: %s", file, err)
continue
}
}
facts := make(map[string]interface{})
err = json.Unmarshal(j, &facts)
if err != nil {
log.Errorf("Could not parse facts file: %s", err)
continue
}
// does a very dumb shallow merge that mimics ruby Hash#merge
// to maintain mcollective compatability
for k, v := range facts {
out[k] = v
}
}
if len(out) == 0 {
return json.RawMessage("{}"), fmt.Errorf("no facts were found in %s", file)
}
j, err := json.Marshal(&out)
if err != nil {
return json.RawMessage("{}"), fmt.Errorf("could not JSON marshal merged facts: %s", err)
}
return json.RawMessage(j), nil
} | go | func JSON(file string, log *logrus.Entry) (json.RawMessage, error) {
out := make(map[string]interface{})
for _, f := range strings.Split(file, string(os.PathListSeparator)) {
if f == "" {
continue
}
if _, err := os.Stat(f); os.IsNotExist(err) {
log.Warnf("Fact file %s does not exist", f)
continue
}
j, err := ioutil.ReadFile(f)
if err != nil {
log.Errorf("Could not read fact file %s: %s", f, err)
continue
}
if strings.HasSuffix(f, "yaml") {
j, err = yaml.YAMLToJSON(j)
if err != nil {
log.Errorf("Could not parse facts file %s as YAML: %s", file, err)
continue
}
}
facts := make(map[string]interface{})
err = json.Unmarshal(j, &facts)
if err != nil {
log.Errorf("Could not parse facts file: %s", err)
continue
}
// does a very dumb shallow merge that mimics ruby Hash#merge
// to maintain mcollective compatability
for k, v := range facts {
out[k] = v
}
}
if len(out) == 0 {
return json.RawMessage("{}"), fmt.Errorf("no facts were found in %s", file)
}
j, err := json.Marshal(&out)
if err != nil {
return json.RawMessage("{}"), fmt.Errorf("could not JSON marshal merged facts: %s", err)
}
return json.RawMessage(j), nil
} | [
"func",
"JSON",
"(",
"file",
"string",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"strings",
".",
"Split",
"(",
"file",
",",
"string",
"(",
"os",
".",
"PathListSeparator",
")",
")",
"{",
"if",
"f",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"f",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"f",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"j",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"f",
",",
"\"",
"\"",
")",
"{",
"j",
",",
"err",
"=",
"yaml",
".",
"YAMLToJSON",
"(",
"j",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"facts",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"j",
",",
"&",
"facts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// does a very dumb shallow merge that mimics ruby Hash#merge",
"// to maintain mcollective compatability",
"for",
"k",
",",
"v",
":=",
"range",
"facts",
"{",
"out",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"out",
")",
"==",
"0",
"{",
"return",
"json",
".",
"RawMessage",
"(",
"\"",
"\"",
")",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"\n\n",
"j",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"&",
"out",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"json",
".",
"RawMessage",
"(",
"\"",
"\"",
")",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"RawMessage",
"(",
"j",
")",
",",
"nil",
"\n",
"}"
] | // JSON parses the data, including doing any conversions needed, and returns JSON text | [
"JSON",
"parses",
"the",
"data",
"including",
"doing",
"any",
"conversions",
"needed",
"and",
"returns",
"JSON",
"text"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/discovery/facts/facts.go#L40-L91 |
15,796 | choria-io/go-choria | server/discovery/facts/facts.go | GetFact | func GetFact(fact string, file string, log *logrus.Entry) ([]byte, gjson.Result, error) {
j, err := JSON(file, log)
if err != nil {
return nil, gjson.Result{}, err
}
found := gjson.GetBytes(j, fact)
if !found.Exists() {
return nil, gjson.Result{}, nil
}
return j, found, nil
} | go | func GetFact(fact string, file string, log *logrus.Entry) ([]byte, gjson.Result, error) {
j, err := JSON(file, log)
if err != nil {
return nil, gjson.Result{}, err
}
found := gjson.GetBytes(j, fact)
if !found.Exists() {
return nil, gjson.Result{}, nil
}
return j, found, nil
} | [
"func",
"GetFact",
"(",
"fact",
"string",
",",
"file",
"string",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"(",
"[",
"]",
"byte",
",",
"gjson",
".",
"Result",
",",
"error",
")",
"{",
"j",
",",
"err",
":=",
"JSON",
"(",
"file",
",",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"gjson",
".",
"Result",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"found",
":=",
"gjson",
".",
"GetBytes",
"(",
"j",
",",
"fact",
")",
"\n",
"if",
"!",
"found",
".",
"Exists",
"(",
")",
"{",
"return",
"nil",
",",
"gjson",
".",
"Result",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"j",
",",
"found",
",",
"nil",
"\n",
"}"
] | // GetFact looks up a single fact from the facts file, errors reading
// the file is reported but an absent fact is handled as empty result
// and no error | [
"GetFact",
"looks",
"up",
"a",
"single",
"fact",
"from",
"the",
"facts",
"file",
"errors",
"reading",
"the",
"file",
"is",
"reported",
"but",
"an",
"absent",
"fact",
"is",
"handled",
"as",
"empty",
"result",
"and",
"no",
"error"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/discovery/facts/facts.go#L96-L108 |
15,797 | choria-io/go-choria | server/discovery/facts/facts.go | HasFact | func HasFact(fact string, operator string, value string, file string, log *logrus.Entry) (bool, error) {
j, found, err := GetFact(fact, file, log)
if err != nil {
return false, err
}
if !found.Exists() {
return false, nil
}
switch operator {
case "==":
return eqMatch(found, value, &j)
case "=~":
return reMatch(found, value, &j)
case "<=":
return leMatch(found, value, &j)
case ">=":
return geMatch(found, value, &j)
case "<":
return ltMatch(found, value, &j)
case ">":
return gtMatch(found, value, &j)
case "!=":
return neMatch(found, value, &j)
default:
return false, fmt.Errorf("Unknown fact matching operator %s while looking for fact %s", operator, fact)
}
} | go | func HasFact(fact string, operator string, value string, file string, log *logrus.Entry) (bool, error) {
j, found, err := GetFact(fact, file, log)
if err != nil {
return false, err
}
if !found.Exists() {
return false, nil
}
switch operator {
case "==":
return eqMatch(found, value, &j)
case "=~":
return reMatch(found, value, &j)
case "<=":
return leMatch(found, value, &j)
case ">=":
return geMatch(found, value, &j)
case "<":
return ltMatch(found, value, &j)
case ">":
return gtMatch(found, value, &j)
case "!=":
return neMatch(found, value, &j)
default:
return false, fmt.Errorf("Unknown fact matching operator %s while looking for fact %s", operator, fact)
}
} | [
"func",
"HasFact",
"(",
"fact",
"string",
",",
"operator",
"string",
",",
"value",
"string",
",",
"file",
"string",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"(",
"bool",
",",
"error",
")",
"{",
"j",
",",
"found",
",",
"err",
":=",
"GetFact",
"(",
"fact",
",",
"file",
",",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
".",
"Exists",
"(",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"switch",
"operator",
"{",
"case",
"\"",
"\"",
":",
"return",
"eqMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"reMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"leMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"geMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ltMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"gtMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"neMatch",
"(",
"found",
",",
"value",
",",
"&",
"j",
")",
"\n",
"default",
":",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"operator",
",",
"fact",
")",
"\n",
"}",
"\n",
"}"
] | // HasFact evaluates the expression against facts in the file | [
"HasFact",
"evaluates",
"the",
"expression",
"against",
"facts",
"in",
"the",
"file"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/server/discovery/facts/facts.go#L111-L139 |
15,798 | choria-io/go-choria | aagent/machine/notifications.go | RegisterNotifier | func (m *Machine) RegisterNotifier(services ...NotificationService) {
for _, service := range services {
m.notifiers = append(m.notifiers, service)
}
} | go | func (m *Machine) RegisterNotifier(services ...NotificationService) {
for _, service := range services {
m.notifiers = append(m.notifiers, service)
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"RegisterNotifier",
"(",
"services",
"...",
"NotificationService",
")",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"services",
"{",
"m",
".",
"notifiers",
"=",
"append",
"(",
"m",
".",
"notifiers",
",",
"service",
")",
"\n",
"}",
"\n",
"}"
] | // RegisterNotifier adds a new NotificationService to the list of ones to receive notifications | [
"RegisterNotifier",
"adds",
"a",
"new",
"NotificationService",
"to",
"the",
"list",
"of",
"ones",
"to",
"receive",
"notifications"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/aagent/machine/notifications.go#L60-L64 |
15,799 | choria-io/go-choria | aagent/machine/notifications.go | Warnf | func (m *Machine) Warnf(watcher string, format string, args ...interface{}) {
for _, n := range m.notifiers {
n.Warnf(m, watcher, format, args...)
}
} | go | func (m *Machine) Warnf(watcher string, format string, args ...interface{}) {
for _, n := range m.notifiers {
n.Warnf(m, watcher, format, args...)
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Warnf",
"(",
"watcher",
"string",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"m",
".",
"notifiers",
"{",
"n",
".",
"Warnf",
"(",
"m",
",",
"watcher",
",",
"format",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Warnf implements NotificationService | [
"Warnf",
"implements",
"NotificationService"
] | 2c773ed36498f426852fd294ebb832c6a2625eba | https://github.com/choria-io/go-choria/blob/2c773ed36498f426852fd294ebb832c6a2625eba/aagent/machine/notifications.go#L81-L85 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.