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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
6,400 | prometheus/common | config/http_config.go | UnmarshalYAML | func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain HTTPClientConfig
if err := unmarshal((*plain)(c)); err != nil {
return err
}
return c.Validate()
} | go | func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain HTTPClientConfig
if err := unmarshal((*plain)(c)); err != nil {
return err
}
return c.Validate()
} | [
"func",
"(",
"c",
"*",
"HTTPClientConfig",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"type",
"plain",
"HTTPClientConfig",
"\n",
"if",
"err",
":=",
"unmarshal",
"(",
"(",
"*",
"plain",
")",
"(",
"c",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // UnmarshalYAML implements the yaml.Unmarshaler interface | [
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Unmarshaler",
"interface"
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L104-L110 |
6,401 | prometheus/common | config/http_config.go | newClient | func newClient(rt http.RoundTripper) *http.Client {
return &http.Client{Transport: rt}
} | go | func newClient(rt http.RoundTripper) *http.Client {
return &http.Client{Transport: rt}
} | [
"func",
"newClient",
"(",
"rt",
"http",
".",
"RoundTripper",
")",
"*",
"http",
".",
"Client",
"{",
"return",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"rt",
"}",
"\n",
"}"
] | // NewClient returns a http.Client using the specified http.RoundTripper. | [
"NewClient",
"returns",
"a",
"http",
".",
"Client",
"using",
"the",
"specified",
"http",
".",
"RoundTripper",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L119-L121 |
6,402 | prometheus/common | config/http_config.go | NewClientFromConfig | func NewClientFromConfig(cfg HTTPClientConfig, name string) (*http.Client, error) {
rt, err := NewRoundTripperFromConfig(cfg, name)
if err != nil {
return nil, err
}
return newClient(rt), nil
} | go | func NewClientFromConfig(cfg HTTPClientConfig, name string) (*http.Client, error) {
rt, err := NewRoundTripperFromConfig(cfg, name)
if err != nil {
return nil, err
}
return newClient(rt), nil
} | [
"func",
"NewClientFromConfig",
"(",
"cfg",
"HTTPClientConfig",
",",
"name",
"string",
")",
"(",
"*",
"http",
".",
"Client",
",",
"error",
")",
"{",
"rt",
",",
"err",
":=",
"NewRoundTripperFromConfig",
"(",
"cfg",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"newClient",
"(",
"rt",
")",
",",
"nil",
"\n",
"}"
] | // NewClientFromConfig returns a new HTTP client configured for the
// given config.HTTPClientConfig. The name is used as go-conntrack metric label. | [
"NewClientFromConfig",
"returns",
"a",
"new",
"HTTP",
"client",
"configured",
"for",
"the",
"given",
"config",
".",
"HTTPClientConfig",
".",
"The",
"name",
"is",
"used",
"as",
"go",
"-",
"conntrack",
"metric",
"label",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L125-L131 |
6,403 | prometheus/common | config/http_config.go | NewRoundTripperFromConfig | func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string) (http.RoundTripper, error) {
newRT := func(tlsConfig *tls.Config) (http.RoundTripper, error) {
// The only timeout we care about is the configured scrape timeout.
// It is applied on request. So we leave out any timings here.
var rt http.RoundTripper = &http.Transport{
Proxy: http.ProxyURL(cfg.ProxyURL.URL),
MaxIdleConns: 20000,
MaxIdleConnsPerHost: 1000, // see https://github.com/golang/go/issues/13801
DisableKeepAlives: false,
TLSClientConfig: tlsConfig,
DisableCompression: true,
// 5 minutes is typically above the maximum sane scrape interval. So we can
// use keepalive for all configurations.
IdleConnTimeout: 5 * time.Minute,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName(name),
),
}
// If a bearer token is provided, create a round tripper that will set the
// Authorization header correctly on each request.
if len(cfg.BearerToken) > 0 {
rt = NewBearerAuthRoundTripper(cfg.BearerToken, rt)
} else if len(cfg.BearerTokenFile) > 0 {
rt = NewBearerAuthFileRoundTripper(cfg.BearerTokenFile, rt)
}
if cfg.BasicAuth != nil {
rt = NewBasicAuthRoundTripper(cfg.BasicAuth.Username, cfg.BasicAuth.Password, cfg.BasicAuth.PasswordFile, rt)
}
// Return a new configured RoundTripper.
return rt, nil
}
tlsConfig, err := NewTLSConfig(&cfg.TLSConfig)
if err != nil {
return nil, err
}
if len(cfg.TLSConfig.CAFile) == 0 {
// No need for a RoundTripper that reloads the CA file automatically.
return newRT(tlsConfig)
}
return newTLSRoundTripper(tlsConfig, cfg.TLSConfig.CAFile, newRT)
} | go | func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string) (http.RoundTripper, error) {
newRT := func(tlsConfig *tls.Config) (http.RoundTripper, error) {
// The only timeout we care about is the configured scrape timeout.
// It is applied on request. So we leave out any timings here.
var rt http.RoundTripper = &http.Transport{
Proxy: http.ProxyURL(cfg.ProxyURL.URL),
MaxIdleConns: 20000,
MaxIdleConnsPerHost: 1000, // see https://github.com/golang/go/issues/13801
DisableKeepAlives: false,
TLSClientConfig: tlsConfig,
DisableCompression: true,
// 5 minutes is typically above the maximum sane scrape interval. So we can
// use keepalive for all configurations.
IdleConnTimeout: 5 * time.Minute,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
conntrack.DialWithName(name),
),
}
// If a bearer token is provided, create a round tripper that will set the
// Authorization header correctly on each request.
if len(cfg.BearerToken) > 0 {
rt = NewBearerAuthRoundTripper(cfg.BearerToken, rt)
} else if len(cfg.BearerTokenFile) > 0 {
rt = NewBearerAuthFileRoundTripper(cfg.BearerTokenFile, rt)
}
if cfg.BasicAuth != nil {
rt = NewBasicAuthRoundTripper(cfg.BasicAuth.Username, cfg.BasicAuth.Password, cfg.BasicAuth.PasswordFile, rt)
}
// Return a new configured RoundTripper.
return rt, nil
}
tlsConfig, err := NewTLSConfig(&cfg.TLSConfig)
if err != nil {
return nil, err
}
if len(cfg.TLSConfig.CAFile) == 0 {
// No need for a RoundTripper that reloads the CA file automatically.
return newRT(tlsConfig)
}
return newTLSRoundTripper(tlsConfig, cfg.TLSConfig.CAFile, newRT)
} | [
"func",
"NewRoundTripperFromConfig",
"(",
"cfg",
"HTTPClientConfig",
",",
"name",
"string",
")",
"(",
"http",
".",
"RoundTripper",
",",
"error",
")",
"{",
"newRT",
":=",
"func",
"(",
"tlsConfig",
"*",
"tls",
".",
"Config",
")",
"(",
"http",
".",
"RoundTripper",
",",
"error",
")",
"{",
"// The only timeout we care about is the configured scrape timeout.",
"// It is applied on request. So we leave out any timings here.",
"var",
"rt",
"http",
".",
"RoundTripper",
"=",
"&",
"http",
".",
"Transport",
"{",
"Proxy",
":",
"http",
".",
"ProxyURL",
"(",
"cfg",
".",
"ProxyURL",
".",
"URL",
")",
",",
"MaxIdleConns",
":",
"20000",
",",
"MaxIdleConnsPerHost",
":",
"1000",
",",
"// see https://github.com/golang/go/issues/13801",
"DisableKeepAlives",
":",
"false",
",",
"TLSClientConfig",
":",
"tlsConfig",
",",
"DisableCompression",
":",
"true",
",",
"// 5 minutes is typically above the maximum sane scrape interval. So we can",
"// use keepalive for all configurations.",
"IdleConnTimeout",
":",
"5",
"*",
"time",
".",
"Minute",
",",
"TLSHandshakeTimeout",
":",
"10",
"*",
"time",
".",
"Second",
",",
"ExpectContinueTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"DialContext",
":",
"conntrack",
".",
"NewDialContextFunc",
"(",
"conntrack",
".",
"DialWithTracing",
"(",
")",
",",
"conntrack",
".",
"DialWithName",
"(",
"name",
")",
",",
")",
",",
"}",
"\n\n",
"// If a bearer token is provided, create a round tripper that will set the",
"// Authorization header correctly on each request.",
"if",
"len",
"(",
"cfg",
".",
"BearerToken",
")",
">",
"0",
"{",
"rt",
"=",
"NewBearerAuthRoundTripper",
"(",
"cfg",
".",
"BearerToken",
",",
"rt",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"cfg",
".",
"BearerTokenFile",
")",
">",
"0",
"{",
"rt",
"=",
"NewBearerAuthFileRoundTripper",
"(",
"cfg",
".",
"BearerTokenFile",
",",
"rt",
")",
"\n",
"}",
"\n\n",
"if",
"cfg",
".",
"BasicAuth",
"!=",
"nil",
"{",
"rt",
"=",
"NewBasicAuthRoundTripper",
"(",
"cfg",
".",
"BasicAuth",
".",
"Username",
",",
"cfg",
".",
"BasicAuth",
".",
"Password",
",",
"cfg",
".",
"BasicAuth",
".",
"PasswordFile",
",",
"rt",
")",
"\n",
"}",
"\n",
"// Return a new configured RoundTripper.",
"return",
"rt",
",",
"nil",
"\n",
"}",
"\n\n",
"tlsConfig",
",",
"err",
":=",
"NewTLSConfig",
"(",
"&",
"cfg",
".",
"TLSConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"cfg",
".",
"TLSConfig",
".",
"CAFile",
")",
"==",
"0",
"{",
"// No need for a RoundTripper that reloads the CA file automatically.",
"return",
"newRT",
"(",
"tlsConfig",
")",
"\n",
"}",
"\n\n",
"return",
"newTLSRoundTripper",
"(",
"tlsConfig",
",",
"cfg",
".",
"TLSConfig",
".",
"CAFile",
",",
"newRT",
")",
"\n",
"}"
] | // NewRoundTripperFromConfig returns a new HTTP RoundTripper configured for the
// given config.HTTPClientConfig. The name is used as go-conntrack metric label. | [
"NewRoundTripperFromConfig",
"returns",
"a",
"new",
"HTTP",
"RoundTripper",
"configured",
"for",
"the",
"given",
"config",
".",
"HTTPClientConfig",
".",
"The",
"name",
"is",
"used",
"as",
"go",
"-",
"conntrack",
"metric",
"label",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L135-L183 |
6,404 | prometheus/common | config/http_config.go | NewBearerAuthFileRoundTripper | func NewBearerAuthFileRoundTripper(bearerFile string, rt http.RoundTripper) http.RoundTripper {
return &bearerAuthFileRoundTripper{bearerFile, rt}
} | go | func NewBearerAuthFileRoundTripper(bearerFile string, rt http.RoundTripper) http.RoundTripper {
return &bearerAuthFileRoundTripper{bearerFile, rt}
} | [
"func",
"NewBearerAuthFileRoundTripper",
"(",
"bearerFile",
"string",
",",
"rt",
"http",
".",
"RoundTripper",
")",
"http",
".",
"RoundTripper",
"{",
"return",
"&",
"bearerAuthFileRoundTripper",
"{",
"bearerFile",
",",
"rt",
"}",
"\n",
"}"
] | // NewBearerAuthFileRoundTripper adds the bearer token read from the provided file to a request unless
// the authorization header has already been set. This file is read for every request. | [
"NewBearerAuthFileRoundTripper",
"adds",
"the",
"bearer",
"token",
"read",
"from",
"the",
"provided",
"file",
"to",
"a",
"request",
"unless",
"the",
"authorization",
"header",
"has",
"already",
"been",
"set",
".",
"This",
"file",
"is",
"read",
"for",
"every",
"request",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L217-L219 |
6,405 | prometheus/common | config/http_config.go | NewTLSConfig | func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify}
// If a CA cert is provided then let's read it in so we can validate the
// scrape target's certificate properly.
if len(cfg.CAFile) > 0 {
b, err := readCAFile(cfg.CAFile)
if err != nil {
return nil, err
}
if !updateRootCA(tlsConfig, b) {
return nil, fmt.Errorf("unable to use specified CA cert %s", cfg.CAFile)
}
}
if len(cfg.ServerName) > 0 {
tlsConfig.ServerName = cfg.ServerName
}
// If a client cert & key is provided then configure TLS config accordingly.
if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 {
return nil, fmt.Errorf("client cert file %q specified without client key file", cfg.CertFile)
} else if len(cfg.KeyFile) > 0 && len(cfg.CertFile) == 0 {
return nil, fmt.Errorf("client key file %q specified without client cert file", cfg.KeyFile)
} else if len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 {
// Verify that client cert and key are valid.
if _, err := cfg.getClientCertificate(nil); err != nil {
return nil, err
}
tlsConfig.GetClientCertificate = cfg.getClientCertificate
}
return tlsConfig, nil
} | go | func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) {
tlsConfig := &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify}
// If a CA cert is provided then let's read it in so we can validate the
// scrape target's certificate properly.
if len(cfg.CAFile) > 0 {
b, err := readCAFile(cfg.CAFile)
if err != nil {
return nil, err
}
if !updateRootCA(tlsConfig, b) {
return nil, fmt.Errorf("unable to use specified CA cert %s", cfg.CAFile)
}
}
if len(cfg.ServerName) > 0 {
tlsConfig.ServerName = cfg.ServerName
}
// If a client cert & key is provided then configure TLS config accordingly.
if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 {
return nil, fmt.Errorf("client cert file %q specified without client key file", cfg.CertFile)
} else if len(cfg.KeyFile) > 0 && len(cfg.CertFile) == 0 {
return nil, fmt.Errorf("client key file %q specified without client cert file", cfg.KeyFile)
} else if len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 {
// Verify that client cert and key are valid.
if _, err := cfg.getClientCertificate(nil); err != nil {
return nil, err
}
tlsConfig.GetClientCertificate = cfg.getClientCertificate
}
return tlsConfig, nil
} | [
"func",
"NewTLSConfig",
"(",
"cfg",
"*",
"TLSConfig",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"tlsConfig",
":=",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"cfg",
".",
"InsecureSkipVerify",
"}",
"\n\n",
"// If a CA cert is provided then let's read it in so we can validate the",
"// scrape target's certificate properly.",
"if",
"len",
"(",
"cfg",
".",
"CAFile",
")",
">",
"0",
"{",
"b",
",",
"err",
":=",
"readCAFile",
"(",
"cfg",
".",
"CAFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"updateRootCA",
"(",
"tlsConfig",
",",
"b",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"CAFile",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"cfg",
".",
"ServerName",
")",
">",
"0",
"{",
"tlsConfig",
".",
"ServerName",
"=",
"cfg",
".",
"ServerName",
"\n",
"}",
"\n",
"// If a client cert & key is provided then configure TLS config accordingly.",
"if",
"len",
"(",
"cfg",
".",
"CertFile",
")",
">",
"0",
"&&",
"len",
"(",
"cfg",
".",
"KeyFile",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"CertFile",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"cfg",
".",
"KeyFile",
")",
">",
"0",
"&&",
"len",
"(",
"cfg",
".",
"CertFile",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"KeyFile",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"cfg",
".",
"CertFile",
")",
">",
"0",
"&&",
"len",
"(",
"cfg",
".",
"KeyFile",
")",
">",
"0",
"{",
"// Verify that client cert and key are valid.",
"if",
"_",
",",
"err",
":=",
"cfg",
".",
"getClientCertificate",
"(",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tlsConfig",
".",
"GetClientCertificate",
"=",
"cfg",
".",
"getClientCertificate",
"\n",
"}",
"\n\n",
"return",
"tlsConfig",
",",
"nil",
"\n",
"}"
] | // NewTLSConfig creates a new tls.Config from the given TLSConfig. | [
"NewTLSConfig",
"creates",
"a",
"new",
"tls",
".",
"Config",
"from",
"the",
"given",
"TLSConfig",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L293-L325 |
6,406 | prometheus/common | config/http_config.go | getClientCertificate | func (c *TLSConfig) getClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
cert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)
if err != nil {
return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", c.CertFile, c.KeyFile, err)
}
return &cert, nil
} | go | func (c *TLSConfig) getClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
cert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)
if err != nil {
return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", c.CertFile, c.KeyFile, err)
}
return &cert, nil
} | [
"func",
"(",
"c",
"*",
"TLSConfig",
")",
"getClientCertificate",
"(",
"*",
"tls",
".",
"CertificateRequestInfo",
")",
"(",
"*",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"c",
".",
"CertFile",
",",
"c",
".",
"KeyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"CertFile",
",",
"c",
".",
"KeyFile",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"cert",
",",
"nil",
"\n",
"}"
] | // getClientCertificate reads the pair of client cert and key from disk and returns a tls.Certificate. | [
"getClientCertificate",
"reads",
"the",
"pair",
"of",
"client",
"cert",
"and",
"key",
"from",
"disk",
"and",
"returns",
"a",
"tls",
".",
"Certificate",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L348-L354 |
6,407 | prometheus/common | config/http_config.go | readCAFile | func readCAFile(f string) ([]byte, error) {
data, err := ioutil.ReadFile(f)
if err != nil {
return nil, fmt.Errorf("unable to load specified CA cert %s: %s", f, err)
}
return data, nil
} | go | func readCAFile(f string) ([]byte, error) {
data, err := ioutil.ReadFile(f)
if err != nil {
return nil, fmt.Errorf("unable to load specified CA cert %s: %s", f, err)
}
return data, nil
} | [
"func",
"readCAFile",
"(",
"f",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // readCAFile reads the CA cert file from disk. | [
"readCAFile",
"reads",
"the",
"CA",
"cert",
"file",
"from",
"disk",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L357-L363 |
6,408 | prometheus/common | config/http_config.go | updateRootCA | func updateRootCA(cfg *tls.Config, b []byte) bool {
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(b) {
return false
}
cfg.RootCAs = caCertPool
return true
} | go | func updateRootCA(cfg *tls.Config, b []byte) bool {
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(b) {
return false
}
cfg.RootCAs = caCertPool
return true
} | [
"func",
"updateRootCA",
"(",
"cfg",
"*",
"tls",
".",
"Config",
",",
"b",
"[",
"]",
"byte",
")",
"bool",
"{",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"if",
"!",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"cfg",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"return",
"true",
"\n",
"}"
] | // updateRootCA parses the given byte slice as a series of PEM encoded certificates and updates tls.Config.RootCAs. | [
"updateRootCA",
"parses",
"the",
"given",
"byte",
"slice",
"as",
"a",
"series",
"of",
"PEM",
"encoded",
"certificates",
"and",
"updates",
"tls",
".",
"Config",
".",
"RootCAs",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L366-L373 |
6,409 | prometheus/common | config/http_config.go | RoundTrip | func (t *tlsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
b, h, err := t.getCAWithHash()
if err != nil {
return nil, err
}
t.mtx.RLock()
equal := bytes.Equal(h[:], t.hashCAFile)
rt := t.rt
t.mtx.RUnlock()
if equal {
// The CA cert hasn't changed, use the existing RoundTripper.
return rt.RoundTrip(req)
}
// Create a new RoundTripper.
tlsConfig := t.tlsConfig.Clone()
if !updateRootCA(tlsConfig, b) {
return nil, fmt.Errorf("unable to use specified CA cert %s", t.caFile)
}
rt, err = t.newRT(tlsConfig)
if err != nil {
return nil, err
}
t.CloseIdleConnections()
t.mtx.Lock()
t.rt = rt
t.hashCAFile = h[:]
t.mtx.Unlock()
return rt.RoundTrip(req)
} | go | func (t *tlsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
b, h, err := t.getCAWithHash()
if err != nil {
return nil, err
}
t.mtx.RLock()
equal := bytes.Equal(h[:], t.hashCAFile)
rt := t.rt
t.mtx.RUnlock()
if equal {
// The CA cert hasn't changed, use the existing RoundTripper.
return rt.RoundTrip(req)
}
// Create a new RoundTripper.
tlsConfig := t.tlsConfig.Clone()
if !updateRootCA(tlsConfig, b) {
return nil, fmt.Errorf("unable to use specified CA cert %s", t.caFile)
}
rt, err = t.newRT(tlsConfig)
if err != nil {
return nil, err
}
t.CloseIdleConnections()
t.mtx.Lock()
t.rt = rt
t.hashCAFile = h[:]
t.mtx.Unlock()
return rt.RoundTrip(req)
} | [
"func",
"(",
"t",
"*",
"tlsRoundTripper",
")",
"RoundTrip",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"b",
",",
"h",
",",
"err",
":=",
"t",
".",
"getCAWithHash",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"t",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"equal",
":=",
"bytes",
".",
"Equal",
"(",
"h",
"[",
":",
"]",
",",
"t",
".",
"hashCAFile",
")",
"\n",
"rt",
":=",
"t",
".",
"rt",
"\n",
"t",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"equal",
"{",
"// The CA cert hasn't changed, use the existing RoundTripper.",
"return",
"rt",
".",
"RoundTrip",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"// Create a new RoundTripper.",
"tlsConfig",
":=",
"t",
".",
"tlsConfig",
".",
"Clone",
"(",
")",
"\n",
"if",
"!",
"updateRootCA",
"(",
"tlsConfig",
",",
"b",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"caFile",
")",
"\n",
"}",
"\n",
"rt",
",",
"err",
"=",
"t",
".",
"newRT",
"(",
"tlsConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"t",
".",
"CloseIdleConnections",
"(",
")",
"\n\n",
"t",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"t",
".",
"rt",
"=",
"rt",
"\n",
"t",
".",
"hashCAFile",
"=",
"h",
"[",
":",
"]",
"\n",
"t",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"rt",
".",
"RoundTrip",
"(",
"req",
")",
"\n",
"}"
] | // RoundTrip implements the http.RoundTrip interface. | [
"RoundTrip",
"implements",
"the",
"http",
".",
"RoundTrip",
"interface",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/http_config.go#L424-L456 |
6,410 | prometheus/common | model/signature.go | labelSetToFastFingerprint | func labelSetToFastFingerprint(ls LabelSet) Fingerprint {
if len(ls) == 0 {
return Fingerprint(emptyLabelSignature)
}
var result uint64
for labelName, labelValue := range ls {
sum := hashNew()
sum = hashAdd(sum, string(labelName))
sum = hashAddByte(sum, SeparatorByte)
sum = hashAdd(sum, string(labelValue))
result ^= sum
}
return Fingerprint(result)
} | go | func labelSetToFastFingerprint(ls LabelSet) Fingerprint {
if len(ls) == 0 {
return Fingerprint(emptyLabelSignature)
}
var result uint64
for labelName, labelValue := range ls {
sum := hashNew()
sum = hashAdd(sum, string(labelName))
sum = hashAddByte(sum, SeparatorByte)
sum = hashAdd(sum, string(labelValue))
result ^= sum
}
return Fingerprint(result)
} | [
"func",
"labelSetToFastFingerprint",
"(",
"ls",
"LabelSet",
")",
"Fingerprint",
"{",
"if",
"len",
"(",
"ls",
")",
"==",
"0",
"{",
"return",
"Fingerprint",
"(",
"emptyLabelSignature",
")",
"\n",
"}",
"\n\n",
"var",
"result",
"uint64",
"\n",
"for",
"labelName",
",",
"labelValue",
":=",
"range",
"ls",
"{",
"sum",
":=",
"hashNew",
"(",
")",
"\n",
"sum",
"=",
"hashAdd",
"(",
"sum",
",",
"string",
"(",
"labelName",
")",
")",
"\n",
"sum",
"=",
"hashAddByte",
"(",
"sum",
",",
"SeparatorByte",
")",
"\n",
"sum",
"=",
"hashAdd",
"(",
"sum",
",",
"string",
"(",
"labelValue",
")",
")",
"\n",
"result",
"^=",
"sum",
"\n",
"}",
"\n",
"return",
"Fingerprint",
"(",
"result",
")",
"\n",
"}"
] | // labelSetToFastFingerprint works similar to labelSetToFingerprint but uses a
// faster and less allocation-heavy hash function, which is more susceptible to
// create hash collisions. Therefore, collision detection should be applied. | [
"labelSetToFastFingerprint",
"works",
"similar",
"to",
"labelSetToFingerprint",
"but",
"uses",
"a",
"faster",
"and",
"less",
"allocation",
"-",
"heavy",
"hash",
"function",
"which",
"is",
"more",
"susceptible",
"to",
"create",
"hash",
"collisions",
".",
"Therefore",
"collision",
"detection",
"should",
"be",
"applied",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/signature.go#L80-L94 |
6,411 | prometheus/common | log/log.go | sourced | func (l logger) sourced() *logrus.Entry {
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
file = file[slash+1:]
}
return l.entry.WithField("source", fmt.Sprintf("%s:%d", file, line))
} | go | func (l logger) sourced() *logrus.Entry {
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
file = file[slash+1:]
}
return l.entry.WithField("source", fmt.Sprintf("%s:%d", file, line))
} | [
"func",
"(",
"l",
"logger",
")",
"sourced",
"(",
")",
"*",
"logrus",
".",
"Entry",
"{",
"_",
",",
"file",
",",
"line",
",",
"ok",
":=",
"runtime",
".",
"Caller",
"(",
"2",
")",
"\n",
"if",
"!",
"ok",
"{",
"file",
"=",
"\"",
"\"",
"\n",
"line",
"=",
"1",
"\n",
"}",
"else",
"{",
"slash",
":=",
"strings",
".",
"LastIndex",
"(",
"file",
",",
"\"",
"\"",
")",
"\n",
"file",
"=",
"file",
"[",
"slash",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"l",
".",
"entry",
".",
"WithField",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"file",
",",
"line",
")",
")",
"\n",
"}"
] | // sourced adds a source field to the logger that contains
// the file name and line where the logging happened. | [
"sourced",
"adds",
"a",
"source",
"field",
"to",
"the",
"logger",
"that",
"contains",
"the",
"file",
"name",
"and",
"line",
"where",
"the",
"logging",
"happened",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/log/log.go#L234-L244 |
6,412 | prometheus/common | log/log.go | NewLogger | func NewLogger(w io.Writer) Logger {
l := logrus.New()
l.Out = w
return logger{entry: logrus.NewEntry(l)}
} | go | func NewLogger(w io.Writer) Logger {
l := logrus.New()
l.Out = w
return logger{entry: logrus.NewEntry(l)}
} | [
"func",
"NewLogger",
"(",
"w",
"io",
".",
"Writer",
")",
"Logger",
"{",
"l",
":=",
"logrus",
".",
"New",
"(",
")",
"\n",
"l",
".",
"Out",
"=",
"w",
"\n",
"return",
"logger",
"{",
"entry",
":",
"logrus",
".",
"NewEntry",
"(",
"l",
")",
"}",
"\n",
"}"
] | // NewLogger returns a new Logger logging to out. | [
"NewLogger",
"returns",
"a",
"new",
"Logger",
"logging",
"to",
"out",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/log/log.go#L255-L259 |
6,413 | prometheus/common | log/log.go | NewNopLogger | func NewNopLogger() Logger {
l := logrus.New()
l.Out = ioutil.Discard
return logger{entry: logrus.NewEntry(l)}
} | go | func NewNopLogger() Logger {
l := logrus.New()
l.Out = ioutil.Discard
return logger{entry: logrus.NewEntry(l)}
} | [
"func",
"NewNopLogger",
"(",
")",
"Logger",
"{",
"l",
":=",
"logrus",
".",
"New",
"(",
")",
"\n",
"l",
".",
"Out",
"=",
"ioutil",
".",
"Discard",
"\n",
"return",
"logger",
"{",
"entry",
":",
"logrus",
".",
"NewEntry",
"(",
"l",
")",
"}",
"\n",
"}"
] | // NewNopLogger returns a logger that discards all log messages. | [
"NewNopLogger",
"returns",
"a",
"logger",
"that",
"discards",
"all",
"log",
"messages",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/log/log.go#L262-L266 |
6,414 | prometheus/common | model/metric.go | Equal | func (m Metric) Equal(o Metric) bool {
return LabelSet(m).Equal(LabelSet(o))
} | go | func (m Metric) Equal(o Metric) bool {
return LabelSet(m).Equal(LabelSet(o))
} | [
"func",
"(",
"m",
"Metric",
")",
"Equal",
"(",
"o",
"Metric",
")",
"bool",
"{",
"return",
"LabelSet",
"(",
"m",
")",
".",
"Equal",
"(",
"LabelSet",
"(",
"o",
")",
")",
"\n",
"}"
] | // Equal compares the metrics. | [
"Equal",
"compares",
"the",
"metrics",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/metric.go#L35-L37 |
6,415 | prometheus/common | model/metric.go | Before | func (m Metric) Before(o Metric) bool {
return LabelSet(m).Before(LabelSet(o))
} | go | func (m Metric) Before(o Metric) bool {
return LabelSet(m).Before(LabelSet(o))
} | [
"func",
"(",
"m",
"Metric",
")",
"Before",
"(",
"o",
"Metric",
")",
"bool",
"{",
"return",
"LabelSet",
"(",
"m",
")",
".",
"Before",
"(",
"LabelSet",
"(",
"o",
")",
")",
"\n",
"}"
] | // Before compares the metrics' underlying label sets. | [
"Before",
"compares",
"the",
"metrics",
"underlying",
"label",
"sets",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/metric.go#L40-L42 |
6,416 | prometheus/common | model/metric.go | Clone | func (m Metric) Clone() Metric {
clone := make(Metric, len(m))
for k, v := range m {
clone[k] = v
}
return clone
} | go | func (m Metric) Clone() Metric {
clone := make(Metric, len(m))
for k, v := range m {
clone[k] = v
}
return clone
} | [
"func",
"(",
"m",
"Metric",
")",
"Clone",
"(",
")",
"Metric",
"{",
"clone",
":=",
"make",
"(",
"Metric",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"clone",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"clone",
"\n",
"}"
] | // Clone returns a copy of the Metric. | [
"Clone",
"returns",
"a",
"copy",
"of",
"the",
"Metric",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/metric.go#L45-L51 |
6,417 | prometheus/common | model/metric.go | IsValidMetricName | func IsValidMetricName(n LabelValue) bool {
if len(n) == 0 {
return false
}
for i, b := range n {
if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) {
return false
}
}
return true
} | go | func IsValidMetricName(n LabelValue) bool {
if len(n) == 0 {
return false
}
for i, b := range n {
if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) {
return false
}
}
return true
} | [
"func",
"IsValidMetricName",
"(",
"n",
"LabelValue",
")",
"bool",
"{",
"if",
"len",
"(",
"n",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"n",
"{",
"if",
"!",
"(",
"(",
"b",
">=",
"'a'",
"&&",
"b",
"<=",
"'z'",
")",
"||",
"(",
"b",
">=",
"'A'",
"&&",
"b",
"<=",
"'Z'",
")",
"||",
"b",
"==",
"'_'",
"||",
"b",
"==",
"':'",
"||",
"(",
"b",
">=",
"'0'",
"&&",
"b",
"<=",
"'9'",
"&&",
"i",
">",
"0",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // IsValidMetricName returns true iff name matches the pattern of MetricNameRE.
// This function, however, does not use MetricNameRE for the check but a much
// faster hardcoded implementation. | [
"IsValidMetricName",
"returns",
"true",
"iff",
"name",
"matches",
"the",
"pattern",
"of",
"MetricNameRE",
".",
"This",
"function",
"however",
"does",
"not",
"use",
"MetricNameRE",
"for",
"the",
"check",
"but",
"a",
"much",
"faster",
"hardcoded",
"implementation",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/metric.go#L92-L102 |
6,418 | prometheus/common | version/info.go | NewCollector | func NewCollector(program string) *prometheus.GaugeVec {
buildInfo := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: program,
Name: "build_info",
Help: fmt.Sprintf(
"A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.",
program,
),
},
[]string{"version", "revision", "branch", "goversion"},
)
buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1)
return buildInfo
} | go | func NewCollector(program string) *prometheus.GaugeVec {
buildInfo := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: program,
Name: "build_info",
Help: fmt.Sprintf(
"A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.",
program,
),
},
[]string{"version", "revision", "branch", "goversion"},
)
buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1)
return buildInfo
} | [
"func",
"NewCollector",
"(",
"program",
"string",
")",
"*",
"prometheus",
".",
"GaugeVec",
"{",
"buildInfo",
":=",
"prometheus",
".",
"NewGaugeVec",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Namespace",
":",
"program",
",",
"Name",
":",
"\"",
"\"",
",",
"Help",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"program",
",",
")",
",",
"}",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
")",
"\n",
"buildInfo",
".",
"WithLabelValues",
"(",
"Version",
",",
"Revision",
",",
"Branch",
",",
"GoVersion",
")",
".",
"Set",
"(",
"1",
")",
"\n",
"return",
"buildInfo",
"\n",
"}"
] | // NewCollector returns a collector which exports metrics about current version information. | [
"NewCollector",
"returns",
"a",
"collector",
"which",
"exports",
"metrics",
"about",
"current",
"version",
"information",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/version/info.go#L37-L51 |
6,419 | prometheus/common | version/info.go | Print | func Print(program string) string {
m := map[string]string{
"program": program,
"version": Version,
"revision": Revision,
"branch": Branch,
"buildUser": BuildUser,
"buildDate": BuildDate,
"goVersion": GoVersion,
}
t := template.Must(template.New("version").Parse(versionInfoTmpl))
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, "version", m); err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
} | go | func Print(program string) string {
m := map[string]string{
"program": program,
"version": Version,
"revision": Revision,
"branch": Branch,
"buildUser": BuildUser,
"buildDate": BuildDate,
"goVersion": GoVersion,
}
t := template.Must(template.New("version").Parse(versionInfoTmpl))
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, "version", m); err != nil {
panic(err)
}
return strings.TrimSpace(buf.String())
} | [
"func",
"Print",
"(",
"program",
"string",
")",
"string",
"{",
"m",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"program",
",",
"\"",
"\"",
":",
"Version",
",",
"\"",
"\"",
":",
"Revision",
",",
"\"",
"\"",
":",
"Branch",
",",
"\"",
"\"",
":",
"BuildUser",
",",
"\"",
"\"",
":",
"BuildDate",
",",
"\"",
"\"",
":",
"GoVersion",
",",
"}",
"\n",
"t",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"versionInfoTmpl",
")",
")",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"t",
".",
"ExecuteTemplate",
"(",
"&",
"buf",
",",
"\"",
"\"",
",",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // Print returns version information. | [
"Print",
"returns",
"version",
"information",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/version/info.go#L62-L79 |
6,420 | prometheus/common | promlog/log.go | Set | func (l *AllowedLevel) Set(s string) error {
switch s {
case "debug":
l.o = level.AllowDebug()
case "info":
l.o = level.AllowInfo()
case "warn":
l.o = level.AllowWarn()
case "error":
l.o = level.AllowError()
default:
return errors.Errorf("unrecognized log level %q", s)
}
l.s = s
return nil
} | go | func (l *AllowedLevel) Set(s string) error {
switch s {
case "debug":
l.o = level.AllowDebug()
case "info":
l.o = level.AllowInfo()
case "warn":
l.o = level.AllowWarn()
case "error":
l.o = level.AllowError()
default:
return errors.Errorf("unrecognized log level %q", s)
}
l.s = s
return nil
} | [
"func",
"(",
"l",
"*",
"AllowedLevel",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"switch",
"s",
"{",
"case",
"\"",
"\"",
":",
"l",
".",
"o",
"=",
"level",
".",
"AllowDebug",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"l",
".",
"o",
"=",
"level",
".",
"AllowInfo",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"l",
".",
"o",
"=",
"level",
".",
"AllowWarn",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"l",
".",
"o",
"=",
"level",
".",
"AllowError",
"(",
")",
"\n",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"l",
".",
"s",
"=",
"s",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set updates the value of the allowed level. | [
"Set",
"updates",
"the",
"value",
"of",
"the",
"allowed",
"level",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/promlog/log.go#L50-L65 |
6,421 | prometheus/common | promlog/log.go | Set | func (f *AllowedFormat) Set(s string) error {
switch s {
case "logfmt", "json":
f.s = s
default:
return errors.Errorf("unrecognized log format %q", s)
}
return nil
} | go | func (f *AllowedFormat) Set(s string) error {
switch s {
case "logfmt", "json":
f.s = s
default:
return errors.Errorf("unrecognized log format %q", s)
}
return nil
} | [
"func",
"(",
"f",
"*",
"AllowedFormat",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"switch",
"s",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"f",
".",
"s",
"=",
"s",
"\n",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set updates the value of the allowed format. | [
"Set",
"updates",
"the",
"value",
"of",
"the",
"allowed",
"format",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/promlog/log.go#L77-L85 |
6,422 | prometheus/common | promlog/log.go | New | func New(config *Config) log.Logger {
var l log.Logger
if config.Format.s == "logfmt" {
l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
} else {
l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
}
l = level.NewFilter(l, config.Level.o)
l = log.With(l, "ts", timestampFormat, "caller", log.DefaultCaller)
return l
} | go | func New(config *Config) log.Logger {
var l log.Logger
if config.Format.s == "logfmt" {
l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
} else {
l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
}
l = level.NewFilter(l, config.Level.o)
l = log.With(l, "ts", timestampFormat, "caller", log.DefaultCaller)
return l
} | [
"func",
"New",
"(",
"config",
"*",
"Config",
")",
"log",
".",
"Logger",
"{",
"var",
"l",
"log",
".",
"Logger",
"\n",
"if",
"config",
".",
"Format",
".",
"s",
"==",
"\"",
"\"",
"{",
"l",
"=",
"log",
".",
"NewLogfmtLogger",
"(",
"log",
".",
"NewSyncWriter",
"(",
"os",
".",
"Stderr",
")",
")",
"\n",
"}",
"else",
"{",
"l",
"=",
"log",
".",
"NewJSONLogger",
"(",
"log",
".",
"NewSyncWriter",
"(",
"os",
".",
"Stderr",
")",
")",
"\n",
"}",
"\n\n",
"l",
"=",
"level",
".",
"NewFilter",
"(",
"l",
",",
"config",
".",
"Level",
".",
"o",
")",
"\n",
"l",
"=",
"log",
".",
"With",
"(",
"l",
",",
"\"",
"\"",
",",
"timestampFormat",
",",
"\"",
"\"",
",",
"log",
".",
"DefaultCaller",
")",
"\n",
"return",
"l",
"\n",
"}"
] | // New returns a new leveled oklog logger. Each logged line will be annotated
// with a timestamp. The output always goes to stderr. | [
"New",
"returns",
"a",
"new",
"leveled",
"oklog",
"logger",
".",
"Each",
"logged",
"line",
"will",
"be",
"annotated",
"with",
"a",
"timestamp",
".",
"The",
"output",
"always",
"goes",
"to",
"stderr",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/promlog/log.go#L95-L106 |
6,423 | prometheus/common | model/labelset.go | Validate | func (ls LabelSet) Validate() error {
for ln, lv := range ls {
if !ln.IsValid() {
return fmt.Errorf("invalid name %q", ln)
}
if !lv.IsValid() {
return fmt.Errorf("invalid value %q", lv)
}
}
return nil
} | go | func (ls LabelSet) Validate() error {
for ln, lv := range ls {
if !ln.IsValid() {
return fmt.Errorf("invalid name %q", ln)
}
if !lv.IsValid() {
return fmt.Errorf("invalid value %q", lv)
}
}
return nil
} | [
"func",
"(",
"ls",
"LabelSet",
")",
"Validate",
"(",
")",
"error",
"{",
"for",
"ln",
",",
"lv",
":=",
"range",
"ls",
"{",
"if",
"!",
"ln",
".",
"IsValid",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ln",
")",
"\n",
"}",
"\n",
"if",
"!",
"lv",
".",
"IsValid",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"lv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate checks whether all names and values in the label set
// are valid. | [
"Validate",
"checks",
"whether",
"all",
"names",
"and",
"values",
"in",
"the",
"label",
"set",
"are",
"valid",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/labelset.go#L32-L42 |
6,424 | prometheus/common | model/labelset.go | Clone | func (ls LabelSet) Clone() LabelSet {
lsn := make(LabelSet, len(ls))
for ln, lv := range ls {
lsn[ln] = lv
}
return lsn
} | go | func (ls LabelSet) Clone() LabelSet {
lsn := make(LabelSet, len(ls))
for ln, lv := range ls {
lsn[ln] = lv
}
return lsn
} | [
"func",
"(",
"ls",
"LabelSet",
")",
"Clone",
"(",
")",
"LabelSet",
"{",
"lsn",
":=",
"make",
"(",
"LabelSet",
",",
"len",
"(",
"ls",
")",
")",
"\n",
"for",
"ln",
",",
"lv",
":=",
"range",
"ls",
"{",
"lsn",
"[",
"ln",
"]",
"=",
"lv",
"\n",
"}",
"\n",
"return",
"lsn",
"\n",
"}"
] | // Clone returns a copy of the label set. | [
"Clone",
"returns",
"a",
"copy",
"of",
"the",
"label",
"set",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/labelset.go#L109-L115 |
6,425 | prometheus/common | model/labelset.go | Merge | func (l LabelSet) Merge(other LabelSet) LabelSet {
result := make(LabelSet, len(l))
for k, v := range l {
result[k] = v
}
for k, v := range other {
result[k] = v
}
return result
} | go | func (l LabelSet) Merge(other LabelSet) LabelSet {
result := make(LabelSet, len(l))
for k, v := range l {
result[k] = v
}
for k, v := range other {
result[k] = v
}
return result
} | [
"func",
"(",
"l",
"LabelSet",
")",
"Merge",
"(",
"other",
"LabelSet",
")",
"LabelSet",
"{",
"result",
":=",
"make",
"(",
"LabelSet",
",",
"len",
"(",
"l",
")",
")",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"l",
"{",
"result",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"other",
"{",
"result",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Merge is a helper function to non-destructively merge two label sets. | [
"Merge",
"is",
"a",
"helper",
"function",
"to",
"non",
"-",
"destructively",
"merge",
"two",
"label",
"sets",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/labelset.go#L118-L130 |
6,426 | prometheus/common | model/time.go | Add | func (t Time) Add(d time.Duration) Time {
return t + Time(d/minimumTick)
} | go | func (t Time) Add(d time.Duration) Time {
return t + Time(d/minimumTick)
} | [
"func",
"(",
"t",
"Time",
")",
"Add",
"(",
"d",
"time",
".",
"Duration",
")",
"Time",
"{",
"return",
"t",
"+",
"Time",
"(",
"d",
"/",
"minimumTick",
")",
"\n",
"}"
] | // Add returns the Time t + d. | [
"Add",
"returns",
"the",
"Time",
"t",
"+",
"d",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/time.go#L84-L86 |
6,427 | prometheus/common | model/time.go | Sub | func (t Time) Sub(o Time) time.Duration {
return time.Duration(t-o) * minimumTick
} | go | func (t Time) Sub(o Time) time.Duration {
return time.Duration(t-o) * minimumTick
} | [
"func",
"(",
"t",
"Time",
")",
"Sub",
"(",
"o",
"Time",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"t",
"-",
"o",
")",
"*",
"minimumTick",
"\n",
"}"
] | // Sub returns the Duration t - o. | [
"Sub",
"returns",
"the",
"Duration",
"t",
"-",
"o",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/time.go#L89-L91 |
6,428 | prometheus/common | model/time.go | Time | func (t Time) Time() time.Time {
return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
} | go | func (t Time) Time() time.Time {
return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
} | [
"func",
"(",
"t",
"Time",
")",
"Time",
"(",
")",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"Unix",
"(",
"int64",
"(",
"t",
")",
"/",
"second",
",",
"(",
"int64",
"(",
"t",
")",
"%",
"second",
")",
"*",
"nanosPerTick",
")",
"\n",
"}"
] | // Time returns the time.Time representation of t. | [
"Time",
"returns",
"the",
"time",
".",
"Time",
"representation",
"of",
"t",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/time.go#L94-L96 |
6,429 | prometheus/common | model/time.go | String | func (t Time) String() string {
return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
} | go | func (t Time) String() string {
return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
} | [
"func",
"(",
"t",
"Time",
")",
"String",
"(",
")",
"string",
"{",
"return",
"strconv",
".",
"FormatFloat",
"(",
"float64",
"(",
"t",
")",
"/",
"float64",
"(",
"second",
")",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
"\n",
"}"
] | // String returns a string representation of the Time. | [
"String",
"returns",
"a",
"string",
"representation",
"of",
"the",
"Time",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/time.go#L114-L116 |
6,430 | prometheus/common | model/time.go | ParseDuration | func ParseDuration(durationStr string) (Duration, error) {
matches := durationRE.FindStringSubmatch(durationStr)
if len(matches) != 3 {
return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
}
var (
n, _ = strconv.Atoi(matches[1])
dur = time.Duration(n) * time.Millisecond
)
switch unit := matches[2]; unit {
case "y":
dur *= 1000 * 60 * 60 * 24 * 365
case "w":
dur *= 1000 * 60 * 60 * 24 * 7
case "d":
dur *= 1000 * 60 * 60 * 24
case "h":
dur *= 1000 * 60 * 60
case "m":
dur *= 1000 * 60
case "s":
dur *= 1000
case "ms":
// Value already correct
default:
return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
}
return Duration(dur), nil
} | go | func ParseDuration(durationStr string) (Duration, error) {
matches := durationRE.FindStringSubmatch(durationStr)
if len(matches) != 3 {
return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
}
var (
n, _ = strconv.Atoi(matches[1])
dur = time.Duration(n) * time.Millisecond
)
switch unit := matches[2]; unit {
case "y":
dur *= 1000 * 60 * 60 * 24 * 365
case "w":
dur *= 1000 * 60 * 60 * 24 * 7
case "d":
dur *= 1000 * 60 * 60 * 24
case "h":
dur *= 1000 * 60 * 60
case "m":
dur *= 1000 * 60
case "s":
dur *= 1000
case "ms":
// Value already correct
default:
return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
}
return Duration(dur), nil
} | [
"func",
"ParseDuration",
"(",
"durationStr",
"string",
")",
"(",
"Duration",
",",
"error",
")",
"{",
"matches",
":=",
"durationRE",
".",
"FindStringSubmatch",
"(",
"durationStr",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"!=",
"3",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"durationStr",
")",
"\n",
"}",
"\n",
"var",
"(",
"n",
",",
"_",
"=",
"strconv",
".",
"Atoi",
"(",
"matches",
"[",
"1",
"]",
")",
"\n",
"dur",
"=",
"time",
".",
"Duration",
"(",
"n",
")",
"*",
"time",
".",
"Millisecond",
"\n",
")",
"\n",
"switch",
"unit",
":=",
"matches",
"[",
"2",
"]",
";",
"unit",
"{",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"*",
"60",
"*",
"60",
"*",
"24",
"*",
"365",
"\n",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"*",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
"\n",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"*",
"60",
"*",
"60",
"*",
"24",
"\n",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"*",
"60",
"*",
"60",
"\n",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"*",
"60",
"\n",
"case",
"\"",
"\"",
":",
"dur",
"*=",
"1000",
"\n",
"case",
"\"",
"\"",
":",
"// Value already correct",
"default",
":",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"unit",
")",
"\n",
"}",
"\n",
"return",
"Duration",
"(",
"dur",
")",
",",
"nil",
"\n",
"}"
] | // ParseDuration parses a string into a time.Duration, assuming that a year
// always has 365d, a week always has 7d, and a day always has 24h. | [
"ParseDuration",
"parses",
"a",
"string",
"into",
"a",
"time",
".",
"Duration",
"assuming",
"that",
"a",
"year",
"always",
"has",
"365d",
"a",
"week",
"always",
"has",
"7d",
"and",
"a",
"day",
"always",
"has",
"24h",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/time.go#L182-L210 |
6,431 | prometheus/common | model/value.go | Equal | func (v SampleValue) Equal(o SampleValue) bool {
if v == o {
return true
}
return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
} | go | func (v SampleValue) Equal(o SampleValue) bool {
if v == o {
return true
}
return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
} | [
"func",
"(",
"v",
"SampleValue",
")",
"Equal",
"(",
"o",
"SampleValue",
")",
"bool",
"{",
"if",
"v",
"==",
"o",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"math",
".",
"IsNaN",
"(",
"float64",
"(",
"v",
")",
")",
"&&",
"math",
".",
"IsNaN",
"(",
"float64",
"(",
"o",
")",
")",
"\n",
"}"
] | // Equal returns true if the value of v and o is equal or if both are NaN. Note
// that v==o is false if both are NaN. If you want the conventional float
// behavior, use == to compare two SampleValues. | [
"Equal",
"returns",
"true",
"if",
"the",
"value",
"of",
"v",
"and",
"o",
"is",
"equal",
"or",
"if",
"both",
"are",
"NaN",
".",
"Note",
"that",
"v",
"==",
"o",
"is",
"false",
"if",
"both",
"are",
"NaN",
".",
"If",
"you",
"want",
"the",
"conventional",
"float",
"behavior",
"use",
"==",
"to",
"compare",
"two",
"SampleValues",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/value.go#L66-L71 |
6,432 | prometheus/common | model/value.go | Equal | func (s *SamplePair) Equal(o *SamplePair) bool {
return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
} | go | func (s *SamplePair) Equal(o *SamplePair) bool {
return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
} | [
"func",
"(",
"s",
"*",
"SamplePair",
")",
"Equal",
"(",
"o",
"*",
"SamplePair",
")",
"bool",
"{",
"return",
"s",
"==",
"o",
"||",
"(",
"s",
".",
"Value",
".",
"Equal",
"(",
"o",
".",
"Value",
")",
"&&",
"s",
".",
"Timestamp",
".",
"Equal",
"(",
"o",
".",
"Timestamp",
")",
")",
"\n",
"}"
] | // Equal returns true if this SamplePair and o have equal Values and equal
// Timestamps. The semantics of Value equality is defined by SampleValue.Equal. | [
"Equal",
"returns",
"true",
"if",
"this",
"SamplePair",
"and",
"o",
"have",
"equal",
"Values",
"and",
"equal",
"Timestamps",
".",
"The",
"semantics",
"of",
"Value",
"equality",
"is",
"defined",
"by",
"SampleValue",
".",
"Equal",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/value.go#L104-L106 |
6,433 | prometheus/common | model/value.go | Equal | func (s *Sample) Equal(o *Sample) bool {
if s == o {
return true
}
if !s.Metric.Equal(o.Metric) {
return false
}
if !s.Timestamp.Equal(o.Timestamp) {
return false
}
return s.Value.Equal(o.Value)
} | go | func (s *Sample) Equal(o *Sample) bool {
if s == o {
return true
}
if !s.Metric.Equal(o.Metric) {
return false
}
if !s.Timestamp.Equal(o.Timestamp) {
return false
}
return s.Value.Equal(o.Value)
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Equal",
"(",
"o",
"*",
"Sample",
")",
"bool",
"{",
"if",
"s",
"==",
"o",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"!",
"s",
".",
"Metric",
".",
"Equal",
"(",
"o",
".",
"Metric",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"s",
".",
"Timestamp",
".",
"Equal",
"(",
"o",
".",
"Timestamp",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"s",
".",
"Value",
".",
"Equal",
"(",
"o",
".",
"Value",
")",
"\n",
"}"
] | // Equal compares first the metrics, then the timestamp, then the value. The
// semantics of value equality is defined by SampleValue.Equal. | [
"Equal",
"compares",
"first",
"the",
"metrics",
"then",
"the",
"timestamp",
"then",
"the",
"value",
".",
"The",
"semantics",
"of",
"value",
"equality",
"is",
"defined",
"by",
"SampleValue",
".",
"Equal",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/value.go#L121-L134 |
6,434 | prometheus/common | expfmt/text_parse.go | parseError | func (p *TextParser) parseError(msg string) {
p.err = ParseError{
Line: p.lineCount,
Msg: msg,
}
} | go | func (p *TextParser) parseError(msg string) {
p.err = ParseError{
Line: p.lineCount,
Msg: msg,
}
} | [
"func",
"(",
"p",
"*",
"TextParser",
")",
"parseError",
"(",
"msg",
"string",
")",
"{",
"p",
".",
"err",
"=",
"ParseError",
"{",
"Line",
":",
"p",
".",
"lineCount",
",",
"Msg",
":",
"msg",
",",
"}",
"\n",
"}"
] | // parseError sets p.err to a ParseError at the current line with the given
// message. | [
"parseError",
"sets",
"p",
".",
"err",
"to",
"a",
"ParseError",
"at",
"the",
"current",
"line",
"with",
"the",
"given",
"message",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/text_parse.go#L518-L523 |
6,435 | prometheus/common | expfmt/text_parse.go | readTokenAsLabelValue | func (p *TextParser) readTokenAsLabelValue() {
p.currentToken.Reset()
escaped := false
for {
if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
return
}
if escaped {
switch p.currentByte {
case '"', '\\':
p.currentToken.WriteByte(p.currentByte)
case 'n':
p.currentToken.WriteByte('\n')
default:
p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
return
}
escaped = false
continue
}
switch p.currentByte {
case '"':
return
case '\n':
p.parseError(fmt.Sprintf("label value %q contains unescaped new-line", p.currentToken.String()))
return
case '\\':
escaped = true
default:
p.currentToken.WriteByte(p.currentByte)
}
}
} | go | func (p *TextParser) readTokenAsLabelValue() {
p.currentToken.Reset()
escaped := false
for {
if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
return
}
if escaped {
switch p.currentByte {
case '"', '\\':
p.currentToken.WriteByte(p.currentByte)
case 'n':
p.currentToken.WriteByte('\n')
default:
p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
return
}
escaped = false
continue
}
switch p.currentByte {
case '"':
return
case '\n':
p.parseError(fmt.Sprintf("label value %q contains unescaped new-line", p.currentToken.String()))
return
case '\\':
escaped = true
default:
p.currentToken.WriteByte(p.currentByte)
}
}
} | [
"func",
"(",
"p",
"*",
"TextParser",
")",
"readTokenAsLabelValue",
"(",
")",
"{",
"p",
".",
"currentToken",
".",
"Reset",
"(",
")",
"\n",
"escaped",
":=",
"false",
"\n",
"for",
"{",
"if",
"p",
".",
"currentByte",
",",
"p",
".",
"err",
"=",
"p",
".",
"buf",
".",
"ReadByte",
"(",
")",
";",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"escaped",
"{",
"switch",
"p",
".",
"currentByte",
"{",
"case",
"'\"'",
",",
"'\\\\'",
":",
"p",
".",
"currentToken",
".",
"WriteByte",
"(",
"p",
".",
"currentByte",
")",
"\n",
"case",
"'n'",
":",
"p",
".",
"currentToken",
".",
"WriteByte",
"(",
"'\\n'",
")",
"\n",
"default",
":",
"p",
".",
"parseError",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\\",
"\"",
",",
"p",
".",
"currentByte",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"escaped",
"=",
"false",
"\n",
"continue",
"\n",
"}",
"\n",
"switch",
"p",
".",
"currentByte",
"{",
"case",
"'\"'",
":",
"return",
"\n",
"case",
"'\\n'",
":",
"p",
".",
"parseError",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"currentToken",
".",
"String",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"case",
"'\\\\'",
":",
"escaped",
"=",
"true",
"\n",
"default",
":",
"p",
".",
"currentToken",
".",
"WriteByte",
"(",
"p",
".",
"currentByte",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // readTokenAsLabelValue copies a label value from p.buf into p.currentToken.
// In contrast to the other 'readTokenAs...' functions, which start with the
// last read byte in p.currentByte, this method ignores p.currentByte and starts
// with reading a new byte from p.buf. The first byte not part of a label value
// is still copied into p.currentByte, but not into p.currentToken. | [
"readTokenAsLabelValue",
"copies",
"a",
"label",
"value",
"from",
"p",
".",
"buf",
"into",
"p",
".",
"currentToken",
".",
"In",
"contrast",
"to",
"the",
"other",
"readTokenAs",
"...",
"functions",
"which",
"start",
"with",
"the",
"last",
"read",
"byte",
"in",
"p",
".",
"currentByte",
"this",
"method",
"ignores",
"p",
".",
"currentByte",
"and",
"starts",
"with",
"reading",
"a",
"new",
"byte",
"from",
"p",
".",
"buf",
".",
"The",
"first",
"byte",
"not",
"part",
"of",
"a",
"label",
"value",
"is",
"still",
"copied",
"into",
"p",
".",
"currentByte",
"but",
"not",
"into",
"p",
".",
"currentToken",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/text_parse.go#L631-L663 |
6,436 | prometheus/common | route/route.go | Param | func Param(ctx context.Context, p string) string {
if v := ctx.Value(param(p)); v != nil {
return v.(string)
}
return ""
} | go | func Param(ctx context.Context, p string) string {
if v := ctx.Value(param(p)); v != nil {
return v.(string)
}
return ""
} | [
"func",
"Param",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"string",
")",
"string",
"{",
"if",
"v",
":=",
"ctx",
".",
"Value",
"(",
"param",
"(",
"p",
")",
")",
";",
"v",
"!=",
"nil",
"{",
"return",
"v",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Param returns param p for the context, or the empty string when
// param does not exist in context. | [
"Param",
"returns",
"param",
"p",
"for",
"the",
"context",
"or",
"the",
"empty",
"string",
"when",
"param",
"does",
"not",
"exist",
"in",
"context",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L27-L32 |
6,437 | prometheus/common | route/route.go | WithParam | func WithParam(ctx context.Context, p, v string) context.Context {
return context.WithValue(ctx, param(p), v)
} | go | func WithParam(ctx context.Context, p, v string) context.Context {
return context.WithValue(ctx, param(p), v)
} | [
"func",
"WithParam",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
",",
"v",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"param",
"(",
"p",
")",
",",
"v",
")",
"\n",
"}"
] | // WithParam returns a new context with param p set to v. | [
"WithParam",
"returns",
"a",
"new",
"context",
"with",
"param",
"p",
"set",
"to",
"v",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L35-L37 |
6,438 | prometheus/common | route/route.go | WithInstrumentation | func (r *Router) WithInstrumentation(instrh func(handlerName string, handler http.HandlerFunc) http.HandlerFunc) *Router {
return &Router{rtr: r.rtr, prefix: r.prefix, instrh: instrh}
} | go | func (r *Router) WithInstrumentation(instrh func(handlerName string, handler http.HandlerFunc) http.HandlerFunc) *Router {
return &Router{rtr: r.rtr, prefix: r.prefix, instrh: instrh}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"WithInstrumentation",
"(",
"instrh",
"func",
"(",
"handlerName",
"string",
",",
"handler",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
")",
"*",
"Router",
"{",
"return",
"&",
"Router",
"{",
"rtr",
":",
"r",
".",
"rtr",
",",
"prefix",
":",
"r",
".",
"prefix",
",",
"instrh",
":",
"instrh",
"}",
"\n",
"}"
] | // WithInstrumentation returns a router with instrumentation support. | [
"WithInstrumentation",
"returns",
"a",
"router",
"with",
"instrumentation",
"support",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L55-L57 |
6,439 | prometheus/common | route/route.go | WithPrefix | func (r *Router) WithPrefix(prefix string) *Router {
return &Router{rtr: r.rtr, prefix: r.prefix + prefix, instrh: r.instrh}
} | go | func (r *Router) WithPrefix(prefix string) *Router {
return &Router{rtr: r.rtr, prefix: r.prefix + prefix, instrh: r.instrh}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"WithPrefix",
"(",
"prefix",
"string",
")",
"*",
"Router",
"{",
"return",
"&",
"Router",
"{",
"rtr",
":",
"r",
".",
"rtr",
",",
"prefix",
":",
"r",
".",
"prefix",
"+",
"prefix",
",",
"instrh",
":",
"r",
".",
"instrh",
"}",
"\n",
"}"
] | // WithPrefix returns a router that prefixes all registered routes with prefix. | [
"WithPrefix",
"returns",
"a",
"router",
"that",
"prefixes",
"all",
"registered",
"routes",
"with",
"prefix",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L60-L62 |
6,440 | prometheus/common | route/route.go | handle | func (r *Router) handle(handlerName string, h http.HandlerFunc) httprouter.Handle {
if r.instrh != nil {
// This needs to be outside the closure to avoid data race when reading and writing to 'h'.
h = r.instrh(handlerName, h)
}
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
for _, p := range params {
ctx = context.WithValue(ctx, param(p.Key), p.Value)
}
h(w, req.WithContext(ctx))
}
} | go | func (r *Router) handle(handlerName string, h http.HandlerFunc) httprouter.Handle {
if r.instrh != nil {
// This needs to be outside the closure to avoid data race when reading and writing to 'h'.
h = r.instrh(handlerName, h)
}
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
for _, p := range params {
ctx = context.WithValue(ctx, param(p.Key), p.Value)
}
h(w, req.WithContext(ctx))
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"handle",
"(",
"handlerName",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"httprouter",
".",
"Handle",
"{",
"if",
"r",
".",
"instrh",
"!=",
"nil",
"{",
"// This needs to be outside the closure to avoid data race when reading and writing to 'h'.",
"h",
"=",
"r",
".",
"instrh",
"(",
"handlerName",
",",
"h",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"httprouter",
".",
"Params",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"req",
".",
"Context",
"(",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"params",
"{",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"param",
"(",
"p",
".",
"Key",
")",
",",
"p",
".",
"Value",
")",
"\n",
"}",
"\n",
"h",
"(",
"w",
",",
"req",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"}",
"\n",
"}"
] | // handle turns a HandlerFunc into an httprouter.Handle. | [
"handle",
"turns",
"a",
"HandlerFunc",
"into",
"an",
"httprouter",
".",
"Handle",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L65-L79 |
6,441 | prometheus/common | route/route.go | Get | func (r *Router) Get(path string, h http.HandlerFunc) {
r.rtr.GET(r.prefix+path, r.handle(path, h))
} | go | func (r *Router) Get(path string, h http.HandlerFunc) {
r.rtr.GET(r.prefix+path, r.handle(path, h))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Get",
"(",
"path",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"rtr",
".",
"GET",
"(",
"r",
".",
"prefix",
"+",
"path",
",",
"r",
".",
"handle",
"(",
"path",
",",
"h",
")",
")",
"\n",
"}"
] | // Get registers a new GET route. | [
"Get",
"registers",
"a",
"new",
"GET",
"route",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L82-L84 |
6,442 | prometheus/common | route/route.go | Options | func (r *Router) Options(path string, h http.HandlerFunc) {
r.rtr.OPTIONS(r.prefix+path, r.handle(path, h))
} | go | func (r *Router) Options(path string, h http.HandlerFunc) {
r.rtr.OPTIONS(r.prefix+path, r.handle(path, h))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Options",
"(",
"path",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"rtr",
".",
"OPTIONS",
"(",
"r",
".",
"prefix",
"+",
"path",
",",
"r",
".",
"handle",
"(",
"path",
",",
"h",
")",
")",
"\n",
"}"
] | // Options registers a new OPTIONS route. | [
"Options",
"registers",
"a",
"new",
"OPTIONS",
"route",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L87-L89 |
6,443 | prometheus/common | route/route.go | Del | func (r *Router) Del(path string, h http.HandlerFunc) {
r.rtr.DELETE(r.prefix+path, r.handle(path, h))
} | go | func (r *Router) Del(path string, h http.HandlerFunc) {
r.rtr.DELETE(r.prefix+path, r.handle(path, h))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Del",
"(",
"path",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"rtr",
".",
"DELETE",
"(",
"r",
".",
"prefix",
"+",
"path",
",",
"r",
".",
"handle",
"(",
"path",
",",
"h",
")",
")",
"\n",
"}"
] | // Del registers a new DELETE route. | [
"Del",
"registers",
"a",
"new",
"DELETE",
"route",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L92-L94 |
6,444 | prometheus/common | route/route.go | Put | func (r *Router) Put(path string, h http.HandlerFunc) {
r.rtr.PUT(r.prefix+path, r.handle(path, h))
} | go | func (r *Router) Put(path string, h http.HandlerFunc) {
r.rtr.PUT(r.prefix+path, r.handle(path, h))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Put",
"(",
"path",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"rtr",
".",
"PUT",
"(",
"r",
".",
"prefix",
"+",
"path",
",",
"r",
".",
"handle",
"(",
"path",
",",
"h",
")",
")",
"\n",
"}"
] | // Put registers a new PUT route. | [
"Put",
"registers",
"a",
"new",
"PUT",
"route",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L97-L99 |
6,445 | prometheus/common | route/route.go | Post | func (r *Router) Post(path string, h http.HandlerFunc) {
r.rtr.POST(r.prefix+path, r.handle(path, h))
} | go | func (r *Router) Post(path string, h http.HandlerFunc) {
r.rtr.POST(r.prefix+path, r.handle(path, h))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Post",
"(",
"path",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"rtr",
".",
"POST",
"(",
"r",
".",
"prefix",
"+",
"path",
",",
"r",
".",
"handle",
"(",
"path",
",",
"h",
")",
")",
"\n",
"}"
] | // Post registers a new POST route. | [
"Post",
"registers",
"a",
"new",
"POST",
"route",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L102-L104 |
6,446 | prometheus/common | route/route.go | Redirect | func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
http.Redirect(w, req, r.prefix+path, code)
} | go | func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
http.Redirect(w, req, r.prefix+path, code)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Redirect",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"path",
"string",
",",
"code",
"int",
")",
"{",
"http",
".",
"Redirect",
"(",
"w",
",",
"req",
",",
"r",
".",
"prefix",
"+",
"path",
",",
"code",
")",
"\n",
"}"
] | // Redirect takes an absolute path and sends an internal HTTP redirect for it,
// prefixed by the router's path prefix. Note that this method does not include
// functionality for handling relative paths or full URL redirects. | [
"Redirect",
"takes",
"an",
"absolute",
"path",
"and",
"sends",
"an",
"internal",
"HTTP",
"redirect",
"for",
"it",
"prefixed",
"by",
"the",
"router",
"s",
"path",
"prefix",
".",
"Note",
"that",
"this",
"method",
"does",
"not",
"include",
"functionality",
"for",
"handling",
"relative",
"paths",
"or",
"full",
"URL",
"redirects",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/route/route.go#L109-L111 |
6,447 | prometheus/common | expfmt/decode.go | ResponseFormat | func ResponseFormat(h http.Header) Format {
ct := h.Get(hdrContentType)
mediatype, params, err := mime.ParseMediaType(ct)
if err != nil {
return FmtUnknown
}
const textType = "text/plain"
switch mediatype {
case ProtoType:
if p, ok := params["proto"]; ok && p != ProtoProtocol {
return FmtUnknown
}
if e, ok := params["encoding"]; ok && e != "delimited" {
return FmtUnknown
}
return FmtProtoDelim
case textType:
if v, ok := params["version"]; ok && v != TextVersion {
return FmtUnknown
}
return FmtText
}
return FmtUnknown
} | go | func ResponseFormat(h http.Header) Format {
ct := h.Get(hdrContentType)
mediatype, params, err := mime.ParseMediaType(ct)
if err != nil {
return FmtUnknown
}
const textType = "text/plain"
switch mediatype {
case ProtoType:
if p, ok := params["proto"]; ok && p != ProtoProtocol {
return FmtUnknown
}
if e, ok := params["encoding"]; ok && e != "delimited" {
return FmtUnknown
}
return FmtProtoDelim
case textType:
if v, ok := params["version"]; ok && v != TextVersion {
return FmtUnknown
}
return FmtText
}
return FmtUnknown
} | [
"func",
"ResponseFormat",
"(",
"h",
"http",
".",
"Header",
")",
"Format",
"{",
"ct",
":=",
"h",
".",
"Get",
"(",
"hdrContentType",
")",
"\n\n",
"mediatype",
",",
"params",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"ct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"FmtUnknown",
"\n",
"}",
"\n\n",
"const",
"textType",
"=",
"\"",
"\"",
"\n\n",
"switch",
"mediatype",
"{",
"case",
"ProtoType",
":",
"if",
"p",
",",
"ok",
":=",
"params",
"[",
"\"",
"\"",
"]",
";",
"ok",
"&&",
"p",
"!=",
"ProtoProtocol",
"{",
"return",
"FmtUnknown",
"\n",
"}",
"\n",
"if",
"e",
",",
"ok",
":=",
"params",
"[",
"\"",
"\"",
"]",
";",
"ok",
"&&",
"e",
"!=",
"\"",
"\"",
"{",
"return",
"FmtUnknown",
"\n",
"}",
"\n",
"return",
"FmtProtoDelim",
"\n\n",
"case",
"textType",
":",
"if",
"v",
",",
"ok",
":=",
"params",
"[",
"\"",
"\"",
"]",
";",
"ok",
"&&",
"v",
"!=",
"TextVersion",
"{",
"return",
"FmtUnknown",
"\n",
"}",
"\n",
"return",
"FmtText",
"\n",
"}",
"\n\n",
"return",
"FmtUnknown",
"\n",
"}"
] | // ResponseFormat extracts the correct format from a HTTP response header.
// If no matching format can be found FormatUnknown is returned. | [
"ResponseFormat",
"extracts",
"the",
"correct",
"format",
"from",
"a",
"HTTP",
"response",
"header",
".",
"If",
"no",
"matching",
"format",
"can",
"be",
"found",
"FormatUnknown",
"is",
"returned",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/decode.go#L42-L70 |
6,448 | prometheus/common | expfmt/decode.go | NewDecoder | func NewDecoder(r io.Reader, format Format) Decoder {
switch format {
case FmtProtoDelim:
return &protoDecoder{r: r}
}
return &textDecoder{r: r}
} | go | func NewDecoder(r io.Reader, format Format) Decoder {
switch format {
case FmtProtoDelim:
return &protoDecoder{r: r}
}
return &textDecoder{r: r}
} | [
"func",
"NewDecoder",
"(",
"r",
"io",
".",
"Reader",
",",
"format",
"Format",
")",
"Decoder",
"{",
"switch",
"format",
"{",
"case",
"FmtProtoDelim",
":",
"return",
"&",
"protoDecoder",
"{",
"r",
":",
"r",
"}",
"\n",
"}",
"\n",
"return",
"&",
"textDecoder",
"{",
"r",
":",
"r",
"}",
"\n",
"}"
] | // NewDecoder returns a new decoder based on the given input format.
// If the input format does not imply otherwise, a text format decoder is returned. | [
"NewDecoder",
"returns",
"a",
"new",
"decoder",
"based",
"on",
"the",
"given",
"input",
"format",
".",
"If",
"the",
"input",
"format",
"does",
"not",
"imply",
"otherwise",
"a",
"text",
"format",
"decoder",
"is",
"returned",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/decode.go#L74-L80 |
6,449 | prometheus/common | expfmt/decode.go | Decode | func (sd *SampleDecoder) Decode(s *model.Vector) error {
err := sd.Dec.Decode(&sd.f)
if err != nil {
return err
}
*s, err = extractSamples(&sd.f, sd.Opts)
return err
} | go | func (sd *SampleDecoder) Decode(s *model.Vector) error {
err := sd.Dec.Decode(&sd.f)
if err != nil {
return err
}
*s, err = extractSamples(&sd.f, sd.Opts)
return err
} | [
"func",
"(",
"sd",
"*",
"SampleDecoder",
")",
"Decode",
"(",
"s",
"*",
"model",
".",
"Vector",
")",
"error",
"{",
"err",
":=",
"sd",
".",
"Dec",
".",
"Decode",
"(",
"&",
"sd",
".",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"s",
",",
"err",
"=",
"extractSamples",
"(",
"&",
"sd",
".",
"f",
",",
"sd",
".",
"Opts",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Decode calls the Decode method of the wrapped Decoder and then extracts the
// samples from the decoded MetricFamily into the provided model.Vector. | [
"Decode",
"calls",
"the",
"Decode",
"method",
"of",
"the",
"wrapped",
"Decoder",
"and",
"then",
"extracts",
"the",
"samples",
"from",
"the",
"decoded",
"MetricFamily",
"into",
"the",
"provided",
"model",
".",
"Vector",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/decode.go#L157-L164 |
6,450 | prometheus/common | expfmt/decode.go | ExtractSamples | func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) {
var (
all model.Vector
lastErr error
)
for _, f := range fams {
some, err := extractSamples(f, o)
if err != nil {
lastErr = err
continue
}
all = append(all, some...)
}
return all, lastErr
} | go | func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) {
var (
all model.Vector
lastErr error
)
for _, f := range fams {
some, err := extractSamples(f, o)
if err != nil {
lastErr = err
continue
}
all = append(all, some...)
}
return all, lastErr
} | [
"func",
"ExtractSamples",
"(",
"o",
"*",
"DecodeOptions",
",",
"fams",
"...",
"*",
"dto",
".",
"MetricFamily",
")",
"(",
"model",
".",
"Vector",
",",
"error",
")",
"{",
"var",
"(",
"all",
"model",
".",
"Vector",
"\n",
"lastErr",
"error",
"\n",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"fams",
"{",
"some",
",",
"err",
":=",
"extractSamples",
"(",
"f",
",",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"lastErr",
"=",
"err",
"\n",
"continue",
"\n",
"}",
"\n",
"all",
"=",
"append",
"(",
"all",
",",
"some",
"...",
")",
"\n",
"}",
"\n",
"return",
"all",
",",
"lastErr",
"\n",
"}"
] | // ExtractSamples builds a slice of samples from the provided metric
// families. If an error occurrs during sample extraction, it continues to
// extract from the remaining metric families. The returned error is the last
// error that has occurred. | [
"ExtractSamples",
"builds",
"a",
"slice",
"of",
"samples",
"from",
"the",
"provided",
"metric",
"families",
".",
"If",
"an",
"error",
"occurrs",
"during",
"sample",
"extraction",
"it",
"continues",
"to",
"extract",
"from",
"the",
"remaining",
"metric",
"families",
".",
"The",
"returned",
"error",
"is",
"the",
"last",
"error",
"that",
"has",
"occurred",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/decode.go#L170-L184 |
6,451 | prometheus/common | config/config.go | UnmarshalYAML | func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain Secret
return unmarshal((*plain)(s))
} | go | func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain Secret
return unmarshal((*plain)(s))
} | [
"func",
"(",
"s",
"*",
"Secret",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"type",
"plain",
"Secret",
"\n",
"return",
"unmarshal",
"(",
"(",
"*",
"plain",
")",
"(",
"s",
")",
")",
"\n",
"}"
] | //UnmarshalYAML implements the yaml.Unmarshaler interface for Secrets. | [
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Unmarshaler",
"interface",
"for",
"Secrets",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/config/config.go#L31-L34 |
6,452 | prometheus/common | expfmt/text_create.go | MetricFamilyToText | func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err error) {
// Fail-fast checks.
if len(in.Metric) == 0 {
return 0, fmt.Errorf("MetricFamily has no metrics: %s", in)
}
name := in.GetName()
if name == "" {
return 0, fmt.Errorf("MetricFamily has no name: %s", in)
}
// Try the interface upgrade. If it doesn't work, we'll use a
// bytes.Buffer from the sync.Pool and write out its content to out in a
// single go in the end.
w, ok := out.(enhancedWriter)
if !ok {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
w = b
defer func() {
bWritten, bErr := out.Write(b.Bytes())
written = bWritten
if err == nil {
err = bErr
}
bufPool.Put(b)
}()
}
var n int
// Comments, first HELP, then TYPE.
if in.Help != nil {
n, err = w.WriteString("# HELP ")
written += n
if err != nil {
return
}
n, err = w.WriteString(name)
written += n
if err != nil {
return
}
err = w.WriteByte(' ')
written++
if err != nil {
return
}
n, err = writeEscapedString(w, *in.Help, false)
written += n
if err != nil {
return
}
err = w.WriteByte('\n')
written++
if err != nil {
return
}
}
n, err = w.WriteString("# TYPE ")
written += n
if err != nil {
return
}
n, err = w.WriteString(name)
written += n
if err != nil {
return
}
metricType := in.GetType()
switch metricType {
case dto.MetricType_COUNTER:
n, err = w.WriteString(" counter\n")
case dto.MetricType_GAUGE:
n, err = w.WriteString(" gauge\n")
case dto.MetricType_SUMMARY:
n, err = w.WriteString(" summary\n")
case dto.MetricType_UNTYPED:
n, err = w.WriteString(" untyped\n")
case dto.MetricType_HISTOGRAM:
n, err = w.WriteString(" histogram\n")
default:
return written, fmt.Errorf("unknown metric type %s", metricType.String())
}
written += n
if err != nil {
return
}
// Finally the samples, one line for each.
for _, metric := range in.Metric {
switch metricType {
case dto.MetricType_COUNTER:
if metric.Counter == nil {
return written, fmt.Errorf(
"expected counter in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Counter.GetValue(),
)
case dto.MetricType_GAUGE:
if metric.Gauge == nil {
return written, fmt.Errorf(
"expected gauge in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Gauge.GetValue(),
)
case dto.MetricType_UNTYPED:
if metric.Untyped == nil {
return written, fmt.Errorf(
"expected untyped in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Untyped.GetValue(),
)
case dto.MetricType_SUMMARY:
if metric.Summary == nil {
return written, fmt.Errorf(
"expected summary in metric %s %s", name, metric,
)
}
for _, q := range metric.Summary.Quantile {
n, err = writeSample(
w, name, "", metric,
model.QuantileLabel, q.GetQuantile(),
q.GetValue(),
)
written += n
if err != nil {
return
}
}
n, err = writeSample(
w, name, "_sum", metric, "", 0,
metric.Summary.GetSampleSum(),
)
written += n
if err != nil {
return
}
n, err = writeSample(
w, name, "_count", metric, "", 0,
float64(metric.Summary.GetSampleCount()),
)
case dto.MetricType_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", name, metric,
)
}
infSeen := false
for _, b := range metric.Histogram.Bucket {
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, b.GetUpperBound(),
float64(b.GetCumulativeCount()),
)
written += n
if err != nil {
return
}
if math.IsInf(b.GetUpperBound(), +1) {
infSeen = true
}
}
if !infSeen {
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, math.Inf(+1),
float64(metric.Histogram.GetSampleCount()),
)
written += n
if err != nil {
return
}
}
n, err = writeSample(
w, name, "_sum", metric, "", 0,
metric.Histogram.GetSampleSum(),
)
written += n
if err != nil {
return
}
n, err = writeSample(
w, name, "_count", metric, "", 0,
float64(metric.Histogram.GetSampleCount()),
)
default:
return written, fmt.Errorf(
"unexpected type in metric %s %s", name, metric,
)
}
written += n
if err != nil {
return
}
}
return
} | go | func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err error) {
// Fail-fast checks.
if len(in.Metric) == 0 {
return 0, fmt.Errorf("MetricFamily has no metrics: %s", in)
}
name := in.GetName()
if name == "" {
return 0, fmt.Errorf("MetricFamily has no name: %s", in)
}
// Try the interface upgrade. If it doesn't work, we'll use a
// bytes.Buffer from the sync.Pool and write out its content to out in a
// single go in the end.
w, ok := out.(enhancedWriter)
if !ok {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
w = b
defer func() {
bWritten, bErr := out.Write(b.Bytes())
written = bWritten
if err == nil {
err = bErr
}
bufPool.Put(b)
}()
}
var n int
// Comments, first HELP, then TYPE.
if in.Help != nil {
n, err = w.WriteString("# HELP ")
written += n
if err != nil {
return
}
n, err = w.WriteString(name)
written += n
if err != nil {
return
}
err = w.WriteByte(' ')
written++
if err != nil {
return
}
n, err = writeEscapedString(w, *in.Help, false)
written += n
if err != nil {
return
}
err = w.WriteByte('\n')
written++
if err != nil {
return
}
}
n, err = w.WriteString("# TYPE ")
written += n
if err != nil {
return
}
n, err = w.WriteString(name)
written += n
if err != nil {
return
}
metricType := in.GetType()
switch metricType {
case dto.MetricType_COUNTER:
n, err = w.WriteString(" counter\n")
case dto.MetricType_GAUGE:
n, err = w.WriteString(" gauge\n")
case dto.MetricType_SUMMARY:
n, err = w.WriteString(" summary\n")
case dto.MetricType_UNTYPED:
n, err = w.WriteString(" untyped\n")
case dto.MetricType_HISTOGRAM:
n, err = w.WriteString(" histogram\n")
default:
return written, fmt.Errorf("unknown metric type %s", metricType.String())
}
written += n
if err != nil {
return
}
// Finally the samples, one line for each.
for _, metric := range in.Metric {
switch metricType {
case dto.MetricType_COUNTER:
if metric.Counter == nil {
return written, fmt.Errorf(
"expected counter in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Counter.GetValue(),
)
case dto.MetricType_GAUGE:
if metric.Gauge == nil {
return written, fmt.Errorf(
"expected gauge in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Gauge.GetValue(),
)
case dto.MetricType_UNTYPED:
if metric.Untyped == nil {
return written, fmt.Errorf(
"expected untyped in metric %s %s", name, metric,
)
}
n, err = writeSample(
w, name, "", metric, "", 0,
metric.Untyped.GetValue(),
)
case dto.MetricType_SUMMARY:
if metric.Summary == nil {
return written, fmt.Errorf(
"expected summary in metric %s %s", name, metric,
)
}
for _, q := range metric.Summary.Quantile {
n, err = writeSample(
w, name, "", metric,
model.QuantileLabel, q.GetQuantile(),
q.GetValue(),
)
written += n
if err != nil {
return
}
}
n, err = writeSample(
w, name, "_sum", metric, "", 0,
metric.Summary.GetSampleSum(),
)
written += n
if err != nil {
return
}
n, err = writeSample(
w, name, "_count", metric, "", 0,
float64(metric.Summary.GetSampleCount()),
)
case dto.MetricType_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", name, metric,
)
}
infSeen := false
for _, b := range metric.Histogram.Bucket {
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, b.GetUpperBound(),
float64(b.GetCumulativeCount()),
)
written += n
if err != nil {
return
}
if math.IsInf(b.GetUpperBound(), +1) {
infSeen = true
}
}
if !infSeen {
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, math.Inf(+1),
float64(metric.Histogram.GetSampleCount()),
)
written += n
if err != nil {
return
}
}
n, err = writeSample(
w, name, "_sum", metric, "", 0,
metric.Histogram.GetSampleSum(),
)
written += n
if err != nil {
return
}
n, err = writeSample(
w, name, "_count", metric, "", 0,
float64(metric.Histogram.GetSampleCount()),
)
default:
return written, fmt.Errorf(
"unexpected type in metric %s %s", name, metric,
)
}
written += n
if err != nil {
return
}
}
return
} | [
"func",
"MetricFamilyToText",
"(",
"out",
"io",
".",
"Writer",
",",
"in",
"*",
"dto",
".",
"MetricFamily",
")",
"(",
"written",
"int",
",",
"err",
"error",
")",
"{",
"// Fail-fast checks.",
"if",
"len",
"(",
"in",
".",
"Metric",
")",
"==",
"0",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"in",
")",
"\n",
"}",
"\n",
"name",
":=",
"in",
".",
"GetName",
"(",
")",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"in",
")",
"\n",
"}",
"\n\n",
"// Try the interface upgrade. If it doesn't work, we'll use a",
"// bytes.Buffer from the sync.Pool and write out its content to out in a",
"// single go in the end.",
"w",
",",
"ok",
":=",
"out",
".",
"(",
"enhancedWriter",
")",
"\n",
"if",
"!",
"ok",
"{",
"b",
":=",
"bufPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"bytes",
".",
"Buffer",
")",
"\n",
"b",
".",
"Reset",
"(",
")",
"\n",
"w",
"=",
"b",
"\n",
"defer",
"func",
"(",
")",
"{",
"bWritten",
",",
"bErr",
":=",
"out",
".",
"Write",
"(",
"b",
".",
"Bytes",
"(",
")",
")",
"\n",
"written",
"=",
"bWritten",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"bErr",
"\n",
"}",
"\n",
"bufPool",
".",
"Put",
"(",
"b",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"n",
"int",
"\n\n",
"// Comments, first HELP, then TYPE.",
"if",
"in",
".",
"Help",
"!=",
"nil",
"{",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"name",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"w",
".",
"WriteByte",
"(",
"' '",
")",
"\n",
"written",
"++",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeEscapedString",
"(",
"w",
",",
"*",
"in",
".",
"Help",
",",
"false",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"w",
".",
"WriteByte",
"(",
"'\\n'",
")",
"\n",
"written",
"++",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"name",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"metricType",
":=",
"in",
".",
"GetType",
"(",
")",
"\n",
"switch",
"metricType",
"{",
"case",
"dto",
".",
"MetricType_COUNTER",
":",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"case",
"dto",
".",
"MetricType_GAUGE",
":",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"case",
"dto",
".",
"MetricType_SUMMARY",
":",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"case",
"dto",
".",
"MetricType_UNTYPED",
":",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"case",
"dto",
".",
"MetricType_HISTOGRAM",
":",
"n",
",",
"err",
"=",
"w",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"default",
":",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"metricType",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Finally the samples, one line for each.",
"for",
"_",
",",
"metric",
":=",
"range",
"in",
".",
"Metric",
"{",
"switch",
"metricType",
"{",
"case",
"dto",
".",
"MetricType_COUNTER",
":",
"if",
"metric",
".",
"Counter",
"==",
"nil",
"{",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"metric",
".",
"Counter",
".",
"GetValue",
"(",
")",
",",
")",
"\n",
"case",
"dto",
".",
"MetricType_GAUGE",
":",
"if",
"metric",
".",
"Gauge",
"==",
"nil",
"{",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"metric",
".",
"Gauge",
".",
"GetValue",
"(",
")",
",",
")",
"\n",
"case",
"dto",
".",
"MetricType_UNTYPED",
":",
"if",
"metric",
".",
"Untyped",
"==",
"nil",
"{",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"metric",
".",
"Untyped",
".",
"GetValue",
"(",
")",
",",
")",
"\n",
"case",
"dto",
".",
"MetricType_SUMMARY",
":",
"if",
"metric",
".",
"Summary",
"==",
"nil",
"{",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"q",
":=",
"range",
"metric",
".",
"Summary",
".",
"Quantile",
"{",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"model",
".",
"QuantileLabel",
",",
"q",
".",
"GetQuantile",
"(",
")",
",",
"q",
".",
"GetValue",
"(",
")",
",",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"metric",
".",
"Summary",
".",
"GetSampleSum",
"(",
")",
",",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"float64",
"(",
"metric",
".",
"Summary",
".",
"GetSampleCount",
"(",
")",
")",
",",
")",
"\n",
"case",
"dto",
".",
"MetricType_HISTOGRAM",
":",
"if",
"metric",
".",
"Histogram",
"==",
"nil",
"{",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"infSeen",
":=",
"false",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"metric",
".",
"Histogram",
".",
"Bucket",
"{",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"model",
".",
"BucketLabel",
",",
"b",
".",
"GetUpperBound",
"(",
")",
",",
"float64",
"(",
"b",
".",
"GetCumulativeCount",
"(",
")",
")",
",",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"math",
".",
"IsInf",
"(",
"b",
".",
"GetUpperBound",
"(",
")",
",",
"+",
"1",
")",
"{",
"infSeen",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"infSeen",
"{",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"model",
".",
"BucketLabel",
",",
"math",
".",
"Inf",
"(",
"+",
"1",
")",
",",
"float64",
"(",
"metric",
".",
"Histogram",
".",
"GetSampleCount",
"(",
")",
")",
",",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"metric",
".",
"Histogram",
".",
"GetSampleSum",
"(",
")",
",",
")",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"writeSample",
"(",
"w",
",",
"name",
",",
"\"",
"\"",
",",
"metric",
",",
"\"",
"\"",
",",
"0",
",",
"float64",
"(",
"metric",
".",
"Histogram",
".",
"GetSampleCount",
"(",
")",
")",
",",
")",
"\n",
"default",
":",
"return",
"written",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"metric",
",",
")",
"\n",
"}",
"\n",
"written",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // MetricFamilyToText converts a MetricFamily proto message into text format and
// writes the resulting lines to 'out'. It returns the number of bytes written
// and any error encountered. The output will have the same order as the input,
// no further sorting is performed. Furthermore, this function assumes the input
// is already sanitized and does not perform any sanity checks. If the input
// contains duplicate metrics or invalid metric or label names, the conversion
// will result in invalid text format output.
//
// This method fulfills the type 'prometheus.encoder'. | [
"MetricFamilyToText",
"converts",
"a",
"MetricFamily",
"proto",
"message",
"into",
"text",
"format",
"and",
"writes",
"the",
"resulting",
"lines",
"to",
"out",
".",
"It",
"returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"encountered",
".",
"The",
"output",
"will",
"have",
"the",
"same",
"order",
"as",
"the",
"input",
"no",
"further",
"sorting",
"is",
"performed",
".",
"Furthermore",
"this",
"function",
"assumes",
"the",
"input",
"is",
"already",
"sanitized",
"and",
"does",
"not",
"perform",
"any",
"sanity",
"checks",
".",
"If",
"the",
"input",
"contains",
"duplicate",
"metrics",
"or",
"invalid",
"metric",
"or",
"label",
"names",
"the",
"conversion",
"will",
"result",
"in",
"invalid",
"text",
"format",
"output",
".",
"This",
"method",
"fulfills",
"the",
"type",
"prometheus",
".",
"encoder",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/text_create.go#L67-L272 |
6,453 | prometheus/common | expfmt/text_create.go | writeFloat | func writeFloat(w enhancedWriter, f float64) (int, error) {
switch {
case f == 1:
return 1, w.WriteByte('1')
case f == 0:
return 1, w.WriteByte('0')
case f == -1:
return w.WriteString("-1")
case math.IsNaN(f):
return w.WriteString("NaN")
case math.IsInf(f, +1):
return w.WriteString("+Inf")
case math.IsInf(f, -1):
return w.WriteString("-Inf")
default:
bp := numBufPool.Get().(*[]byte)
*bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64)
written, err := w.Write(*bp)
numBufPool.Put(bp)
return written, err
}
} | go | func writeFloat(w enhancedWriter, f float64) (int, error) {
switch {
case f == 1:
return 1, w.WriteByte('1')
case f == 0:
return 1, w.WriteByte('0')
case f == -1:
return w.WriteString("-1")
case math.IsNaN(f):
return w.WriteString("NaN")
case math.IsInf(f, +1):
return w.WriteString("+Inf")
case math.IsInf(f, -1):
return w.WriteString("-Inf")
default:
bp := numBufPool.Get().(*[]byte)
*bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64)
written, err := w.Write(*bp)
numBufPool.Put(bp)
return written, err
}
} | [
"func",
"writeFloat",
"(",
"w",
"enhancedWriter",
",",
"f",
"float64",
")",
"(",
"int",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"f",
"==",
"1",
":",
"return",
"1",
",",
"w",
".",
"WriteByte",
"(",
"'1'",
")",
"\n",
"case",
"f",
"==",
"0",
":",
"return",
"1",
",",
"w",
".",
"WriteByte",
"(",
"'0'",
")",
"\n",
"case",
"f",
"==",
"-",
"1",
":",
"return",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"case",
"math",
".",
"IsNaN",
"(",
"f",
")",
":",
"return",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"case",
"math",
".",
"IsInf",
"(",
"f",
",",
"+",
"1",
")",
":",
"return",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"case",
"math",
".",
"IsInf",
"(",
"f",
",",
"-",
"1",
")",
":",
"return",
"w",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"default",
":",
"bp",
":=",
"numBufPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"[",
"]",
"byte",
")",
"\n",
"*",
"bp",
"=",
"strconv",
".",
"AppendFloat",
"(",
"(",
"*",
"bp",
")",
"[",
":",
"0",
"]",
",",
"f",
",",
"'g'",
",",
"-",
"1",
",",
"64",
")",
"\n",
"written",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"*",
"bp",
")",
"\n",
"numBufPool",
".",
"Put",
"(",
"bp",
")",
"\n",
"return",
"written",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // writeFloat is equivalent to fmt.Fprint with a float64 argument but hardcodes
// a few common cases for increased efficiency. For non-hardcoded cases, it uses
// strconv.AppendFloat to avoid allocations, similar to writeInt. | [
"writeFloat",
"is",
"equivalent",
"to",
"fmt",
".",
"Fprint",
"with",
"a",
"float64",
"argument",
"but",
"hardcodes",
"a",
"few",
"common",
"cases",
"for",
"increased",
"efficiency",
".",
"For",
"non",
"-",
"hardcoded",
"cases",
"it",
"uses",
"strconv",
".",
"AppendFloat",
"to",
"avoid",
"allocations",
"similar",
"to",
"writeInt",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/text_create.go#L436-L457 |
6,454 | prometheus/common | expfmt/text_create.go | writeInt | func writeInt(w enhancedWriter, i int64) (int, error) {
bp := numBufPool.Get().(*[]byte)
*bp = strconv.AppendInt((*bp)[:0], i, 10)
written, err := w.Write(*bp)
numBufPool.Put(bp)
return written, err
} | go | func writeInt(w enhancedWriter, i int64) (int, error) {
bp := numBufPool.Get().(*[]byte)
*bp = strconv.AppendInt((*bp)[:0], i, 10)
written, err := w.Write(*bp)
numBufPool.Put(bp)
return written, err
} | [
"func",
"writeInt",
"(",
"w",
"enhancedWriter",
",",
"i",
"int64",
")",
"(",
"int",
",",
"error",
")",
"{",
"bp",
":=",
"numBufPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"[",
"]",
"byte",
")",
"\n",
"*",
"bp",
"=",
"strconv",
".",
"AppendInt",
"(",
"(",
"*",
"bp",
")",
"[",
":",
"0",
"]",
",",
"i",
",",
"10",
")",
"\n",
"written",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"*",
"bp",
")",
"\n",
"numBufPool",
".",
"Put",
"(",
"bp",
")",
"\n",
"return",
"written",
",",
"err",
"\n",
"}"
] | // writeInt is equivalent to fmt.Fprint with an int64 argument but uses
// strconv.AppendInt with a byte slice taken from a sync.Pool to avoid
// allocations. | [
"writeInt",
"is",
"equivalent",
"to",
"fmt",
".",
"Fprint",
"with",
"an",
"int64",
"argument",
"but",
"uses",
"strconv",
".",
"AppendInt",
"with",
"a",
"byte",
"slice",
"taken",
"from",
"a",
"sync",
".",
"Pool",
"to",
"avoid",
"allocations",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/expfmt/text_create.go#L462-L468 |
6,455 | prometheus/common | model/alert.go | Validate | func (a *Alert) Validate() error {
if a.StartsAt.IsZero() {
return fmt.Errorf("start time missing")
}
if !a.EndsAt.IsZero() && a.EndsAt.Before(a.StartsAt) {
return fmt.Errorf("start time must be before end time")
}
if err := a.Labels.Validate(); err != nil {
return fmt.Errorf("invalid label set: %s", err)
}
if len(a.Labels) == 0 {
return fmt.Errorf("at least one label pair required")
}
if err := a.Annotations.Validate(); err != nil {
return fmt.Errorf("invalid annotations: %s", err)
}
return nil
} | go | func (a *Alert) Validate() error {
if a.StartsAt.IsZero() {
return fmt.Errorf("start time missing")
}
if !a.EndsAt.IsZero() && a.EndsAt.Before(a.StartsAt) {
return fmt.Errorf("start time must be before end time")
}
if err := a.Labels.Validate(); err != nil {
return fmt.Errorf("invalid label set: %s", err)
}
if len(a.Labels) == 0 {
return fmt.Errorf("at least one label pair required")
}
if err := a.Annotations.Validate(); err != nil {
return fmt.Errorf("invalid annotations: %s", err)
}
return nil
} | [
"func",
"(",
"a",
"*",
"Alert",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"a",
".",
"StartsAt",
".",
"IsZero",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"a",
".",
"EndsAt",
".",
"IsZero",
"(",
")",
"&&",
"a",
".",
"EndsAt",
".",
"Before",
"(",
"a",
".",
"StartsAt",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"Labels",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"a",
".",
"Labels",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"Annotations",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate checks whether the alert data is inconsistent. | [
"Validate",
"checks",
"whether",
"the",
"alert",
"data",
"is",
"inconsistent",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/alert.go#L85-L102 |
6,456 | prometheus/common | model/alert.go | HasFiring | func (as Alerts) HasFiring() bool {
for _, a := range as {
if !a.Resolved() {
return true
}
}
return false
} | go | func (as Alerts) HasFiring() bool {
for _, a := range as {
if !a.Resolved() {
return true
}
}
return false
} | [
"func",
"(",
"as",
"Alerts",
")",
"HasFiring",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"as",
"{",
"if",
"!",
"a",
".",
"Resolved",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasFiring returns true iff one of the alerts is not resolved. | [
"HasFiring",
"returns",
"true",
"iff",
"one",
"of",
"the",
"alerts",
"is",
"not",
"resolved",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/alert.go#L121-L128 |
6,457 | prometheus/common | model/labels.go | IsValid | func (ln LabelName) IsValid() bool {
if len(ln) == 0 {
return false
}
for i, b := range ln {
if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || (b >= '0' && b <= '9' && i > 0)) {
return false
}
}
return true
} | go | func (ln LabelName) IsValid() bool {
if len(ln) == 0 {
return false
}
for i, b := range ln {
if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || (b >= '0' && b <= '9' && i > 0)) {
return false
}
}
return true
} | [
"func",
"(",
"ln",
"LabelName",
")",
"IsValid",
"(",
")",
"bool",
"{",
"if",
"len",
"(",
"ln",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"ln",
"{",
"if",
"!",
"(",
"(",
"b",
">=",
"'a'",
"&&",
"b",
"<=",
"'z'",
")",
"||",
"(",
"b",
">=",
"'A'",
"&&",
"b",
"<=",
"'Z'",
")",
"||",
"b",
"==",
"'_'",
"||",
"(",
"b",
">=",
"'0'",
"&&",
"b",
"<=",
"'9'",
"&&",
"i",
">",
"0",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // IsValid is true iff the label name matches the pattern of LabelNameRE. This
// method, however, does not use LabelNameRE for the check but a much faster
// hardcoded implementation. | [
"IsValid",
"is",
"true",
"iff",
"the",
"label",
"name",
"matches",
"the",
"pattern",
"of",
"LabelNameRE",
".",
"This",
"method",
"however",
"does",
"not",
"use",
"LabelNameRE",
"for",
"the",
"check",
"but",
"a",
"much",
"faster",
"hardcoded",
"implementation",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/labels.go#L95-L105 |
6,458 | prometheus/common | model/silence.go | Validate | func (m *Matcher) Validate() error {
if !m.Name.IsValid() {
return fmt.Errorf("invalid name %q", m.Name)
}
if m.IsRegex {
if _, err := regexp.Compile(m.Value); err != nil {
return fmt.Errorf("invalid regular expression %q", m.Value)
}
} else if !LabelValue(m.Value).IsValid() || len(m.Value) == 0 {
return fmt.Errorf("invalid value %q", m.Value)
}
return nil
} | go | func (m *Matcher) Validate() error {
if !m.Name.IsValid() {
return fmt.Errorf("invalid name %q", m.Name)
}
if m.IsRegex {
if _, err := regexp.Compile(m.Value); err != nil {
return fmt.Errorf("invalid regular expression %q", m.Value)
}
} else if !LabelValue(m.Value).IsValid() || len(m.Value) == 0 {
return fmt.Errorf("invalid value %q", m.Value)
}
return nil
} | [
"func",
"(",
"m",
"*",
"Matcher",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"!",
"m",
".",
"Name",
".",
"IsValid",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"IsRegex",
"{",
"if",
"_",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"m",
".",
"Value",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"LabelValue",
"(",
"m",
".",
"Value",
")",
".",
"IsValid",
"(",
")",
"||",
"len",
"(",
"m",
".",
"Value",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
".",
"Value",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns true iff all fields of the matcher have valid values. | [
"Validate",
"returns",
"true",
"iff",
"all",
"fields",
"of",
"the",
"matcher",
"have",
"valid",
"values",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/silence.go#L48-L60 |
6,459 | prometheus/common | model/silence.go | Validate | func (s *Silence) Validate() error {
if len(s.Matchers) == 0 {
return fmt.Errorf("at least one matcher required")
}
for _, m := range s.Matchers {
if err := m.Validate(); err != nil {
return fmt.Errorf("invalid matcher: %s", err)
}
}
if s.StartsAt.IsZero() {
return fmt.Errorf("start time missing")
}
if s.EndsAt.IsZero() {
return fmt.Errorf("end time missing")
}
if s.EndsAt.Before(s.StartsAt) {
return fmt.Errorf("start time must be before end time")
}
if s.CreatedBy == "" {
return fmt.Errorf("creator information missing")
}
if s.Comment == "" {
return fmt.Errorf("comment missing")
}
if s.CreatedAt.IsZero() {
return fmt.Errorf("creation timestamp missing")
}
return nil
} | go | func (s *Silence) Validate() error {
if len(s.Matchers) == 0 {
return fmt.Errorf("at least one matcher required")
}
for _, m := range s.Matchers {
if err := m.Validate(); err != nil {
return fmt.Errorf("invalid matcher: %s", err)
}
}
if s.StartsAt.IsZero() {
return fmt.Errorf("start time missing")
}
if s.EndsAt.IsZero() {
return fmt.Errorf("end time missing")
}
if s.EndsAt.Before(s.StartsAt) {
return fmt.Errorf("start time must be before end time")
}
if s.CreatedBy == "" {
return fmt.Errorf("creator information missing")
}
if s.Comment == "" {
return fmt.Errorf("comment missing")
}
if s.CreatedAt.IsZero() {
return fmt.Errorf("creation timestamp missing")
}
return nil
} | [
"func",
"(",
"s",
"*",
"Silence",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"s",
".",
"Matchers",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"s",
".",
"Matchers",
"{",
"if",
"err",
":=",
"m",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"s",
".",
"StartsAt",
".",
"IsZero",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"EndsAt",
".",
"IsZero",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"EndsAt",
".",
"Before",
"(",
"s",
".",
"StartsAt",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"CreatedBy",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"Comment",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"CreatedAt",
".",
"IsZero",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns true iff all fields of the silence have valid values. | [
"Validate",
"returns",
"true",
"iff",
"all",
"fields",
"of",
"the",
"silence",
"have",
"valid",
"values",
"."
] | c873fb1f9420b83ee703b4361c61183b4619f74d | https://github.com/prometheus/common/blob/c873fb1f9420b83ee703b4361c61183b4619f74d/model/silence.go#L78-L106 |
6,460 | dustin/go-coap | client.go | Dial | func Dial(n, addr string) (*Conn, error) {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return nil, err
}
s, err := net.DialUDP("udp", nil, uaddr)
if err != nil {
return nil, err
}
return &Conn{s, make([]byte, maxPktLen)}, nil
} | go | func Dial(n, addr string) (*Conn, error) {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return nil, err
}
s, err := net.DialUDP("udp", nil, uaddr)
if err != nil {
return nil, err
}
return &Conn{s, make([]byte, maxPktLen)}, nil
} | [
"func",
"Dial",
"(",
"n",
",",
"addr",
"string",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"uaddr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"n",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
",",
"err",
":=",
"net",
".",
"DialUDP",
"(",
"\"",
"\"",
",",
"nil",
",",
"uaddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Conn",
"{",
"s",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"maxPktLen",
")",
"}",
",",
"nil",
"\n",
"}"
] | // Dial connects a CoAP client. | [
"Dial",
"connects",
"a",
"CoAP",
"client",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/client.go#L26-L38 |
6,461 | dustin/go-coap | client.go | Send | func (c *Conn) Send(req Message) (*Message, error) {
err := Transmit(c.conn, nil, req)
if err != nil {
return nil, err
}
if !req.IsConfirmable() {
return nil, nil
}
rv, err := Receive(c.conn, c.buf)
if err != nil {
return nil, err
}
return &rv, nil
} | go | func (c *Conn) Send(req Message) (*Message, error) {
err := Transmit(c.conn, nil, req)
if err != nil {
return nil, err
}
if !req.IsConfirmable() {
return nil, nil
}
rv, err := Receive(c.conn, c.buf)
if err != nil {
return nil, err
}
return &rv, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Send",
"(",
"req",
"Message",
")",
"(",
"*",
"Message",
",",
"error",
")",
"{",
"err",
":=",
"Transmit",
"(",
"c",
".",
"conn",
",",
"nil",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"req",
".",
"IsConfirmable",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"rv",
",",
"err",
":=",
"Receive",
"(",
"c",
".",
"conn",
",",
"c",
".",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"rv",
",",
"nil",
"\n",
"}"
] | // Send a message. Get a response if there is one. | [
"Send",
"a",
"message",
".",
"Get",
"a",
"response",
"if",
"there",
"is",
"one",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/client.go#L41-L57 |
6,462 | dustin/go-coap | servmux.go | pathMatch | func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
} | go | func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
} | [
"func",
"pathMatch",
"(",
"pattern",
",",
"path",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"pattern",
")",
"==",
"0",
"{",
"// should not happen",
"return",
"false",
"\n",
"}",
"\n",
"n",
":=",
"len",
"(",
"pattern",
")",
"\n",
"if",
"pattern",
"[",
"n",
"-",
"1",
"]",
"!=",
"'/'",
"{",
"return",
"pattern",
"==",
"path",
"\n",
"}",
"\n",
"return",
"len",
"(",
"path",
")",
">=",
"n",
"&&",
"path",
"[",
"0",
":",
"n",
"]",
"==",
"pattern",
"\n",
"}"
] | // Does path match pattern? | [
"Does",
"path",
"match",
"pattern?"
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/servmux.go#L22-L32 |
6,463 | dustin/go-coap | servmux.go | ServeCOAP | func (mux *ServeMux) ServeCOAP(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message {
h, _ := mux.match(m.PathString())
if h == nil {
h, _ = funcHandler(notFoundHandler), ""
}
// TODO: Rewrite path?
return h.ServeCOAP(l, a, m)
} | go | func (mux *ServeMux) ServeCOAP(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message {
h, _ := mux.match(m.PathString())
if h == nil {
h, _ = funcHandler(notFoundHandler), ""
}
// TODO: Rewrite path?
return h.ServeCOAP(l, a, m)
} | [
"func",
"(",
"mux",
"*",
"ServeMux",
")",
"ServeCOAP",
"(",
"l",
"*",
"net",
".",
"UDPConn",
",",
"a",
"*",
"net",
".",
"UDPAddr",
",",
"m",
"*",
"Message",
")",
"*",
"Message",
"{",
"h",
",",
"_",
":=",
"mux",
".",
"match",
"(",
"m",
".",
"PathString",
"(",
")",
")",
"\n",
"if",
"h",
"==",
"nil",
"{",
"h",
",",
"_",
"=",
"funcHandler",
"(",
"notFoundHandler",
")",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"// TODO: Rewrite path?",
"return",
"h",
".",
"ServeCOAP",
"(",
"l",
",",
"a",
",",
"m",
")",
"\n",
"}"
] | // ServeCOAP handles a single COAP message. The message arrives from
// the given listener having originated from the given UDPAddr. | [
"ServeCOAP",
"handles",
"a",
"single",
"COAP",
"message",
".",
"The",
"message",
"arrives",
"from",
"the",
"given",
"listener",
"having",
"originated",
"from",
"the",
"given",
"UDPAddr",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/servmux.go#L65-L72 |
6,464 | dustin/go-coap | servmux.go | Handle | func (mux *ServeMux) Handle(pattern string, handler Handler) {
for pattern != "" && pattern[0] == '/' {
pattern = pattern[1:]
}
if pattern == "" {
panic("http: invalid pattern " + pattern)
}
if handler == nil {
panic("http: nil handler")
}
mux.m[pattern] = muxEntry{h: handler, pattern: pattern}
} | go | func (mux *ServeMux) Handle(pattern string, handler Handler) {
for pattern != "" && pattern[0] == '/' {
pattern = pattern[1:]
}
if pattern == "" {
panic("http: invalid pattern " + pattern)
}
if handler == nil {
panic("http: nil handler")
}
mux.m[pattern] = muxEntry{h: handler, pattern: pattern}
} | [
"func",
"(",
"mux",
"*",
"ServeMux",
")",
"Handle",
"(",
"pattern",
"string",
",",
"handler",
"Handler",
")",
"{",
"for",
"pattern",
"!=",
"\"",
"\"",
"&&",
"pattern",
"[",
"0",
"]",
"==",
"'/'",
"{",
"pattern",
"=",
"pattern",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"if",
"pattern",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"pattern",
")",
"\n",
"}",
"\n",
"if",
"handler",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"mux",
".",
"m",
"[",
"pattern",
"]",
"=",
"muxEntry",
"{",
"h",
":",
"handler",
",",
"pattern",
":",
"pattern",
"}",
"\n",
"}"
] | // Handle configures a handler for the given path. | [
"Handle",
"configures",
"a",
"handler",
"for",
"the",
"given",
"path",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/servmux.go#L75-L88 |
6,465 | dustin/go-coap | servmux.go | HandleFunc | func (mux *ServeMux) HandleFunc(pattern string,
f func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message) {
mux.Handle(pattern, FuncHandler(f))
} | go | func (mux *ServeMux) HandleFunc(pattern string,
f func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message) {
mux.Handle(pattern, FuncHandler(f))
} | [
"func",
"(",
"mux",
"*",
"ServeMux",
")",
"HandleFunc",
"(",
"pattern",
"string",
",",
"f",
"func",
"(",
"l",
"*",
"net",
".",
"UDPConn",
",",
"a",
"*",
"net",
".",
"UDPAddr",
",",
"m",
"*",
"Message",
")",
"*",
"Message",
")",
"{",
"mux",
".",
"Handle",
"(",
"pattern",
",",
"FuncHandler",
"(",
"f",
")",
")",
"\n",
"}"
] | // HandleFunc configures a handler for the given path. | [
"HandleFunc",
"configures",
"a",
"handler",
"for",
"the",
"given",
"path",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/servmux.go#L91-L94 |
6,466 | dustin/go-coap | server.go | FuncHandler | func FuncHandler(f func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message) Handler {
return funcHandler(f)
} | go | func FuncHandler(f func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message) Handler {
return funcHandler(f)
} | [
"func",
"FuncHandler",
"(",
"f",
"func",
"(",
"l",
"*",
"net",
".",
"UDPConn",
",",
"a",
"*",
"net",
".",
"UDPAddr",
",",
"m",
"*",
"Message",
")",
"*",
"Message",
")",
"Handler",
"{",
"return",
"funcHandler",
"(",
"f",
")",
"\n",
"}"
] | // FuncHandler builds a handler from a function. | [
"FuncHandler",
"builds",
"a",
"handler",
"from",
"a",
"function",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/server.go#L25-L27 |
6,467 | dustin/go-coap | server.go | Transmit | func Transmit(l *net.UDPConn, a *net.UDPAddr, m Message) error {
d, err := m.MarshalBinary()
if err != nil {
return err
}
if a == nil {
_, err = l.Write(d)
} else {
_, err = l.WriteTo(d, a)
}
return err
} | go | func Transmit(l *net.UDPConn, a *net.UDPAddr, m Message) error {
d, err := m.MarshalBinary()
if err != nil {
return err
}
if a == nil {
_, err = l.Write(d)
} else {
_, err = l.WriteTo(d, a)
}
return err
} | [
"func",
"Transmit",
"(",
"l",
"*",
"net",
".",
"UDPConn",
",",
"a",
"*",
"net",
".",
"UDPAddr",
",",
"m",
"Message",
")",
"error",
"{",
"d",
",",
"err",
":=",
"m",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"a",
"==",
"nil",
"{",
"_",
",",
"err",
"=",
"l",
".",
"Write",
"(",
"d",
")",
"\n",
"}",
"else",
"{",
"_",
",",
"err",
"=",
"l",
".",
"WriteTo",
"(",
"d",
",",
"a",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Transmit a message. | [
"Transmit",
"a",
"message",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/server.go#L45-L57 |
6,468 | dustin/go-coap | server.go | ListenAndServe | func ListenAndServe(n, addr string, rh Handler) error {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return err
}
l, err := net.ListenUDP(n, uaddr)
if err != nil {
return err
}
return Serve(l, rh)
} | go | func ListenAndServe(n, addr string, rh Handler) error {
uaddr, err := net.ResolveUDPAddr(n, addr)
if err != nil {
return err
}
l, err := net.ListenUDP(n, uaddr)
if err != nil {
return err
}
return Serve(l, rh)
} | [
"func",
"ListenAndServe",
"(",
"n",
",",
"addr",
"string",
",",
"rh",
"Handler",
")",
"error",
"{",
"uaddr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"n",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"l",
",",
"err",
":=",
"net",
".",
"ListenUDP",
"(",
"n",
",",
"uaddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"Serve",
"(",
"l",
",",
"rh",
")",
"\n",
"}"
] | // ListenAndServe binds to the given address and serve requests forever. | [
"ListenAndServe",
"binds",
"to",
"the",
"given",
"address",
"and",
"serve",
"requests",
"forever",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/server.go#L71-L83 |
6,469 | dustin/go-coap | message.go | Options | func (m Message) Options(o OptionID) []interface{} {
var rv []interface{}
for _, v := range m.opts {
if o == v.ID {
rv = append(rv, v.Value)
}
}
return rv
} | go | func (m Message) Options(o OptionID) []interface{} {
var rv []interface{}
for _, v := range m.opts {
if o == v.ID {
rv = append(rv, v.Value)
}
}
return rv
} | [
"func",
"(",
"m",
"Message",
")",
"Options",
"(",
"o",
"OptionID",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"var",
"rv",
"[",
"]",
"interface",
"{",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"m",
".",
"opts",
"{",
"if",
"o",
"==",
"v",
".",
"ID",
"{",
"rv",
"=",
"append",
"(",
"rv",
",",
"v",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"rv",
"\n",
"}"
] | // Options gets all the values for the given option. | [
"Options",
"gets",
"all",
"the",
"values",
"for",
"the",
"given",
"option",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L354-L364 |
6,470 | dustin/go-coap | message.go | Option | func (m Message) Option(o OptionID) interface{} {
for _, v := range m.opts {
if o == v.ID {
return v.Value
}
}
return nil
} | go | func (m Message) Option(o OptionID) interface{} {
for _, v := range m.opts {
if o == v.ID {
return v.Value
}
}
return nil
} | [
"func",
"(",
"m",
"Message",
")",
"Option",
"(",
"o",
"OptionID",
")",
"interface",
"{",
"}",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"m",
".",
"opts",
"{",
"if",
"o",
"==",
"v",
".",
"ID",
"{",
"return",
"v",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Option gets the first value for the given option ID. | [
"Option",
"gets",
"the",
"first",
"value",
"for",
"the",
"given",
"option",
"ID",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L367-L374 |
6,471 | dustin/go-coap | message.go | RemoveOption | func (m *Message) RemoveOption(opID OptionID) {
m.opts = m.opts.Minus(opID)
} | go | func (m *Message) RemoveOption(opID OptionID) {
m.opts = m.opts.Minus(opID)
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"RemoveOption",
"(",
"opID",
"OptionID",
")",
"{",
"m",
".",
"opts",
"=",
"m",
".",
"opts",
".",
"Minus",
"(",
"opID",
")",
"\n",
"}"
] | // RemoveOption removes all references to an option | [
"RemoveOption",
"removes",
"all",
"references",
"to",
"an",
"option"
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L408-L410 |
6,472 | dustin/go-coap | message.go | AddOption | func (m *Message) AddOption(opID OptionID, val interface{}) {
iv := reflect.ValueOf(val)
if (iv.Kind() == reflect.Slice || iv.Kind() == reflect.Array) &&
iv.Type().Elem().Kind() == reflect.String {
for i := 0; i < iv.Len(); i++ {
m.opts = append(m.opts, option{opID, iv.Index(i).Interface()})
}
return
}
m.opts = append(m.opts, option{opID, val})
} | go | func (m *Message) AddOption(opID OptionID, val interface{}) {
iv := reflect.ValueOf(val)
if (iv.Kind() == reflect.Slice || iv.Kind() == reflect.Array) &&
iv.Type().Elem().Kind() == reflect.String {
for i := 0; i < iv.Len(); i++ {
m.opts = append(m.opts, option{opID, iv.Index(i).Interface()})
}
return
}
m.opts = append(m.opts, option{opID, val})
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"AddOption",
"(",
"opID",
"OptionID",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"iv",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n",
"if",
"(",
"iv",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"||",
"iv",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Array",
")",
"&&",
"iv",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"String",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"iv",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"m",
".",
"opts",
"=",
"append",
"(",
"m",
".",
"opts",
",",
"option",
"{",
"opID",
",",
"iv",
".",
"Index",
"(",
"i",
")",
".",
"Interface",
"(",
")",
"}",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"m",
".",
"opts",
"=",
"append",
"(",
"m",
".",
"opts",
",",
"option",
"{",
"opID",
",",
"val",
"}",
")",
"\n",
"}"
] | // AddOption adds an option. | [
"AddOption",
"adds",
"an",
"option",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L413-L423 |
6,473 | dustin/go-coap | message.go | SetOption | func (m *Message) SetOption(opID OptionID, val interface{}) {
m.RemoveOption(opID)
m.AddOption(opID, val)
} | go | func (m *Message) SetOption(opID OptionID, val interface{}) {
m.RemoveOption(opID)
m.AddOption(opID, val)
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"SetOption",
"(",
"opID",
"OptionID",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"m",
".",
"RemoveOption",
"(",
"opID",
")",
"\n",
"m",
".",
"AddOption",
"(",
"opID",
",",
"val",
")",
"\n",
"}"
] | // SetOption sets an option, discarding any previous value | [
"SetOption",
"sets",
"an",
"option",
"discarding",
"any",
"previous",
"value"
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L426-L429 |
6,474 | dustin/go-coap | message.go | MarshalBinary | func (m *Message) MarshalBinary() ([]byte, error) {
tmpbuf := []byte{0, 0}
binary.BigEndian.PutUint16(tmpbuf, m.MessageID)
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| T | TKL | Code | Message ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Token (if any, TKL bytes) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 1 1 1 1 1 1 1| Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
buf := bytes.Buffer{}
buf.Write([]byte{
(1 << 6) | (uint8(m.Type) << 4) | uint8(0xf&len(m.Token)),
byte(m.Code),
tmpbuf[0], tmpbuf[1],
})
buf.Write(m.Token)
/*
0 1 2 3 4 5 6 7
+---------------+---------------+
| | |
| Option Delta | Option Length | 1 byte
| | |
+---------------+---------------+
\ \
/ Option Delta / 0-2 bytes
\ (extended) \
+-------------------------------+
\ \
/ Option Length / 0-2 bytes
\ (extended) \
+-------------------------------+
\ \
/ /
\ \
/ Option Value / 0 or more bytes
\ \
/ /
\ \
+-------------------------------+
See parseExtOption(), extendOption()
and writeOptionHeader() below for implementation details
*/
extendOpt := func(opt int) (int, int) {
ext := 0
if opt >= extoptByteAddend {
if opt >= extoptWordAddend {
ext = opt - extoptWordAddend
opt = extoptWordCode
} else {
ext = opt - extoptByteAddend
opt = extoptByteCode
}
}
return opt, ext
}
writeOptHeader := func(delta, length int) {
d, dx := extendOpt(delta)
l, lx := extendOpt(length)
buf.WriteByte(byte(d<<4) | byte(l))
tmp := []byte{0, 0}
writeExt := func(opt, ext int) {
switch opt {
case extoptByteCode:
buf.WriteByte(byte(ext))
case extoptWordCode:
binary.BigEndian.PutUint16(tmp, uint16(ext))
buf.Write(tmp)
}
}
writeExt(d, dx)
writeExt(l, lx)
}
sort.Stable(&m.opts)
prev := 0
for _, o := range m.opts {
b := o.toBytes()
writeOptHeader(int(o.ID)-prev, len(b))
buf.Write(b)
prev = int(o.ID)
}
if len(m.Payload) > 0 {
buf.Write([]byte{0xff})
}
buf.Write(m.Payload)
return buf.Bytes(), nil
} | go | func (m *Message) MarshalBinary() ([]byte, error) {
tmpbuf := []byte{0, 0}
binary.BigEndian.PutUint16(tmpbuf, m.MessageID)
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| T | TKL | Code | Message ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Token (if any, TKL bytes) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 1 1 1 1 1 1 1| Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
buf := bytes.Buffer{}
buf.Write([]byte{
(1 << 6) | (uint8(m.Type) << 4) | uint8(0xf&len(m.Token)),
byte(m.Code),
tmpbuf[0], tmpbuf[1],
})
buf.Write(m.Token)
/*
0 1 2 3 4 5 6 7
+---------------+---------------+
| | |
| Option Delta | Option Length | 1 byte
| | |
+---------------+---------------+
\ \
/ Option Delta / 0-2 bytes
\ (extended) \
+-------------------------------+
\ \
/ Option Length / 0-2 bytes
\ (extended) \
+-------------------------------+
\ \
/ /
\ \
/ Option Value / 0 or more bytes
\ \
/ /
\ \
+-------------------------------+
See parseExtOption(), extendOption()
and writeOptionHeader() below for implementation details
*/
extendOpt := func(opt int) (int, int) {
ext := 0
if opt >= extoptByteAddend {
if opt >= extoptWordAddend {
ext = opt - extoptWordAddend
opt = extoptWordCode
} else {
ext = opt - extoptByteAddend
opt = extoptByteCode
}
}
return opt, ext
}
writeOptHeader := func(delta, length int) {
d, dx := extendOpt(delta)
l, lx := extendOpt(length)
buf.WriteByte(byte(d<<4) | byte(l))
tmp := []byte{0, 0}
writeExt := func(opt, ext int) {
switch opt {
case extoptByteCode:
buf.WriteByte(byte(ext))
case extoptWordCode:
binary.BigEndian.PutUint16(tmp, uint16(ext))
buf.Write(tmp)
}
}
writeExt(d, dx)
writeExt(l, lx)
}
sort.Stable(&m.opts)
prev := 0
for _, o := range m.opts {
b := o.toBytes()
writeOptHeader(int(o.ID)-prev, len(b))
buf.Write(b)
prev = int(o.ID)
}
if len(m.Payload) > 0 {
buf.Write([]byte{0xff})
}
buf.Write(m.Payload)
return buf.Bytes(), nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"tmpbuf",
":=",
"[",
"]",
"byte",
"{",
"0",
",",
"0",
"}",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"tmpbuf",
",",
"m",
".",
"MessageID",
")",
"\n\n",
"/*\n\t 0 1 2 3\n\t 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t |Ver| T | TKL | Code | Message ID |\n\t +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t | Token (if any, TKL bytes) ...\n\t +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t | Options (if any) ...\n\t +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t |1 1 1 1 1 1 1 1| Payload (if any) ...\n\t +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t*/",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"(",
"1",
"<<",
"6",
")",
"|",
"(",
"uint8",
"(",
"m",
".",
"Type",
")",
"<<",
"4",
")",
"|",
"uint8",
"(",
"0xf",
"&",
"len",
"(",
"m",
".",
"Token",
")",
")",
",",
"byte",
"(",
"m",
".",
"Code",
")",
",",
"tmpbuf",
"[",
"0",
"]",
",",
"tmpbuf",
"[",
"1",
"]",
",",
"}",
")",
"\n",
"buf",
".",
"Write",
"(",
"m",
".",
"Token",
")",
"\n\n",
"/*\n\t 0 1 2 3 4 5 6 7\n\t +---------------+---------------+\n\t | | |\n\t | Option Delta | Option Length | 1 byte\n\t | | |\n\t +---------------+---------------+\n\t \\ \\\n\t / Option Delta / 0-2 bytes\n\t \\ (extended) \\\n\t +-------------------------------+\n\t \\ \\\n\t / Option Length / 0-2 bytes\n\t \\ (extended) \\\n\t +-------------------------------+\n\t \\ \\\n\t / /\n\t \\ \\\n\t / Option Value / 0 or more bytes\n\t \\ \\\n\t / /\n\t \\ \\\n\t +-------------------------------+\n\n\t See parseExtOption(), extendOption()\n\t and writeOptionHeader() below for implementation details\n\t*/",
"extendOpt",
":=",
"func",
"(",
"opt",
"int",
")",
"(",
"int",
",",
"int",
")",
"{",
"ext",
":=",
"0",
"\n",
"if",
"opt",
">=",
"extoptByteAddend",
"{",
"if",
"opt",
">=",
"extoptWordAddend",
"{",
"ext",
"=",
"opt",
"-",
"extoptWordAddend",
"\n",
"opt",
"=",
"extoptWordCode",
"\n",
"}",
"else",
"{",
"ext",
"=",
"opt",
"-",
"extoptByteAddend",
"\n",
"opt",
"=",
"extoptByteCode",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"opt",
",",
"ext",
"\n",
"}",
"\n\n",
"writeOptHeader",
":=",
"func",
"(",
"delta",
",",
"length",
"int",
")",
"{",
"d",
",",
"dx",
":=",
"extendOpt",
"(",
"delta",
")",
"\n",
"l",
",",
"lx",
":=",
"extendOpt",
"(",
"length",
")",
"\n\n",
"buf",
".",
"WriteByte",
"(",
"byte",
"(",
"d",
"<<",
"4",
")",
"|",
"byte",
"(",
"l",
")",
")",
"\n\n",
"tmp",
":=",
"[",
"]",
"byte",
"{",
"0",
",",
"0",
"}",
"\n",
"writeExt",
":=",
"func",
"(",
"opt",
",",
"ext",
"int",
")",
"{",
"switch",
"opt",
"{",
"case",
"extoptByteCode",
":",
"buf",
".",
"WriteByte",
"(",
"byte",
"(",
"ext",
")",
")",
"\n",
"case",
"extoptWordCode",
":",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"tmp",
",",
"uint16",
"(",
"ext",
")",
")",
"\n",
"buf",
".",
"Write",
"(",
"tmp",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"writeExt",
"(",
"d",
",",
"dx",
")",
"\n",
"writeExt",
"(",
"l",
",",
"lx",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Stable",
"(",
"&",
"m",
".",
"opts",
")",
"\n\n",
"prev",
":=",
"0",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"m",
".",
"opts",
"{",
"b",
":=",
"o",
".",
"toBytes",
"(",
")",
"\n",
"writeOptHeader",
"(",
"int",
"(",
"o",
".",
"ID",
")",
"-",
"prev",
",",
"len",
"(",
"b",
")",
")",
"\n",
"buf",
".",
"Write",
"(",
"b",
")",
"\n",
"prev",
"=",
"int",
"(",
"o",
".",
"ID",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"m",
".",
"Payload",
")",
">",
"0",
"{",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"0xff",
"}",
")",
"\n",
"}",
"\n\n",
"buf",
".",
"Write",
"(",
"m",
".",
"Payload",
")",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary produces the binary form of this Message. | [
"MarshalBinary",
"produces",
"the",
"binary",
"form",
"of",
"this",
"Message",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L440-L547 |
6,475 | dustin/go-coap | message.go | ParseMessage | func ParseMessage(data []byte) (Message, error) {
rv := Message{}
return rv, rv.UnmarshalBinary(data)
} | go | func ParseMessage(data []byte) (Message, error) {
rv := Message{}
return rv, rv.UnmarshalBinary(data)
} | [
"func",
"ParseMessage",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"Message",
",",
"error",
")",
"{",
"rv",
":=",
"Message",
"{",
"}",
"\n",
"return",
"rv",
",",
"rv",
".",
"UnmarshalBinary",
"(",
"data",
")",
"\n",
"}"
] | // ParseMessage extracts the Message from the given input. | [
"ParseMessage",
"extracts",
"the",
"Message",
"from",
"the",
"given",
"input",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/message.go#L550-L553 |
6,476 | dustin/go-coap | messagetcp.go | Decode | func Decode(r io.Reader) (*TcpMessage, error) {
var ln uint16
err := binary.Read(r, binary.BigEndian, &ln)
if err != nil {
return nil, err
}
packet := make([]byte, ln)
_, err = io.ReadFull(r, packet)
if err != nil {
return nil, err
}
m := TcpMessage{}
err = m.UnmarshalBinary(packet)
return &m, err
} | go | func Decode(r io.Reader) (*TcpMessage, error) {
var ln uint16
err := binary.Read(r, binary.BigEndian, &ln)
if err != nil {
return nil, err
}
packet := make([]byte, ln)
_, err = io.ReadFull(r, packet)
if err != nil {
return nil, err
}
m := TcpMessage{}
err = m.UnmarshalBinary(packet)
return &m, err
} | [
"func",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"TcpMessage",
",",
"error",
")",
"{",
"var",
"ln",
"uint16",
"\n",
"err",
":=",
"binary",
".",
"Read",
"(",
"r",
",",
"binary",
".",
"BigEndian",
",",
"&",
"ln",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"packet",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"ln",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"packet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"m",
":=",
"TcpMessage",
"{",
"}",
"\n\n",
"err",
"=",
"m",
".",
"UnmarshalBinary",
"(",
"packet",
")",
"\n",
"return",
"&",
"m",
",",
"err",
"\n",
"}"
] | // Decode reads a single message from its input. | [
"Decode",
"reads",
"a",
"single",
"message",
"from",
"its",
"input",
"."
] | ddcc80675fa42611359d91a6dfa5aa57fb90e72b | https://github.com/dustin/go-coap/blob/ddcc80675fa42611359d91a6dfa5aa57fb90e72b/messagetcp.go#L52-L69 |
6,477 | santhosh-tekuri/jsonschema | formats.go | isDate | func isDate(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := time.Parse("2006-01-02", s)
return err == nil
} | go | func isDate(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := time.Parse("2006-01-02", s)
return err == nil
} | [
"func",
"isDate",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] | // isDate tells whether given string is a valid full-date production
// as defined by RFC 3339, section 5.6. | [
"isDate",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"full",
"-",
"date",
"production",
"as",
"defined",
"by",
"RFC",
"3339",
"section",
"5",
".",
"6",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L62-L69 |
6,478 | santhosh-tekuri/jsonschema | formats.go | isTime | func isTime(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
if _, err := time.Parse("15:04:05Z07:00", s); err == nil {
return true
}
if _, err := time.Parse("15:04:05.999999999Z07:00", s); err == nil {
return true
}
return false
} | go | func isTime(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
if _, err := time.Parse("15:04:05Z07:00", s); err == nil {
return true
}
if _, err := time.Parse("15:04:05.999999999Z07:00", s); err == nil {
return true
}
return false
} | [
"func",
"isTime",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"s",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"s",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isTime tells whether given string is a valid full-time production
// as defined by RFC 3339, section 5.6. | [
"isTime",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"full",
"-",
"time",
"production",
"as",
"defined",
"by",
"RFC",
"3339",
"section",
"5",
".",
"6",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L73-L85 |
6,479 | santhosh-tekuri/jsonschema | formats.go | isIPV4 | func isIPV4(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
groups := strings.Split(s, ".")
if len(groups) != 4 {
return false
}
for _, group := range groups {
n, err := strconv.Atoi(group)
if err != nil {
return false
}
if n < 0 || n > 255 {
return false
}
}
return true
} | go | func isIPV4(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
groups := strings.Split(s, ".")
if len(groups) != 4 {
return false
}
for _, group := range groups {
n, err := strconv.Atoi(group)
if err != nil {
return false
}
if n < 0 || n > 255 {
return false
}
}
return true
} | [
"func",
"isIPV4",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"groups",
":=",
"strings",
".",
"Split",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"groups",
")",
"!=",
"4",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"group",
":=",
"range",
"groups",
"{",
"n",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"group",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"n",
"<",
"0",
"||",
"n",
">",
"255",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // isIPV4 tells whether given string is a valid representation of an IPv4 address
// according to the "dotted-quad" ABNF syntax as defined in RFC 2673, section 3.2. | [
"isIPV4",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"representation",
"of",
"an",
"IPv4",
"address",
"according",
"to",
"the",
"dotted",
"-",
"quad",
"ABNF",
"syntax",
"as",
"defined",
"in",
"RFC",
"2673",
"section",
"3",
".",
"2",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L172-L191 |
6,480 | santhosh-tekuri/jsonschema | formats.go | isIPV6 | func isIPV6(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
if !strings.Contains(s, ":") {
return false
}
return net.ParseIP(s) != nil
} | go | func isIPV6(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
if !strings.Contains(s, ":") {
return false
}
return net.ParseIP(s) != nil
} | [
"func",
"isIPV6",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"s",
",",
"\"",
"\"",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"net",
".",
"ParseIP",
"(",
"s",
")",
"!=",
"nil",
"\n",
"}"
] | // isIPV6 tells whether given string is a valid representation of an IPv6 address
// as defined in RFC 2373, section 2.2. | [
"isIPV6",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"representation",
"of",
"an",
"IPv6",
"address",
"as",
"defined",
"in",
"RFC",
"2373",
"section",
"2",
".",
"2",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L195-L204 |
6,481 | santhosh-tekuri/jsonschema | formats.go | isURI | func isURI(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
u, err := url.Parse(s)
return err == nil && u.IsAbs()
} | go | func isURI(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
u, err := url.Parse(s)
return err == nil && u.IsAbs()
} | [
"func",
"isURI",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"u",
".",
"IsAbs",
"(",
")",
"\n",
"}"
] | // isURI tells whether given string is valid URI, according to RFC 3986. | [
"isURI",
"tells",
"whether",
"given",
"string",
"is",
"valid",
"URI",
"according",
"to",
"RFC",
"3986",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L207-L214 |
6,482 | santhosh-tekuri/jsonschema | formats.go | isURITemplate | func isURITemplate(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
u, err := url.Parse(s)
if err != nil {
return false
}
for _, item := range strings.Split(u.RawPath, "/") {
depth := 0
for _, ch := range item {
switch ch {
case '{':
depth++
if depth != 1 {
return false
}
case '}':
depth--
if depth != 0 {
return false
}
}
}
if depth != 0 {
return false
}
}
return true
} | go | func isURITemplate(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
u, err := url.Parse(s)
if err != nil {
return false
}
for _, item := range strings.Split(u.RawPath, "/") {
depth := 0
for _, ch := range item {
switch ch {
case '{':
depth++
if depth != 1 {
return false
}
case '}':
depth--
if depth != 0 {
return false
}
}
}
if depth != 0 {
return false
}
}
return true
} | [
"func",
"isURITemplate",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"strings",
".",
"Split",
"(",
"u",
".",
"RawPath",
",",
"\"",
"\"",
")",
"{",
"depth",
":=",
"0",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"item",
"{",
"switch",
"ch",
"{",
"case",
"'{'",
":",
"depth",
"++",
"\n",
"if",
"depth",
"!=",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"'}'",
":",
"depth",
"--",
"\n",
"if",
"depth",
"!=",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"depth",
"!=",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // isURITemplate tells whether given string is a valid URI Template
// according to RFC6570.
//
// Current implementation does minimal validation. | [
"isURITemplate",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"URI",
"Template",
"according",
"to",
"RFC6570",
".",
"Current",
"implementation",
"does",
"minimal",
"validation",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L231-L261 |
6,483 | santhosh-tekuri/jsonschema | formats.go | isRegex | func isRegex(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := regexp.Compile(s)
return err == nil
} | go | func isRegex(v interface{}) bool {
s, ok := v.(string)
if !ok {
return false
}
_, err := regexp.Compile(s)
return err == nil
} | [
"func",
"isRegex",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"s",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] | // isRegex tells whether given string is a valid regular expression,
// according to the ECMA 262 regular expression dialect.
//
// The implementation uses go-lang regexp package. | [
"isRegex",
"tells",
"whether",
"given",
"string",
"is",
"a",
"valid",
"regular",
"expression",
"according",
"to",
"the",
"ECMA",
"262",
"regular",
"expression",
"dialect",
".",
"The",
"implementation",
"uses",
"go",
"-",
"lang",
"regexp",
"package",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/formats.go#L267-L274 |
6,484 | santhosh-tekuri/jsonschema | resource.go | DecodeJSON | func DecodeJSON(r io.Reader) (interface{}, error) {
decoder := json.NewDecoder(r)
decoder.UseNumber()
var doc interface{}
if err := decoder.Decode(&doc); err != nil {
return nil, err
}
if t, _ := decoder.Token(); t != nil {
return nil, fmt.Errorf("invalid character %v after top-level value", t)
}
return doc, nil
} | go | func DecodeJSON(r io.Reader) (interface{}, error) {
decoder := json.NewDecoder(r)
decoder.UseNumber()
var doc interface{}
if err := decoder.Decode(&doc); err != nil {
return nil, err
}
if t, _ := decoder.Token(); t != nil {
return nil, fmt.Errorf("invalid character %v after top-level value", t)
}
return doc, nil
} | [
"func",
"DecodeJSON",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"decoder",
".",
"UseNumber",
"(",
")",
"\n",
"var",
"doc",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"t",
",",
"_",
":=",
"decoder",
".",
"Token",
"(",
")",
";",
"t",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"}",
"\n",
"return",
"doc",
",",
"nil",
"\n",
"}"
] | // DecodeJSON decodes json document from r.
//
// Note that number is decoded into json.Number instead of as a float64 | [
"DecodeJSON",
"decodes",
"json",
"document",
"from",
"r",
".",
"Note",
"that",
"number",
"is",
"decoded",
"into",
"json",
".",
"Number",
"instead",
"of",
"as",
"a",
"float64"
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/resource.go#L28-L39 |
6,485 | santhosh-tekuri/jsonschema | schema.go | jsonType | func jsonType(v interface{}) string {
switch v.(type) {
case nil:
return "null"
case bool:
return "boolean"
case json.Number, float64, int, int32, int64:
return "number"
case string:
return "string"
case []interface{}:
return "array"
case map[string]interface{}:
return "object"
}
panic(InvalidJSONTypeError(fmt.Sprintf("%T", v)))
} | go | func jsonType(v interface{}) string {
switch v.(type) {
case nil:
return "null"
case bool:
return "boolean"
case json.Number, float64, int, int32, int64:
return "number"
case string:
return "string"
case []interface{}:
return "array"
case map[string]interface{}:
return "object"
}
panic(InvalidJSONTypeError(fmt.Sprintf("%T", v)))
} | [
"func",
"jsonType",
"(",
"v",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"v",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"\"",
"\"",
"\n",
"case",
"bool",
":",
"return",
"\"",
"\"",
"\n",
"case",
"json",
".",
"Number",
",",
"float64",
",",
"int",
",",
"int32",
",",
"int64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"string",
":",
"return",
"\"",
"\"",
"\n",
"case",
"[",
"]",
"interface",
"{",
"}",
":",
"return",
"\"",
"\"",
"\n",
"case",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"panic",
"(",
"InvalidJSONTypeError",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
")",
")",
")",
"\n",
"}"
] | // jsonType returns the json type of given value v.
//
// It panics if the given value is not valid json value | [
"jsonType",
"returns",
"the",
"json",
"type",
"of",
"given",
"value",
"v",
".",
"It",
"panics",
"if",
"the",
"given",
"value",
"is",
"not",
"valid",
"json",
"value"
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/schema.go#L491-L507 |
6,486 | santhosh-tekuri/jsonschema | schema.go | equals | func equals(v1, v2 interface{}) bool {
v1Type := jsonType(v1)
if v1Type != jsonType(v2) {
return false
}
switch v1Type {
case "array":
arr1, arr2 := v1.([]interface{}), v2.([]interface{})
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if !equals(arr1[i], arr2[i]) {
return false
}
}
return true
case "object":
obj1, obj2 := v1.(map[string]interface{}), v2.(map[string]interface{})
if len(obj1) != len(obj2) {
return false
}
for k, v1 := range obj1 {
if v2, ok := obj2[k]; ok {
if !equals(v1, v2) {
return false
}
} else {
return false
}
}
return true
case "number":
num1, _ := new(big.Float).SetString(string(v1.(json.Number)))
num2, _ := new(big.Float).SetString(string(v2.(json.Number)))
return num1.Cmp(num2) == 0
default:
return v1 == v2
}
} | go | func equals(v1, v2 interface{}) bool {
v1Type := jsonType(v1)
if v1Type != jsonType(v2) {
return false
}
switch v1Type {
case "array":
arr1, arr2 := v1.([]interface{}), v2.([]interface{})
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if !equals(arr1[i], arr2[i]) {
return false
}
}
return true
case "object":
obj1, obj2 := v1.(map[string]interface{}), v2.(map[string]interface{})
if len(obj1) != len(obj2) {
return false
}
for k, v1 := range obj1 {
if v2, ok := obj2[k]; ok {
if !equals(v1, v2) {
return false
}
} else {
return false
}
}
return true
case "number":
num1, _ := new(big.Float).SetString(string(v1.(json.Number)))
num2, _ := new(big.Float).SetString(string(v2.(json.Number)))
return num1.Cmp(num2) == 0
default:
return v1 == v2
}
} | [
"func",
"equals",
"(",
"v1",
",",
"v2",
"interface",
"{",
"}",
")",
"bool",
"{",
"v1Type",
":=",
"jsonType",
"(",
"v1",
")",
"\n",
"if",
"v1Type",
"!=",
"jsonType",
"(",
"v2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"v1Type",
"{",
"case",
"\"",
"\"",
":",
"arr1",
",",
"arr2",
":=",
"v1",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
",",
"v2",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"len",
"(",
"arr1",
")",
"!=",
"len",
"(",
"arr2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"arr1",
"{",
"if",
"!",
"equals",
"(",
"arr1",
"[",
"i",
"]",
",",
"arr2",
"[",
"i",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"case",
"\"",
"\"",
":",
"obj1",
",",
"obj2",
":=",
"v1",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"v2",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"len",
"(",
"obj1",
")",
"!=",
"len",
"(",
"obj2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"k",
",",
"v1",
":=",
"range",
"obj1",
"{",
"if",
"v2",
",",
"ok",
":=",
"obj2",
"[",
"k",
"]",
";",
"ok",
"{",
"if",
"!",
"equals",
"(",
"v1",
",",
"v2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"case",
"\"",
"\"",
":",
"num1",
",",
"_",
":=",
"new",
"(",
"big",
".",
"Float",
")",
".",
"SetString",
"(",
"string",
"(",
"v1",
".",
"(",
"json",
".",
"Number",
")",
")",
")",
"\n",
"num2",
",",
"_",
":=",
"new",
"(",
"big",
".",
"Float",
")",
".",
"SetString",
"(",
"string",
"(",
"v2",
".",
"(",
"json",
".",
"Number",
")",
")",
")",
"\n",
"return",
"num1",
".",
"Cmp",
"(",
"num2",
")",
"==",
"0",
"\n",
"default",
":",
"return",
"v1",
"==",
"v2",
"\n",
"}",
"\n",
"}"
] | // equals tells if given two json values are equal or not. | [
"equals",
"tells",
"if",
"given",
"two",
"json",
"values",
"are",
"equal",
"or",
"not",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/schema.go#L510-L549 |
6,487 | santhosh-tekuri/jsonschema | schema.go | escape | func escape(token string) string {
token = strings.Replace(token, "~", "~0", -1)
token = strings.Replace(token, "/", "~1", -1)
return url.PathEscape(token)
} | go | func escape(token string) string {
token = strings.Replace(token, "~", "~0", -1)
token = strings.Replace(token, "/", "~1", -1)
return url.PathEscape(token)
} | [
"func",
"escape",
"(",
"token",
"string",
")",
"string",
"{",
"token",
"=",
"strings",
".",
"Replace",
"(",
"token",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"token",
"=",
"strings",
".",
"Replace",
"(",
"token",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"url",
".",
"PathEscape",
"(",
"token",
")",
"\n",
"}"
] | // escape converts given token to valid json-pointer token | [
"escape",
"converts",
"given",
"token",
"to",
"valid",
"json",
"-",
"pointer",
"token"
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/schema.go#L552-L556 |
6,488 | santhosh-tekuri/jsonschema | compiler.go | AddResource | func (c *Compiler) AddResource(url string, r io.Reader) error {
res, err := newResource(url, r)
if err != nil {
return err
}
c.resources[res.url] = res
return nil
} | go | func (c *Compiler) AddResource(url string, r io.Reader) error {
res, err := newResource(url, r)
if err != nil {
return err
}
c.resources[res.url] = res
return nil
} | [
"func",
"(",
"c",
"*",
"Compiler",
")",
"AddResource",
"(",
"url",
"string",
",",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"res",
",",
"err",
":=",
"newResource",
"(",
"url",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"resources",
"[",
"res",
".",
"url",
"]",
"=",
"res",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddResource adds in-memory resource to the compiler.
//
// Note that url must not have fragment | [
"AddResource",
"adds",
"in",
"-",
"memory",
"resource",
"to",
"the",
"compiler",
".",
"Note",
"that",
"url",
"must",
"not",
"have",
"fragment"
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/compiler.go#L77-L84 |
6,489 | santhosh-tekuri/jsonschema | compiler.go | Compile | func (c *Compiler) Compile(url string) (*Schema, error) {
base, fragment := split(url)
if _, ok := c.resources[base]; !ok {
r, err := LoadURL(base)
if err != nil {
return nil, err
}
defer r.Close()
if err := c.AddResource(base, r); err != nil {
return nil, err
}
}
r := c.resources[base]
if r.draft == nil {
if m, ok := r.doc.(map[string]interface{}); ok {
if url, ok := m["$schema"]; ok {
switch url {
case "http://json-schema.org/schema#":
r.draft = latest
case "http://json-schema.org/draft-07/schema#":
r.draft = Draft7
case "http://json-schema.org/draft-06/schema#":
r.draft = Draft6
case "http://json-schema.org/draft-04/schema#":
r.draft = Draft4
default:
return nil, fmt.Errorf("unknown $schema %q", url)
}
}
}
if r.draft == nil {
r.draft = c.Draft
}
}
return c.compileRef(r, r.url, fragment)
} | go | func (c *Compiler) Compile(url string) (*Schema, error) {
base, fragment := split(url)
if _, ok := c.resources[base]; !ok {
r, err := LoadURL(base)
if err != nil {
return nil, err
}
defer r.Close()
if err := c.AddResource(base, r); err != nil {
return nil, err
}
}
r := c.resources[base]
if r.draft == nil {
if m, ok := r.doc.(map[string]interface{}); ok {
if url, ok := m["$schema"]; ok {
switch url {
case "http://json-schema.org/schema#":
r.draft = latest
case "http://json-schema.org/draft-07/schema#":
r.draft = Draft7
case "http://json-schema.org/draft-06/schema#":
r.draft = Draft6
case "http://json-schema.org/draft-04/schema#":
r.draft = Draft4
default:
return nil, fmt.Errorf("unknown $schema %q", url)
}
}
}
if r.draft == nil {
r.draft = c.Draft
}
}
return c.compileRef(r, r.url, fragment)
} | [
"func",
"(",
"c",
"*",
"Compiler",
")",
"Compile",
"(",
"url",
"string",
")",
"(",
"*",
"Schema",
",",
"error",
")",
"{",
"base",
",",
"fragment",
":=",
"split",
"(",
"url",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"resources",
"[",
"base",
"]",
";",
"!",
"ok",
"{",
"r",
",",
"err",
":=",
"LoadURL",
"(",
"base",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
":=",
"c",
".",
"AddResource",
"(",
"base",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"r",
":=",
"c",
".",
"resources",
"[",
"base",
"]",
"\n",
"if",
"r",
".",
"draft",
"==",
"nil",
"{",
"if",
"m",
",",
"ok",
":=",
"r",
".",
"doc",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"url",
",",
"ok",
":=",
"m",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"switch",
"url",
"{",
"case",
"\"",
"\"",
":",
"r",
".",
"draft",
"=",
"latest",
"\n",
"case",
"\"",
"\"",
":",
"r",
".",
"draft",
"=",
"Draft7",
"\n",
"case",
"\"",
"\"",
":",
"r",
".",
"draft",
"=",
"Draft6",
"\n",
"case",
"\"",
"\"",
":",
"r",
".",
"draft",
"=",
"Draft4",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"draft",
"==",
"nil",
"{",
"r",
".",
"draft",
"=",
"c",
".",
"Draft",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"c",
".",
"compileRef",
"(",
"r",
",",
"r",
".",
"url",
",",
"fragment",
")",
"\n",
"}"
] | // Compile parses json-schema at given url returns, if successful,
// a Schema object that can be used to match against json. | [
"Compile",
"parses",
"json",
"-",
"schema",
"at",
"given",
"url",
"returns",
"if",
"successful",
"a",
"Schema",
"object",
"that",
"can",
"be",
"used",
"to",
"match",
"against",
"json",
"."
] | 3187f5dd695e7a7fe4c2254be6fb4f0737fec928 | https://github.com/santhosh-tekuri/jsonschema/blob/3187f5dd695e7a7fe4c2254be6fb4f0737fec928/compiler.go#L98-L133 |
6,490 | sanbornm/go-selfupdate | selfupdate/selfupdate.go | BackgroundRun | func (u *Updater) BackgroundRun() error {
if err := os.MkdirAll(u.getExecRelativeDir(u.Dir), 0777); err != nil {
// fail
return err
}
if u.wantUpdate() {
if err := up.CanUpdate(); err != nil {
// fail
return err
}
//self, err := osext.Executable()
//if err != nil {
// fail update, couldn't figure out path to self
//return
//}
// TODO(bgentry): logger isn't on Windows. Replace w/ proper error reports.
if err := u.update(); err != nil {
return err
}
}
return nil
} | go | func (u *Updater) BackgroundRun() error {
if err := os.MkdirAll(u.getExecRelativeDir(u.Dir), 0777); err != nil {
// fail
return err
}
if u.wantUpdate() {
if err := up.CanUpdate(); err != nil {
// fail
return err
}
//self, err := osext.Executable()
//if err != nil {
// fail update, couldn't figure out path to self
//return
//}
// TODO(bgentry): logger isn't on Windows. Replace w/ proper error reports.
if err := u.update(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"u",
"*",
"Updater",
")",
"BackgroundRun",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"u",
".",
"getExecRelativeDir",
"(",
"u",
".",
"Dir",
")",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"// fail",
"return",
"err",
"\n",
"}",
"\n",
"if",
"u",
".",
"wantUpdate",
"(",
")",
"{",
"if",
"err",
":=",
"up",
".",
"CanUpdate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"// fail",
"return",
"err",
"\n",
"}",
"\n",
"//self, err := osext.Executable()",
"//if err != nil {",
"// fail update, couldn't figure out path to self",
"//return",
"//}",
"// TODO(bgentry): logger isn't on Windows. Replace w/ proper error reports.",
"if",
"err",
":=",
"u",
".",
"update",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // BackgroundRun starts the update check and apply cycle. | [
"BackgroundRun",
"starts",
"the",
"update",
"check",
"and",
"apply",
"cycle",
"."
] | f041b81ae5e69ec5628a0e882a9d58f2950c11c5 | https://github.com/sanbornm/go-selfupdate/blob/f041b81ae5e69ec5628a0e882a9d58f2950c11c5/selfupdate/selfupdate.go#L100-L121 |
6,491 | sanbornm/go-selfupdate | selfupdate/requester.go | Fetch | func (httpRequester *HTTPRequester) Fetch(url string) (io.ReadCloser, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("bad http status from %s: %v", url, resp.Status)
}
return resp.Body, nil
} | go | func (httpRequester *HTTPRequester) Fetch(url string) (io.ReadCloser, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("bad http status from %s: %v", url, resp.Status)
}
return resp.Body, nil
} | [
"func",
"(",
"httpRequester",
"*",
"HTTPRequester",
")",
"Fetch",
"(",
"url",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"url",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"return",
"resp",
".",
"Body",
",",
"nil",
"\n",
"}"
] | // Fetch will return an HTTP request to the specified url and return
// the body of the result. An error will occur for a non 200 status code. | [
"Fetch",
"will",
"return",
"an",
"HTTP",
"request",
"to",
"the",
"specified",
"url",
"and",
"return",
"the",
"body",
"of",
"the",
"result",
".",
"An",
"error",
"will",
"occur",
"for",
"a",
"non",
"200",
"status",
"code",
"."
] | f041b81ae5e69ec5628a0e882a9d58f2950c11c5 | https://github.com/sanbornm/go-selfupdate/blob/f041b81ae5e69ec5628a0e882a9d58f2950c11c5/selfupdate/requester.go#L22-L33 |
6,492 | opencontainers/selinux | go-selinux/label/label_selinux.go | InitLabels | func InitLabels(options []string) (plabel string, mlabel string, Err error) {
if !selinux.GetEnabled() {
return "", "", nil
}
processLabel, mountLabel := selinux.ContainerLabels()
if processLabel != "" {
defer func() {
if Err != nil {
ReleaseLabel(mountLabel)
}
}()
pcon, err := selinux.NewContext(processLabel)
if err != nil {
return "", "", err
}
mcon, err := selinux.NewContext(mountLabel)
if err != nil {
return "", "", err
}
for _, opt := range options {
if opt == "disable" {
return "", mountLabel, nil
}
if i := strings.Index(opt, ":"); i == -1 {
return "", "", fmt.Errorf("Bad label option %q, valid options 'disable' or \n'user, role, level, type' followed by ':' and a value", opt)
}
con := strings.SplitN(opt, ":", 2)
if !validOptions[con[0]] {
return "", "", fmt.Errorf("Bad label option %q, valid options 'disable, user, role, level, type'", con[0])
}
pcon[con[0]] = con[1]
if con[0] == "level" || con[0] == "user" {
mcon[con[0]] = con[1]
}
}
_ = ReleaseLabel(processLabel)
processLabel = pcon.Get()
mountLabel = mcon.Get()
_ = ReserveLabel(processLabel)
}
return processLabel, mountLabel, nil
} | go | func InitLabels(options []string) (plabel string, mlabel string, Err error) {
if !selinux.GetEnabled() {
return "", "", nil
}
processLabel, mountLabel := selinux.ContainerLabels()
if processLabel != "" {
defer func() {
if Err != nil {
ReleaseLabel(mountLabel)
}
}()
pcon, err := selinux.NewContext(processLabel)
if err != nil {
return "", "", err
}
mcon, err := selinux.NewContext(mountLabel)
if err != nil {
return "", "", err
}
for _, opt := range options {
if opt == "disable" {
return "", mountLabel, nil
}
if i := strings.Index(opt, ":"); i == -1 {
return "", "", fmt.Errorf("Bad label option %q, valid options 'disable' or \n'user, role, level, type' followed by ':' and a value", opt)
}
con := strings.SplitN(opt, ":", 2)
if !validOptions[con[0]] {
return "", "", fmt.Errorf("Bad label option %q, valid options 'disable, user, role, level, type'", con[0])
}
pcon[con[0]] = con[1]
if con[0] == "level" || con[0] == "user" {
mcon[con[0]] = con[1]
}
}
_ = ReleaseLabel(processLabel)
processLabel = pcon.Get()
mountLabel = mcon.Get()
_ = ReserveLabel(processLabel)
}
return processLabel, mountLabel, nil
} | [
"func",
"InitLabels",
"(",
"options",
"[",
"]",
"string",
")",
"(",
"plabel",
"string",
",",
"mlabel",
"string",
",",
"Err",
"error",
")",
"{",
"if",
"!",
"selinux",
".",
"GetEnabled",
"(",
")",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"processLabel",
",",
"mountLabel",
":=",
"selinux",
".",
"ContainerLabels",
"(",
")",
"\n",
"if",
"processLabel",
"!=",
"\"",
"\"",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"Err",
"!=",
"nil",
"{",
"ReleaseLabel",
"(",
"mountLabel",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"pcon",
",",
"err",
":=",
"selinux",
".",
"NewContext",
"(",
"processLabel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"mcon",
",",
"err",
":=",
"selinux",
".",
"NewContext",
"(",
"mountLabel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"options",
"{",
"if",
"opt",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"mountLabel",
",",
"nil",
"\n",
"}",
"\n",
"if",
"i",
":=",
"strings",
".",
"Index",
"(",
"opt",
",",
"\"",
"\"",
")",
";",
"i",
"==",
"-",
"1",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"opt",
")",
"\n",
"}",
"\n",
"con",
":=",
"strings",
".",
"SplitN",
"(",
"opt",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"!",
"validOptions",
"[",
"con",
"[",
"0",
"]",
"]",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"con",
"[",
"0",
"]",
")",
"\n\n",
"}",
"\n",
"pcon",
"[",
"con",
"[",
"0",
"]",
"]",
"=",
"con",
"[",
"1",
"]",
"\n",
"if",
"con",
"[",
"0",
"]",
"==",
"\"",
"\"",
"||",
"con",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"mcon",
"[",
"con",
"[",
"0",
"]",
"]",
"=",
"con",
"[",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"_",
"=",
"ReleaseLabel",
"(",
"processLabel",
")",
"\n",
"processLabel",
"=",
"pcon",
".",
"Get",
"(",
")",
"\n",
"mountLabel",
"=",
"mcon",
".",
"Get",
"(",
")",
"\n",
"_",
"=",
"ReserveLabel",
"(",
"processLabel",
")",
"\n",
"}",
"\n",
"return",
"processLabel",
",",
"mountLabel",
",",
"nil",
"\n",
"}"
] | // InitLabels returns the process label and file labels to be used within
// the container. A list of options can be passed into this function to alter
// the labels. The labels returned will include a random MCS String, that is
// guaranteed to be unique. | [
"InitLabels",
"returns",
"the",
"process",
"label",
"and",
"file",
"labels",
"to",
"be",
"used",
"within",
"the",
"container",
".",
"A",
"list",
"of",
"options",
"can",
"be",
"passed",
"into",
"this",
"function",
"to",
"alter",
"the",
"labels",
".",
"The",
"labels",
"returned",
"will",
"include",
"a",
"random",
"MCS",
"String",
"that",
"is",
"guaranteed",
"to",
"be",
"unique",
"."
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L29-L72 |
6,493 | opencontainers/selinux | go-selinux/label/label_selinux.go | SetFileLabel | func SetFileLabel(path string, fileLabel string) error {
if selinux.GetEnabled() && fileLabel != "" {
return selinux.SetFileLabel(path, fileLabel)
}
return nil
} | go | func SetFileLabel(path string, fileLabel string) error {
if selinux.GetEnabled() && fileLabel != "" {
return selinux.SetFileLabel(path, fileLabel)
}
return nil
} | [
"func",
"SetFileLabel",
"(",
"path",
"string",
",",
"fileLabel",
"string",
")",
"error",
"{",
"if",
"selinux",
".",
"GetEnabled",
"(",
")",
"&&",
"fileLabel",
"!=",
"\"",
"\"",
"{",
"return",
"selinux",
".",
"SetFileLabel",
"(",
"path",
",",
"fileLabel",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetFileLabel modifies the "path" label to the specified file label | [
"SetFileLabel",
"modifies",
"the",
"path",
"label",
"to",
"the",
"specified",
"file",
"label"
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L142-L147 |
6,494 | opencontainers/selinux | go-selinux/label/label_selinux.go | SetFileCreateLabel | func SetFileCreateLabel(fileLabel string) error {
if selinux.GetEnabled() {
return selinux.SetFSCreateLabel(fileLabel)
}
return nil
} | go | func SetFileCreateLabel(fileLabel string) error {
if selinux.GetEnabled() {
return selinux.SetFSCreateLabel(fileLabel)
}
return nil
} | [
"func",
"SetFileCreateLabel",
"(",
"fileLabel",
"string",
")",
"error",
"{",
"if",
"selinux",
".",
"GetEnabled",
"(",
")",
"{",
"return",
"selinux",
".",
"SetFSCreateLabel",
"(",
"fileLabel",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetFileCreateLabel tells the kernel the label for all files to be created | [
"SetFileCreateLabel",
"tells",
"the",
"kernel",
"the",
"label",
"for",
"all",
"files",
"to",
"be",
"created"
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L150-L155 |
6,495 | opencontainers/selinux | go-selinux/label/label_selinux.go | Relabel | func Relabel(path string, fileLabel string, shared bool) error {
if !selinux.GetEnabled() {
return nil
}
if fileLabel == "" {
return nil
}
exclude_paths := map[string]bool{
"/": true,
"/bin": true,
"/boot": true,
"/dev": true,
"/etc": true,
"/etc/passwd": true,
"/etc/pki": true,
"/etc/shadow": true,
"/home": true,
"/lib": true,
"/lib64": true,
"/media": true,
"/opt": true,
"/proc": true,
"/root": true,
"/run": true,
"/sbin": true,
"/srv": true,
"/sys": true,
"/tmp": true,
"/usr": true,
"/var": true,
"/var/lib": true,
"/var/log": true,
}
if home := os.Getenv("HOME"); home != "" {
exclude_paths[home] = true
}
if sudoUser := os.Getenv("SUDO_USER"); sudoUser != "" {
if usr, err := user.Lookup(sudoUser); err == nil {
exclude_paths[usr.HomeDir] = true
}
}
if path != "/" {
path = strings.TrimSuffix(path, "/")
}
if exclude_paths[path] {
return fmt.Errorf("SELinux relabeling of %s is not allowed", path)
}
if shared {
c, err := selinux.NewContext(fileLabel)
if err != nil {
return err
}
c["level"] = "s0"
fileLabel = c.Get()
}
if err := selinux.Chcon(path, fileLabel, true); err != nil {
return err
}
return nil
} | go | func Relabel(path string, fileLabel string, shared bool) error {
if !selinux.GetEnabled() {
return nil
}
if fileLabel == "" {
return nil
}
exclude_paths := map[string]bool{
"/": true,
"/bin": true,
"/boot": true,
"/dev": true,
"/etc": true,
"/etc/passwd": true,
"/etc/pki": true,
"/etc/shadow": true,
"/home": true,
"/lib": true,
"/lib64": true,
"/media": true,
"/opt": true,
"/proc": true,
"/root": true,
"/run": true,
"/sbin": true,
"/srv": true,
"/sys": true,
"/tmp": true,
"/usr": true,
"/var": true,
"/var/lib": true,
"/var/log": true,
}
if home := os.Getenv("HOME"); home != "" {
exclude_paths[home] = true
}
if sudoUser := os.Getenv("SUDO_USER"); sudoUser != "" {
if usr, err := user.Lookup(sudoUser); err == nil {
exclude_paths[usr.HomeDir] = true
}
}
if path != "/" {
path = strings.TrimSuffix(path, "/")
}
if exclude_paths[path] {
return fmt.Errorf("SELinux relabeling of %s is not allowed", path)
}
if shared {
c, err := selinux.NewContext(fileLabel)
if err != nil {
return err
}
c["level"] = "s0"
fileLabel = c.Get()
}
if err := selinux.Chcon(path, fileLabel, true); err != nil {
return err
}
return nil
} | [
"func",
"Relabel",
"(",
"path",
"string",
",",
"fileLabel",
"string",
",",
"shared",
"bool",
")",
"error",
"{",
"if",
"!",
"selinux",
".",
"GetEnabled",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"fileLabel",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"exclude_paths",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"}",
"\n\n",
"if",
"home",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"home",
"!=",
"\"",
"\"",
"{",
"exclude_paths",
"[",
"home",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"sudoUser",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"sudoUser",
"!=",
"\"",
"\"",
"{",
"if",
"usr",
",",
"err",
":=",
"user",
".",
"Lookup",
"(",
"sudoUser",
")",
";",
"err",
"==",
"nil",
"{",
"exclude_paths",
"[",
"usr",
".",
"HomeDir",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"path",
"=",
"strings",
".",
"TrimSuffix",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"exclude_paths",
"[",
"path",
"]",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"if",
"shared",
"{",
"c",
",",
"err",
":=",
"selinux",
".",
"NewContext",
"(",
"fileLabel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"c",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"fileLabel",
"=",
"c",
".",
"Get",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"selinux",
".",
"Chcon",
"(",
"path",
",",
"fileLabel",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Relabel changes the label of path to the filelabel string.
// It changes the MCS label to s0 if shared is true.
// This will allow all containers to share the content. | [
"Relabel",
"changes",
"the",
"label",
"of",
"path",
"to",
"the",
"filelabel",
"string",
".",
"It",
"changes",
"the",
"MCS",
"label",
"to",
"s0",
"if",
"shared",
"is",
"true",
".",
"This",
"will",
"allow",
"all",
"containers",
"to",
"share",
"the",
"content",
"."
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L160-L226 |
6,496 | opencontainers/selinux | go-selinux/label/label_selinux.go | Validate | func Validate(label string) error {
if strings.Contains(label, "z") && strings.Contains(label, "Z") {
return ErrIncompatibleLabel
}
return nil
} | go | func Validate(label string) error {
if strings.Contains(label, "z") && strings.Contains(label, "Z") {
return ErrIncompatibleLabel
}
return nil
} | [
"func",
"Validate",
"(",
"label",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"Contains",
"(",
"label",
",",
"\"",
"\"",
")",
"&&",
"strings",
".",
"Contains",
"(",
"label",
",",
"\"",
"\"",
")",
"{",
"return",
"ErrIncompatibleLabel",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate checks that the label does not include unexpected options | [
"Validate",
"checks",
"that",
"the",
"label",
"does",
"not",
"include",
"unexpected",
"options"
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L272-L277 |
6,497 | opencontainers/selinux | go-selinux/label/label_selinux.go | RelabelNeeded | func RelabelNeeded(label string) bool {
return strings.Contains(label, "z") || strings.Contains(label, "Z")
} | go | func RelabelNeeded(label string) bool {
return strings.Contains(label, "z") || strings.Contains(label, "Z")
} | [
"func",
"RelabelNeeded",
"(",
"label",
"string",
")",
"bool",
"{",
"return",
"strings",
".",
"Contains",
"(",
"label",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"label",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // RelabelNeeded checks whether the user requested a relabel | [
"RelabelNeeded",
"checks",
"whether",
"the",
"user",
"requested",
"a",
"relabel"
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/label/label_selinux.go#L280-L282 |
6,498 | opencontainers/selinux | go-selinux/selinux_linux.go | findSELinuxfsMount | func findSELinuxfsMount(s *bufio.Scanner) string {
for s.Scan() {
txt := s.Text()
// The first field after - is fs type.
// Safe as spaces in mountpoints are encoded as \040
if !strings.Contains(txt, " - selinuxfs ") {
continue
}
const mPos = 5 // mount point is 5th field
fields := strings.SplitN(txt, " ", mPos+1)
if len(fields) < mPos+1 {
continue
}
return fields[mPos-1]
}
return ""
} | go | func findSELinuxfsMount(s *bufio.Scanner) string {
for s.Scan() {
txt := s.Text()
// The first field after - is fs type.
// Safe as spaces in mountpoints are encoded as \040
if !strings.Contains(txt, " - selinuxfs ") {
continue
}
const mPos = 5 // mount point is 5th field
fields := strings.SplitN(txt, " ", mPos+1)
if len(fields) < mPos+1 {
continue
}
return fields[mPos-1]
}
return ""
} | [
"func",
"findSELinuxfsMount",
"(",
"s",
"*",
"bufio",
".",
"Scanner",
")",
"string",
"{",
"for",
"s",
".",
"Scan",
"(",
")",
"{",
"txt",
":=",
"s",
".",
"Text",
"(",
")",
"\n",
"// The first field after - is fs type.",
"// Safe as spaces in mountpoints are encoded as \\040",
"if",
"!",
"strings",
".",
"Contains",
"(",
"txt",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"const",
"mPos",
"=",
"5",
"// mount point is 5th field",
"\n",
"fields",
":=",
"strings",
".",
"SplitN",
"(",
"txt",
",",
"\"",
"\"",
",",
"mPos",
"+",
"1",
")",
"\n",
"if",
"len",
"(",
"fields",
")",
"<",
"mPos",
"+",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"fields",
"[",
"mPos",
"-",
"1",
"]",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // findSELinuxfsMount returns a next selinuxfs mount point found,
// if there is one, or an empty string in case of EOF or error. | [
"findSELinuxfsMount",
"returns",
"a",
"next",
"selinuxfs",
"mount",
"point",
"found",
"if",
"there",
"is",
"one",
"or",
"an",
"empty",
"string",
"in",
"case",
"of",
"EOF",
"or",
"error",
"."
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/selinux_linux.go#L165-L182 |
6,499 | opencontainers/selinux | go-selinux/selinux_linux.go | SetFileLabel | func SetFileLabel(fpath string, label string) error {
if fpath == "" {
return ErrEmptyPath
}
return lsetxattr(fpath, xattrNameSelinux, []byte(label), 0)
} | go | func SetFileLabel(fpath string, label string) error {
if fpath == "" {
return ErrEmptyPath
}
return lsetxattr(fpath, xattrNameSelinux, []byte(label), 0)
} | [
"func",
"SetFileLabel",
"(",
"fpath",
"string",
",",
"label",
"string",
")",
"error",
"{",
"if",
"fpath",
"==",
"\"",
"\"",
"{",
"return",
"ErrEmptyPath",
"\n",
"}",
"\n",
"return",
"lsetxattr",
"(",
"fpath",
",",
"xattrNameSelinux",
",",
"[",
"]",
"byte",
"(",
"label",
")",
",",
"0",
")",
"\n",
"}"
] | // SetFileLabel sets the SELinux label for this path or returns an error. | [
"SetFileLabel",
"sets",
"the",
"SELinux",
"label",
"for",
"this",
"path",
"or",
"returns",
"an",
"error",
"."
] | bed85457b2045f53cd0d11ef8b5a8af23079720e | https://github.com/opencontainers/selinux/blob/bed85457b2045f53cd0d11ef8b5a8af23079720e/go-selinux/selinux_linux.go#L274-L279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.