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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,000 | itsabot/itsabot | shared/plugin/plugin.go | SetKeywords | func SetKeywords(p *dt.Plugin, khs ...dt.KeywordHandler) {
p.Keywords = &dt.Keywords{
Dict: map[string]dt.KeywordFn{},
}
for _, kh := range khs {
for _, intent := range kh.Trigger.Intents {
intent = strings.ToLower(intent)
if !language.Contains(p.Trigger.Intents, intent) {
p.Trigger.Intents = append(p.Trigger.Intents, intent)
}
key := "I_" + intent
_, exists := p.Keywords.Dict[key]
if exists {
continue
}
p.Keywords.Dict[key] = kh.Fn
}
eng := porter2.Stemmer
for _, cmd := range kh.Trigger.Commands {
cmd = strings.ToLower(eng.Stem(cmd))
if !language.Contains(p.Trigger.Commands, cmd) {
p.Trigger.Commands = append(p.Trigger.Commands, cmd)
}
for _, obj := range kh.Trigger.Objects {
obj = strings.ToLower(eng.Stem(obj))
if !language.Contains(p.Trigger.Objects, obj) {
p.Trigger.Objects = append(p.Trigger.Objects, obj)
}
key := "CO_" + cmd + "_" + obj
p.Keywords.Dict[key] = kh.Fn
}
}
}
} | go | func SetKeywords(p *dt.Plugin, khs ...dt.KeywordHandler) {
p.Keywords = &dt.Keywords{
Dict: map[string]dt.KeywordFn{},
}
for _, kh := range khs {
for _, intent := range kh.Trigger.Intents {
intent = strings.ToLower(intent)
if !language.Contains(p.Trigger.Intents, intent) {
p.Trigger.Intents = append(p.Trigger.Intents, intent)
}
key := "I_" + intent
_, exists := p.Keywords.Dict[key]
if exists {
continue
}
p.Keywords.Dict[key] = kh.Fn
}
eng := porter2.Stemmer
for _, cmd := range kh.Trigger.Commands {
cmd = strings.ToLower(eng.Stem(cmd))
if !language.Contains(p.Trigger.Commands, cmd) {
p.Trigger.Commands = append(p.Trigger.Commands, cmd)
}
for _, obj := range kh.Trigger.Objects {
obj = strings.ToLower(eng.Stem(obj))
if !language.Contains(p.Trigger.Objects, obj) {
p.Trigger.Objects = append(p.Trigger.Objects, obj)
}
key := "CO_" + cmd + "_" + obj
p.Keywords.Dict[key] = kh.Fn
}
}
}
} | [
"func",
"SetKeywords",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"khs",
"...",
"dt",
".",
"KeywordHandler",
")",
"{",
"p",
".",
"Keywords",
"=",
"&",
"dt",
".",
"Keywords",
"{",
"Dict",
":",
"map",
"[",
"string",
"]",
"dt",
".",
"KeywordFn",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"kh",
":=",
"range",
"khs",
"{",
"for",
"_",
",",
"intent",
":=",
"range",
"kh",
".",
"Trigger",
".",
"Intents",
"{",
"intent",
"=",
"strings",
".",
"ToLower",
"(",
"intent",
")",
"\n",
"if",
"!",
"language",
".",
"Contains",
"(",
"p",
".",
"Trigger",
".",
"Intents",
",",
"intent",
")",
"{",
"p",
".",
"Trigger",
".",
"Intents",
"=",
"append",
"(",
"p",
".",
"Trigger",
".",
"Intents",
",",
"intent",
")",
"\n",
"}",
"\n",
"key",
":=",
"\"",
"\"",
"+",
"intent",
"\n",
"_",
",",
"exists",
":=",
"p",
".",
"Keywords",
".",
"Dict",
"[",
"key",
"]",
"\n",
"if",
"exists",
"{",
"continue",
"\n",
"}",
"\n",
"p",
".",
"Keywords",
".",
"Dict",
"[",
"key",
"]",
"=",
"kh",
".",
"Fn",
"\n",
"}",
"\n",
"eng",
":=",
"porter2",
".",
"Stemmer",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"kh",
".",
"Trigger",
".",
"Commands",
"{",
"cmd",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"cmd",
")",
")",
"\n",
"if",
"!",
"language",
".",
"Contains",
"(",
"p",
".",
"Trigger",
".",
"Commands",
",",
"cmd",
")",
"{",
"p",
".",
"Trigger",
".",
"Commands",
"=",
"append",
"(",
"p",
".",
"Trigger",
".",
"Commands",
",",
"cmd",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"kh",
".",
"Trigger",
".",
"Objects",
"{",
"obj",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"obj",
")",
")",
"\n",
"if",
"!",
"language",
".",
"Contains",
"(",
"p",
".",
"Trigger",
".",
"Objects",
",",
"obj",
")",
"{",
"p",
".",
"Trigger",
".",
"Objects",
"=",
"append",
"(",
"p",
".",
"Trigger",
".",
"Objects",
",",
"obj",
")",
"\n",
"}",
"\n",
"key",
":=",
"\"",
"\"",
"+",
"cmd",
"+",
"\"",
"\"",
"+",
"obj",
"\n",
"p",
".",
"Keywords",
".",
"Dict",
"[",
"key",
"]",
"=",
"kh",
".",
"Fn",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // SetKeywords processes and registers keywords with Abot's core for routing. | [
"SetKeywords",
"processes",
"and",
"registers",
"keywords",
"with",
"Abot",
"s",
"core",
"for",
"routing",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/plugin/plugin.go#L151-L184 |
5,001 | itsabot/itsabot | shared/plugin/plugin.go | SetStates | func SetStates(p *dt.Plugin, states [][]dt.State) {
p.States = []dt.State{}
for _, ss := range states {
p.States = append(p.States, ss...)
}
} | go | func SetStates(p *dt.Plugin, states [][]dt.State) {
p.States = []dt.State{}
for _, ss := range states {
p.States = append(p.States, ss...)
}
} | [
"func",
"SetStates",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"states",
"[",
"]",
"[",
"]",
"dt",
".",
"State",
")",
"{",
"p",
".",
"States",
"=",
"[",
"]",
"dt",
".",
"State",
"{",
"}",
"\n",
"for",
"_",
",",
"ss",
":=",
"range",
"states",
"{",
"p",
".",
"States",
"=",
"append",
"(",
"p",
".",
"States",
",",
"ss",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // SetStates is a convenience function provided to match the API of NewKeywords
// and AppendTrigger. | [
"SetStates",
"is",
"a",
"convenience",
"function",
"provided",
"to",
"match",
"the",
"API",
"of",
"NewKeywords",
"and",
"AppendTrigger",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/plugin/plugin.go#L188-L193 |
5,002 | itsabot/itsabot | shared/plugin/plugin.go | AppendTrigger | func AppendTrigger(p *dt.Plugin, t *dt.StructuredInput) {
eng := porter2.Stemmer
for _, cmd := range t.Commands {
cmd = eng.Stem(cmd)
if !language.Contains(p.Trigger.Commands, cmd) {
p.Trigger.Commands = append(p.Trigger.Commands, cmd)
}
}
for _, obj := range t.Objects {
obj = eng.Stem(obj)
if !language.Contains(p.Trigger.Objects, obj) {
p.Trigger.Objects = append(p.Trigger.Objects, obj)
}
}
} | go | func AppendTrigger(p *dt.Plugin, t *dt.StructuredInput) {
eng := porter2.Stemmer
for _, cmd := range t.Commands {
cmd = eng.Stem(cmd)
if !language.Contains(p.Trigger.Commands, cmd) {
p.Trigger.Commands = append(p.Trigger.Commands, cmd)
}
}
for _, obj := range t.Objects {
obj = eng.Stem(obj)
if !language.Contains(p.Trigger.Objects, obj) {
p.Trigger.Objects = append(p.Trigger.Objects, obj)
}
}
} | [
"func",
"AppendTrigger",
"(",
"p",
"*",
"dt",
".",
"Plugin",
",",
"t",
"*",
"dt",
".",
"StructuredInput",
")",
"{",
"eng",
":=",
"porter2",
".",
"Stemmer",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"t",
".",
"Commands",
"{",
"cmd",
"=",
"eng",
".",
"Stem",
"(",
"cmd",
")",
"\n",
"if",
"!",
"language",
".",
"Contains",
"(",
"p",
".",
"Trigger",
".",
"Commands",
",",
"cmd",
")",
"{",
"p",
".",
"Trigger",
".",
"Commands",
"=",
"append",
"(",
"p",
".",
"Trigger",
".",
"Commands",
",",
"cmd",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"t",
".",
"Objects",
"{",
"obj",
"=",
"eng",
".",
"Stem",
"(",
"obj",
")",
"\n",
"if",
"!",
"language",
".",
"Contains",
"(",
"p",
".",
"Trigger",
".",
"Objects",
",",
"obj",
")",
"{",
"p",
".",
"Trigger",
".",
"Objects",
"=",
"append",
"(",
"p",
".",
"Trigger",
".",
"Objects",
",",
"obj",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // AppendTrigger appends the StructuredInput's modified contents to a plugin.
// All Commands and Objects stemmed using the Porter2 Snowball algorithm. | [
"AppendTrigger",
"appends",
"the",
"StructuredInput",
"s",
"modified",
"contents",
"to",
"a",
"plugin",
".",
"All",
"Commands",
"and",
"Objects",
"stemmed",
"using",
"the",
"Porter2",
"Snowball",
"algorithm",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/plugin/plugin.go#L197-L211 |
5,003 | itsabot/itsabot | shared/datatypes/user.go | GetUser | func GetUser(db *sqlx.DB, req *Request) (*User, error) {
u := &User{}
u.FlexID = req.FlexID
u.FlexIDType = req.FlexIDType
if req.UserID == 0 {
if req.FlexID == "" {
return nil, ErrMissingFlexID
}
switch req.FlexIDType {
case FIDTEmail, FIDTPhone, FIDTSession:
// Do nothing
default:
return nil, ErrInvalidFlexIDType
}
log.Debug("searching for user from", req.FlexID, req.FlexIDType)
q := `SELECT userid
FROM userflexids
WHERE flexid=$1 AND flexidtype=$2
ORDER BY createdat DESC`
err := db.Get(&req.UserID, q, req.FlexID, req.FlexIDType)
if err == sql.ErrNoRows {
return u, nil
}
log.Debug("got uid", req.UserID)
if err != nil {
return nil, err
}
}
q := `SELECT id, name, email FROM users WHERE id=$1`
if err := db.Get(u, q, req.UserID); err != nil {
if err == sql.ErrNoRows {
return u, nil
}
return nil, err
}
return u, nil
} | go | func GetUser(db *sqlx.DB, req *Request) (*User, error) {
u := &User{}
u.FlexID = req.FlexID
u.FlexIDType = req.FlexIDType
if req.UserID == 0 {
if req.FlexID == "" {
return nil, ErrMissingFlexID
}
switch req.FlexIDType {
case FIDTEmail, FIDTPhone, FIDTSession:
// Do nothing
default:
return nil, ErrInvalidFlexIDType
}
log.Debug("searching for user from", req.FlexID, req.FlexIDType)
q := `SELECT userid
FROM userflexids
WHERE flexid=$1 AND flexidtype=$2
ORDER BY createdat DESC`
err := db.Get(&req.UserID, q, req.FlexID, req.FlexIDType)
if err == sql.ErrNoRows {
return u, nil
}
log.Debug("got uid", req.UserID)
if err != nil {
return nil, err
}
}
q := `SELECT id, name, email FROM users WHERE id=$1`
if err := db.Get(u, q, req.UserID); err != nil {
if err == sql.ErrNoRows {
return u, nil
}
return nil, err
}
return u, nil
} | [
"func",
"GetUser",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"req",
"*",
"Request",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"u",
":=",
"&",
"User",
"{",
"}",
"\n",
"u",
".",
"FlexID",
"=",
"req",
".",
"FlexID",
"\n",
"u",
".",
"FlexIDType",
"=",
"req",
".",
"FlexIDType",
"\n",
"if",
"req",
".",
"UserID",
"==",
"0",
"{",
"if",
"req",
".",
"FlexID",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"ErrMissingFlexID",
"\n",
"}",
"\n",
"switch",
"req",
".",
"FlexIDType",
"{",
"case",
"FIDTEmail",
",",
"FIDTPhone",
",",
"FIDTSession",
":",
"// Do nothing",
"default",
":",
"return",
"nil",
",",
"ErrInvalidFlexIDType",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"req",
".",
"FlexID",
",",
"req",
".",
"FlexIDType",
")",
"\n",
"q",
":=",
"`SELECT userid\n\t\t FROM userflexids\n\t\t WHERE flexid=$1 AND flexidtype=$2\n\t\t ORDER BY createdat DESC`",
"\n",
"err",
":=",
"db",
".",
"Get",
"(",
"&",
"req",
".",
"UserID",
",",
"q",
",",
"req",
".",
"FlexID",
",",
"req",
".",
"FlexIDType",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"u",
",",
"nil",
"\n",
"}",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"req",
".",
"UserID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT id, name, email FROM users WHERE id=$1`",
"\n",
"if",
"err",
":=",
"db",
".",
"Get",
"(",
"u",
",",
"q",
",",
"req",
".",
"UserID",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"u",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"u",
",",
"nil",
"\n",
"}"
] | // GetUser from an HTTP request. | [
"GetUser",
"from",
"an",
"HTTP",
"request",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/user.go#L63-L99 |
5,004 | itsabot/itsabot | shared/datatypes/user.go | Create | func (u *User) Create(db *sqlx.DB, fidT FlexIDType, fid string) error {
// Create the password hash
hpw, err := bcrypt.GenerateFromPassword([]byte(u.Password), 10)
if err != nil {
return err
}
tx, err := db.Beginx()
if err != nil {
return err
}
q := `INSERT INTO users (name, email, password, locationid, admin)
VALUES ($1, $2, $3, 0, $4)
RETURNING id`
var uid uint64
err = tx.QueryRowx(q, u.Name, u.Email, hpw, u.Admin).Scan(&uid)
if err != nil && err.Error() ==
`pq: duplicate key value violates unique constraint "users_email_key"` {
_ = tx.Rollback()
return err
}
if uid == 0 {
_ = tx.Rollback()
return err
}
q = `INSERT INTO userflexids (userid, flexid, flexidtype)
VALUES ($1, $2, $3)`
_, err = tx.Exec(q, uid, u.Email, 1)
if err != nil {
_ = tx.Rollback()
return err
}
_, err = tx.Exec(q, uid, fid, 2)
if err != nil {
_ = tx.Rollback()
return err
}
if err = tx.Commit(); err != nil {
return err
}
u.ID = uid
return nil
} | go | func (u *User) Create(db *sqlx.DB, fidT FlexIDType, fid string) error {
// Create the password hash
hpw, err := bcrypt.GenerateFromPassword([]byte(u.Password), 10)
if err != nil {
return err
}
tx, err := db.Beginx()
if err != nil {
return err
}
q := `INSERT INTO users (name, email, password, locationid, admin)
VALUES ($1, $2, $3, 0, $4)
RETURNING id`
var uid uint64
err = tx.QueryRowx(q, u.Name, u.Email, hpw, u.Admin).Scan(&uid)
if err != nil && err.Error() ==
`pq: duplicate key value violates unique constraint "users_email_key"` {
_ = tx.Rollback()
return err
}
if uid == 0 {
_ = tx.Rollback()
return err
}
q = `INSERT INTO userflexids (userid, flexid, flexidtype)
VALUES ($1, $2, $3)`
_, err = tx.Exec(q, uid, u.Email, 1)
if err != nil {
_ = tx.Rollback()
return err
}
_, err = tx.Exec(q, uid, fid, 2)
if err != nil {
_ = tx.Rollback()
return err
}
if err = tx.Commit(); err != nil {
return err
}
u.ID = uid
return nil
} | [
"func",
"(",
"u",
"*",
"User",
")",
"Create",
"(",
"db",
"*",
"sqlx",
".",
"DB",
",",
"fidT",
"FlexIDType",
",",
"fid",
"string",
")",
"error",
"{",
"// Create the password hash",
"hpw",
",",
"err",
":=",
"bcrypt",
".",
"GenerateFromPassword",
"(",
"[",
"]",
"byte",
"(",
"u",
".",
"Password",
")",
",",
"10",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"db",
".",
"Beginx",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"q",
":=",
"`INSERT INTO users (name, email, password, locationid, admin)\n\t VALUES ($1, $2, $3, 0, $4)\n\t RETURNING id`",
"\n",
"var",
"uid",
"uint64",
"\n",
"err",
"=",
"tx",
".",
"QueryRowx",
"(",
"q",
",",
"u",
".",
"Name",
",",
"u",
".",
"Email",
",",
"hpw",
",",
"u",
".",
"Admin",
")",
".",
"Scan",
"(",
"&",
"uid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"==",
"`pq: duplicate key value violates unique constraint \"users_email_key\"`",
"{",
"_",
"=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"uid",
"==",
"0",
"{",
"_",
"=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"q",
"=",
"`INSERT INTO userflexids (userid, flexid, flexidtype)\n\t VALUES ($1, $2, $3)`",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"q",
",",
"uid",
",",
"u",
".",
"Email",
",",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"_",
"=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"q",
",",
"uid",
",",
"fid",
",",
"2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"_",
"=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"u",
".",
"ID",
"=",
"uid",
"\n",
"return",
"nil",
"\n",
"}"
] | // Create a new user in the database. | [
"Create",
"a",
"new",
"user",
"in",
"the",
"database",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/user.go#L102-L143 |
5,005 | itsabot/itsabot | shared/datatypes/user.go | DeleteSessions | func (u *User) DeleteSessions(db *sqlx.DB) error {
q := `DELETE FROM sessions WHERE userid=$1`
_, err := db.Exec(q, u.ID)
if err != nil && err != sql.ErrNoRows {
return err
}
return nil
} | go | func (u *User) DeleteSessions(db *sqlx.DB) error {
q := `DELETE FROM sessions WHERE userid=$1`
_, err := db.Exec(q, u.ID)
if err != nil && err != sql.ErrNoRows {
return err
}
return nil
} | [
"func",
"(",
"u",
"*",
"User",
")",
"DeleteSessions",
"(",
"db",
"*",
"sqlx",
".",
"DB",
")",
"error",
"{",
"q",
":=",
"`DELETE FROM sessions WHERE userid=$1`",
"\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"u",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"sql",
".",
"ErrNoRows",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteSessions removes any open sessions by the user. This enables "logging
// out" of the web-based client. | [
"DeleteSessions",
"removes",
"any",
"open",
"sessions",
"by",
"the",
"user",
".",
"This",
"enables",
"logging",
"out",
"of",
"the",
"web",
"-",
"based",
"client",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/user.go#L147-L154 |
5,006 | itsabot/itsabot | shared/datatypes/keywords.go | handle | func (k *Keywords) handle(m *Msg) string {
if k == nil {
return ""
}
for _, intent := range m.StructuredInput.Intents {
fn, ok := k.Dict["I_"+intent]
if !ok {
continue
}
// If we find an intent function, use that.
return fn(m)
}
// No matching intent was found, so check for both Command and Object.
eng := porter2.Stemmer
for _, cmd := range m.StructuredInput.Commands {
cmd = strings.ToLower(eng.Stem(cmd))
for _, obj := range m.StructuredInput.Objects {
obj = strings.ToLower(eng.Stem(obj))
fn, ok := k.Dict["CO_"+cmd+"_"+obj]
if !ok {
continue
}
return fn(m)
}
}
return ""
} | go | func (k *Keywords) handle(m *Msg) string {
if k == nil {
return ""
}
for _, intent := range m.StructuredInput.Intents {
fn, ok := k.Dict["I_"+intent]
if !ok {
continue
}
// If we find an intent function, use that.
return fn(m)
}
// No matching intent was found, so check for both Command and Object.
eng := porter2.Stemmer
for _, cmd := range m.StructuredInput.Commands {
cmd = strings.ToLower(eng.Stem(cmd))
for _, obj := range m.StructuredInput.Objects {
obj = strings.ToLower(eng.Stem(obj))
fn, ok := k.Dict["CO_"+cmd+"_"+obj]
if !ok {
continue
}
return fn(m)
}
}
return ""
} | [
"func",
"(",
"k",
"*",
"Keywords",
")",
"handle",
"(",
"m",
"*",
"Msg",
")",
"string",
"{",
"if",
"k",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"for",
"_",
",",
"intent",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Intents",
"{",
"fn",
",",
"ok",
":=",
"k",
".",
"Dict",
"[",
"\"",
"\"",
"+",
"intent",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"// If we find an intent function, use that.",
"return",
"fn",
"(",
"m",
")",
"\n",
"}",
"\n\n",
"// No matching intent was found, so check for both Command and Object.",
"eng",
":=",
"porter2",
".",
"Stemmer",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Commands",
"{",
"cmd",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"cmd",
")",
")",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"m",
".",
"StructuredInput",
".",
"Objects",
"{",
"obj",
"=",
"strings",
".",
"ToLower",
"(",
"eng",
".",
"Stem",
"(",
"obj",
")",
")",
"\n",
"fn",
",",
"ok",
":=",
"k",
".",
"Dict",
"[",
"\"",
"\"",
"+",
"cmd",
"+",
"\"",
"\"",
"+",
"obj",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"fn",
"(",
"m",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // handle runs the first matching KeywordFn in the sentence. | [
"handle",
"runs",
"the",
"first",
"matching",
"KeywordFn",
"in",
"the",
"sentence",
"."
] | 48a5b1e70afca321d0c522922746b667c29a6070 | https://github.com/itsabot/itsabot/blob/48a5b1e70afca321d0c522922746b667c29a6070/shared/datatypes/keywords.go#L29-L57 |
5,007 | mdlayher/arp | client.go | Dial | func Dial(ifi *net.Interface) (*Client, error) {
// Open raw socket to send and receive ARP packets using ethernet frames
// we build ourselves.
p, err := raw.ListenPacket(ifi, protocolARP, nil)
if err != nil {
return nil, err
}
return New(ifi, p)
} | go | func Dial(ifi *net.Interface) (*Client, error) {
// Open raw socket to send and receive ARP packets using ethernet frames
// we build ourselves.
p, err := raw.ListenPacket(ifi, protocolARP, nil)
if err != nil {
return nil, err
}
return New(ifi, p)
} | [
"func",
"Dial",
"(",
"ifi",
"*",
"net",
".",
"Interface",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"// Open raw socket to send and receive ARP packets using ethernet frames",
"// we build ourselves.",
"p",
",",
"err",
":=",
"raw",
".",
"ListenPacket",
"(",
"ifi",
",",
"protocolARP",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"New",
"(",
"ifi",
",",
"p",
")",
"\n",
"}"
] | // Dial creates a new Client using the specified network interface.
// Dial retrieves the IPv4 address of the interface and binds a raw socket
// to send and receive ARP packets. | [
"Dial",
"creates",
"a",
"new",
"Client",
"using",
"the",
"specified",
"network",
"interface",
".",
"Dial",
"retrieves",
"the",
"IPv4",
"address",
"of",
"the",
"interface",
"and",
"binds",
"a",
"raw",
"socket",
"to",
"send",
"and",
"receive",
"ARP",
"packets",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L33-L41 |
5,008 | mdlayher/arp | client.go | newClient | func newClient(ifi *net.Interface, p net.PacketConn, addrs []net.Addr) (*Client, error) {
ip, err := firstIPv4Addr(addrs)
if err != nil {
return nil, err
}
return &Client{
ifi: ifi,
ip: ip,
p: p,
}, nil
} | go | func newClient(ifi *net.Interface, p net.PacketConn, addrs []net.Addr) (*Client, error) {
ip, err := firstIPv4Addr(addrs)
if err != nil {
return nil, err
}
return &Client{
ifi: ifi,
ip: ip,
p: p,
}, nil
} | [
"func",
"newClient",
"(",
"ifi",
"*",
"net",
".",
"Interface",
",",
"p",
"net",
".",
"PacketConn",
",",
"addrs",
"[",
"]",
"net",
".",
"Addr",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"ip",
",",
"err",
":=",
"firstIPv4Addr",
"(",
"addrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Client",
"{",
"ifi",
":",
"ifi",
",",
"ip",
":",
"ip",
",",
"p",
":",
"p",
",",
"}",
",",
"nil",
"\n",
"}"
] | // newClient is the internal, generic implementation of newClient. It is used
// to allow an arbitrary net.PacketConn to be used in a Client, so testing
// is easier to accomplish. | [
"newClient",
"is",
"the",
"internal",
"generic",
"implementation",
"of",
"newClient",
".",
"It",
"is",
"used",
"to",
"allow",
"an",
"arbitrary",
"net",
".",
"PacketConn",
"to",
"be",
"used",
"in",
"a",
"Client",
"so",
"testing",
"is",
"easier",
"to",
"accomplish",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L61-L72 |
5,009 | mdlayher/arp | client.go | Request | func (c *Client) Request(ip net.IP) error {
if c.ip == nil {
return errNoIPv4Addr
}
// Create ARP packet for broadcast address to attempt to find the
// hardware address of the input IP address
arp, err := NewPacket(OperationRequest, c.ifi.HardwareAddr, c.ip, ethernet.Broadcast, ip)
if err != nil {
return err
}
return c.WriteTo(arp, ethernet.Broadcast)
} | go | func (c *Client) Request(ip net.IP) error {
if c.ip == nil {
return errNoIPv4Addr
}
// Create ARP packet for broadcast address to attempt to find the
// hardware address of the input IP address
arp, err := NewPacket(OperationRequest, c.ifi.HardwareAddr, c.ip, ethernet.Broadcast, ip)
if err != nil {
return err
}
return c.WriteTo(arp, ethernet.Broadcast)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Request",
"(",
"ip",
"net",
".",
"IP",
")",
"error",
"{",
"if",
"c",
".",
"ip",
"==",
"nil",
"{",
"return",
"errNoIPv4Addr",
"\n",
"}",
"\n\n",
"// Create ARP packet for broadcast address to attempt to find the",
"// hardware address of the input IP address",
"arp",
",",
"err",
":=",
"NewPacket",
"(",
"OperationRequest",
",",
"c",
".",
"ifi",
".",
"HardwareAddr",
",",
"c",
".",
"ip",
",",
"ethernet",
".",
"Broadcast",
",",
"ip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"WriteTo",
"(",
"arp",
",",
"ethernet",
".",
"Broadcast",
")",
"\n",
"}"
] | // Request sends an ARP request, asking for the hardware address
// associated with an IPv4 address. The response, if any, can be read
// with the Read method.
//
// Unlike Resolve, which provides an easier interface for getting the
// hardware address, Request allows sending many requests in a row,
// retrieving the responses afterwards. | [
"Request",
"sends",
"an",
"ARP",
"request",
"asking",
"for",
"the",
"hardware",
"address",
"associated",
"with",
"an",
"IPv4",
"address",
".",
"The",
"response",
"if",
"any",
"can",
"be",
"read",
"with",
"the",
"Read",
"method",
".",
"Unlike",
"Resolve",
"which",
"provides",
"an",
"easier",
"interface",
"for",
"getting",
"the",
"hardware",
"address",
"Request",
"allows",
"sending",
"many",
"requests",
"in",
"a",
"row",
"retrieving",
"the",
"responses",
"afterwards",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L87-L99 |
5,010 | mdlayher/arp | client.go | Read | func (c *Client) Read() (*Packet, *ethernet.Frame, error) {
buf := make([]byte, 128)
for {
n, _, err := c.p.ReadFrom(buf)
if err != nil {
return nil, nil, err
}
p, eth, err := parsePacket(buf[:n])
if err != nil {
if err == errInvalidARPPacket {
continue
}
return nil, nil, err
}
return p, eth, nil
}
} | go | func (c *Client) Read() (*Packet, *ethernet.Frame, error) {
buf := make([]byte, 128)
for {
n, _, err := c.p.ReadFrom(buf)
if err != nil {
return nil, nil, err
}
p, eth, err := parsePacket(buf[:n])
if err != nil {
if err == errInvalidARPPacket {
continue
}
return nil, nil, err
}
return p, eth, nil
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Read",
"(",
")",
"(",
"*",
"Packet",
",",
"*",
"ethernet",
".",
"Frame",
",",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"128",
")",
"\n",
"for",
"{",
"n",
",",
"_",
",",
"err",
":=",
"c",
".",
"p",
".",
"ReadFrom",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"p",
",",
"eth",
",",
"err",
":=",
"parsePacket",
"(",
"buf",
"[",
":",
"n",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errInvalidARPPacket",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"p",
",",
"eth",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // Read reads a single ARP packet and returns it, together with its
// ethernet frame. | [
"Read",
"reads",
"a",
"single",
"ARP",
"packet",
"and",
"returns",
"it",
"together",
"with",
"its",
"ethernet",
"frame",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L129-L146 |
5,011 | mdlayher/arp | client.go | WriteTo | func (c *Client) WriteTo(p *Packet, addr net.HardwareAddr) error {
pb, err := p.MarshalBinary()
if err != nil {
return err
}
f := ðernet.Frame{
Destination: p.TargetHardwareAddr,
Source: p.SenderHardwareAddr,
EtherType: ethernet.EtherTypeARP,
Payload: pb,
}
fb, err := f.MarshalBinary()
if err != nil {
return err
}
_, err = c.p.WriteTo(fb, &raw.Addr{HardwareAddr: addr})
return err
} | go | func (c *Client) WriteTo(p *Packet, addr net.HardwareAddr) error {
pb, err := p.MarshalBinary()
if err != nil {
return err
}
f := ðernet.Frame{
Destination: p.TargetHardwareAddr,
Source: p.SenderHardwareAddr,
EtherType: ethernet.EtherTypeARP,
Payload: pb,
}
fb, err := f.MarshalBinary()
if err != nil {
return err
}
_, err = c.p.WriteTo(fb, &raw.Addr{HardwareAddr: addr})
return err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"WriteTo",
"(",
"p",
"*",
"Packet",
",",
"addr",
"net",
".",
"HardwareAddr",
")",
"error",
"{",
"pb",
",",
"err",
":=",
"p",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"f",
":=",
"&",
"ethernet",
".",
"Frame",
"{",
"Destination",
":",
"p",
".",
"TargetHardwareAddr",
",",
"Source",
":",
"p",
".",
"SenderHardwareAddr",
",",
"EtherType",
":",
"ethernet",
".",
"EtherTypeARP",
",",
"Payload",
":",
"pb",
",",
"}",
"\n\n",
"fb",
",",
"err",
":=",
"f",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"c",
".",
"p",
".",
"WriteTo",
"(",
"fb",
",",
"&",
"raw",
".",
"Addr",
"{",
"HardwareAddr",
":",
"addr",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // WriteTo writes a single ARP packet to addr. Note that addr should,
// but doesn't have to, match the target hardware address of the ARP
// packet. | [
"WriteTo",
"writes",
"a",
"single",
"ARP",
"packet",
"to",
"addr",
".",
"Note",
"that",
"addr",
"should",
"but",
"doesn",
"t",
"have",
"to",
"match",
"the",
"target",
"hardware",
"address",
"of",
"the",
"ARP",
"packet",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L151-L171 |
5,012 | mdlayher/arp | client.go | Reply | func (c *Client) Reply(req *Packet, hwAddr net.HardwareAddr, ip net.IP) error {
p, err := NewPacket(OperationReply, hwAddr, ip, req.SenderHardwareAddr, req.SenderIP)
if err != nil {
return err
}
return c.WriteTo(p, req.SenderHardwareAddr)
} | go | func (c *Client) Reply(req *Packet, hwAddr net.HardwareAddr, ip net.IP) error {
p, err := NewPacket(OperationReply, hwAddr, ip, req.SenderHardwareAddr, req.SenderIP)
if err != nil {
return err
}
return c.WriteTo(p, req.SenderHardwareAddr)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Reply",
"(",
"req",
"*",
"Packet",
",",
"hwAddr",
"net",
".",
"HardwareAddr",
",",
"ip",
"net",
".",
"IP",
")",
"error",
"{",
"p",
",",
"err",
":=",
"NewPacket",
"(",
"OperationReply",
",",
"hwAddr",
",",
"ip",
",",
"req",
".",
"SenderHardwareAddr",
",",
"req",
".",
"SenderIP",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"WriteTo",
"(",
"p",
",",
"req",
".",
"SenderHardwareAddr",
")",
"\n",
"}"
] | // Reply constructs and sends a reply to an ARP request. On the ARP
// layer, it will be addressed to the sender address of the packet. On
// the ethernet layer, it will be sent to the actual remote address
// from which the request was received.
//
// For more fine-grained control, use WriteTo to write a custom
// response. | [
"Reply",
"constructs",
"and",
"sends",
"a",
"reply",
"to",
"an",
"ARP",
"request",
".",
"On",
"the",
"ARP",
"layer",
"it",
"will",
"be",
"addressed",
"to",
"the",
"sender",
"address",
"of",
"the",
"packet",
".",
"On",
"the",
"ethernet",
"layer",
"it",
"will",
"be",
"sent",
"to",
"the",
"actual",
"remote",
"address",
"from",
"which",
"the",
"request",
"was",
"received",
".",
"For",
"more",
"fine",
"-",
"grained",
"control",
"use",
"WriteTo",
"to",
"write",
"a",
"custom",
"response",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L180-L186 |
5,013 | mdlayher/arp | client.go | firstIPv4Addr | func firstIPv4Addr(addrs []net.Addr) (net.IP, error) {
for _, a := range addrs {
if a.Network() != "ip+net" {
continue
}
ip, _, err := net.ParseCIDR(a.String())
if err != nil {
return nil, err
}
// "If ip is not an IPv4 address, To4 returns nil."
// Reference: http://golang.org/pkg/net/#IP.To4
if ip4 := ip.To4(); ip4 != nil {
return ip4, nil
}
}
return nil, nil
} | go | func firstIPv4Addr(addrs []net.Addr) (net.IP, error) {
for _, a := range addrs {
if a.Network() != "ip+net" {
continue
}
ip, _, err := net.ParseCIDR(a.String())
if err != nil {
return nil, err
}
// "If ip is not an IPv4 address, To4 returns nil."
// Reference: http://golang.org/pkg/net/#IP.To4
if ip4 := ip.To4(); ip4 != nil {
return ip4, nil
}
}
return nil, nil
} | [
"func",
"firstIPv4Addr",
"(",
"addrs",
"[",
"]",
"net",
".",
"Addr",
")",
"(",
"net",
".",
"IP",
",",
"error",
")",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"addrs",
"{",
"if",
"a",
".",
"Network",
"(",
")",
"!=",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"a",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// \"If ip is not an IPv4 address, To4 returns nil.\"",
"// Reference: http://golang.org/pkg/net/#IP.To4",
"if",
"ip4",
":=",
"ip",
".",
"To4",
"(",
")",
";",
"ip4",
"!=",
"nil",
"{",
"return",
"ip4",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // firstIPv4Addr attempts to retrieve the first detected IPv4 address from an
// input slice of network addresses. | [
"firstIPv4Addr",
"attempts",
"to",
"retrieve",
"the",
"first",
"detected",
"IPv4",
"address",
"from",
"an",
"input",
"slice",
"of",
"network",
"addresses",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/client.go#L228-L247 |
5,014 | mdlayher/arp | packet.go | MarshalBinary | func (p *Packet) MarshalBinary() ([]byte, error) {
// 2 bytes: hardware type
// 2 bytes: protocol type
// 1 byte : hardware address length
// 1 byte : protocol length
// 2 bytes: operation
// N bytes: source hardware address
// N bytes: source protocol address
// N bytes: target hardware address
// N bytes: target protocol address
// Though an IPv4 address should always 4 bytes, go-fuzz
// very quickly created several crasher scenarios which
// indicated that these values can lie.
b := make([]byte, 2+2+1+1+2+(p.IPLength*2)+(p.HardwareAddrLength*2))
// Marshal fixed length data
binary.BigEndian.PutUint16(b[0:2], p.HardwareType)
binary.BigEndian.PutUint16(b[2:4], p.ProtocolType)
b[4] = p.HardwareAddrLength
b[5] = p.IPLength
binary.BigEndian.PutUint16(b[6:8], uint16(p.Operation))
// Marshal variable length data at correct offset using lengths
// defined in p
n := 8
hal := int(p.HardwareAddrLength)
pl := int(p.IPLength)
copy(b[n:n+hal], p.SenderHardwareAddr)
n += hal
copy(b[n:n+pl], p.SenderIP)
n += pl
copy(b[n:n+hal], p.TargetHardwareAddr)
n += hal
copy(b[n:n+pl], p.TargetIP)
return b, nil
} | go | func (p *Packet) MarshalBinary() ([]byte, error) {
// 2 bytes: hardware type
// 2 bytes: protocol type
// 1 byte : hardware address length
// 1 byte : protocol length
// 2 bytes: operation
// N bytes: source hardware address
// N bytes: source protocol address
// N bytes: target hardware address
// N bytes: target protocol address
// Though an IPv4 address should always 4 bytes, go-fuzz
// very quickly created several crasher scenarios which
// indicated that these values can lie.
b := make([]byte, 2+2+1+1+2+(p.IPLength*2)+(p.HardwareAddrLength*2))
// Marshal fixed length data
binary.BigEndian.PutUint16(b[0:2], p.HardwareType)
binary.BigEndian.PutUint16(b[2:4], p.ProtocolType)
b[4] = p.HardwareAddrLength
b[5] = p.IPLength
binary.BigEndian.PutUint16(b[6:8], uint16(p.Operation))
// Marshal variable length data at correct offset using lengths
// defined in p
n := 8
hal := int(p.HardwareAddrLength)
pl := int(p.IPLength)
copy(b[n:n+hal], p.SenderHardwareAddr)
n += hal
copy(b[n:n+pl], p.SenderIP)
n += pl
copy(b[n:n+hal], p.TargetHardwareAddr)
n += hal
copy(b[n:n+pl], p.TargetIP)
return b, nil
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// 2 bytes: hardware type",
"// 2 bytes: protocol type",
"// 1 byte : hardware address length",
"// 1 byte : protocol length",
"// 2 bytes: operation",
"// N bytes: source hardware address",
"// N bytes: source protocol address",
"// N bytes: target hardware address",
"// N bytes: target protocol address",
"// Though an IPv4 address should always 4 bytes, go-fuzz",
"// very quickly created several crasher scenarios which",
"// indicated that these values can lie.",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
"+",
"2",
"+",
"1",
"+",
"1",
"+",
"2",
"+",
"(",
"p",
".",
"IPLength",
"*",
"2",
")",
"+",
"(",
"p",
".",
"HardwareAddrLength",
"*",
"2",
")",
")",
"\n\n",
"// Marshal fixed length data",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"b",
"[",
"0",
":",
"2",
"]",
",",
"p",
".",
"HardwareType",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"b",
"[",
"2",
":",
"4",
"]",
",",
"p",
".",
"ProtocolType",
")",
"\n\n",
"b",
"[",
"4",
"]",
"=",
"p",
".",
"HardwareAddrLength",
"\n",
"b",
"[",
"5",
"]",
"=",
"p",
".",
"IPLength",
"\n\n",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"b",
"[",
"6",
":",
"8",
"]",
",",
"uint16",
"(",
"p",
".",
"Operation",
")",
")",
"\n\n",
"// Marshal variable length data at correct offset using lengths",
"// defined in p",
"n",
":=",
"8",
"\n",
"hal",
":=",
"int",
"(",
"p",
".",
"HardwareAddrLength",
")",
"\n",
"pl",
":=",
"int",
"(",
"p",
".",
"IPLength",
")",
"\n\n",
"copy",
"(",
"b",
"[",
"n",
":",
"n",
"+",
"hal",
"]",
",",
"p",
".",
"SenderHardwareAddr",
")",
"\n",
"n",
"+=",
"hal",
"\n\n",
"copy",
"(",
"b",
"[",
"n",
":",
"n",
"+",
"pl",
"]",
",",
"p",
".",
"SenderIP",
")",
"\n",
"n",
"+=",
"pl",
"\n\n",
"copy",
"(",
"b",
"[",
"n",
":",
"n",
"+",
"hal",
"]",
",",
"p",
".",
"TargetHardwareAddr",
")",
"\n",
"n",
"+=",
"hal",
"\n\n",
"copy",
"(",
"b",
"[",
"n",
":",
"n",
"+",
"pl",
"]",
",",
"p",
".",
"TargetIP",
")",
"\n\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // MarshalBinary allocates a byte slice containing the data from a Packet.
//
// MarshalBinary never returns an error. | [
"MarshalBinary",
"allocates",
"a",
"byte",
"slice",
"containing",
"the",
"data",
"from",
"a",
"Packet",
".",
"MarshalBinary",
"never",
"returns",
"an",
"error",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/packet.go#L127-L172 |
5,015 | mdlayher/arp | packet.go | UnmarshalBinary | func (p *Packet) UnmarshalBinary(b []byte) error {
// Must have enough room to retrieve hardware address and IP lengths
if len(b) < 8 {
return io.ErrUnexpectedEOF
}
// Retrieve fixed length data
p.HardwareType = binary.BigEndian.Uint16(b[0:2])
p.ProtocolType = binary.BigEndian.Uint16(b[2:4])
p.HardwareAddrLength = b[4]
p.IPLength = b[5]
p.Operation = Operation(binary.BigEndian.Uint16(b[6:8]))
// Unmarshal variable length data at correct offset using lengths
// defined by ml and il
//
// These variables are meant to improve readability of offset calculations
// for the code below
n := 8
ml := int(p.HardwareAddrLength)
ml2 := ml * 2
il := int(p.IPLength)
il2 := il * 2
// Must have enough room to retrieve both hardware address and IP addresses
addrl := n + ml2 + il2
if len(b) < addrl {
return io.ErrUnexpectedEOF
}
// Allocate single byte slice to store address information, which
// is resliced into fields
bb := make([]byte, addrl-n)
// Sender hardware address
copy(bb[0:ml], b[n:n+ml])
p.SenderHardwareAddr = bb[0:ml]
n += ml
// Sender IP address
copy(bb[ml:ml+il], b[n:n+il])
p.SenderIP = bb[ml : ml+il]
n += il
// Target hardware address
copy(bb[ml+il:ml2+il], b[n:n+ml])
p.TargetHardwareAddr = bb[ml+il : ml2+il]
n += ml
// Target IP address
copy(bb[ml2+il:ml2+il2], b[n:n+il])
p.TargetIP = bb[ml2+il : ml2+il2]
return nil
} | go | func (p *Packet) UnmarshalBinary(b []byte) error {
// Must have enough room to retrieve hardware address and IP lengths
if len(b) < 8 {
return io.ErrUnexpectedEOF
}
// Retrieve fixed length data
p.HardwareType = binary.BigEndian.Uint16(b[0:2])
p.ProtocolType = binary.BigEndian.Uint16(b[2:4])
p.HardwareAddrLength = b[4]
p.IPLength = b[5]
p.Operation = Operation(binary.BigEndian.Uint16(b[6:8]))
// Unmarshal variable length data at correct offset using lengths
// defined by ml and il
//
// These variables are meant to improve readability of offset calculations
// for the code below
n := 8
ml := int(p.HardwareAddrLength)
ml2 := ml * 2
il := int(p.IPLength)
il2 := il * 2
// Must have enough room to retrieve both hardware address and IP addresses
addrl := n + ml2 + il2
if len(b) < addrl {
return io.ErrUnexpectedEOF
}
// Allocate single byte slice to store address information, which
// is resliced into fields
bb := make([]byte, addrl-n)
// Sender hardware address
copy(bb[0:ml], b[n:n+ml])
p.SenderHardwareAddr = bb[0:ml]
n += ml
// Sender IP address
copy(bb[ml:ml+il], b[n:n+il])
p.SenderIP = bb[ml : ml+il]
n += il
// Target hardware address
copy(bb[ml+il:ml2+il], b[n:n+ml])
p.TargetHardwareAddr = bb[ml+il : ml2+il]
n += ml
// Target IP address
copy(bb[ml2+il:ml2+il2], b[n:n+il])
p.TargetIP = bb[ml2+il : ml2+il2]
return nil
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"UnmarshalBinary",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"// Must have enough room to retrieve hardware address and IP lengths",
"if",
"len",
"(",
"b",
")",
"<",
"8",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"// Retrieve fixed length data",
"p",
".",
"HardwareType",
"=",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"b",
"[",
"0",
":",
"2",
"]",
")",
"\n",
"p",
".",
"ProtocolType",
"=",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"b",
"[",
"2",
":",
"4",
"]",
")",
"\n\n",
"p",
".",
"HardwareAddrLength",
"=",
"b",
"[",
"4",
"]",
"\n",
"p",
".",
"IPLength",
"=",
"b",
"[",
"5",
"]",
"\n\n",
"p",
".",
"Operation",
"=",
"Operation",
"(",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"b",
"[",
"6",
":",
"8",
"]",
")",
")",
"\n\n",
"// Unmarshal variable length data at correct offset using lengths",
"// defined by ml and il",
"//",
"// These variables are meant to improve readability of offset calculations",
"// for the code below",
"n",
":=",
"8",
"\n",
"ml",
":=",
"int",
"(",
"p",
".",
"HardwareAddrLength",
")",
"\n",
"ml2",
":=",
"ml",
"*",
"2",
"\n",
"il",
":=",
"int",
"(",
"p",
".",
"IPLength",
")",
"\n",
"il2",
":=",
"il",
"*",
"2",
"\n\n",
"// Must have enough room to retrieve both hardware address and IP addresses",
"addrl",
":=",
"n",
"+",
"ml2",
"+",
"il2",
"\n",
"if",
"len",
"(",
"b",
")",
"<",
"addrl",
"{",
"return",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n\n",
"// Allocate single byte slice to store address information, which",
"// is resliced into fields",
"bb",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"addrl",
"-",
"n",
")",
"\n\n",
"// Sender hardware address",
"copy",
"(",
"bb",
"[",
"0",
":",
"ml",
"]",
",",
"b",
"[",
"n",
":",
"n",
"+",
"ml",
"]",
")",
"\n",
"p",
".",
"SenderHardwareAddr",
"=",
"bb",
"[",
"0",
":",
"ml",
"]",
"\n",
"n",
"+=",
"ml",
"\n\n",
"// Sender IP address",
"copy",
"(",
"bb",
"[",
"ml",
":",
"ml",
"+",
"il",
"]",
",",
"b",
"[",
"n",
":",
"n",
"+",
"il",
"]",
")",
"\n",
"p",
".",
"SenderIP",
"=",
"bb",
"[",
"ml",
":",
"ml",
"+",
"il",
"]",
"\n",
"n",
"+=",
"il",
"\n\n",
"// Target hardware address",
"copy",
"(",
"bb",
"[",
"ml",
"+",
"il",
":",
"ml2",
"+",
"il",
"]",
",",
"b",
"[",
"n",
":",
"n",
"+",
"ml",
"]",
")",
"\n",
"p",
".",
"TargetHardwareAddr",
"=",
"bb",
"[",
"ml",
"+",
"il",
":",
"ml2",
"+",
"il",
"]",
"\n",
"n",
"+=",
"ml",
"\n\n",
"// Target IP address",
"copy",
"(",
"bb",
"[",
"ml2",
"+",
"il",
":",
"ml2",
"+",
"il2",
"]",
",",
"b",
"[",
"n",
":",
"n",
"+",
"il",
"]",
")",
"\n",
"p",
".",
"TargetIP",
"=",
"bb",
"[",
"ml2",
"+",
"il",
":",
"ml2",
"+",
"il2",
"]",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinary unmarshals a raw byte slice into a Packet. | [
"UnmarshalBinary",
"unmarshals",
"a",
"raw",
"byte",
"slice",
"into",
"a",
"Packet",
"."
] | 98a83c8a27177c5179d02d41ad50b0cce8e59338 | https://github.com/mdlayher/arp/blob/98a83c8a27177c5179d02d41ad50b0cce8e59338/packet.go#L175-L232 |
5,016 | nleof/goyesql | goyesql.go | ParseFile | func ParseFile(path string) (Queries, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return ParseReader(file)
} | go | func ParseFile(path string) (Queries, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return ParseReader(file)
} | [
"func",
"ParseFile",
"(",
"path",
"string",
")",
"(",
"Queries",
",",
"error",
")",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"return",
"ParseReader",
"(",
"file",
")",
"\n",
"}"
] | // Some helpers to read files
// ParseFile reads a file and return Queries or an error | [
"Some",
"helpers",
"to",
"read",
"files",
"ParseFile",
"reads",
"a",
"file",
"and",
"return",
"Queries",
"or",
"an",
"error"
] | 531a8afe09e9f59b27f7988fae377ecdc015eb11 | https://github.com/nleof/goyesql/blob/531a8afe09e9f59b27f7988fae377ecdc015eb11/goyesql.go#L16-L24 |
5,017 | nleof/goyesql | goyesql.go | MustParseFile | func MustParseFile(path string) Queries {
queries, err := ParseFile(path)
if err != nil {
panic(err)
}
return queries
} | go | func MustParseFile(path string) Queries {
queries, err := ParseFile(path)
if err != nil {
panic(err)
}
return queries
} | [
"func",
"MustParseFile",
"(",
"path",
"string",
")",
"Queries",
"{",
"queries",
",",
"err",
":=",
"ParseFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"queries",
"\n",
"}"
] | // MustParseFile calls ParseFile but panic if an error occurs | [
"MustParseFile",
"calls",
"ParseFile",
"but",
"panic",
"if",
"an",
"error",
"occurs"
] | 531a8afe09e9f59b27f7988fae377ecdc015eb11 | https://github.com/nleof/goyesql/blob/531a8afe09e9f59b27f7988fae377ecdc015eb11/goyesql.go#L27-L34 |
5,018 | nleof/goyesql | goyesql.go | MustParseBytes | func MustParseBytes(b []byte) Queries {
queries, err := ParseBytes(b)
if err != nil {
panic(err)
}
return queries
} | go | func MustParseBytes(b []byte) Queries {
queries, err := ParseBytes(b)
if err != nil {
panic(err)
}
return queries
} | [
"func",
"MustParseBytes",
"(",
"b",
"[",
"]",
"byte",
")",
"Queries",
"{",
"queries",
",",
"err",
":=",
"ParseBytes",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"queries",
"\n",
"}"
] | // MustParseBytes parses bytes but panics if an error occurs. | [
"MustParseBytes",
"parses",
"bytes",
"but",
"panics",
"if",
"an",
"error",
"occurs",
"."
] | 531a8afe09e9f59b27f7988fae377ecdc015eb11 | https://github.com/nleof/goyesql/blob/531a8afe09e9f59b27f7988fae377ecdc015eb11/goyesql.go#L42-L49 |
5,019 | nleof/goyesql | scanner.go | ParseReader | func ParseReader(reader io.Reader) (Queries, error) {
var (
lastTag Tag
lastLine parsedLine
)
queries := make(Queries)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := parseLine(scanner.Text())
switch line.Type {
case lineBlank, lineComment:
// we don't care about blank and comment lines
continue
case lineQuery:
// got a query but no tag before
if lastTag == "" {
return nil, ErrTagMissing
}
query := line.Value
// if query is multiline
if queries[lastTag] != "" {
query = " " + query
}
queries[lastTag] += query
case lineTag:
// got a tag after another tag
if lastLine.Type == lineTag {
return nil, ErrTagOverwritten
}
lastTag = Tag(line.Value)
}
lastLine = line
}
if err := scanner.Err(); err != nil {
return nil, err
}
return queries, nil
} | go | func ParseReader(reader io.Reader) (Queries, error) {
var (
lastTag Tag
lastLine parsedLine
)
queries := make(Queries)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := parseLine(scanner.Text())
switch line.Type {
case lineBlank, lineComment:
// we don't care about blank and comment lines
continue
case lineQuery:
// got a query but no tag before
if lastTag == "" {
return nil, ErrTagMissing
}
query := line.Value
// if query is multiline
if queries[lastTag] != "" {
query = " " + query
}
queries[lastTag] += query
case lineTag:
// got a tag after another tag
if lastLine.Type == lineTag {
return nil, ErrTagOverwritten
}
lastTag = Tag(line.Value)
}
lastLine = line
}
if err := scanner.Err(); err != nil {
return nil, err
}
return queries, nil
} | [
"func",
"ParseReader",
"(",
"reader",
"io",
".",
"Reader",
")",
"(",
"Queries",
",",
"error",
")",
"{",
"var",
"(",
"lastTag",
"Tag",
"\n",
"lastLine",
"parsedLine",
"\n",
")",
"\n\n",
"queries",
":=",
"make",
"(",
"Queries",
")",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"reader",
")",
"\n\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"parseLine",
"(",
"scanner",
".",
"Text",
"(",
")",
")",
"\n\n",
"switch",
"line",
".",
"Type",
"{",
"case",
"lineBlank",
",",
"lineComment",
":",
"// we don't care about blank and comment lines",
"continue",
"\n\n",
"case",
"lineQuery",
":",
"// got a query but no tag before",
"if",
"lastTag",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"ErrTagMissing",
"\n",
"}",
"\n\n",
"query",
":=",
"line",
".",
"Value",
"\n",
"// if query is multiline",
"if",
"queries",
"[",
"lastTag",
"]",
"!=",
"\"",
"\"",
"{",
"query",
"=",
"\"",
"\"",
"+",
"query",
"\n",
"}",
"\n",
"queries",
"[",
"lastTag",
"]",
"+=",
"query",
"\n\n",
"case",
"lineTag",
":",
"// got a tag after another tag",
"if",
"lastLine",
".",
"Type",
"==",
"lineTag",
"{",
"return",
"nil",
",",
"ErrTagOverwritten",
"\n",
"}",
"\n\n",
"lastTag",
"=",
"Tag",
"(",
"line",
".",
"Value",
")",
"\n\n",
"}",
"\n\n",
"lastLine",
"=",
"line",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"scanner",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"queries",
",",
"nil",
"\n",
"}"
] | // ParseReader takes an io.Reader and returns Queries or an error. | [
"ParseReader",
"takes",
"an",
"io",
".",
"Reader",
"and",
"returns",
"Queries",
"or",
"an",
"error",
"."
] | 531a8afe09e9f59b27f7988fae377ecdc015eb11 | https://github.com/nleof/goyesql/blob/531a8afe09e9f59b27f7988fae377ecdc015eb11/scanner.go#L24-L73 |
5,020 | cactus/go-statsd-client | statsd/client.go | Close | func (s *Client) Close() error {
if s == nil {
return nil
}
err := s.sender.Close()
return err
} | go | func (s *Client) Close() error {
if s == nil {
return nil
}
err := s.sender.Close()
return err
} | [
"func",
"(",
"s",
"*",
"Client",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"s",
".",
"sender",
".",
"Close",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Close closes the connection and cleans up. | [
"Close",
"closes",
"the",
"connection",
"and",
"cleans",
"up",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L68-L75 |
5,021 | cactus/go-statsd-client | statsd/client.go | submit | func (s *Client) submit(stat, vprefix string, value interface{}, suffix string, rate float32) error {
data := bufPool.Get()
defer bufPool.Put(data)
if s.prefix != "" {
data.WriteString(s.prefix)
data.WriteString(".")
}
data.WriteString(stat)
data.WriteString(":")
if vprefix != "" {
data.WriteString(vprefix)
}
// sadly, no way to jam this back into the bytes.Buffer without
// doing a few allocations... avoiding those is the whole point here...
// so from here on out just use it as a raw []byte
b := data.Bytes()
switch v := value.(type) {
case string:
b = append(b, v...)
case int64:
b = strconv.AppendInt(b, v, 10)
case float64:
b = strconv.AppendFloat(b, v, 'f', -1, 64)
default:
return fmt.Errorf("No matching type format")
}
if suffix != "" {
b = append(b, suffix...)
}
if rate < 1 {
b = append(b, "|@"...)
b = strconv.AppendFloat(b, float64(rate), 'f', 6, 32)
}
_, err := s.sender.Send(b)
return err
} | go | func (s *Client) submit(stat, vprefix string, value interface{}, suffix string, rate float32) error {
data := bufPool.Get()
defer bufPool.Put(data)
if s.prefix != "" {
data.WriteString(s.prefix)
data.WriteString(".")
}
data.WriteString(stat)
data.WriteString(":")
if vprefix != "" {
data.WriteString(vprefix)
}
// sadly, no way to jam this back into the bytes.Buffer without
// doing a few allocations... avoiding those is the whole point here...
// so from here on out just use it as a raw []byte
b := data.Bytes()
switch v := value.(type) {
case string:
b = append(b, v...)
case int64:
b = strconv.AppendInt(b, v, 10)
case float64:
b = strconv.AppendFloat(b, v, 'f', -1, 64)
default:
return fmt.Errorf("No matching type format")
}
if suffix != "" {
b = append(b, suffix...)
}
if rate < 1 {
b = append(b, "|@"...)
b = strconv.AppendFloat(b, float64(rate), 'f', 6, 32)
}
_, err := s.sender.Send(b)
return err
} | [
"func",
"(",
"s",
"*",
"Client",
")",
"submit",
"(",
"stat",
",",
"vprefix",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"suffix",
"string",
",",
"rate",
"float32",
")",
"error",
"{",
"data",
":=",
"bufPool",
".",
"Get",
"(",
")",
"\n",
"defer",
"bufPool",
".",
"Put",
"(",
"data",
")",
"\n\n",
"if",
"s",
".",
"prefix",
"!=",
"\"",
"\"",
"{",
"data",
".",
"WriteString",
"(",
"s",
".",
"prefix",
")",
"\n",
"data",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"data",
".",
"WriteString",
"(",
"stat",
")",
"\n",
"data",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"vprefix",
"!=",
"\"",
"\"",
"{",
"data",
".",
"WriteString",
"(",
"vprefix",
")",
"\n",
"}",
"\n\n",
"// sadly, no way to jam this back into the bytes.Buffer without",
"// doing a few allocations... avoiding those is the whole point here...",
"// so from here on out just use it as a raw []byte",
"b",
":=",
"data",
".",
"Bytes",
"(",
")",
"\n\n",
"switch",
"v",
":=",
"value",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"b",
"=",
"append",
"(",
"b",
",",
"v",
"...",
")",
"\n",
"case",
"int64",
":",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"v",
",",
"10",
")",
"\n",
"case",
"float64",
":",
"b",
"=",
"strconv",
".",
"AppendFloat",
"(",
"b",
",",
"v",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"suffix",
"!=",
"\"",
"\"",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"suffix",
"...",
")",
"\n",
"}",
"\n\n",
"if",
"rate",
"<",
"1",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"\"",
"\"",
"...",
")",
"\n",
"b",
"=",
"strconv",
".",
"AppendFloat",
"(",
"b",
",",
"float64",
"(",
"rate",
")",
",",
"'f'",
",",
"6",
",",
"32",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"s",
".",
"sender",
".",
"Send",
"(",
"b",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // submit an already sampled raw stat | [
"submit",
"an",
"already",
"sampled",
"raw",
"stat"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L200-L243 |
5,022 | cactus/go-statsd-client | statsd/client.go | includeStat | func (s *Client) includeStat(rate float32) bool {
if s == nil {
return false
}
// test for nil in case someone builds their own
// client without calling new (result is nil sampler)
if s.sampler != nil {
return s.sampler(rate)
}
return DefaultSampler(rate)
} | go | func (s *Client) includeStat(rate float32) bool {
if s == nil {
return false
}
// test for nil in case someone builds their own
// client without calling new (result is nil sampler)
if s.sampler != nil {
return s.sampler(rate)
}
return DefaultSampler(rate)
} | [
"func",
"(",
"s",
"*",
"Client",
")",
"includeStat",
"(",
"rate",
"float32",
")",
"bool",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// test for nil in case someone builds their own",
"// client without calling new (result is nil sampler)",
"if",
"s",
".",
"sampler",
"!=",
"nil",
"{",
"return",
"s",
".",
"sampler",
"(",
"rate",
")",
"\n",
"}",
"\n",
"return",
"DefaultSampler",
"(",
"rate",
")",
"\n",
"}"
] | // check for nil client, and perform sampling calculation | [
"check",
"for",
"nil",
"client",
"and",
"perform",
"sampling",
"calculation"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L246-L257 |
5,023 | cactus/go-statsd-client | statsd/client.go | NewSubStatter | func (s *Client) NewSubStatter(prefix string) SubStatter {
var c *Client
if s != nil {
c = &Client{
prefix: joinPathComp(s.prefix, prefix),
sender: s.sender,
sampler: s.sampler,
}
}
return c
} | go | func (s *Client) NewSubStatter(prefix string) SubStatter {
var c *Client
if s != nil {
c = &Client{
prefix: joinPathComp(s.prefix, prefix),
sender: s.sender,
sampler: s.sampler,
}
}
return c
} | [
"func",
"(",
"s",
"*",
"Client",
")",
"NewSubStatter",
"(",
"prefix",
"string",
")",
"SubStatter",
"{",
"var",
"c",
"*",
"Client",
"\n",
"if",
"s",
"!=",
"nil",
"{",
"c",
"=",
"&",
"Client",
"{",
"prefix",
":",
"joinPathComp",
"(",
"s",
".",
"prefix",
",",
"prefix",
")",
",",
"sender",
":",
"s",
".",
"sender",
",",
"sampler",
":",
"s",
".",
"sampler",
",",
"}",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // NewSubStatter returns a SubStatter with appended prefix | [
"NewSubStatter",
"returns",
"a",
"SubStatter",
"with",
"appended",
"prefix"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L270-L280 |
5,024 | cactus/go-statsd-client | statsd/client.go | NewClientWithSender | func NewClientWithSender(sender Sender, prefix string) (Statter, error) {
if sender == nil {
return nil, fmt.Errorf("Client sender may not be nil")
}
return &Client{prefix: prefix, sender: sender}, nil
} | go | func NewClientWithSender(sender Sender, prefix string) (Statter, error) {
if sender == nil {
return nil, fmt.Errorf("Client sender may not be nil")
}
return &Client{prefix: prefix, sender: sender}, nil
} | [
"func",
"NewClientWithSender",
"(",
"sender",
"Sender",
",",
"prefix",
"string",
")",
"(",
"Statter",
",",
"error",
")",
"{",
"if",
"sender",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Client",
"{",
"prefix",
":",
"prefix",
",",
"sender",
":",
"sender",
"}",
",",
"nil",
"\n",
"}"
] | // NewClientWithSender returns a pointer to a new Client and an error.
//
// sender is an instance of a statsd.Sender interface and may not be nil
//
// prefix is the stastd client prefix. Can be "" if no prefix is desired. | [
"NewClientWithSender",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Client",
"and",
"an",
"error",
".",
"sender",
"is",
"an",
"instance",
"of",
"a",
"statsd",
".",
"Sender",
"interface",
"and",
"may",
"not",
"be",
"nil",
"prefix",
"is",
"the",
"stastd",
"client",
"prefix",
".",
"Can",
"be",
"if",
"no",
"prefix",
"is",
"desired",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L302-L308 |
5,025 | cactus/go-statsd-client | statsd/client.go | joinPathComp | func joinPathComp(prefix, suffix string) string {
suffix = strings.TrimLeft(suffix, ".")
if prefix != "" && suffix != "" {
return prefix + "." + suffix
}
return prefix + suffix
} | go | func joinPathComp(prefix, suffix string) string {
suffix = strings.TrimLeft(suffix, ".")
if prefix != "" && suffix != "" {
return prefix + "." + suffix
}
return prefix + suffix
} | [
"func",
"joinPathComp",
"(",
"prefix",
",",
"suffix",
"string",
")",
"string",
"{",
"suffix",
"=",
"strings",
".",
"TrimLeft",
"(",
"suffix",
",",
"\"",
"\"",
")",
"\n",
"if",
"prefix",
"!=",
"\"",
"\"",
"&&",
"suffix",
"!=",
"\"",
"\"",
"{",
"return",
"prefix",
"+",
"\"",
"\"",
"+",
"suffix",
"\n",
"}",
"\n",
"return",
"prefix",
"+",
"suffix",
"\n",
"}"
] | // joinPathComp is a helper that ensures we combine path components with a dot
// when it's appropriate to do so; prefix is the existing prefix and suffix is
// the new component being added.
//
// It returns the joined prefix. | [
"joinPathComp",
"is",
"a",
"helper",
"that",
"ensures",
"we",
"combine",
"path",
"components",
"with",
"a",
"dot",
"when",
"it",
"s",
"appropriate",
"to",
"do",
"so",
";",
"prefix",
"is",
"the",
"existing",
"prefix",
"and",
"suffix",
"is",
"the",
"new",
"component",
"being",
"added",
".",
"It",
"returns",
"the",
"joined",
"prefix",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/client.go#L315-L321 |
5,026 | cactus/go-statsd-client | statsd/sender_buffered.go | Send | func (s *BufferedSender) Send(data []byte) (int, error) {
s.runmx.RLock()
if !s.running {
s.runmx.RUnlock()
return 0, fmt.Errorf("BufferedSender is not running")
}
s.withBufferLock(func() {
blen := s.buffer.Len()
if blen > 0 && blen+len(data)+1 >= s.flushBytes {
s.swapnqueue()
}
s.buffer.Write(data)
s.buffer.WriteByte('\n')
if s.buffer.Len() >= s.flushBytes {
s.swapnqueue()
}
})
s.runmx.RUnlock()
return len(data), nil
} | go | func (s *BufferedSender) Send(data []byte) (int, error) {
s.runmx.RLock()
if !s.running {
s.runmx.RUnlock()
return 0, fmt.Errorf("BufferedSender is not running")
}
s.withBufferLock(func() {
blen := s.buffer.Len()
if blen > 0 && blen+len(data)+1 >= s.flushBytes {
s.swapnqueue()
}
s.buffer.Write(data)
s.buffer.WriteByte('\n')
if s.buffer.Len() >= s.flushBytes {
s.swapnqueue()
}
})
s.runmx.RUnlock()
return len(data), nil
} | [
"func",
"(",
"s",
"*",
"BufferedSender",
")",
"Send",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"s",
".",
"runmx",
".",
"RLock",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"running",
"{",
"s",
".",
"runmx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"withBufferLock",
"(",
"func",
"(",
")",
"{",
"blen",
":=",
"s",
".",
"buffer",
".",
"Len",
"(",
")",
"\n",
"if",
"blen",
">",
"0",
"&&",
"blen",
"+",
"len",
"(",
"data",
")",
"+",
"1",
">=",
"s",
".",
"flushBytes",
"{",
"s",
".",
"swapnqueue",
"(",
")",
"\n",
"}",
"\n\n",
"s",
".",
"buffer",
".",
"Write",
"(",
"data",
")",
"\n",
"s",
".",
"buffer",
".",
"WriteByte",
"(",
"'\\n'",
")",
"\n\n",
"if",
"s",
".",
"buffer",
".",
"Len",
"(",
")",
">=",
"s",
".",
"flushBytes",
"{",
"s",
".",
"swapnqueue",
"(",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"s",
".",
"runmx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] | // Send bytes. | [
"Send",
"bytes",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/sender_buffered.go#L33-L55 |
5,027 | cactus/go-statsd-client | statsd/sender_buffered.go | Close | func (s *BufferedSender) Close() error {
// since we are running, write lock during cleanup
s.runmx.Lock()
defer s.runmx.Unlock()
if !s.running {
return nil
}
errChan := make(chan error)
s.running = false
s.shutdown <- errChan
return <-errChan
} | go | func (s *BufferedSender) Close() error {
// since we are running, write lock during cleanup
s.runmx.Lock()
defer s.runmx.Unlock()
if !s.running {
return nil
}
errChan := make(chan error)
s.running = false
s.shutdown <- errChan
return <-errChan
} | [
"func",
"(",
"s",
"*",
"BufferedSender",
")",
"Close",
"(",
")",
"error",
"{",
"// since we are running, write lock during cleanup",
"s",
".",
"runmx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"runmx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"running",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"errChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"s",
".",
"running",
"=",
"false",
"\n",
"s",
".",
"shutdown",
"<-",
"errChan",
"\n",
"return",
"<-",
"errChan",
"\n",
"}"
] | // Close Buffered Sender | [
"Close",
"Buffered",
"Sender"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/sender_buffered.go#L58-L70 |
5,028 | cactus/go-statsd-client | statsd/sender_buffered.go | Start | func (s *BufferedSender) Start() {
// write lock to start running
s.runmx.Lock()
defer s.runmx.Unlock()
if s.running {
return
}
s.running = true
s.bufs = make(chan *bytes.Buffer, 32)
go s.run()
} | go | func (s *BufferedSender) Start() {
// write lock to start running
s.runmx.Lock()
defer s.runmx.Unlock()
if s.running {
return
}
s.running = true
s.bufs = make(chan *bytes.Buffer, 32)
go s.run()
} | [
"func",
"(",
"s",
"*",
"BufferedSender",
")",
"Start",
"(",
")",
"{",
"// write lock to start running",
"s",
".",
"runmx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"runmx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"running",
"{",
"return",
"\n",
"}",
"\n\n",
"s",
".",
"running",
"=",
"true",
"\n",
"s",
".",
"bufs",
"=",
"make",
"(",
"chan",
"*",
"bytes",
".",
"Buffer",
",",
"32",
")",
"\n",
"go",
"s",
".",
"run",
"(",
")",
"\n",
"}"
] | // Start Buffered Sender
// Begins ticker and read loop | [
"Start",
"Buffered",
"Sender",
"Begins",
"ticker",
"and",
"read",
"loop"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/sender_buffered.go#L74-L85 |
5,029 | cactus/go-statsd-client | statsd/sender_buffered.go | flush | func (s *BufferedSender) flush(b *bytes.Buffer) (int, error) {
bb := b.Bytes()
bbl := len(bb)
if bb[bbl-1] == '\n' {
bb = bb[:bbl-1]
}
//n, err := s.sender.Send(bytes.TrimSuffix(b.Bytes(), []byte("\n")))
n, err := s.sender.Send(bb)
b.Truncate(0) // clear the buffer
return n, err
} | go | func (s *BufferedSender) flush(b *bytes.Buffer) (int, error) {
bb := b.Bytes()
bbl := len(bb)
if bb[bbl-1] == '\n' {
bb = bb[:bbl-1]
}
//n, err := s.sender.Send(bytes.TrimSuffix(b.Bytes(), []byte("\n")))
n, err := s.sender.Send(bb)
b.Truncate(0) // clear the buffer
return n, err
} | [
"func",
"(",
"s",
"*",
"BufferedSender",
")",
"flush",
"(",
"b",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"int",
",",
"error",
")",
"{",
"bb",
":=",
"b",
".",
"Bytes",
"(",
")",
"\n",
"bbl",
":=",
"len",
"(",
"bb",
")",
"\n",
"if",
"bb",
"[",
"bbl",
"-",
"1",
"]",
"==",
"'\\n'",
"{",
"bb",
"=",
"bb",
"[",
":",
"bbl",
"-",
"1",
"]",
"\n",
"}",
"\n",
"//n, err := s.sender.Send(bytes.TrimSuffix(b.Bytes(), []byte(\"\\n\")))",
"n",
",",
"err",
":=",
"s",
".",
"sender",
".",
"Send",
"(",
"bb",
")",
"\n",
"b",
".",
"Truncate",
"(",
"0",
")",
"// clear the buffer",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // send to remove endpoint and truncate buffer | [
"send",
"to",
"remove",
"endpoint",
"and",
"truncate",
"buffer"
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/sender_buffered.go#L135-L145 |
5,030 | cactus/go-statsd-client | statsd/validator.go | CheckName | func CheckName(stat string) error {
if !safeName.MatchString(stat) {
return fmt.Errorf("invalid stat name: %s", stat)
}
return nil
} | go | func CheckName(stat string) error {
if !safeName.MatchString(stat) {
return fmt.Errorf("invalid stat name: %s", stat)
}
return nil
} | [
"func",
"CheckName",
"(",
"stat",
"string",
")",
"error",
"{",
"if",
"!",
"safeName",
".",
"MatchString",
"(",
"stat",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"stat",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckName may be used to validate whether a stat name contains invalid
// characters. If invalid characters are found, the function will return an
// error. | [
"CheckName",
"may",
"be",
"used",
"to",
"validate",
"whether",
"a",
"stat",
"name",
"contains",
"invalid",
"characters",
".",
"If",
"invalid",
"characters",
"are",
"found",
"the",
"function",
"will",
"return",
"an",
"error",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/validator.go#L21-L26 |
5,031 | cactus/go-statsd-client | statsd/sender.go | Send | func (s *SimpleSender) Send(data []byte) (int, error) {
// no need for locking here, as the underlying fdNet
// already serialized writes
n, err := s.c.(*net.UDPConn).WriteToUDP(data, s.ra)
if err != nil {
return 0, err
}
if n == 0 {
return n, errors.New("Wrote no bytes")
}
return n, nil
} | go | func (s *SimpleSender) Send(data []byte) (int, error) {
// no need for locking here, as the underlying fdNet
// already serialized writes
n, err := s.c.(*net.UDPConn).WriteToUDP(data, s.ra)
if err != nil {
return 0, err
}
if n == 0 {
return n, errors.New("Wrote no bytes")
}
return n, nil
} | [
"func",
"(",
"s",
"*",
"SimpleSender",
")",
"Send",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"// no need for locking here, as the underlying fdNet",
"// already serialized writes",
"n",
",",
"err",
":=",
"s",
".",
"c",
".",
"(",
"*",
"net",
".",
"UDPConn",
")",
".",
"WriteToUDP",
"(",
"data",
",",
"s",
".",
"ra",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
"==",
"0",
"{",
"return",
"n",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // Send sends the data to the server endpoint. | [
"Send",
"sends",
"the",
"data",
"to",
"the",
"server",
"endpoint",
"."
] | 9a76926395884c24387e06773401e4d54cdee9df | https://github.com/cactus/go-statsd-client/blob/9a76926395884c24387e06773401e4d54cdee9df/statsd/sender.go#L27-L38 |
5,032 | gobuffalo/validate | validate.go | NewErrors | func NewErrors() *Errors {
return &Errors{
Errors: make(map[string][]string),
Lock: new(sync.RWMutex),
}
} | go | func NewErrors() *Errors {
return &Errors{
Errors: make(map[string][]string),
Lock: new(sync.RWMutex),
}
} | [
"func",
"NewErrors",
"(",
")",
"*",
"Errors",
"{",
"return",
"&",
"Errors",
"{",
"Errors",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
",",
"Lock",
":",
"new",
"(",
"sync",
".",
"RWMutex",
")",
",",
"}",
"\n",
"}"
] | // NewErrors returns a pointer to a Errors
// object that has been primed and ready to go. | [
"NewErrors",
"returns",
"a",
"pointer",
"to",
"a",
"Errors",
"object",
"that",
"has",
"been",
"primed",
"and",
"ready",
"to",
"go",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validate.go#L69-L74 |
5,033 | gobuffalo/validate | validate.go | Append | func (v *Errors) Append(ers *Errors) {
for key, value := range ers.Errors {
for _, msg := range value {
v.Add(key, msg)
}
}
} | go | func (v *Errors) Append(ers *Errors) {
for key, value := range ers.Errors {
for _, msg := range value {
v.Add(key, msg)
}
}
} | [
"func",
"(",
"v",
"*",
"Errors",
")",
"Append",
"(",
"ers",
"*",
"Errors",
")",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"ers",
".",
"Errors",
"{",
"for",
"_",
",",
"msg",
":=",
"range",
"value",
"{",
"v",
".",
"Add",
"(",
"key",
",",
"msg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Append concatenates two Errors objects together.
// This will modify the first object in place. | [
"Append",
"concatenates",
"two",
"Errors",
"objects",
"together",
".",
"This",
"will",
"modify",
"the",
"first",
"object",
"in",
"place",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validate.go#L98-L104 |
5,034 | gobuffalo/validate | validate.go | Add | func (v *Errors) Add(key string, msg string) {
v.Lock.Lock()
v.Errors[key] = append(v.Errors[key], msg)
v.Lock.Unlock()
} | go | func (v *Errors) Add(key string, msg string) {
v.Lock.Lock()
v.Errors[key] = append(v.Errors[key], msg)
v.Lock.Unlock()
} | [
"func",
"(",
"v",
"*",
"Errors",
")",
"Add",
"(",
"key",
"string",
",",
"msg",
"string",
")",
"{",
"v",
".",
"Lock",
".",
"Lock",
"(",
")",
"\n",
"v",
".",
"Errors",
"[",
"key",
"]",
"=",
"append",
"(",
"v",
".",
"Errors",
"[",
"key",
"]",
",",
"msg",
")",
"\n",
"v",
".",
"Lock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Add will add a new message to the list of errors using
// the given key. If the key already exists the message will
// be appended to the array of the existing messages. | [
"Add",
"will",
"add",
"a",
"new",
"message",
"to",
"the",
"list",
"of",
"errors",
"using",
"the",
"given",
"key",
".",
"If",
"the",
"key",
"already",
"exists",
"the",
"message",
"will",
"be",
"appended",
"to",
"the",
"array",
"of",
"the",
"existing",
"messages",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validate.go#L109-L113 |
5,035 | gobuffalo/validate | validate.go | Keys | func (v *Errors) Keys() []string {
keys := []string{}
for key := range v.Errors {
keys = append(keys, key)
}
return keys
} | go | func (v *Errors) Keys() []string {
keys := []string{}
for key := range v.Errors {
keys = append(keys, key)
}
return keys
} | [
"func",
"(",
"v",
"*",
"Errors",
")",
"Keys",
"(",
")",
"[",
"]",
"string",
"{",
"keys",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
":=",
"range",
"v",
".",
"Errors",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n\n",
"return",
"keys",
"\n",
"}"
] | // Keys return all field names which have error | [
"Keys",
"return",
"all",
"field",
"names",
"which",
"have",
"error"
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validate.go#L126-L133 |
5,036 | gobuffalo/validate | validators/strings_match.go | IsValid | func (v *StringsMatch) IsValid(errors *validate.Errors) {
if strings.TrimSpace(v.Field) != strings.TrimSpace(v.Field2) {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not equal %s.", v.Field, v.Field2)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
} | go | func (v *StringsMatch) IsValid(errors *validate.Errors) {
if strings.TrimSpace(v.Field) != strings.TrimSpace(v.Field2) {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not equal %s.", v.Field, v.Field2)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
} | [
"func",
"(",
"v",
"*",
"StringsMatch",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"v",
".",
"Field",
")",
"!=",
"strings",
".",
"TrimSpace",
"(",
"v",
".",
"Field2",
")",
"{",
"if",
"v",
".",
"Message",
"==",
"\"",
"\"",
"{",
"v",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Field",
",",
"v",
".",
"Field2",
")",
"\n",
"}",
"\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"}",
"\n",
"}"
] | // IsValid performs the validation equality of two strings. | [
"IsValid",
"performs",
"the",
"validation",
"equality",
"of",
"two",
"strings",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/strings_match.go#L18-L25 |
5,037 | gobuffalo/validate | validators/int_is_present.go | IsValid | func (v *IntIsPresent) IsValid(errors *validate.Errors) {
if v.Field != 0 {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | go | func (v *IntIsPresent) IsValid(errors *validate.Errors) {
if v.Field != 0 {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | [
"func",
"(",
"v",
"*",
"IntIsPresent",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"if",
"v",
".",
"Field",
"!=",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
")",
"\n",
"}"
] | // IsValid adds an error if the field equals 0. | [
"IsValid",
"adds",
"an",
"error",
"if",
"the",
"field",
"equals",
"0",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/int_is_present.go#L16-L27 |
5,038 | gobuffalo/validate | validators/uuid_is_present.go | IsValid | func (v *UUIDIsPresent) IsValid(errors *validate.Errors) {
s := v.Field.String()
if strings.TrimSpace(s) != "" && v.Field != uuid.Nil {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | go | func (v *UUIDIsPresent) IsValid(errors *validate.Errors) {
s := v.Field.String()
if strings.TrimSpace(s) != "" && v.Field != uuid.Nil {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | [
"func",
"(",
"v",
"*",
"UUIDIsPresent",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"s",
":=",
"v",
".",
"Field",
".",
"String",
"(",
")",
"\n",
"if",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
"!=",
"\"",
"\"",
"&&",
"v",
".",
"Field",
"!=",
"uuid",
".",
"Nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
")",
"\n",
"}"
] | // IsValid adds an error if the field is not a valid uuid. | [
"IsValid",
"adds",
"an",
"error",
"if",
"the",
"field",
"is",
"not",
"a",
"valid",
"uuid",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/uuid_is_present.go#L18-L30 |
5,039 | gobuffalo/validate | validators/time_is_before_time.go | IsValid | func (v *TimeIsBeforeTime) IsValid(errors *validate.Errors) {
if v.FirstTime.UnixNano() <= v.SecondTime.UnixNano() {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.FirstName), v.Message)
return
}
errors.Add(GenerateKey(v.FirstName), fmt.Sprintf("%s must be before %s.", v.FirstName, v.SecondName))
} | go | func (v *TimeIsBeforeTime) IsValid(errors *validate.Errors) {
if v.FirstTime.UnixNano() <= v.SecondTime.UnixNano() {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.FirstName), v.Message)
return
}
errors.Add(GenerateKey(v.FirstName), fmt.Sprintf("%s must be before %s.", v.FirstName, v.SecondName))
} | [
"func",
"(",
"v",
"*",
"TimeIsBeforeTime",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"if",
"v",
".",
"FirstTime",
".",
"UnixNano",
"(",
")",
"<=",
"v",
".",
"SecondTime",
".",
"UnixNano",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"FirstName",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"FirstName",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"FirstName",
",",
"v",
".",
"SecondName",
")",
")",
"\n",
"}"
] | // IsValid adds an error if the FirstTime is after the SecondTime. | [
"IsValid",
"adds",
"an",
"error",
"if",
"the",
"FirstTime",
"is",
"after",
"the",
"SecondTime",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/time_is_before_time.go#L19-L30 |
5,040 | gobuffalo/validate | validators/time_is_present.go | IsValid | func (v *TimeIsPresent) IsValid(errors *validate.Errors) {
t := time.Time{}
if v.Field.UnixNano() != t.UnixNano() {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | go | func (v *TimeIsPresent) IsValid(errors *validate.Errors) {
t := time.Time{}
if v.Field.UnixNano() != t.UnixNano() {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | [
"func",
"(",
"v",
"*",
"TimeIsPresent",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"t",
":=",
"time",
".",
"Time",
"{",
"}",
"\n",
"if",
"v",
".",
"Field",
".",
"UnixNano",
"(",
")",
"!=",
"t",
".",
"UnixNano",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
")",
"\n",
"}"
] | // IsValid adds an error if the field is not a valid time. | [
"IsValid",
"adds",
"an",
"error",
"if",
"the",
"field",
"is",
"not",
"a",
"valid",
"time",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/time_is_present.go#L17-L29 |
5,041 | gobuffalo/validate | validators/string_is_present.go | IsValid | func (v *StringIsPresent) IsValid(errors *validate.Errors) {
if strings.TrimSpace(v.Field) != "" {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | go | func (v *StringIsPresent) IsValid(errors *validate.Errors) {
if strings.TrimSpace(v.Field) != "" {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s can not be blank.", v.Name))
} | [
"func",
"(",
"v",
"*",
"StringIsPresent",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"v",
".",
"Field",
")",
"!=",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
")",
"\n",
"}"
] | // IsValid adds an error if the field is empty. | [
"IsValid",
"adds",
"an",
"error",
"if",
"the",
"field",
"is",
"empty",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/string_is_present.go#L17-L28 |
5,042 | gobuffalo/validate | validators/email_is_present.go | IsValid | func (v *EmailIsPresent) IsValid(errors *validate.Errors) {
if !rxEmail.Match([]byte(v.Field)) {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format.", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
} | go | func (v *EmailIsPresent) IsValid(errors *validate.Errors) {
if !rxEmail.Match([]byte(v.Field)) {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format.", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
} | [
"func",
"(",
"v",
"*",
"EmailIsPresent",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"if",
"!",
"rxEmail",
".",
"Match",
"(",
"[",
"]",
"byte",
"(",
"v",
".",
"Field",
")",
")",
"{",
"if",
"v",
".",
"Message",
"==",
"\"",
"\"",
"{",
"v",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
"\n",
"}",
"\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"}",
"\n",
"}"
] | // IsValid performs the validation based on the email regexp match. | [
"IsValid",
"performs",
"the",
"validation",
"based",
"on",
"the",
"email",
"regexp",
"match",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/email_is_present.go#L24-L31 |
5,043 | gobuffalo/validate | validators/email_is_present.go | IsValid | func (v *EmailLike) IsValid(errors *validate.Errors) {
parts := strings.Split(v.Field, "@")
if len(parts) != 2 || len(parts[0]) == 0 || len(parts[1]) == 0 {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format.", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
} else if len(parts) == 2 {
domain := parts[1]
// Check that domain is valid
if len(strings.Split(domain, ".")) < 2 {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format (email domain).", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
}
} | go | func (v *EmailLike) IsValid(errors *validate.Errors) {
parts := strings.Split(v.Field, "@")
if len(parts) != 2 || len(parts[0]) == 0 || len(parts[1]) == 0 {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format.", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
} else if len(parts) == 2 {
domain := parts[1]
// Check that domain is valid
if len(strings.Split(domain, ".")) < 2 {
if v.Message == "" {
v.Message = fmt.Sprintf("%s does not match the email format (email domain).", v.Name)
}
errors.Add(GenerateKey(v.Name), v.Message)
}
}
} | [
"func",
"(",
"v",
"*",
"EmailLike",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"v",
".",
"Field",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
"||",
"len",
"(",
"parts",
"[",
"0",
"]",
")",
"==",
"0",
"||",
"len",
"(",
"parts",
"[",
"1",
"]",
")",
"==",
"0",
"{",
"if",
"v",
".",
"Message",
"==",
"\"",
"\"",
"{",
"v",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
"\n",
"}",
"\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
"{",
"domain",
":=",
"parts",
"[",
"1",
"]",
"\n",
"// Check that domain is valid",
"if",
"len",
"(",
"strings",
".",
"Split",
"(",
"domain",
",",
"\"",
"\"",
")",
")",
"<",
"2",
"{",
"if",
"v",
".",
"Message",
"==",
"\"",
"\"",
"{",
"v",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
"\n",
"}",
"\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // IsValid performs the validation based on email struct (username@domain) | [
"IsValid",
"performs",
"the",
"validation",
"based",
"on",
"email",
"struct",
"(",
"username"
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/email_is_present.go#L42-L59 |
5,044 | gobuffalo/validate | validators/regex_match.go | IsValid | func (v *RegexMatch) IsValid(errors *validate.Errors) {
r := regexp.MustCompile(v.Expr)
if r.Match([]byte(v.Field)) {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s does not match the expected format.", v.Name))
} | go | func (v *RegexMatch) IsValid(errors *validate.Errors) {
r := regexp.MustCompile(v.Expr)
if r.Match([]byte(v.Field)) {
return
}
if len(v.Message) > 0 {
errors.Add(GenerateKey(v.Name), v.Message)
return
}
errors.Add(GenerateKey(v.Name), fmt.Sprintf("%s does not match the expected format.", v.Name))
} | [
"func",
"(",
"v",
"*",
"RegexMatch",
")",
"IsValid",
"(",
"errors",
"*",
"validate",
".",
"Errors",
")",
"{",
"r",
":=",
"regexp",
".",
"MustCompile",
"(",
"v",
".",
"Expr",
")",
"\n",
"if",
"r",
".",
"Match",
"(",
"[",
"]",
"byte",
"(",
"v",
".",
"Field",
")",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"v",
".",
"Message",
")",
">",
"0",
"{",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"v",
".",
"Message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"errors",
".",
"Add",
"(",
"GenerateKey",
"(",
"v",
".",
"Name",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Name",
")",
")",
"\n",
"}"
] | // IsValid performs the validation based on the regexp match. | [
"IsValid",
"performs",
"the",
"validation",
"based",
"on",
"the",
"regexp",
"match",
"."
] | 2ada686bcfc51eb528382b5134818852f918fe24 | https://github.com/gobuffalo/validate/blob/2ada686bcfc51eb528382b5134818852f918fe24/validators/regex_match.go#L19-L31 |
5,045 | PuerkitoBio/purell | purell.go | MustNormalizeURLString | func MustNormalizeURLString(u string, f NormalizationFlags) string {
result, e := NormalizeURLString(u, f)
if e != nil {
panic(e)
}
return result
} | go | func MustNormalizeURLString(u string, f NormalizationFlags) string {
result, e := NormalizeURLString(u, f)
if e != nil {
panic(e)
}
return result
} | [
"func",
"MustNormalizeURLString",
"(",
"u",
"string",
",",
"f",
"NormalizationFlags",
")",
"string",
"{",
"result",
",",
"e",
":=",
"NormalizeURLString",
"(",
"u",
",",
"f",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // MustNormalizeURLString returns the normalized string, and panics if an error occurs.
// It takes an URL string as input, as well as the normalization flags. | [
"MustNormalizeURLString",
"returns",
"the",
"normalized",
"string",
"and",
"panics",
"if",
"an",
"error",
"occurs",
".",
"It",
"takes",
"an",
"URL",
"string",
"as",
"input",
"as",
"well",
"as",
"the",
"normalization",
"flags",
"."
] | 44968752391892e1b0d0b821ee79e9a85fa13049 | https://github.com/PuerkitoBio/purell/blob/44968752391892e1b0d0b821ee79e9a85fa13049/purell.go#L142-L148 |
5,046 | PuerkitoBio/purell | purell.go | NormalizeURLString | func NormalizeURLString(u string, f NormalizationFlags) (string, error) {
parsed, err := url.Parse(u)
if err != nil {
return "", err
}
if f&FlagLowercaseHost == FlagLowercaseHost {
parsed.Host = strings.ToLower(parsed.Host)
}
// The idna package doesn't fully conform to RFC 5895
// (https://tools.ietf.org/html/rfc5895), so we do it here.
// Taken from Go 1.8 cycle source, courtesy of bradfitz.
// TODO: Remove when (if?) idna package conforms to RFC 5895.
parsed.Host = width.Fold.String(parsed.Host)
parsed.Host = norm.NFC.String(parsed.Host)
if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil {
return "", err
}
return NormalizeURL(parsed, f), nil
} | go | func NormalizeURLString(u string, f NormalizationFlags) (string, error) {
parsed, err := url.Parse(u)
if err != nil {
return "", err
}
if f&FlagLowercaseHost == FlagLowercaseHost {
parsed.Host = strings.ToLower(parsed.Host)
}
// The idna package doesn't fully conform to RFC 5895
// (https://tools.ietf.org/html/rfc5895), so we do it here.
// Taken from Go 1.8 cycle source, courtesy of bradfitz.
// TODO: Remove when (if?) idna package conforms to RFC 5895.
parsed.Host = width.Fold.String(parsed.Host)
parsed.Host = norm.NFC.String(parsed.Host)
if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil {
return "", err
}
return NormalizeURL(parsed, f), nil
} | [
"func",
"NormalizeURLString",
"(",
"u",
"string",
",",
"f",
"NormalizationFlags",
")",
"(",
"string",
",",
"error",
")",
"{",
"parsed",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"f",
"&",
"FlagLowercaseHost",
"==",
"FlagLowercaseHost",
"{",
"parsed",
".",
"Host",
"=",
"strings",
".",
"ToLower",
"(",
"parsed",
".",
"Host",
")",
"\n",
"}",
"\n\n",
"// The idna package doesn't fully conform to RFC 5895",
"// (https://tools.ietf.org/html/rfc5895), so we do it here.",
"// Taken from Go 1.8 cycle source, courtesy of bradfitz.",
"// TODO: Remove when (if?) idna package conforms to RFC 5895.",
"parsed",
".",
"Host",
"=",
"width",
".",
"Fold",
".",
"String",
"(",
"parsed",
".",
"Host",
")",
"\n",
"parsed",
".",
"Host",
"=",
"norm",
".",
"NFC",
".",
"String",
"(",
"parsed",
".",
"Host",
")",
"\n",
"if",
"parsed",
".",
"Host",
",",
"err",
"=",
"idna",
".",
"ToASCII",
"(",
"parsed",
".",
"Host",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NormalizeURL",
"(",
"parsed",
",",
"f",
")",
",",
"nil",
"\n",
"}"
] | // NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object.
// It takes an URL string as input, as well as the normalization flags. | [
"NormalizeURLString",
"returns",
"the",
"normalized",
"string",
"or",
"an",
"error",
"if",
"it",
"can",
"t",
"be",
"parsed",
"into",
"an",
"URL",
"object",
".",
"It",
"takes",
"an",
"URL",
"string",
"as",
"input",
"as",
"well",
"as",
"the",
"normalization",
"flags",
"."
] | 44968752391892e1b0d0b821ee79e9a85fa13049 | https://github.com/PuerkitoBio/purell/blob/44968752391892e1b0d0b821ee79e9a85fa13049/purell.go#L152-L173 |
5,047 | PuerkitoBio/purell | purell.go | NormalizeURL | func NormalizeURL(u *url.URL, f NormalizationFlags) string {
for _, k := range flagsOrder {
if f&k == k {
flags[k](u)
}
}
return urlesc.Escape(u)
} | go | func NormalizeURL(u *url.URL, f NormalizationFlags) string {
for _, k := range flagsOrder {
if f&k == k {
flags[k](u)
}
}
return urlesc.Escape(u)
} | [
"func",
"NormalizeURL",
"(",
"u",
"*",
"url",
".",
"URL",
",",
"f",
"NormalizationFlags",
")",
"string",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"flagsOrder",
"{",
"if",
"f",
"&",
"k",
"==",
"k",
"{",
"flags",
"[",
"k",
"]",
"(",
"u",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"urlesc",
".",
"Escape",
"(",
"u",
")",
"\n",
"}"
] | // NormalizeURL returns the normalized string.
// It takes a parsed URL object as input, as well as the normalization flags. | [
"NormalizeURL",
"returns",
"the",
"normalized",
"string",
".",
"It",
"takes",
"a",
"parsed",
"URL",
"object",
"as",
"input",
"as",
"well",
"as",
"the",
"normalization",
"flags",
"."
] | 44968752391892e1b0d0b821ee79e9a85fa13049 | https://github.com/PuerkitoBio/purell/blob/44968752391892e1b0d0b821ee79e9a85fa13049/purell.go#L177-L184 |
5,048 | rexray/gocsi | middleware/serialvolume/serial_volume_locker.go | WithTimeout | func WithTimeout(t time.Duration) Option {
return func(o *opts) {
o.timeout = t
}
} | go | func WithTimeout(t time.Duration) Option {
return func(o *opts) {
o.timeout = t
}
} | [
"func",
"WithTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"opts",
")",
"{",
"o",
".",
"timeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithTimeout is an Option that sets the timeout used by the interceptor. | [
"WithTimeout",
"is",
"an",
"Option",
"that",
"sets",
"the",
"timeout",
"used",
"by",
"the",
"interceptor",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/serial_volume_locker.go#L29-L33 |
5,049 | rexray/gocsi | middleware/serialvolume/serial_volume_locker.go | WithLockProvider | func WithLockProvider(p mwtypes.VolumeLockerProvider) Option {
return func(o *opts) {
o.locker = p
}
} | go | func WithLockProvider(p mwtypes.VolumeLockerProvider) Option {
return func(o *opts) {
o.locker = p
}
} | [
"func",
"WithLockProvider",
"(",
"p",
"mwtypes",
".",
"VolumeLockerProvider",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"opts",
")",
"{",
"o",
".",
"locker",
"=",
"p",
"\n",
"}",
"\n",
"}"
] | // WithLockProvider is an Option that sets the lock provider used by the
// interceptor. | [
"WithLockProvider",
"is",
"an",
"Option",
"that",
"sets",
"the",
"lock",
"provider",
"used",
"by",
"the",
"interceptor",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/serial_volume_locker.go#L37-L41 |
5,050 | rexray/gocsi | middleware/serialvolume/etcd/etcd_lock_provider.go | New | func New(
ctx context.Context,
domain string,
ttl time.Duration,
config *etcd.Config) (mwtypes.VolumeLockerProvider, error) {
fields := map[string]interface{}{}
if domain == "" {
domain = csictx.Getenv(ctx, EnvVarDomain)
}
domain = path.Join("/", domain)
fields["serialvol.etcd.domain"] = domain
if ttl == 0 {
ttl, _ = time.ParseDuration(csictx.Getenv(ctx, EnvVarTTL))
if ttl > 0 {
fields["serialvol.etcd.ttl"] = ttl
}
}
if config == nil {
cfg, err := initConfig(ctx, fields)
if err != nil {
return nil, err
}
config = &cfg
}
log.WithFields(fields).Info("creating serial vol etcd lock provider")
client, err := etcd.New(*config)
if err != nil {
return nil, err
}
return &provider{
client: client,
domain: domain,
ttl: int(ttl.Seconds()),
}, nil
} | go | func New(
ctx context.Context,
domain string,
ttl time.Duration,
config *etcd.Config) (mwtypes.VolumeLockerProvider, error) {
fields := map[string]interface{}{}
if domain == "" {
domain = csictx.Getenv(ctx, EnvVarDomain)
}
domain = path.Join("/", domain)
fields["serialvol.etcd.domain"] = domain
if ttl == 0 {
ttl, _ = time.ParseDuration(csictx.Getenv(ctx, EnvVarTTL))
if ttl > 0 {
fields["serialvol.etcd.ttl"] = ttl
}
}
if config == nil {
cfg, err := initConfig(ctx, fields)
if err != nil {
return nil, err
}
config = &cfg
}
log.WithFields(fields).Info("creating serial vol etcd lock provider")
client, err := etcd.New(*config)
if err != nil {
return nil, err
}
return &provider{
client: client,
domain: domain,
ttl: int(ttl.Seconds()),
}, nil
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"domain",
"string",
",",
"ttl",
"time",
".",
"Duration",
",",
"config",
"*",
"etcd",
".",
"Config",
")",
"(",
"mwtypes",
".",
"VolumeLockerProvider",
",",
"error",
")",
"{",
"fields",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n\n",
"if",
"domain",
"==",
"\"",
"\"",
"{",
"domain",
"=",
"csictx",
".",
"Getenv",
"(",
"ctx",
",",
"EnvVarDomain",
")",
"\n",
"}",
"\n",
"domain",
"=",
"path",
".",
"Join",
"(",
"\"",
"\"",
",",
"domain",
")",
"\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"domain",
"\n\n",
"if",
"ttl",
"==",
"0",
"{",
"ttl",
",",
"_",
"=",
"time",
".",
"ParseDuration",
"(",
"csictx",
".",
"Getenv",
"(",
"ctx",
",",
"EnvVarTTL",
")",
")",
"\n",
"if",
"ttl",
">",
"0",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"ttl",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"config",
"==",
"nil",
"{",
"cfg",
",",
"err",
":=",
"initConfig",
"(",
"ctx",
",",
"fields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
"=",
"&",
"cfg",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"fields",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"client",
",",
"err",
":=",
"etcd",
".",
"New",
"(",
"*",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"provider",
"{",
"client",
":",
"client",
",",
"domain",
":",
"domain",
",",
"ttl",
":",
"int",
"(",
"ttl",
".",
"Seconds",
"(",
")",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // New returns a new etcd volume lock provider. | [
"New",
"returns",
"a",
"new",
"etcd",
"volume",
"lock",
"provider",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/etcd/etcd_lock_provider.go#L21-L62 |
5,051 | rexray/gocsi | middleware/serialvolume/etcd/etcd_lock_provider.go | Lock | func (m *TryMutex) Lock() {
//log.Debug("TryMutex: lock")
ctx := m.LockCtx
if ctx == nil {
ctx = m.ctx
}
if err := m.mtx.Lock(ctx); err != nil {
log.Debugf("TryMutex: lock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: lock panic: %v", err)
}
}
} | go | func (m *TryMutex) Lock() {
//log.Debug("TryMutex: lock")
ctx := m.LockCtx
if ctx == nil {
ctx = m.ctx
}
if err := m.mtx.Lock(ctx); err != nil {
log.Debugf("TryMutex: lock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: lock panic: %v", err)
}
}
} | [
"func",
"(",
"m",
"*",
"TryMutex",
")",
"Lock",
"(",
")",
"{",
"//log.Debug(\"TryMutex: lock\")",
"ctx",
":=",
"m",
".",
"LockCtx",
"\n",
"if",
"ctx",
"==",
"nil",
"{",
"ctx",
"=",
"m",
".",
"ctx",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"mtx",
".",
"Lock",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"if",
"err",
"!=",
"context",
".",
"Canceled",
"&&",
"err",
"!=",
"context",
".",
"DeadlineExceeded",
"{",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Lock locks m. If the lock is already in use, the calling goroutine blocks
// until the mutex is available. | [
"Lock",
"locks",
"m",
".",
"If",
"the",
"lock",
"is",
"already",
"in",
"use",
"the",
"calling",
"goroutine",
"blocks",
"until",
"the",
"mutex",
"is",
"available",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/etcd/etcd_lock_provider.go#L231-L243 |
5,052 | rexray/gocsi | middleware/serialvolume/etcd/etcd_lock_provider.go | Unlock | func (m *TryMutex) Unlock() {
//log.Debug("TryMutex: unlock")
ctx := m.UnlockCtx
if ctx == nil {
ctx = m.ctx
}
if err := m.mtx.Unlock(ctx); err != nil {
log.Debugf("TryMutex: unlock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: unlock panic: %v", err)
}
}
} | go | func (m *TryMutex) Unlock() {
//log.Debug("TryMutex: unlock")
ctx := m.UnlockCtx
if ctx == nil {
ctx = m.ctx
}
if err := m.mtx.Unlock(ctx); err != nil {
log.Debugf("TryMutex: unlock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: unlock panic: %v", err)
}
}
} | [
"func",
"(",
"m",
"*",
"TryMutex",
")",
"Unlock",
"(",
")",
"{",
"//log.Debug(\"TryMutex: unlock\")",
"ctx",
":=",
"m",
".",
"UnlockCtx",
"\n",
"if",
"ctx",
"==",
"nil",
"{",
"ctx",
"=",
"m",
".",
"ctx",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"mtx",
".",
"Unlock",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"if",
"err",
"!=",
"context",
".",
"Canceled",
"&&",
"err",
"!=",
"context",
".",
"DeadlineExceeded",
"{",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Unlock unlocks m. It is a run-time error if m is not locked on entry to
// Unlock.
//
// A locked TryMutex is not associated with a particular goroutine. It is
// allowed for one goroutine to lock a Mutex and then arrange for another
// goroutine to unlock it. | [
"Unlock",
"unlocks",
"m",
".",
"It",
"is",
"a",
"run",
"-",
"time",
"error",
"if",
"m",
"is",
"not",
"locked",
"on",
"entry",
"to",
"Unlock",
".",
"A",
"locked",
"TryMutex",
"is",
"not",
"associated",
"with",
"a",
"particular",
"goroutine",
".",
"It",
"is",
"allowed",
"for",
"one",
"goroutine",
"to",
"lock",
"a",
"Mutex",
"and",
"then",
"arrange",
"for",
"another",
"goroutine",
"to",
"unlock",
"it",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/etcd/etcd_lock_provider.go#L251-L263 |
5,053 | rexray/gocsi | middleware/serialvolume/etcd/etcd_lock_provider.go | Close | func (m *TryMutex) Close() error {
//log.Debug("TryMutex: close")
if err := m.sess.Close(); err != nil {
log.Errorf("TryMutex: close err: %v", err)
return err
}
return nil
} | go | func (m *TryMutex) Close() error {
//log.Debug("TryMutex: close")
if err := m.sess.Close(); err != nil {
log.Errorf("TryMutex: close err: %v", err)
return err
}
return nil
} | [
"func",
"(",
"m",
"*",
"TryMutex",
")",
"Close",
"(",
")",
"error",
"{",
"//log.Debug(\"TryMutex: close\")",
"if",
"err",
":=",
"m",
".",
"sess",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes and cleans up the underlying concurrency session. | [
"Close",
"closes",
"and",
"cleans",
"up",
"the",
"underlying",
"concurrency",
"session",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/etcd/etcd_lock_provider.go#L266-L273 |
5,054 | rexray/gocsi | middleware/serialvolume/etcd/etcd_lock_provider.go | TryLock | func (m *TryMutex) TryLock(timeout time.Duration) bool {
ctx := m.TryLockCtx
if ctx == nil {
ctx = m.ctx
}
// Create a timeout context only if the timeout is greater than zero.
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
if err := m.mtx.Lock(ctx); err != nil {
log.Debugf("TryMutex: TryLock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: TryLock panic: %v", err)
}
return false
}
return true
} | go | func (m *TryMutex) TryLock(timeout time.Duration) bool {
ctx := m.TryLockCtx
if ctx == nil {
ctx = m.ctx
}
// Create a timeout context only if the timeout is greater than zero.
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
if err := m.mtx.Lock(ctx); err != nil {
log.Debugf("TryMutex: TryLock err: %v", err)
if err != context.Canceled && err != context.DeadlineExceeded {
log.Panicf("TryMutex: TryLock panic: %v", err)
}
return false
}
return true
} | [
"func",
"(",
"m",
"*",
"TryMutex",
")",
"TryLock",
"(",
"timeout",
"time",
".",
"Duration",
")",
"bool",
"{",
"ctx",
":=",
"m",
".",
"TryLockCtx",
"\n",
"if",
"ctx",
"==",
"nil",
"{",
"ctx",
"=",
"m",
".",
"ctx",
"\n",
"}",
"\n\n",
"// Create a timeout context only if the timeout is greater than zero.",
"if",
"timeout",
">",
"0",
"{",
"var",
"cancel",
"context",
".",
"CancelFunc",
"\n",
"ctx",
",",
"cancel",
"=",
"context",
".",
"WithTimeout",
"(",
"ctx",
",",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"m",
".",
"mtx",
".",
"Lock",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"if",
"err",
"!=",
"context",
".",
"Canceled",
"&&",
"err",
"!=",
"context",
".",
"DeadlineExceeded",
"{",
"log",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // TryLock attempts to lock m. If no lock can be obtained in the specified
// duration then a false value is returned. | [
"TryLock",
"attempts",
"to",
"lock",
"m",
".",
"If",
"no",
"lock",
"can",
"be",
"obtained",
"in",
"the",
"specified",
"duration",
"then",
"a",
"false",
"value",
"is",
"returned",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/serialvolume/etcd/etcd_lock_provider.go#L277-L299 |
5,055 | rexray/gocsi | gocsi.go | Serve | func (sp *StoragePlugin) Serve(ctx context.Context, lis net.Listener) error {
var err error
sp.serveOnce.Do(func() {
// Please note that the order of the below init functions is
// important and should not be altered unless by someone aware
// of how they work.
// Adding this function to the context allows `csictx.LookupEnv`
// to search this SP's default env vars for a value.
ctx = csictx.WithLookupEnv(ctx, sp.lookupEnv)
// Adding this function to the context allows `csictx.Setenv`
// to set environment variables in this SP's env var store.
ctx = csictx.WithSetenv(ctx, sp.setenv)
// Initialize the storage plug-in's environment variables map.
sp.initEnvVars(ctx)
// Adjust the endpoint's file permissions.
if err = sp.initEndpointPerms(ctx, lis); err != nil {
return
}
// Adjust the endpoint's file ownership.
if err = sp.initEndpointOwner(ctx, lis); err != nil {
return
}
// Initialize the storage plug-in's info.
sp.initPluginInfo(ctx)
// Initialize the interceptors.
sp.initInterceptors(ctx)
// Invoke the SP's BeforeServe function to give the SP a chance
// to perform any local initialization routines.
if f := sp.BeforeServe; f != nil {
if err = f(ctx, sp, lis); err != nil {
return
}
}
// Add the interceptors to the server if any are configured.
if i := sp.Interceptors; len(i) > 0 {
sp.ServerOpts = append(sp.ServerOpts,
grpc.UnaryInterceptor(utils.ChainUnaryServer(i...)))
}
// Initialize the gRPC server.
sp.server = grpc.NewServer(sp.ServerOpts...)
// Register the CSI services.
// Always require the identity service.
if sp.Identity == nil {
err = errors.New("identity service is required")
return
}
// Either a Controller or Node service should be supplied.
if sp.Controller == nil && sp.Node == nil {
err = errors.New(
"either a controller or node service is required")
return
}
// Always register the identity service.
csi.RegisterIdentityServer(sp.server, sp.Identity)
log.Info("identity service registered")
// Determine which of the controller/node services to register
mode := csictx.Getenv(ctx, EnvVarMode)
if strings.EqualFold(mode, "controller") {
mode = "controller"
} else if strings.EqualFold(mode, "node") {
mode = "node"
} else {
mode = ""
}
if mode == "" || mode == "controller" {
if sp.Controller == nil {
err = errors.New("controller service is required")
return
}
csi.RegisterControllerServer(sp.server, sp.Controller)
log.Info("controller service registered")
}
if mode == "" || mode == "node" {
if sp.Node == nil {
err = errors.New("node service is required")
return
}
csi.RegisterNodeServer(sp.server, sp.Node)
log.Info("node service registered")
}
endpoint := fmt.Sprintf(
"%s://%s",
lis.Addr().Network(), lis.Addr().String())
log.WithField("endpoint", endpoint).Info("serving")
// Start the gRPC server.
err = sp.server.Serve(lis)
return
})
return err
} | go | func (sp *StoragePlugin) Serve(ctx context.Context, lis net.Listener) error {
var err error
sp.serveOnce.Do(func() {
// Please note that the order of the below init functions is
// important and should not be altered unless by someone aware
// of how they work.
// Adding this function to the context allows `csictx.LookupEnv`
// to search this SP's default env vars for a value.
ctx = csictx.WithLookupEnv(ctx, sp.lookupEnv)
// Adding this function to the context allows `csictx.Setenv`
// to set environment variables in this SP's env var store.
ctx = csictx.WithSetenv(ctx, sp.setenv)
// Initialize the storage plug-in's environment variables map.
sp.initEnvVars(ctx)
// Adjust the endpoint's file permissions.
if err = sp.initEndpointPerms(ctx, lis); err != nil {
return
}
// Adjust the endpoint's file ownership.
if err = sp.initEndpointOwner(ctx, lis); err != nil {
return
}
// Initialize the storage plug-in's info.
sp.initPluginInfo(ctx)
// Initialize the interceptors.
sp.initInterceptors(ctx)
// Invoke the SP's BeforeServe function to give the SP a chance
// to perform any local initialization routines.
if f := sp.BeforeServe; f != nil {
if err = f(ctx, sp, lis); err != nil {
return
}
}
// Add the interceptors to the server if any are configured.
if i := sp.Interceptors; len(i) > 0 {
sp.ServerOpts = append(sp.ServerOpts,
grpc.UnaryInterceptor(utils.ChainUnaryServer(i...)))
}
// Initialize the gRPC server.
sp.server = grpc.NewServer(sp.ServerOpts...)
// Register the CSI services.
// Always require the identity service.
if sp.Identity == nil {
err = errors.New("identity service is required")
return
}
// Either a Controller or Node service should be supplied.
if sp.Controller == nil && sp.Node == nil {
err = errors.New(
"either a controller or node service is required")
return
}
// Always register the identity service.
csi.RegisterIdentityServer(sp.server, sp.Identity)
log.Info("identity service registered")
// Determine which of the controller/node services to register
mode := csictx.Getenv(ctx, EnvVarMode)
if strings.EqualFold(mode, "controller") {
mode = "controller"
} else if strings.EqualFold(mode, "node") {
mode = "node"
} else {
mode = ""
}
if mode == "" || mode == "controller" {
if sp.Controller == nil {
err = errors.New("controller service is required")
return
}
csi.RegisterControllerServer(sp.server, sp.Controller)
log.Info("controller service registered")
}
if mode == "" || mode == "node" {
if sp.Node == nil {
err = errors.New("node service is required")
return
}
csi.RegisterNodeServer(sp.server, sp.Node)
log.Info("node service registered")
}
endpoint := fmt.Sprintf(
"%s://%s",
lis.Addr().Network(), lis.Addr().String())
log.WithField("endpoint", endpoint).Info("serving")
// Start the gRPC server.
err = sp.server.Serve(lis)
return
})
return err
} | [
"func",
"(",
"sp",
"*",
"StoragePlugin",
")",
"Serve",
"(",
"ctx",
"context",
".",
"Context",
",",
"lis",
"net",
".",
"Listener",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"sp",
".",
"serveOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"// Please note that the order of the below init functions is",
"// important and should not be altered unless by someone aware",
"// of how they work.",
"// Adding this function to the context allows `csictx.LookupEnv`",
"// to search this SP's default env vars for a value.",
"ctx",
"=",
"csictx",
".",
"WithLookupEnv",
"(",
"ctx",
",",
"sp",
".",
"lookupEnv",
")",
"\n\n",
"// Adding this function to the context allows `csictx.Setenv`",
"// to set environment variables in this SP's env var store.",
"ctx",
"=",
"csictx",
".",
"WithSetenv",
"(",
"ctx",
",",
"sp",
".",
"setenv",
")",
"\n\n",
"// Initialize the storage plug-in's environment variables map.",
"sp",
".",
"initEnvVars",
"(",
"ctx",
")",
"\n\n",
"// Adjust the endpoint's file permissions.",
"if",
"err",
"=",
"sp",
".",
"initEndpointPerms",
"(",
"ctx",
",",
"lis",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Adjust the endpoint's file ownership.",
"if",
"err",
"=",
"sp",
".",
"initEndpointOwner",
"(",
"ctx",
",",
"lis",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Initialize the storage plug-in's info.",
"sp",
".",
"initPluginInfo",
"(",
"ctx",
")",
"\n\n",
"// Initialize the interceptors.",
"sp",
".",
"initInterceptors",
"(",
"ctx",
")",
"\n\n",
"// Invoke the SP's BeforeServe function to give the SP a chance",
"// to perform any local initialization routines.",
"if",
"f",
":=",
"sp",
".",
"BeforeServe",
";",
"f",
"!=",
"nil",
"{",
"if",
"err",
"=",
"f",
"(",
"ctx",
",",
"sp",
",",
"lis",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Add the interceptors to the server if any are configured.",
"if",
"i",
":=",
"sp",
".",
"Interceptors",
";",
"len",
"(",
"i",
")",
">",
"0",
"{",
"sp",
".",
"ServerOpts",
"=",
"append",
"(",
"sp",
".",
"ServerOpts",
",",
"grpc",
".",
"UnaryInterceptor",
"(",
"utils",
".",
"ChainUnaryServer",
"(",
"i",
"...",
")",
")",
")",
"\n",
"}",
"\n\n",
"// Initialize the gRPC server.",
"sp",
".",
"server",
"=",
"grpc",
".",
"NewServer",
"(",
"sp",
".",
"ServerOpts",
"...",
")",
"\n\n",
"// Register the CSI services.",
"// Always require the identity service.",
"if",
"sp",
".",
"Identity",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Either a Controller or Node service should be supplied.",
"if",
"sp",
".",
"Controller",
"==",
"nil",
"&&",
"sp",
".",
"Node",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Always register the identity service.",
"csi",
".",
"RegisterIdentityServer",
"(",
"sp",
".",
"server",
",",
"sp",
".",
"Identity",
")",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Determine which of the controller/node services to register",
"mode",
":=",
"csictx",
".",
"Getenv",
"(",
"ctx",
",",
"EnvVarMode",
")",
"\n",
"if",
"strings",
".",
"EqualFold",
"(",
"mode",
",",
"\"",
"\"",
")",
"{",
"mode",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"strings",
".",
"EqualFold",
"(",
"mode",
",",
"\"",
"\"",
")",
"{",
"mode",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"mode",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"mode",
"==",
"\"",
"\"",
"||",
"mode",
"==",
"\"",
"\"",
"{",
"if",
"sp",
".",
"Controller",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"csi",
".",
"RegisterControllerServer",
"(",
"sp",
".",
"server",
",",
"sp",
".",
"Controller",
")",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"mode",
"==",
"\"",
"\"",
"||",
"mode",
"==",
"\"",
"\"",
"{",
"if",
"sp",
".",
"Node",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"csi",
".",
"RegisterNodeServer",
"(",
"sp",
".",
"server",
",",
"sp",
".",
"Node",
")",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"endpoint",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"lis",
".",
"Addr",
"(",
")",
".",
"Network",
"(",
")",
",",
"lis",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"endpoint",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Start the gRPC server.",
"err",
"=",
"sp",
".",
"server",
".",
"Serve",
"(",
"lis",
")",
"\n",
"return",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Serve accepts incoming connections on the listener lis, creating
// a new ServerTransport and service goroutine for each. The service
// goroutine read gRPC requests and then call the registered handlers
// to reply to them. Serve returns when lis.Accept fails with fatal
// errors. lis will be closed when this method returns.
// Serve always returns non-nil error. | [
"Serve",
"accepts",
"incoming",
"connections",
"on",
"the",
"listener",
"lis",
"creating",
"a",
"new",
"ServerTransport",
"and",
"service",
"goroutine",
"for",
"each",
".",
"The",
"service",
"goroutine",
"read",
"gRPC",
"requests",
"and",
"then",
"call",
"the",
"registered",
"handlers",
"to",
"reply",
"to",
"them",
".",
"Serve",
"returns",
"when",
"lis",
".",
"Accept",
"fails",
"with",
"fatal",
"errors",
".",
"lis",
"will",
"be",
"closed",
"when",
"this",
"method",
"returns",
".",
"Serve",
"always",
"returns",
"non",
"-",
"nil",
"error",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/gocsi.go#L209-L314 |
5,056 | rexray/gocsi | gocsi.go | isExitSignal | func isExitSignal(s os.Signal) (bool, bool) {
switch s {
case syscall.SIGTERM,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGQUIT:
return true, true
default:
return false, false
}
} | go | func isExitSignal(s os.Signal) (bool, bool) {
switch s {
case syscall.SIGTERM,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGQUIT:
return true, true
default:
return false, false
}
} | [
"func",
"isExitSignal",
"(",
"s",
"os",
".",
"Signal",
")",
"(",
"bool",
",",
"bool",
")",
"{",
"switch",
"s",
"{",
"case",
"syscall",
".",
"SIGTERM",
",",
"syscall",
".",
"SIGHUP",
",",
"syscall",
".",
"SIGINT",
",",
"syscall",
".",
"SIGQUIT",
":",
"return",
"true",
",",
"true",
"\n",
"default",
":",
"return",
"false",
",",
"false",
"\n",
"}",
"\n",
"}"
] | // isExitSignal returns a flag indicating whether a signal SIGHUP,
// SIGINT, SIGTERM, or SIGQUIT. The second return value is whether it is a
// graceful exit. This flag is true for SIGTERM, SIGHUP, SIGINT, and SIGQUIT. | [
"isExitSignal",
"returns",
"a",
"flag",
"indicating",
"whether",
"a",
"signal",
"SIGHUP",
"SIGINT",
"SIGTERM",
"or",
"SIGQUIT",
".",
"The",
"second",
"return",
"value",
"is",
"whether",
"it",
"is",
"a",
"graceful",
"exit",
".",
"This",
"flag",
"is",
"true",
"for",
"SIGTERM",
"SIGHUP",
"SIGINT",
"and",
"SIGQUIT",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/gocsi.go#L512-L522 |
5,057 | rexray/gocsi | middleware/logging/logging_interceptor.go | WithRequestLogging | func WithRequestLogging(w io.Writer) Option {
return func(o *opts) {
if w == nil {
w = os.Stdout
}
o.reqw = w
}
} | go | func WithRequestLogging(w io.Writer) Option {
return func(o *opts) {
if w == nil {
w = os.Stdout
}
o.reqw = w
}
} | [
"func",
"WithRequestLogging",
"(",
"w",
"io",
".",
"Writer",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"opts",
")",
"{",
"if",
"w",
"==",
"nil",
"{",
"w",
"=",
"os",
".",
"Stdout",
"\n",
"}",
"\n",
"o",
".",
"reqw",
"=",
"w",
"\n",
"}",
"\n",
"}"
] | // WithRequestLogging is a Option that enables request logging
// for the logging interceptor. | [
"WithRequestLogging",
"is",
"a",
"Option",
"that",
"enables",
"request",
"logging",
"for",
"the",
"logging",
"interceptor",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/logging/logging_interceptor.go#L29-L36 |
5,058 | rexray/gocsi | middleware/logging/logging_interceptor.go | WithResponseLogging | func WithResponseLogging(w io.Writer) Option {
return func(o *opts) {
if w == nil {
w = os.Stdout
}
o.repw = w
}
} | go | func WithResponseLogging(w io.Writer) Option {
return func(o *opts) {
if w == nil {
w = os.Stdout
}
o.repw = w
}
} | [
"func",
"WithResponseLogging",
"(",
"w",
"io",
".",
"Writer",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"opts",
")",
"{",
"if",
"w",
"==",
"nil",
"{",
"w",
"=",
"os",
".",
"Stdout",
"\n",
"}",
"\n",
"o",
".",
"repw",
"=",
"w",
"\n",
"}",
"\n",
"}"
] | // WithResponseLogging is a Option that enables response logging
// for the logging interceptor. | [
"WithResponseLogging",
"is",
"a",
"Option",
"that",
"enables",
"response",
"logging",
"for",
"the",
"logging",
"interceptor",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/logging/logging_interceptor.go#L40-L47 |
5,059 | rexray/gocsi | middleware/logging/logging_interceptor.go | rprintReqOrRep | func rprintReqOrRep(w io.Writer, obj interface{}) {
rv := reflect.ValueOf(obj).Elem()
tv := rv.Type()
nf := tv.NumField()
printedColon := false
printComma := false
for i := 0; i < nf; i++ {
name := tv.Field(i).Name
if strings.Contains(name, "Secrets") {
continue
}
sv := fmt.Sprintf("%v", rv.Field(i).Interface())
if emptyValRX.MatchString(sv) {
continue
}
if printComma {
fmt.Fprintf(w, ", ")
}
if !printedColon {
fmt.Fprintf(w, ": ")
printedColon = true
}
printComma = true
fmt.Fprintf(w, "%s=%s", name, sv)
}
} | go | func rprintReqOrRep(w io.Writer, obj interface{}) {
rv := reflect.ValueOf(obj).Elem()
tv := rv.Type()
nf := tv.NumField()
printedColon := false
printComma := false
for i := 0; i < nf; i++ {
name := tv.Field(i).Name
if strings.Contains(name, "Secrets") {
continue
}
sv := fmt.Sprintf("%v", rv.Field(i).Interface())
if emptyValRX.MatchString(sv) {
continue
}
if printComma {
fmt.Fprintf(w, ", ")
}
if !printedColon {
fmt.Fprintf(w, ": ")
printedColon = true
}
printComma = true
fmt.Fprintf(w, "%s=%s", name, sv)
}
} | [
"func",
"rprintReqOrRep",
"(",
"w",
"io",
".",
"Writer",
",",
"obj",
"interface",
"{",
"}",
")",
"{",
"rv",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
".",
"Elem",
"(",
")",
"\n",
"tv",
":=",
"rv",
".",
"Type",
"(",
")",
"\n",
"nf",
":=",
"tv",
".",
"NumField",
"(",
")",
"\n",
"printedColon",
":=",
"false",
"\n",
"printComma",
":=",
"false",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nf",
";",
"i",
"++",
"{",
"name",
":=",
"tv",
".",
"Field",
"(",
"i",
")",
".",
"Name",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"sv",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rv",
".",
"Field",
"(",
"i",
")",
".",
"Interface",
"(",
")",
")",
"\n",
"if",
"emptyValRX",
".",
"MatchString",
"(",
"sv",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"printComma",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"printedColon",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"printedColon",
"=",
"true",
"\n",
"}",
"\n",
"printComma",
"=",
"true",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
",",
"name",
",",
"sv",
")",
"\n",
"}",
"\n",
"}"
] | // rprintReqOrRep is used by the server-side interceptors that log
// requests and responses. | [
"rprintReqOrRep",
"is",
"used",
"by",
"the",
"server",
"-",
"side",
"interceptors",
"that",
"log",
"requests",
"and",
"responses",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/middleware/logging/logging_interceptor.go#L162-L187 |
5,060 | rexray/gocsi | mock/service/service.go | New | func New() Service {
s := &service{nodeID: Name}
s.vols = []csi.Volume{
s.newVolume("Mock Volume 1", gib100),
s.newVolume("Mock Volume 2", gib100),
s.newVolume("Mock Volume 3", gib100),
}
return s
} | go | func New() Service {
s := &service{nodeID: Name}
s.vols = []csi.Volume{
s.newVolume("Mock Volume 1", gib100),
s.newVolume("Mock Volume 2", gib100),
s.newVolume("Mock Volume 3", gib100),
}
return s
} | [
"func",
"New",
"(",
")",
"Service",
"{",
"s",
":=",
"&",
"service",
"{",
"nodeID",
":",
"Name",
"}",
"\n",
"s",
".",
"vols",
"=",
"[",
"]",
"csi",
".",
"Volume",
"{",
"s",
".",
"newVolume",
"(",
"\"",
"\"",
",",
"gib100",
")",
",",
"s",
".",
"newVolume",
"(",
"\"",
"\"",
",",
"gib100",
")",
",",
"s",
".",
"newVolume",
"(",
"\"",
"\"",
",",
"gib100",
")",
",",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // New returns a new Service. | [
"New",
"returns",
"a",
"new",
"Service",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/mock/service/service.go#L47-L55 |
5,061 | rexray/gocsi | utils/utils.go | GetCSIEndpoint | func GetCSIEndpoint() (network, addr string, err error) {
protoAddr := os.Getenv(CSIEndpoint)
if emptyRX.MatchString(protoAddr) {
return "", "", errors.New("missing CSI_ENDPOINT")
}
return ParseProtoAddr(protoAddr)
} | go | func GetCSIEndpoint() (network, addr string, err error) {
protoAddr := os.Getenv(CSIEndpoint)
if emptyRX.MatchString(protoAddr) {
return "", "", errors.New("missing CSI_ENDPOINT")
}
return ParseProtoAddr(protoAddr)
} | [
"func",
"GetCSIEndpoint",
"(",
")",
"(",
"network",
",",
"addr",
"string",
",",
"err",
"error",
")",
"{",
"protoAddr",
":=",
"os",
".",
"Getenv",
"(",
"CSIEndpoint",
")",
"\n",
"if",
"emptyRX",
".",
"MatchString",
"(",
"protoAddr",
")",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ParseProtoAddr",
"(",
"protoAddr",
")",
"\n",
"}"
] | // GetCSIEndpoint returns the network address specified by the
// environment variable CSI_ENDPOINT. | [
"GetCSIEndpoint",
"returns",
"the",
"network",
"address",
"specified",
"by",
"the",
"environment",
"variable",
"CSI_ENDPOINT",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L31-L37 |
5,062 | rexray/gocsi | utils/utils.go | GetCSIEndpointListener | func GetCSIEndpointListener() (net.Listener, error) {
proto, addr, err := GetCSIEndpoint()
if err != nil {
return nil, err
}
return net.Listen(proto, addr)
} | go | func GetCSIEndpointListener() (net.Listener, error) {
proto, addr, err := GetCSIEndpoint()
if err != nil {
return nil, err
}
return net.Listen(proto, addr)
} | [
"func",
"GetCSIEndpointListener",
"(",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"proto",
",",
"addr",
",",
"err",
":=",
"GetCSIEndpoint",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"net",
".",
"Listen",
"(",
"proto",
",",
"addr",
")",
"\n",
"}"
] | // GetCSIEndpointListener returns the net.Listener for the endpoint
// specified by the environment variable CSI_ENDPOINT. | [
"GetCSIEndpointListener",
"returns",
"the",
"net",
".",
"Listener",
"for",
"the",
"endpoint",
"specified",
"by",
"the",
"environment",
"variable",
"CSI_ENDPOINT",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L41-L47 |
5,063 | rexray/gocsi | utils/utils.go | ParseProtoAddr | func ParseProtoAddr(protoAddr string) (proto string, addr string, err error) {
if emptyRX.MatchString(protoAddr) {
return "", "", ErrParseProtoAddrRequired
}
// If the provided network address does not begin with one
// of the valid network protocols then treat the string as a
// file path.
//
// First check to see if the file exists at the specified path.
// If it does then assume it's a valid file path and return it.
//
// Otherwise attempt to create the file. If the file can be created
// without error then remove the file and return the result a UNIX
// socket file path.
if !protoAddrGuessRX.MatchString(protoAddr) {
// If the file already exists then assume it's a valid sock
// file and return it.
if _, err := os.Stat(protoAddr); !os.IsNotExist(err) {
return "unix", protoAddr, nil
}
f, err := os.Create(protoAddr)
if err != nil {
return "", "", fmt.Errorf(
"invalid implied sock file: %s: %v", protoAddr, err)
}
if err := f.Close(); err != nil {
return "", "", fmt.Errorf(
"failed to verify network address as sock file: %s", protoAddr)
}
if err := os.RemoveAll(protoAddr); err != nil {
return "", "", fmt.Errorf(
"failed to remove verified sock file: %s", protoAddr)
}
return "unix", protoAddr, nil
}
// Parse the provided network address into the protocol and address parts.
m := protoAddrExactRX.FindStringSubmatch(protoAddr)
if m == nil {
return "", "", fmt.Errorf("invalid network address: %s", protoAddr)
}
return m[1], m[2], nil
} | go | func ParseProtoAddr(protoAddr string) (proto string, addr string, err error) {
if emptyRX.MatchString(protoAddr) {
return "", "", ErrParseProtoAddrRequired
}
// If the provided network address does not begin with one
// of the valid network protocols then treat the string as a
// file path.
//
// First check to see if the file exists at the specified path.
// If it does then assume it's a valid file path and return it.
//
// Otherwise attempt to create the file. If the file can be created
// without error then remove the file and return the result a UNIX
// socket file path.
if !protoAddrGuessRX.MatchString(protoAddr) {
// If the file already exists then assume it's a valid sock
// file and return it.
if _, err := os.Stat(protoAddr); !os.IsNotExist(err) {
return "unix", protoAddr, nil
}
f, err := os.Create(protoAddr)
if err != nil {
return "", "", fmt.Errorf(
"invalid implied sock file: %s: %v", protoAddr, err)
}
if err := f.Close(); err != nil {
return "", "", fmt.Errorf(
"failed to verify network address as sock file: %s", protoAddr)
}
if err := os.RemoveAll(protoAddr); err != nil {
return "", "", fmt.Errorf(
"failed to remove verified sock file: %s", protoAddr)
}
return "unix", protoAddr, nil
}
// Parse the provided network address into the protocol and address parts.
m := protoAddrExactRX.FindStringSubmatch(protoAddr)
if m == nil {
return "", "", fmt.Errorf("invalid network address: %s", protoAddr)
}
return m[1], m[2], nil
} | [
"func",
"ParseProtoAddr",
"(",
"protoAddr",
"string",
")",
"(",
"proto",
"string",
",",
"addr",
"string",
",",
"err",
"error",
")",
"{",
"if",
"emptyRX",
".",
"MatchString",
"(",
"protoAddr",
")",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ErrParseProtoAddrRequired",
"\n",
"}",
"\n\n",
"// If the provided network address does not begin with one",
"// of the valid network protocols then treat the string as a",
"// file path.",
"//",
"// First check to see if the file exists at the specified path.",
"// If it does then assume it's a valid file path and return it.",
"//",
"// Otherwise attempt to create the file. If the file can be created",
"// without error then remove the file and return the result a UNIX",
"// socket file path.",
"if",
"!",
"protoAddrGuessRX",
".",
"MatchString",
"(",
"protoAddr",
")",
"{",
"// If the file already exists then assume it's a valid sock",
"// file and return it.",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"protoAddr",
")",
";",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"\"",
"\"",
",",
"protoAddr",
",",
"nil",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"protoAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"protoAddr",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"protoAddr",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"protoAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"protoAddr",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"protoAddr",
",",
"nil",
"\n",
"}",
"\n\n",
"// Parse the provided network address into the protocol and address parts.",
"m",
":=",
"protoAddrExactRX",
".",
"FindStringSubmatch",
"(",
"protoAddr",
")",
"\n",
"if",
"m",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"protoAddr",
")",
"\n",
"}",
"\n",
"return",
"m",
"[",
"1",
"]",
",",
"m",
"[",
"2",
"]",
",",
"nil",
"\n",
"}"
] | // ParseProtoAddr parses a Golang network address. | [
"ParseProtoAddr",
"parses",
"a",
"Golang",
"network",
"address",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L68-L114 |
5,064 | rexray/gocsi | utils/utils.go | PageVolumes | func PageVolumes(
ctx context.Context,
client csi.ControllerClient,
req csi.ListVolumesRequest,
opts ...grpc.CallOption) (<-chan csi.Volume, <-chan error) {
var (
cvol = make(chan csi.Volume)
cerr = make(chan error)
)
// Execute the RPC in a goroutine, looping until there are no
// more volumes available.
go func() {
var (
wg sync.WaitGroup
pages int
cancel context.CancelFunc
)
// Get a cancellation context used to control the interaction
// between returning volumes and the possibility of an error.
ctx, cancel = context.WithCancel(ctx)
// waitAndClose closes the volume and error channels after all
// channel-dependent goroutines have completed their work
defer func() {
wg.Wait()
close(cerr)
close(cvol)
log.WithField("pages", pages).Debug("PageAllVolumes: exit")
}()
sendVolumes := func(res csi.ListVolumesResponse) {
// Loop over the volume entries until they're all gone
// or the context is cancelled.
var i int
for i = 0; i < len(res.Entries) && ctx.Err() == nil; i++ {
// Send the volume over the channel.
cvol <- *res.Entries[i].Volume
// Let the wait group know that this worker has completed
// its task.
wg.Done()
}
// If not all volumes have been sent over the channel then
// deduct the remaining number from the wait group.
if i != len(res.Entries) {
rem := len(res.Entries) - i
log.WithFields(map[string]interface{}{
"cancel": ctx.Err(),
"remaining": rem,
}).Warn("PageAllVolumes: cancelled w unprocessed results")
wg.Add(-rem)
}
}
// listVolumes returns true if there are more volumes to list.
listVolumes := func() bool {
// The wait group "wg" is blocked during the execution of
// this function.
wg.Add(1)
defer wg.Done()
res, err := client.ListVolumes(ctx, &req, opts...)
if err != nil {
cerr <- err
// Invoke the cancellation context function to
// ensure that work wraps up as quickly as possible.
cancel()
return false
}
// Add to the number of workers
wg.Add(len(res.Entries))
// Process the retrieved volumes.
go sendVolumes(*res)
// Set the request's starting token to the response's
// next token.
req.StartingToken = res.NextToken
return req.StartingToken != ""
}
// List volumes until there are no more volumes or the context
// is cancelled.
for {
if ctx.Err() != nil {
break
}
if !listVolumes() {
break
}
pages++
}
}()
return cvol, cerr
} | go | func PageVolumes(
ctx context.Context,
client csi.ControllerClient,
req csi.ListVolumesRequest,
opts ...grpc.CallOption) (<-chan csi.Volume, <-chan error) {
var (
cvol = make(chan csi.Volume)
cerr = make(chan error)
)
// Execute the RPC in a goroutine, looping until there are no
// more volumes available.
go func() {
var (
wg sync.WaitGroup
pages int
cancel context.CancelFunc
)
// Get a cancellation context used to control the interaction
// between returning volumes and the possibility of an error.
ctx, cancel = context.WithCancel(ctx)
// waitAndClose closes the volume and error channels after all
// channel-dependent goroutines have completed their work
defer func() {
wg.Wait()
close(cerr)
close(cvol)
log.WithField("pages", pages).Debug("PageAllVolumes: exit")
}()
sendVolumes := func(res csi.ListVolumesResponse) {
// Loop over the volume entries until they're all gone
// or the context is cancelled.
var i int
for i = 0; i < len(res.Entries) && ctx.Err() == nil; i++ {
// Send the volume over the channel.
cvol <- *res.Entries[i].Volume
// Let the wait group know that this worker has completed
// its task.
wg.Done()
}
// If not all volumes have been sent over the channel then
// deduct the remaining number from the wait group.
if i != len(res.Entries) {
rem := len(res.Entries) - i
log.WithFields(map[string]interface{}{
"cancel": ctx.Err(),
"remaining": rem,
}).Warn("PageAllVolumes: cancelled w unprocessed results")
wg.Add(-rem)
}
}
// listVolumes returns true if there are more volumes to list.
listVolumes := func() bool {
// The wait group "wg" is blocked during the execution of
// this function.
wg.Add(1)
defer wg.Done()
res, err := client.ListVolumes(ctx, &req, opts...)
if err != nil {
cerr <- err
// Invoke the cancellation context function to
// ensure that work wraps up as quickly as possible.
cancel()
return false
}
// Add to the number of workers
wg.Add(len(res.Entries))
// Process the retrieved volumes.
go sendVolumes(*res)
// Set the request's starting token to the response's
// next token.
req.StartingToken = res.NextToken
return req.StartingToken != ""
}
// List volumes until there are no more volumes or the context
// is cancelled.
for {
if ctx.Err() != nil {
break
}
if !listVolumes() {
break
}
pages++
}
}()
return cvol, cerr
} | [
"func",
"PageVolumes",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"csi",
".",
"ControllerClient",
",",
"req",
"csi",
".",
"ListVolumesRequest",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"(",
"<-",
"chan",
"csi",
".",
"Volume",
",",
"<-",
"chan",
"error",
")",
"{",
"var",
"(",
"cvol",
"=",
"make",
"(",
"chan",
"csi",
".",
"Volume",
")",
"\n",
"cerr",
"=",
"make",
"(",
"chan",
"error",
")",
"\n",
")",
"\n\n",
"// Execute the RPC in a goroutine, looping until there are no",
"// more volumes available.",
"go",
"func",
"(",
")",
"{",
"var",
"(",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"pages",
"int",
"\n",
"cancel",
"context",
".",
"CancelFunc",
"\n",
")",
"\n\n",
"// Get a cancellation context used to control the interaction",
"// between returning volumes and the possibility of an error.",
"ctx",
",",
"cancel",
"=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n\n",
"// waitAndClose closes the volume and error channels after all",
"// channel-dependent goroutines have completed their work",
"defer",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"cerr",
")",
"\n",
"close",
"(",
"cvol",
")",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"pages",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"(",
")",
"\n\n",
"sendVolumes",
":=",
"func",
"(",
"res",
"csi",
".",
"ListVolumesResponse",
")",
"{",
"// Loop over the volume entries until they're all gone",
"// or the context is cancelled.",
"var",
"i",
"int",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"len",
"(",
"res",
".",
"Entries",
")",
"&&",
"ctx",
".",
"Err",
"(",
")",
"==",
"nil",
";",
"i",
"++",
"{",
"// Send the volume over the channel.",
"cvol",
"<-",
"*",
"res",
".",
"Entries",
"[",
"i",
"]",
".",
"Volume",
"\n\n",
"// Let the wait group know that this worker has completed",
"// its task.",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"\n",
"// If not all volumes have been sent over the channel then",
"// deduct the remaining number from the wait group.",
"if",
"i",
"!=",
"len",
"(",
"res",
".",
"Entries",
")",
"{",
"rem",
":=",
"len",
"(",
"res",
".",
"Entries",
")",
"-",
"i",
"\n",
"log",
".",
"WithFields",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"ctx",
".",
"Err",
"(",
")",
",",
"\"",
"\"",
":",
"rem",
",",
"}",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"wg",
".",
"Add",
"(",
"-",
"rem",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// listVolumes returns true if there are more volumes to list.",
"listVolumes",
":=",
"func",
"(",
")",
"bool",
"{",
"// The wait group \"wg\" is blocked during the execution of",
"// this function.",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"client",
".",
"ListVolumes",
"(",
"ctx",
",",
"&",
"req",
",",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cerr",
"<-",
"err",
"\n\n",
"// Invoke the cancellation context function to",
"// ensure that work wraps up as quickly as possible.",
"cancel",
"(",
")",
"\n\n",
"return",
"false",
"\n",
"}",
"\n\n",
"// Add to the number of workers",
"wg",
".",
"Add",
"(",
"len",
"(",
"res",
".",
"Entries",
")",
")",
"\n\n",
"// Process the retrieved volumes.",
"go",
"sendVolumes",
"(",
"*",
"res",
")",
"\n\n",
"// Set the request's starting token to the response's",
"// next token.",
"req",
".",
"StartingToken",
"=",
"res",
".",
"NextToken",
"\n",
"return",
"req",
".",
"StartingToken",
"!=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// List volumes until there are no more volumes or the context",
"// is cancelled.",
"for",
"{",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"!",
"listVolumes",
"(",
")",
"{",
"break",
"\n",
"}",
"\n",
"pages",
"++",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"cvol",
",",
"cerr",
"\n",
"}"
] | // PageVolumes issues one or more ListVolumes requests to retrieve
// all available volumes, returning them over a Go channel. | [
"PageVolumes",
"issues",
"one",
"or",
"more",
"ListVolumes",
"requests",
"to",
"retrieve",
"all",
"available",
"volumes",
"returning",
"them",
"over",
"a",
"Go",
"channel",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L307-L410 |
5,065 | rexray/gocsi | utils/utils.go | PageSnapshots | func PageSnapshots(
ctx context.Context,
client csi.ControllerClient,
req csi.ListSnapshotsRequest,
opts ...grpc.CallOption) (<-chan csi.Snapshot, <-chan error) {
var (
csnap = make(chan csi.Snapshot)
cerr = make(chan error)
)
// Execute the RPC in a goroutine, looping until there are no
// more snaphsots available.
go func() {
var (
wg sync.WaitGroup
pages int
cancel context.CancelFunc
)
// Get a cancellation context used to control the interaction
// between returning snaphsots and the possibility of an error.
ctx, cancel = context.WithCancel(ctx)
// waitAndClose closes the snaphsot and error channels after all
// channel-dependent goroutines have completed their work
defer func() {
wg.Wait()
close(cerr)
close(csnap)
log.WithField("pages", pages).Debug("PageAllSnapshots: exit")
}()
sendSnapshots := func(res csi.ListSnapshotsResponse) {
// Loop over the snaphsot entries until they're all gone
// or the context is cancelled.
var i int
for i = 0; i < len(res.Entries) && ctx.Err() == nil; i++ {
// Send the snaphsot over the channel.
csnap <- *res.Entries[i].Snapshot
// Let the wait group know that this worker has completed
// its task.
wg.Done()
}
// If not all snaphsots have been sent over the channel then
// deduct the remaining number from the wait group.
if i != len(res.Entries) {
rem := len(res.Entries) - i
log.WithFields(map[string]interface{}{
"cancel": ctx.Err(),
"remaining": rem,
}).Warn("PageAllSnapshots: cancelled w unprocessed results")
wg.Add(-rem)
}
}
// listSnapshots returns true if there are more snaphsots to list.
listSnapshots := func() bool {
// The wait group "wg" is blocked during the execution of
// this function.
wg.Add(1)
defer wg.Done()
res, err := client.ListSnapshots(ctx, &req, opts...)
if err != nil {
cerr <- err
// Invoke the cancellation context function to
// ensure that work wraps up as quickly as possible.
cancel()
return false
}
// Add to the number of workers
wg.Add(len(res.Entries))
// Process the retrieved snaphsots.
go sendSnapshots(*res)
// Set the request's starting token to the response's
// next token.
req.StartingToken = res.NextToken
return req.StartingToken != ""
}
// List snaphsots until there are no more snaphsots or the context
// is cancelled.
for {
if ctx.Err() != nil {
break
}
if !listSnapshots() {
break
}
pages++
}
}()
return csnap, cerr
} | go | func PageSnapshots(
ctx context.Context,
client csi.ControllerClient,
req csi.ListSnapshotsRequest,
opts ...grpc.CallOption) (<-chan csi.Snapshot, <-chan error) {
var (
csnap = make(chan csi.Snapshot)
cerr = make(chan error)
)
// Execute the RPC in a goroutine, looping until there are no
// more snaphsots available.
go func() {
var (
wg sync.WaitGroup
pages int
cancel context.CancelFunc
)
// Get a cancellation context used to control the interaction
// between returning snaphsots and the possibility of an error.
ctx, cancel = context.WithCancel(ctx)
// waitAndClose closes the snaphsot and error channels after all
// channel-dependent goroutines have completed their work
defer func() {
wg.Wait()
close(cerr)
close(csnap)
log.WithField("pages", pages).Debug("PageAllSnapshots: exit")
}()
sendSnapshots := func(res csi.ListSnapshotsResponse) {
// Loop over the snaphsot entries until they're all gone
// or the context is cancelled.
var i int
for i = 0; i < len(res.Entries) && ctx.Err() == nil; i++ {
// Send the snaphsot over the channel.
csnap <- *res.Entries[i].Snapshot
// Let the wait group know that this worker has completed
// its task.
wg.Done()
}
// If not all snaphsots have been sent over the channel then
// deduct the remaining number from the wait group.
if i != len(res.Entries) {
rem := len(res.Entries) - i
log.WithFields(map[string]interface{}{
"cancel": ctx.Err(),
"remaining": rem,
}).Warn("PageAllSnapshots: cancelled w unprocessed results")
wg.Add(-rem)
}
}
// listSnapshots returns true if there are more snaphsots to list.
listSnapshots := func() bool {
// The wait group "wg" is blocked during the execution of
// this function.
wg.Add(1)
defer wg.Done()
res, err := client.ListSnapshots(ctx, &req, opts...)
if err != nil {
cerr <- err
// Invoke the cancellation context function to
// ensure that work wraps up as quickly as possible.
cancel()
return false
}
// Add to the number of workers
wg.Add(len(res.Entries))
// Process the retrieved snaphsots.
go sendSnapshots(*res)
// Set the request's starting token to the response's
// next token.
req.StartingToken = res.NextToken
return req.StartingToken != ""
}
// List snaphsots until there are no more snaphsots or the context
// is cancelled.
for {
if ctx.Err() != nil {
break
}
if !listSnapshots() {
break
}
pages++
}
}()
return csnap, cerr
} | [
"func",
"PageSnapshots",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"csi",
".",
"ControllerClient",
",",
"req",
"csi",
".",
"ListSnapshotsRequest",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"(",
"<-",
"chan",
"csi",
".",
"Snapshot",
",",
"<-",
"chan",
"error",
")",
"{",
"var",
"(",
"csnap",
"=",
"make",
"(",
"chan",
"csi",
".",
"Snapshot",
")",
"\n",
"cerr",
"=",
"make",
"(",
"chan",
"error",
")",
"\n",
")",
"\n\n",
"// Execute the RPC in a goroutine, looping until there are no",
"// more snaphsots available.",
"go",
"func",
"(",
")",
"{",
"var",
"(",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"pages",
"int",
"\n",
"cancel",
"context",
".",
"CancelFunc",
"\n",
")",
"\n\n",
"// Get a cancellation context used to control the interaction",
"// between returning snaphsots and the possibility of an error.",
"ctx",
",",
"cancel",
"=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n\n",
"// waitAndClose closes the snaphsot and error channels after all",
"// channel-dependent goroutines have completed their work",
"defer",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"cerr",
")",
"\n",
"close",
"(",
"csnap",
")",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"pages",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"(",
")",
"\n\n",
"sendSnapshots",
":=",
"func",
"(",
"res",
"csi",
".",
"ListSnapshotsResponse",
")",
"{",
"// Loop over the snaphsot entries until they're all gone",
"// or the context is cancelled.",
"var",
"i",
"int",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"len",
"(",
"res",
".",
"Entries",
")",
"&&",
"ctx",
".",
"Err",
"(",
")",
"==",
"nil",
";",
"i",
"++",
"{",
"// Send the snaphsot over the channel.",
"csnap",
"<-",
"*",
"res",
".",
"Entries",
"[",
"i",
"]",
".",
"Snapshot",
"\n\n",
"// Let the wait group know that this worker has completed",
"// its task.",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"\n",
"// If not all snaphsots have been sent over the channel then",
"// deduct the remaining number from the wait group.",
"if",
"i",
"!=",
"len",
"(",
"res",
".",
"Entries",
")",
"{",
"rem",
":=",
"len",
"(",
"res",
".",
"Entries",
")",
"-",
"i",
"\n",
"log",
".",
"WithFields",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"ctx",
".",
"Err",
"(",
")",
",",
"\"",
"\"",
":",
"rem",
",",
"}",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"wg",
".",
"Add",
"(",
"-",
"rem",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// listSnapshots returns true if there are more snaphsots to list.",
"listSnapshots",
":=",
"func",
"(",
")",
"bool",
"{",
"// The wait group \"wg\" is blocked during the execution of",
"// this function.",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"client",
".",
"ListSnapshots",
"(",
"ctx",
",",
"&",
"req",
",",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cerr",
"<-",
"err",
"\n\n",
"// Invoke the cancellation context function to",
"// ensure that work wraps up as quickly as possible.",
"cancel",
"(",
")",
"\n\n",
"return",
"false",
"\n",
"}",
"\n\n",
"// Add to the number of workers",
"wg",
".",
"Add",
"(",
"len",
"(",
"res",
".",
"Entries",
")",
")",
"\n\n",
"// Process the retrieved snaphsots.",
"go",
"sendSnapshots",
"(",
"*",
"res",
")",
"\n\n",
"// Set the request's starting token to the response's",
"// next token.",
"req",
".",
"StartingToken",
"=",
"res",
".",
"NextToken",
"\n",
"return",
"req",
".",
"StartingToken",
"!=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// List snaphsots until there are no more snaphsots or the context",
"// is cancelled.",
"for",
"{",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"!",
"listSnapshots",
"(",
")",
"{",
"break",
"\n",
"}",
"\n",
"pages",
"++",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"csnap",
",",
"cerr",
"\n",
"}"
] | // PageSnapshots issues one or more ListSnapshots requests to retrieve
// all available snaphsots, returning them over a Go channel. | [
"PageSnapshots",
"issues",
"one",
"or",
"more",
"ListSnapshots",
"requests",
"to",
"retrieve",
"all",
"available",
"snaphsots",
"returning",
"them",
"over",
"a",
"Go",
"channel",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L414-L517 |
5,066 | rexray/gocsi | utils/utils.go | AreVolumeCapabilitiesCompatible | func AreVolumeCapabilitiesCompatible(
a, b []*csi.VolumeCapability) (bool, error) {
if len(a) > len(b) {
return false, status.Error(
codes.AlreadyExists,
"requested capabilities exceed existing")
}
var i int
for _, va := range a {
for _, vb := range b {
if EqualVolumeCapability(va, vb) {
i++
}
}
}
return i >= len(a), nil
} | go | func AreVolumeCapabilitiesCompatible(
a, b []*csi.VolumeCapability) (bool, error) {
if len(a) > len(b) {
return false, status.Error(
codes.AlreadyExists,
"requested capabilities exceed existing")
}
var i int
for _, va := range a {
for _, vb := range b {
if EqualVolumeCapability(va, vb) {
i++
}
}
}
return i >= len(a), nil
} | [
"func",
"AreVolumeCapabilitiesCompatible",
"(",
"a",
",",
"b",
"[",
"]",
"*",
"csi",
".",
"VolumeCapability",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"len",
"(",
"a",
")",
">",
"len",
"(",
"b",
")",
"{",
"return",
"false",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"AlreadyExists",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"i",
"int",
"\n\n",
"for",
"_",
",",
"va",
":=",
"range",
"a",
"{",
"for",
"_",
",",
"vb",
":=",
"range",
"b",
"{",
"if",
"EqualVolumeCapability",
"(",
"va",
",",
"vb",
")",
"{",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"i",
">=",
"len",
"(",
"a",
")",
",",
"nil",
"\n",
"}"
] | // AreVolumeCapabilitiesCompatible returns a flag indicating whether
// the volume capability array "a" is compatible with "b". A true value
// indicates that "a" and "b" are equivalent or "b" is a superset of "a". | [
"AreVolumeCapabilitiesCompatible",
"returns",
"a",
"flag",
"indicating",
"whether",
"the",
"volume",
"capability",
"array",
"a",
"is",
"compatible",
"with",
"b",
".",
"A",
"true",
"value",
"indicates",
"that",
"a",
"and",
"b",
"are",
"equivalent",
"or",
"b",
"is",
"a",
"superset",
"of",
"a",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L550-L570 |
5,067 | rexray/gocsi | utils/utils.go | IsVolumeCapabilityCompatible | func IsVolumeCapabilityCompatible(
a *csi.VolumeCapability, b []*csi.VolumeCapability) (bool, error) {
return AreVolumeCapabilitiesCompatible([]*csi.VolumeCapability{a}, b)
} | go | func IsVolumeCapabilityCompatible(
a *csi.VolumeCapability, b []*csi.VolumeCapability) (bool, error) {
return AreVolumeCapabilitiesCompatible([]*csi.VolumeCapability{a}, b)
} | [
"func",
"IsVolumeCapabilityCompatible",
"(",
"a",
"*",
"csi",
".",
"VolumeCapability",
",",
"b",
"[",
"]",
"*",
"csi",
".",
"VolumeCapability",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"AreVolumeCapabilitiesCompatible",
"(",
"[",
"]",
"*",
"csi",
".",
"VolumeCapability",
"{",
"a",
"}",
",",
"b",
")",
"\n",
"}"
] | // IsVolumeCapabilityCompatible returns a flag indicating whether
// the volume capability "a" is compatible with the set "b". A true value
// indicates that "a" and "b" are equivalent or "b" is a superset of "a". | [
"IsVolumeCapabilityCompatible",
"returns",
"a",
"flag",
"indicating",
"whether",
"the",
"volume",
"capability",
"a",
"is",
"compatible",
"with",
"the",
"set",
"b",
".",
"A",
"true",
"value",
"indicates",
"that",
"a",
"and",
"b",
"are",
"equivalent",
"or",
"b",
"is",
"a",
"superset",
"of",
"a",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L575-L579 |
5,068 | rexray/gocsi | utils/utils.go | EqualVolumeCapability | func EqualVolumeCapability(a, b *csi.VolumeCapability) bool {
if a == nil || b == nil {
return false
}
// Compare access modes.
if a.AccessMode != nil && b.AccessMode == nil {
return false
}
if a.AccessMode == nil && b.AccessMode != nil {
return false
}
if a.AccessMode != nil && b.AccessMode != nil &&
a.AccessMode.Mode != b.AccessMode.Mode {
return false
}
// If both capabilities are block then return true.
if a.GetBlock() != nil && b.GetBlock() != nil {
return true
}
aMount := a.GetMount()
bMount := b.GetMount()
if aMount != nil && bMount != nil {
// If the filesystem types are incompatible then return false.
if aMount.FsType != bMount.FsType {
return false
}
// Compare the mount flags lengths.
if len(aMount.MountFlags) != len(bMount.MountFlags) {
return false
}
// Copy the mount flags to prevent the original order
// from changing due to the sort operation below.
af := append([]string{}, aMount.MountFlags...)
bf := append([]string{}, bMount.MountFlags...)
// Sort the mount flags prior to comparison.
sort.Strings(af)
sort.Strings(bf)
// Compare the mount flags.
for j := range af {
if af[j] != bf[j] {
return false
}
}
// The mount capabilities are compatible; return true.
return true
}
return false
} | go | func EqualVolumeCapability(a, b *csi.VolumeCapability) bool {
if a == nil || b == nil {
return false
}
// Compare access modes.
if a.AccessMode != nil && b.AccessMode == nil {
return false
}
if a.AccessMode == nil && b.AccessMode != nil {
return false
}
if a.AccessMode != nil && b.AccessMode != nil &&
a.AccessMode.Mode != b.AccessMode.Mode {
return false
}
// If both capabilities are block then return true.
if a.GetBlock() != nil && b.GetBlock() != nil {
return true
}
aMount := a.GetMount()
bMount := b.GetMount()
if aMount != nil && bMount != nil {
// If the filesystem types are incompatible then return false.
if aMount.FsType != bMount.FsType {
return false
}
// Compare the mount flags lengths.
if len(aMount.MountFlags) != len(bMount.MountFlags) {
return false
}
// Copy the mount flags to prevent the original order
// from changing due to the sort operation below.
af := append([]string{}, aMount.MountFlags...)
bf := append([]string{}, bMount.MountFlags...)
// Sort the mount flags prior to comparison.
sort.Strings(af)
sort.Strings(bf)
// Compare the mount flags.
for j := range af {
if af[j] != bf[j] {
return false
}
}
// The mount capabilities are compatible; return true.
return true
}
return false
} | [
"func",
"EqualVolumeCapability",
"(",
"a",
",",
"b",
"*",
"csi",
".",
"VolumeCapability",
")",
"bool",
"{",
"if",
"a",
"==",
"nil",
"||",
"b",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Compare access modes.",
"if",
"a",
".",
"AccessMode",
"!=",
"nil",
"&&",
"b",
".",
"AccessMode",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"a",
".",
"AccessMode",
"==",
"nil",
"&&",
"b",
".",
"AccessMode",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"a",
".",
"AccessMode",
"!=",
"nil",
"&&",
"b",
".",
"AccessMode",
"!=",
"nil",
"&&",
"a",
".",
"AccessMode",
".",
"Mode",
"!=",
"b",
".",
"AccessMode",
".",
"Mode",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// If both capabilities are block then return true.",
"if",
"a",
".",
"GetBlock",
"(",
")",
"!=",
"nil",
"&&",
"b",
".",
"GetBlock",
"(",
")",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"aMount",
":=",
"a",
".",
"GetMount",
"(",
")",
"\n",
"bMount",
":=",
"b",
".",
"GetMount",
"(",
")",
"\n",
"if",
"aMount",
"!=",
"nil",
"&&",
"bMount",
"!=",
"nil",
"{",
"// If the filesystem types are incompatible then return false.",
"if",
"aMount",
".",
"FsType",
"!=",
"bMount",
".",
"FsType",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Compare the mount flags lengths.",
"if",
"len",
"(",
"aMount",
".",
"MountFlags",
")",
"!=",
"len",
"(",
"bMount",
".",
"MountFlags",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Copy the mount flags to prevent the original order",
"// from changing due to the sort operation below.",
"af",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"aMount",
".",
"MountFlags",
"...",
")",
"\n",
"bf",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"bMount",
".",
"MountFlags",
"...",
")",
"\n\n",
"// Sort the mount flags prior to comparison.",
"sort",
".",
"Strings",
"(",
"af",
")",
"\n",
"sort",
".",
"Strings",
"(",
"bf",
")",
"\n\n",
"// Compare the mount flags.",
"for",
"j",
":=",
"range",
"af",
"{",
"if",
"af",
"[",
"j",
"]",
"!=",
"bf",
"[",
"j",
"]",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"// The mount capabilities are compatible; return true.",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // EqualVolumeCapability returns a flag indicating if two csi.VolumeCapability
// objects are equal. If a and b are both nil then false is returned. | [
"EqualVolumeCapability",
"returns",
"a",
"flag",
"indicating",
"if",
"two",
"csi",
".",
"VolumeCapability",
"objects",
"are",
"equal",
".",
"If",
"a",
"and",
"b",
"are",
"both",
"nil",
"then",
"false",
"is",
"returned",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L583-L640 |
5,069 | rexray/gocsi | utils/utils.go | EqualVolume | func EqualVolume(a, b *csi.Volume) bool {
if a == nil || b == nil {
return false
}
return CompareVolume(*a, *b) == 0
} | go | func EqualVolume(a, b *csi.Volume) bool {
if a == nil || b == nil {
return false
}
return CompareVolume(*a, *b) == 0
} | [
"func",
"EqualVolume",
"(",
"a",
",",
"b",
"*",
"csi",
".",
"Volume",
")",
"bool",
"{",
"if",
"a",
"==",
"nil",
"||",
"b",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"CompareVolume",
"(",
"*",
"a",
",",
"*",
"b",
")",
"==",
"0",
"\n",
"}"
] | // EqualVolume returns a flag indicating if two csi.Volume
// objects are equal. If a and b are both nil then false is returned. | [
"EqualVolume",
"returns",
"a",
"flag",
"indicating",
"if",
"two",
"csi",
".",
"Volume",
"objects",
"are",
"equal",
".",
"If",
"a",
"and",
"b",
"are",
"both",
"nil",
"then",
"false",
"is",
"returned",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils.go#L644-L649 |
5,070 | rexray/gocsi | context/context.go | GetRequestID | func GetRequestID(ctx context.Context) (uint64, bool) {
var (
szID []string
szIDOK bool
)
// Prefer the incoming context, but look in both types.
if md, ok := metadata.FromIncomingContext(ctx); ok {
szID, szIDOK = md[RequestIDKey]
} else if md, ok := metadata.FromOutgoingContext(ctx); ok {
szID, szIDOK = md[RequestIDKey]
}
if szIDOK && len(szID) == 1 {
if id, err := strconv.ParseUint(szID[0], 10, 64); err == nil {
return id, true
}
}
return 0, false
} | go | func GetRequestID(ctx context.Context) (uint64, bool) {
var (
szID []string
szIDOK bool
)
// Prefer the incoming context, but look in both types.
if md, ok := metadata.FromIncomingContext(ctx); ok {
szID, szIDOK = md[RequestIDKey]
} else if md, ok := metadata.FromOutgoingContext(ctx); ok {
szID, szIDOK = md[RequestIDKey]
}
if szIDOK && len(szID) == 1 {
if id, err := strconv.ParseUint(szID[0], 10, 64); err == nil {
return id, true
}
}
return 0, false
} | [
"func",
"GetRequestID",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"uint64",
",",
"bool",
")",
"{",
"var",
"(",
"szID",
"[",
"]",
"string",
"\n",
"szIDOK",
"bool",
"\n",
")",
"\n\n",
"// Prefer the incoming context, but look in both types.",
"if",
"md",
",",
"ok",
":=",
"metadata",
".",
"FromIncomingContext",
"(",
"ctx",
")",
";",
"ok",
"{",
"szID",
",",
"szIDOK",
"=",
"md",
"[",
"RequestIDKey",
"]",
"\n",
"}",
"else",
"if",
"md",
",",
"ok",
":=",
"metadata",
".",
"FromOutgoingContext",
"(",
"ctx",
")",
";",
"ok",
"{",
"szID",
",",
"szIDOK",
"=",
"md",
"[",
"RequestIDKey",
"]",
"\n",
"}",
"\n\n",
"if",
"szIDOK",
"&&",
"len",
"(",
"szID",
")",
"==",
"1",
"{",
"if",
"id",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"szID",
"[",
"0",
"]",
",",
"10",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"id",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"0",
",",
"false",
"\n",
"}"
] | // GetRequestID inspects the context for gRPC metadata and returns
// its request ID if available. | [
"GetRequestID",
"inspects",
"the",
"context",
"for",
"gRPC",
"metadata",
"and",
"returns",
"its",
"request",
"ID",
"if",
"available",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/context/context.go#L43-L63 |
5,071 | rexray/gocsi | context/context.go | WithEnviron | func WithEnviron(ctx context.Context, v []string) context.Context {
return context.WithValue(ctx, ctxOSEnviron, v)
} | go | func WithEnviron(ctx context.Context, v []string) context.Context {
return context.WithValue(ctx, ctxOSEnviron, v)
} | [
"func",
"WithEnviron",
"(",
"ctx",
"context",
".",
"Context",
",",
"v",
"[",
"]",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"ctxOSEnviron",
",",
"v",
")",
"\n",
"}"
] | // WithEnviron returns a new Context with the provided environment variable
// string slice. | [
"WithEnviron",
"returns",
"a",
"new",
"Context",
"with",
"the",
"provided",
"environment",
"variable",
"string",
"slice",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/context/context.go#L67-L69 |
5,072 | rexray/gocsi | context/context.go | WithLookupEnv | func WithLookupEnv(ctx context.Context, f lookupEnvFunc) context.Context {
return context.WithValue(ctx, ctxOSLookupEnvKey, f)
} | go | func WithLookupEnv(ctx context.Context, f lookupEnvFunc) context.Context {
return context.WithValue(ctx, ctxOSLookupEnvKey, f)
} | [
"func",
"WithLookupEnv",
"(",
"ctx",
"context",
".",
"Context",
",",
"f",
"lookupEnvFunc",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"ctxOSLookupEnvKey",
",",
"f",
")",
"\n",
"}"
] | // WithLookupEnv returns a new Context with the provided function. | [
"WithLookupEnv",
"returns",
"a",
"new",
"Context",
"with",
"the",
"provided",
"function",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/context/context.go#L72-L74 |
5,073 | rexray/gocsi | context/context.go | WithSetenv | func WithSetenv(ctx context.Context, f setenvFunc) context.Context {
return context.WithValue(ctx, ctxOSSetenvKey, f)
} | go | func WithSetenv(ctx context.Context, f setenvFunc) context.Context {
return context.WithValue(ctx, ctxOSSetenvKey, f)
} | [
"func",
"WithSetenv",
"(",
"ctx",
"context",
".",
"Context",
",",
"f",
"setenvFunc",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"ctxOSSetenvKey",
",",
"f",
")",
"\n",
"}"
] | // WithSetenv returns a new Context with the provided function. | [
"WithSetenv",
"returns",
"a",
"new",
"Context",
"with",
"the",
"provided",
"function",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/context/context.go#L77-L79 |
5,074 | rexray/gocsi | context/context.go | Getenv | func Getenv(ctx context.Context, key string) string {
val, _ := LookupEnv(ctx, key)
return val
} | go | func Getenv(ctx context.Context, key string) string {
val, _ := LookupEnv(ctx, key)
return val
} | [
"func",
"Getenv",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"string",
"{",
"val",
",",
"_",
":=",
"LookupEnv",
"(",
"ctx",
",",
"key",
")",
"\n",
"return",
"val",
"\n",
"}"
] | // Getenv is an alias for LookupEnv and drops the boolean return value. | [
"Getenv",
"is",
"an",
"alias",
"for",
"LookupEnv",
"and",
"drops",
"the",
"boolean",
"return",
"value",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/context/context.go#L114-L117 |
5,075 | rexray/gocsi | mock/provider/provider.go | New | func New() gocsi.StoragePluginProvider {
svc := service.New()
return &gocsi.StoragePlugin{
Controller: svc,
Identity: svc,
Node: svc,
// BeforeServe allows the SP to participate in the startup
// sequence. This function is invoked directly before the
// gRPC server is created, giving the callback the ability to
// modify the SP's interceptors, server options, or prevent the
// server from starting by returning a non-nil error.
BeforeServe: func(
ctx context.Context,
sp *gocsi.StoragePlugin,
lis net.Listener) error {
log.WithField("service", service.Name).Debug("BeforeServe")
return nil
},
EnvVars: []string{
// Enable serial volume access.
gocsi.EnvVarSerialVolAccess + "=true",
// Enable request and response validation.
gocsi.EnvVarSpecValidation + "=true",
// Treat the following fields as required:
// * ControllerPublishVolumeRequest.NodeId
// * NodeGetNodeIdResponse.NodeId
gocsi.EnvVarRequireNodeID + "=true",
// Treat the following fields as required:
// * ControllerPublishVolumeResponse.PublishInfo
// * NodePublishVolumeRequest.PublishInfo
gocsi.EnvVarRequirePubVolContext + "=true",
},
}
} | go | func New() gocsi.StoragePluginProvider {
svc := service.New()
return &gocsi.StoragePlugin{
Controller: svc,
Identity: svc,
Node: svc,
// BeforeServe allows the SP to participate in the startup
// sequence. This function is invoked directly before the
// gRPC server is created, giving the callback the ability to
// modify the SP's interceptors, server options, or prevent the
// server from starting by returning a non-nil error.
BeforeServe: func(
ctx context.Context,
sp *gocsi.StoragePlugin,
lis net.Listener) error {
log.WithField("service", service.Name).Debug("BeforeServe")
return nil
},
EnvVars: []string{
// Enable serial volume access.
gocsi.EnvVarSerialVolAccess + "=true",
// Enable request and response validation.
gocsi.EnvVarSpecValidation + "=true",
// Treat the following fields as required:
// * ControllerPublishVolumeRequest.NodeId
// * NodeGetNodeIdResponse.NodeId
gocsi.EnvVarRequireNodeID + "=true",
// Treat the following fields as required:
// * ControllerPublishVolumeResponse.PublishInfo
// * NodePublishVolumeRequest.PublishInfo
gocsi.EnvVarRequirePubVolContext + "=true",
},
}
} | [
"func",
"New",
"(",
")",
"gocsi",
".",
"StoragePluginProvider",
"{",
"svc",
":=",
"service",
".",
"New",
"(",
")",
"\n",
"return",
"&",
"gocsi",
".",
"StoragePlugin",
"{",
"Controller",
":",
"svc",
",",
"Identity",
":",
"svc",
",",
"Node",
":",
"svc",
",",
"// BeforeServe allows the SP to participate in the startup",
"// sequence. This function is invoked directly before the",
"// gRPC server is created, giving the callback the ability to",
"// modify the SP's interceptors, server options, or prevent the",
"// server from starting by returning a non-nil error.",
"BeforeServe",
":",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"sp",
"*",
"gocsi",
".",
"StoragePlugin",
",",
"lis",
"net",
".",
"Listener",
")",
"error",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"service",
".",
"Name",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
",",
"EnvVars",
":",
"[",
"]",
"string",
"{",
"// Enable serial volume access.",
"gocsi",
".",
"EnvVarSerialVolAccess",
"+",
"\"",
"\"",
",",
"// Enable request and response validation.",
"gocsi",
".",
"EnvVarSpecValidation",
"+",
"\"",
"\"",
",",
"// Treat the following fields as required:",
"// * ControllerPublishVolumeRequest.NodeId",
"// * NodeGetNodeIdResponse.NodeId",
"gocsi",
".",
"EnvVarRequireNodeID",
"+",
"\"",
"\"",
",",
"// Treat the following fields as required:",
"// * ControllerPublishVolumeResponse.PublishInfo",
"// * NodePublishVolumeRequest.PublishInfo",
"gocsi",
".",
"EnvVarRequirePubVolContext",
"+",
"\"",
"\"",
",",
"}",
",",
"}",
"\n",
"}"
] | // New returns a new Mock Storage Plug-in Provider. | [
"New",
"returns",
"a",
"new",
"Mock",
"Storage",
"Plug",
"-",
"in",
"Provider",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/mock/provider/provider.go#L14-L53 |
5,076 | rexray/gocsi | utils/utils_middleware.go | ChainUnaryClient | func ChainUnaryClient(
i ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {
switch len(i) {
case 0:
return func(
ctx context.Context,
method string,
req, rep interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption) error {
return invoker(ctx, method, req, rep, cc, opts...)
}
case 1:
return i[0]
}
return func(
ctx context.Context,
method string,
req, rep interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption) error {
bc := func(
cur grpc.UnaryClientInterceptor,
nxt grpc.UnaryInvoker) grpc.UnaryInvoker {
return func(
curCtx context.Context,
curMethod string,
curReq, curRep interface{},
curCC *grpc.ClientConn,
curOpts ...grpc.CallOption) error {
return cur(
curCtx,
curMethod,
curReq, curRep,
curCC, nxt,
curOpts...)
}
}
c := invoker
for j := len(i) - 1; j >= 0; j-- {
c = bc(i[j], c)
}
return c(ctx, method, req, rep, cc, opts...)
}
} | go | func ChainUnaryClient(
i ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {
switch len(i) {
case 0:
return func(
ctx context.Context,
method string,
req, rep interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption) error {
return invoker(ctx, method, req, rep, cc, opts...)
}
case 1:
return i[0]
}
return func(
ctx context.Context,
method string,
req, rep interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption) error {
bc := func(
cur grpc.UnaryClientInterceptor,
nxt grpc.UnaryInvoker) grpc.UnaryInvoker {
return func(
curCtx context.Context,
curMethod string,
curReq, curRep interface{},
curCC *grpc.ClientConn,
curOpts ...grpc.CallOption) error {
return cur(
curCtx,
curMethod,
curReq, curRep,
curCC, nxt,
curOpts...)
}
}
c := invoker
for j := len(i) - 1; j >= 0; j-- {
c = bc(i[j], c)
}
return c(ctx, method, req, rep, cc, opts...)
}
} | [
"func",
"ChainUnaryClient",
"(",
"i",
"...",
"grpc",
".",
"UnaryClientInterceptor",
")",
"grpc",
".",
"UnaryClientInterceptor",
"{",
"switch",
"len",
"(",
"i",
")",
"{",
"case",
"0",
":",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
"string",
",",
"req",
",",
"rep",
"interface",
"{",
"}",
",",
"cc",
"*",
"grpc",
".",
"ClientConn",
",",
"invoker",
"grpc",
".",
"UnaryInvoker",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"error",
"{",
"return",
"invoker",
"(",
"ctx",
",",
"method",
",",
"req",
",",
"rep",
",",
"cc",
",",
"opts",
"...",
")",
"\n",
"}",
"\n",
"case",
"1",
":",
"return",
"i",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
"string",
",",
"req",
",",
"rep",
"interface",
"{",
"}",
",",
"cc",
"*",
"grpc",
".",
"ClientConn",
",",
"invoker",
"grpc",
".",
"UnaryInvoker",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"error",
"{",
"bc",
":=",
"func",
"(",
"cur",
"grpc",
".",
"UnaryClientInterceptor",
",",
"nxt",
"grpc",
".",
"UnaryInvoker",
")",
"grpc",
".",
"UnaryInvoker",
"{",
"return",
"func",
"(",
"curCtx",
"context",
".",
"Context",
",",
"curMethod",
"string",
",",
"curReq",
",",
"curRep",
"interface",
"{",
"}",
",",
"curCC",
"*",
"grpc",
".",
"ClientConn",
",",
"curOpts",
"...",
"grpc",
".",
"CallOption",
")",
"error",
"{",
"return",
"cur",
"(",
"curCtx",
",",
"curMethod",
",",
"curReq",
",",
"curRep",
",",
"curCC",
",",
"nxt",
",",
"curOpts",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"c",
":=",
"invoker",
"\n",
"for",
"j",
":=",
"len",
"(",
"i",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"c",
"=",
"bc",
"(",
"i",
"[",
"j",
"]",
",",
"c",
")",
"\n",
"}",
"\n\n",
"return",
"c",
"(",
"ctx",
",",
"method",
",",
"req",
",",
"rep",
",",
"cc",
",",
"opts",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // ChainUnaryClient chains one or more unary, client interceptors
// together into a left-to-right series that can be provided to a
// new gRPC client. | [
"ChainUnaryClient",
"chains",
"one",
"or",
"more",
"unary",
"client",
"interceptors",
"together",
"into",
"a",
"left",
"-",
"to",
"-",
"right",
"series",
"that",
"can",
"be",
"provided",
"to",
"a",
"new",
"gRPC",
"client",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils_middleware.go#L13-L66 |
5,077 | rexray/gocsi | utils/utils_middleware.go | ChainUnaryServer | func ChainUnaryServer(
i ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
switch len(i) {
case 0:
return func(
ctx context.Context,
req interface{},
_ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
case 1:
return i[0]
}
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
bc := func(
cur grpc.UnaryServerInterceptor,
nxt grpc.UnaryHandler) grpc.UnaryHandler {
return func(
curCtx context.Context,
curReq interface{}) (interface{}, error) {
return cur(curCtx, curReq, info, nxt)
}
}
c := handler
for j := len(i) - 1; j >= 0; j-- {
c = bc(i[j], c)
}
return c(ctx, req)
}
} | go | func ChainUnaryServer(
i ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
switch len(i) {
case 0:
return func(
ctx context.Context,
req interface{},
_ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
case 1:
return i[0]
}
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
bc := func(
cur grpc.UnaryServerInterceptor,
nxt grpc.UnaryHandler) grpc.UnaryHandler {
return func(
curCtx context.Context,
curReq interface{}) (interface{}, error) {
return cur(curCtx, curReq, info, nxt)
}
}
c := handler
for j := len(i) - 1; j >= 0; j-- {
c = bc(i[j], c)
}
return c(ctx, req)
}
} | [
"func",
"ChainUnaryServer",
"(",
"i",
"...",
"grpc",
".",
"UnaryServerInterceptor",
")",
"grpc",
".",
"UnaryServerInterceptor",
"{",
"switch",
"len",
"(",
"i",
")",
"{",
"case",
"0",
":",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"interface",
"{",
"}",
",",
"_",
"*",
"grpc",
".",
"UnaryServerInfo",
",",
"handler",
"grpc",
".",
"UnaryHandler",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"handler",
"(",
"ctx",
",",
"req",
")",
"\n",
"}",
"\n",
"case",
"1",
":",
"return",
"i",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"interface",
"{",
"}",
",",
"info",
"*",
"grpc",
".",
"UnaryServerInfo",
",",
"handler",
"grpc",
".",
"UnaryHandler",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"bc",
":=",
"func",
"(",
"cur",
"grpc",
".",
"UnaryServerInterceptor",
",",
"nxt",
"grpc",
".",
"UnaryHandler",
")",
"grpc",
".",
"UnaryHandler",
"{",
"return",
"func",
"(",
"curCtx",
"context",
".",
"Context",
",",
"curReq",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"cur",
"(",
"curCtx",
",",
"curReq",
",",
"info",
",",
"nxt",
")",
"\n",
"}",
"\n",
"}",
"\n",
"c",
":=",
"handler",
"\n",
"for",
"j",
":=",
"len",
"(",
"i",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"c",
"=",
"bc",
"(",
"i",
"[",
"j",
"]",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"c",
"(",
"ctx",
",",
"req",
")",
"\n",
"}",
"\n",
"}"
] | // ChainUnaryServer chains one or more unary, server interceptors
// together into a left-to-right series that can be provided to a
// new gRPC server. | [
"ChainUnaryServer",
"chains",
"one",
"or",
"more",
"unary",
"server",
"interceptors",
"together",
"into",
"a",
"left",
"-",
"to",
"-",
"right",
"series",
"that",
"can",
"be",
"provided",
"to",
"a",
"new",
"gRPC",
"server",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils_middleware.go#L71-L108 |
5,078 | rexray/gocsi | utils/utils_middleware.go | IsNilResponse | func IsNilResponse(rep interface{}) bool {
// Determine whether or not the resposne is nil. Otherwise it
// will no longer be possible to perform a nil equality check on the
// response to the interface{} rules for nil comparison. For more info
// please see https://golang.org/doc/faq#nil_error and
// https://github.com/grpc/grpc-go/issues/532.
if rep == nil {
return true
}
rv := reflect.ValueOf(rep)
switch rv.Kind() {
case reflect.Chan,
reflect.Func,
reflect.Interface,
reflect.Map,
reflect.Ptr,
reflect.Slice:
return rv.IsNil()
}
return false
} | go | func IsNilResponse(rep interface{}) bool {
// Determine whether or not the resposne is nil. Otherwise it
// will no longer be possible to perform a nil equality check on the
// response to the interface{} rules for nil comparison. For more info
// please see https://golang.org/doc/faq#nil_error and
// https://github.com/grpc/grpc-go/issues/532.
if rep == nil {
return true
}
rv := reflect.ValueOf(rep)
switch rv.Kind() {
case reflect.Chan,
reflect.Func,
reflect.Interface,
reflect.Map,
reflect.Ptr,
reflect.Slice:
return rv.IsNil()
}
return false
} | [
"func",
"IsNilResponse",
"(",
"rep",
"interface",
"{",
"}",
")",
"bool",
"{",
"// Determine whether or not the resposne is nil. Otherwise it",
"// will no longer be possible to perform a nil equality check on the",
"// response to the interface{} rules for nil comparison. For more info",
"// please see https://golang.org/doc/faq#nil_error and",
"// https://github.com/grpc/grpc-go/issues/532.",
"if",
"rep",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"rv",
":=",
"reflect",
".",
"ValueOf",
"(",
"rep",
")",
"\n",
"switch",
"rv",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Chan",
",",
"reflect",
".",
"Func",
",",
"reflect",
".",
"Interface",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Ptr",
",",
"reflect",
".",
"Slice",
":",
"return",
"rv",
".",
"IsNil",
"(",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsNilResponse returns a flag indicating whether or not the provided
// response object is a nil object wrapped inside a non-nil interface. | [
"IsNilResponse",
"returns",
"a",
"flag",
"indicating",
"whether",
"or",
"not",
"the",
"provided",
"response",
"object",
"is",
"a",
"nil",
"object",
"wrapped",
"inside",
"a",
"non",
"-",
"nil",
"interface",
"."
] | 9407f5f4ed38592fe11b57c1c9d3621df05b753b | https://github.com/rexray/gocsi/blob/9407f5f4ed38592fe11b57c1c9d3621df05b753b/utils/utils_middleware.go#L112-L132 |
5,079 | dustin/go-broadcast | broadcaster.go | NewBroadcaster | func NewBroadcaster(buflen int) Broadcaster {
b := &broadcaster{
input: make(chan interface{}, buflen),
reg: make(chan chan<- interface{}),
unreg: make(chan chan<- interface{}),
outputs: make(map[chan<- interface{}]bool),
}
go b.run()
return b
} | go | func NewBroadcaster(buflen int) Broadcaster {
b := &broadcaster{
input: make(chan interface{}, buflen),
reg: make(chan chan<- interface{}),
unreg: make(chan chan<- interface{}),
outputs: make(map[chan<- interface{}]bool),
}
go b.run()
return b
} | [
"func",
"NewBroadcaster",
"(",
"buflen",
"int",
")",
"Broadcaster",
"{",
"b",
":=",
"&",
"broadcaster",
"{",
"input",
":",
"make",
"(",
"chan",
"interface",
"{",
"}",
",",
"buflen",
")",
",",
"reg",
":",
"make",
"(",
"chan",
"chan",
"<-",
"interface",
"{",
"}",
")",
",",
"unreg",
":",
"make",
"(",
"chan",
"chan",
"<-",
"interface",
"{",
"}",
")",
",",
"outputs",
":",
"make",
"(",
"map",
"[",
"chan",
"<-",
"interface",
"{",
"}",
"]",
"bool",
")",
",",
"}",
"\n\n",
"go",
"b",
".",
"run",
"(",
")",
"\n\n",
"return",
"b",
"\n",
"}"
] | // NewBroadcaster creates a new broadcaster with the given input
// channel buffer length. | [
"NewBroadcaster",
"creates",
"a",
"new",
"broadcaster",
"with",
"the",
"given",
"input",
"channel",
"buffer",
"length",
"."
] | f664265f5a662fb4d1df7f3533b1e8d0e0277120 | https://github.com/dustin/go-broadcast/blob/f664265f5a662fb4d1df7f3533b1e8d0e0277120/broadcaster.go#L56-L67 |
5,080 | tomasen/fcgi_client | fcgiclient.go | Dial | func Dial(network, address string) (fcgi *FCGIClient, err error) {
var conn net.Conn
conn, err = net.Dial(network, address)
if err != nil {
return
}
fcgi = &FCGIClient{
rwc: conn,
keepAlive: false,
reqId: 1,
}
return
} | go | func Dial(network, address string) (fcgi *FCGIClient, err error) {
var conn net.Conn
conn, err = net.Dial(network, address)
if err != nil {
return
}
fcgi = &FCGIClient{
rwc: conn,
keepAlive: false,
reqId: 1,
}
return
} | [
"func",
"Dial",
"(",
"network",
",",
"address",
"string",
")",
"(",
"fcgi",
"*",
"FCGIClient",
",",
"err",
"error",
")",
"{",
"var",
"conn",
"net",
".",
"Conn",
"\n\n",
"conn",
",",
"err",
"=",
"net",
".",
"Dial",
"(",
"network",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"fcgi",
"=",
"&",
"FCGIClient",
"{",
"rwc",
":",
"conn",
",",
"keepAlive",
":",
"false",
",",
"reqId",
":",
"1",
",",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Connects to the fcgi responder at the specified network address.
// See func net.Dial for a description of the network and address parameters. | [
"Connects",
"to",
"the",
"fcgi",
"responder",
"at",
"the",
"specified",
"network",
"address",
".",
"See",
"func",
"net",
".",
"Dial",
"for",
"a",
"description",
"of",
"the",
"network",
"and",
"address",
"parameters",
"."
] | 2bb3d819fd19569919d3b9ccf746e1bb9938fa8d | https://github.com/tomasen/fcgi_client/blob/2bb3d819fd19569919d3b9ccf746e1bb9938fa8d/fcgiclient.go#L136-L151 |
5,081 | tomasen/fcgi_client | fcgiclient.go | Post | func (this *FCGIClient) Post(p map[string]string, bodyType string, body io.Reader, l int) (resp *http.Response, err error) {
if len(p["REQUEST_METHOD"]) == 0 || p["REQUEST_METHOD"] == "GET" {
p["REQUEST_METHOD"] = "POST"
}
p["CONTENT_LENGTH"] = strconv.Itoa(l)
if len(bodyType) > 0 {
p["CONTENT_TYPE"] = bodyType
} else {
p["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
}
return this.Request(p, body)
} | go | func (this *FCGIClient) Post(p map[string]string, bodyType string, body io.Reader, l int) (resp *http.Response, err error) {
if len(p["REQUEST_METHOD"]) == 0 || p["REQUEST_METHOD"] == "GET" {
p["REQUEST_METHOD"] = "POST"
}
p["CONTENT_LENGTH"] = strconv.Itoa(l)
if len(bodyType) > 0 {
p["CONTENT_TYPE"] = bodyType
} else {
p["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
}
return this.Request(p, body)
} | [
"func",
"(",
"this",
"*",
"FCGIClient",
")",
"Post",
"(",
"p",
"map",
"[",
"string",
"]",
"string",
",",
"bodyType",
"string",
",",
"body",
"io",
".",
"Reader",
",",
"l",
"int",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"p",
"[",
"\"",
"\"",
"]",
")",
"==",
"0",
"||",
"p",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"{",
"p",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"p",
"[",
"\"",
"\"",
"]",
"=",
"strconv",
".",
"Itoa",
"(",
"l",
")",
"\n",
"if",
"len",
"(",
"bodyType",
")",
">",
"0",
"{",
"p",
"[",
"\"",
"\"",
"]",
"=",
"bodyType",
"\n",
"}",
"else",
"{",
"p",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"this",
".",
"Request",
"(",
"p",
",",
"body",
")",
"\n",
"}"
] | // Get issues a Post request to the fcgi responder. with request body
// in the format that bodyType specified | [
"Get",
"issues",
"a",
"Post",
"request",
"to",
"the",
"fcgi",
"responder",
".",
"with",
"request",
"body",
"in",
"the",
"format",
"that",
"bodyType",
"specified"
] | 2bb3d819fd19569919d3b9ccf746e1bb9938fa8d | https://github.com/tomasen/fcgi_client/blob/2bb3d819fd19569919d3b9ccf746e1bb9938fa8d/fcgiclient.go#L453-L466 |
5,082 | kung-foo/freki | netfilter/netfilter.go | New | func New(queueID uint16, maxPacketsInQueue uint32, packetSize uint32) (nfq *Queue, err error) {
nfq = &Queue{
ID: queueID,
// TODO: what should the chan size be?
packets: make(chan *RawPacket, 1024),
}
var ret C.int
defer func() {
if err != nil && nfq != nil {
if nfq.qh != nil {
C.nfq_destroy_queue(nfq.qh)
}
if nfq.h != nil {
C.nfq_close(nfq.h)
}
}
}()
if nfq.h, err = C.nfq_open(); err != nil {
err = errors.Wrap(err, "netfilter: unable to open nfq queue handle.")
return
}
if ret, err = C.nfq_unbind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to unbind existing nfq handler.")
return
}
if ret, err = C.nfq_bind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to bind to AF_INET protocol family.")
return
}
if nfq.qh, err = C.CreateQueue(nfq.h, C.u_int16_t(queueID)); err != nil || nfq.qh == nil {
err = errors.Wrap(err, "netfilter: unable to create nfq queue.")
return
}
if ret, err = C.nfq_set_queue_maxlen(nfq.qh, C.u_int32_t(maxPacketsInQueue)); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to set nfq max queue length.")
return
}
if C.nfq_set_mode(nfq.qh, C.u_int8_t(2), C.uint(packetSize)) < 0 {
err = errors.Wrap(err, "netfilter: unable to set packet copy mode.")
return
}
if nfq.fd, err = C.nfq_fd(nfq.h); err != nil {
err = errors.Wrap(err, "netfilter: unable to get nfq queue file-descriptor.")
return
}
// TODO: error handling
// me: https://i.imgur.com/Lmy5P.gif
C.nfnl_rcvbufsiz(C.nfq_nfnlh(nfq.h), 1024*16384)
// register this queue object with the global dispatcher
register(queueID, nfq.packets)
return
} | go | func New(queueID uint16, maxPacketsInQueue uint32, packetSize uint32) (nfq *Queue, err error) {
nfq = &Queue{
ID: queueID,
// TODO: what should the chan size be?
packets: make(chan *RawPacket, 1024),
}
var ret C.int
defer func() {
if err != nil && nfq != nil {
if nfq.qh != nil {
C.nfq_destroy_queue(nfq.qh)
}
if nfq.h != nil {
C.nfq_close(nfq.h)
}
}
}()
if nfq.h, err = C.nfq_open(); err != nil {
err = errors.Wrap(err, "netfilter: unable to open nfq queue handle.")
return
}
if ret, err = C.nfq_unbind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to unbind existing nfq handler.")
return
}
if ret, err = C.nfq_bind_pf(nfq.h, AF_INET); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to bind to AF_INET protocol family.")
return
}
if nfq.qh, err = C.CreateQueue(nfq.h, C.u_int16_t(queueID)); err != nil || nfq.qh == nil {
err = errors.Wrap(err, "netfilter: unable to create nfq queue.")
return
}
if ret, err = C.nfq_set_queue_maxlen(nfq.qh, C.u_int32_t(maxPacketsInQueue)); err != nil || ret < 0 {
err = errors.Wrap(err, "netfilter: unable to set nfq max queue length.")
return
}
if C.nfq_set_mode(nfq.qh, C.u_int8_t(2), C.uint(packetSize)) < 0 {
err = errors.Wrap(err, "netfilter: unable to set packet copy mode.")
return
}
if nfq.fd, err = C.nfq_fd(nfq.h); err != nil {
err = errors.Wrap(err, "netfilter: unable to get nfq queue file-descriptor.")
return
}
// TODO: error handling
// me: https://i.imgur.com/Lmy5P.gif
C.nfnl_rcvbufsiz(C.nfq_nfnlh(nfq.h), 1024*16384)
// register this queue object with the global dispatcher
register(queueID, nfq.packets)
return
} | [
"func",
"New",
"(",
"queueID",
"uint16",
",",
"maxPacketsInQueue",
"uint32",
",",
"packetSize",
"uint32",
")",
"(",
"nfq",
"*",
"Queue",
",",
"err",
"error",
")",
"{",
"nfq",
"=",
"&",
"Queue",
"{",
"ID",
":",
"queueID",
",",
"// TODO: what should the chan size be?",
"packets",
":",
"make",
"(",
"chan",
"*",
"RawPacket",
",",
"1024",
")",
",",
"}",
"\n",
"var",
"ret",
"C",
".",
"int",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"&&",
"nfq",
"!=",
"nil",
"{",
"if",
"nfq",
".",
"qh",
"!=",
"nil",
"{",
"C",
".",
"nfq_destroy_queue",
"(",
"nfq",
".",
"qh",
")",
"\n",
"}",
"\n\n",
"if",
"nfq",
".",
"h",
"!=",
"nil",
"{",
"C",
".",
"nfq_close",
"(",
"nfq",
".",
"h",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"nfq",
".",
"h",
",",
"err",
"=",
"C",
".",
"nfq_open",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"ret",
",",
"err",
"=",
"C",
".",
"nfq_unbind_pf",
"(",
"nfq",
".",
"h",
",",
"AF_INET",
")",
";",
"err",
"!=",
"nil",
"||",
"ret",
"<",
"0",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"ret",
",",
"err",
"=",
"C",
".",
"nfq_bind_pf",
"(",
"nfq",
".",
"h",
",",
"AF_INET",
")",
";",
"err",
"!=",
"nil",
"||",
"ret",
"<",
"0",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"nfq",
".",
"qh",
",",
"err",
"=",
"C",
".",
"CreateQueue",
"(",
"nfq",
".",
"h",
",",
"C",
".",
"u_int16_t",
"(",
"queueID",
")",
")",
";",
"err",
"!=",
"nil",
"||",
"nfq",
".",
"qh",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"ret",
",",
"err",
"=",
"C",
".",
"nfq_set_queue_maxlen",
"(",
"nfq",
".",
"qh",
",",
"C",
".",
"u_int32_t",
"(",
"maxPacketsInQueue",
")",
")",
";",
"err",
"!=",
"nil",
"||",
"ret",
"<",
"0",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"C",
".",
"nfq_set_mode",
"(",
"nfq",
".",
"qh",
",",
"C",
".",
"u_int8_t",
"(",
"2",
")",
",",
"C",
".",
"uint",
"(",
"packetSize",
")",
")",
"<",
"0",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"nfq",
".",
"fd",
",",
"err",
"=",
"C",
".",
"nfq_fd",
"(",
"nfq",
".",
"h",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n\n",
"}",
"\n\n",
"// TODO: error handling",
"// me: https://i.imgur.com/Lmy5P.gif",
"C",
".",
"nfnl_rcvbufsiz",
"(",
"C",
".",
"nfq_nfnlh",
"(",
"nfq",
".",
"h",
")",
",",
"1024",
"*",
"16384",
")",
"\n\n",
"// register this queue object with the global dispatcher",
"register",
"(",
"queueID",
",",
"nfq",
".",
"packets",
")",
"\n\n",
"return",
"\n",
"}"
] | // New creates a new Queue with the given queue id. | [
"New",
"creates",
"a",
"new",
"Queue",
"with",
"the",
"given",
"queue",
"id",
"."
] | 37bf522904e242e4b820d9c52667937ea90e24f7 | https://github.com/kung-foo/freki/blob/37bf522904e242e4b820d9c52667937ea90e24f7/netfilter/netfilter.go#L80-L144 |
5,083 | kung-foo/freki | netfilter/netfilter.go | SetVerdict | func (nfq *Queue) SetVerdict(packet *RawPacket, verdict Verdict) (err error) {
// TODO: make functions explicit. for example: SetVerdictAccept, SetVerdictDrop
// TODO: get error
C.nfq_set_verdict(
nfq.qh,
C.u_int32_t(packet.ID),
C.u_int32_t(verdict),
0,
nil,
)
return
} | go | func (nfq *Queue) SetVerdict(packet *RawPacket, verdict Verdict) (err error) {
// TODO: make functions explicit. for example: SetVerdictAccept, SetVerdictDrop
// TODO: get error
C.nfq_set_verdict(
nfq.qh,
C.u_int32_t(packet.ID),
C.u_int32_t(verdict),
0,
nil,
)
return
} | [
"func",
"(",
"nfq",
"*",
"Queue",
")",
"SetVerdict",
"(",
"packet",
"*",
"RawPacket",
",",
"verdict",
"Verdict",
")",
"(",
"err",
"error",
")",
"{",
"// TODO: make functions explicit. for example: SetVerdictAccept, SetVerdictDrop",
"// TODO: get error",
"C",
".",
"nfq_set_verdict",
"(",
"nfq",
".",
"qh",
",",
"C",
".",
"u_int32_t",
"(",
"packet",
".",
"ID",
")",
",",
"C",
".",
"u_int32_t",
"(",
"verdict",
")",
",",
"0",
",",
"nil",
",",
")",
"\n",
"return",
"\n",
"}"
] | // SetVerdict tells nfq how to handle the packet. | [
"SetVerdict",
"tells",
"nfq",
"how",
"to",
"handle",
"the",
"packet",
"."
] | 37bf522904e242e4b820d9c52667937ea90e24f7 | https://github.com/kung-foo/freki/blob/37bf522904e242e4b820d9c52667937ea90e24f7/netfilter/netfilter.go#L161-L172 |
5,084 | kung-foo/freki | netfilter/netfilter.go | SetVerdictModifed | func (nfq *Queue) SetVerdictModifed(packet *RawPacket, buffer []byte, verdict Verdict) (err error) {
C.nfq_set_verdict(
nfq.qh,
C.u_int32_t(packet.ID),
C.u_int32_t(verdict),
C.u_int32_t(len(buffer)),
(*C.uchar)(unsafe.Pointer(&buffer[0])),
)
return
} | go | func (nfq *Queue) SetVerdictModifed(packet *RawPacket, buffer []byte, verdict Verdict) (err error) {
C.nfq_set_verdict(
nfq.qh,
C.u_int32_t(packet.ID),
C.u_int32_t(verdict),
C.u_int32_t(len(buffer)),
(*C.uchar)(unsafe.Pointer(&buffer[0])),
)
return
} | [
"func",
"(",
"nfq",
"*",
"Queue",
")",
"SetVerdictModifed",
"(",
"packet",
"*",
"RawPacket",
",",
"buffer",
"[",
"]",
"byte",
",",
"verdict",
"Verdict",
")",
"(",
"err",
"error",
")",
"{",
"C",
".",
"nfq_set_verdict",
"(",
"nfq",
".",
"qh",
",",
"C",
".",
"u_int32_t",
"(",
"packet",
".",
"ID",
")",
",",
"C",
".",
"u_int32_t",
"(",
"verdict",
")",
",",
"C",
".",
"u_int32_t",
"(",
"len",
"(",
"buffer",
")",
")",
",",
"(",
"*",
"C",
".",
"uchar",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"buffer",
"[",
"0",
"]",
")",
")",
",",
")",
"\n",
"return",
"\n",
"}"
] | // SetVerdictModifed tells nfq that the packet should be replaced with what is
// in buffer. | [
"SetVerdictModifed",
"tells",
"nfq",
"that",
"the",
"packet",
"should",
"be",
"replaced",
"with",
"what",
"is",
"in",
"buffer",
"."
] | 37bf522904e242e4b820d9c52667937ea90e24f7 | https://github.com/kung-foo/freki/blob/37bf522904e242e4b820d9c52667937ea90e24f7/netfilter/netfilter.go#L176-L185 |
5,085 | kung-foo/freki | netfilter/dispatch.go | register | func register(qid uint16, c chan *RawPacket) {
_dispatcher.Lock()
_dispatcher.queues[qid] = c
_dispatcher.Unlock()
} | go | func register(qid uint16, c chan *RawPacket) {
_dispatcher.Lock()
_dispatcher.queues[qid] = c
_dispatcher.Unlock()
} | [
"func",
"register",
"(",
"qid",
"uint16",
",",
"c",
"chan",
"*",
"RawPacket",
")",
"{",
"_dispatcher",
".",
"Lock",
"(",
")",
"\n",
"_dispatcher",
".",
"queues",
"[",
"qid",
"]",
"=",
"c",
"\n",
"_dispatcher",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // register registers a RawPacket channel associated with a queue_id. | [
"register",
"registers",
"a",
"RawPacket",
"channel",
"associated",
"with",
"a",
"queue_id",
"."
] | 37bf522904e242e4b820d9c52667937ea90e24f7 | https://github.com/kung-foo/freki/blob/37bf522904e242e4b820d9c52667937ea90e24f7/netfilter/dispatch.go#L20-L24 |
5,086 | kung-foo/freki | netfilter/dispatch.go | dispatch | func dispatch(qid uint16, packet *RawPacket) {
_dispatcher.RLock()
// TODO: what should happen when this blocks?
_dispatcher.queues[qid] <- packet
_dispatcher.RUnlock()
} | go | func dispatch(qid uint16, packet *RawPacket) {
_dispatcher.RLock()
// TODO: what should happen when this blocks?
_dispatcher.queues[qid] <- packet
_dispatcher.RUnlock()
} | [
"func",
"dispatch",
"(",
"qid",
"uint16",
",",
"packet",
"*",
"RawPacket",
")",
"{",
"_dispatcher",
".",
"RLock",
"(",
")",
"\n",
"// TODO: what should happen when this blocks?",
"_dispatcher",
".",
"queues",
"[",
"qid",
"]",
"<-",
"packet",
"\n",
"_dispatcher",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // dispatch routes the RawPacket to the correct handler. | [
"dispatch",
"routes",
"the",
"RawPacket",
"to",
"the",
"correct",
"handler",
"."
] | 37bf522904e242e4b820d9c52667937ea90e24f7 | https://github.com/kung-foo/freki/blob/37bf522904e242e4b820d9c52667937ea90e24f7/netfilter/dispatch.go#L27-L32 |
5,087 | d4l3k/messagediff | messagediff.go | PrettyDiff | func PrettyDiff(a, b interface{}, options ...Option) (string, bool) {
d, equal := DeepDiff(a, b, options...)
var dstr []string
for path, added := range d.Added {
dstr = append(dstr, fmt.Sprintf("added: %s = %#v\n", path.String(), added))
}
for path, removed := range d.Removed {
dstr = append(dstr, fmt.Sprintf("removed: %s = %#v\n", path.String(), removed))
}
for path, modified := range d.Modified {
dstr = append(dstr, fmt.Sprintf("modified: %s = %#v\n", path.String(), modified))
}
sort.Strings(dstr)
return strings.Join(dstr, ""), equal
} | go | func PrettyDiff(a, b interface{}, options ...Option) (string, bool) {
d, equal := DeepDiff(a, b, options...)
var dstr []string
for path, added := range d.Added {
dstr = append(dstr, fmt.Sprintf("added: %s = %#v\n", path.String(), added))
}
for path, removed := range d.Removed {
dstr = append(dstr, fmt.Sprintf("removed: %s = %#v\n", path.String(), removed))
}
for path, modified := range d.Modified {
dstr = append(dstr, fmt.Sprintf("modified: %s = %#v\n", path.String(), modified))
}
sort.Strings(dstr)
return strings.Join(dstr, ""), equal
} | [
"func",
"PrettyDiff",
"(",
"a",
",",
"b",
"interface",
"{",
"}",
",",
"options",
"...",
"Option",
")",
"(",
"string",
",",
"bool",
")",
"{",
"d",
",",
"equal",
":=",
"DeepDiff",
"(",
"a",
",",
"b",
",",
"options",
"...",
")",
"\n",
"var",
"dstr",
"[",
"]",
"string",
"\n",
"for",
"path",
",",
"added",
":=",
"range",
"d",
".",
"Added",
"{",
"dstr",
"=",
"append",
"(",
"dstr",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"path",
".",
"String",
"(",
")",
",",
"added",
")",
")",
"\n",
"}",
"\n",
"for",
"path",
",",
"removed",
":=",
"range",
"d",
".",
"Removed",
"{",
"dstr",
"=",
"append",
"(",
"dstr",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"path",
".",
"String",
"(",
")",
",",
"removed",
")",
")",
"\n",
"}",
"\n",
"for",
"path",
",",
"modified",
":=",
"range",
"d",
".",
"Modified",
"{",
"dstr",
"=",
"append",
"(",
"dstr",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"path",
".",
"String",
"(",
")",
",",
"modified",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"dstr",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"dstr",
",",
"\"",
"\"",
")",
",",
"equal",
"\n",
"}"
] | // PrettyDiff does a deep comparison and returns the nicely formated results.
// See DeepDiff for more details. | [
"PrettyDiff",
"does",
"a",
"deep",
"comparison",
"and",
"returns",
"the",
"nicely",
"formated",
"results",
".",
"See",
"DeepDiff",
"for",
"more",
"details",
"."
] | b9e99b2f9263a86c71c1ca4507f34502448c58a4 | https://github.com/d4l3k/messagediff/blob/b9e99b2f9263a86c71c1ca4507f34502448c58a4/messagediff.go#L14-L28 |
5,088 | d4l3k/messagediff | messagediff.go | DeepDiff | func DeepDiff(a, b interface{}, options ...Option) (*Diff, bool) {
d := newDiff()
opts := &opts{}
for _, o := range options {
o.apply(opts)
}
return d, d.diff(reflect.ValueOf(a), reflect.ValueOf(b), nil, opts)
} | go | func DeepDiff(a, b interface{}, options ...Option) (*Diff, bool) {
d := newDiff()
opts := &opts{}
for _, o := range options {
o.apply(opts)
}
return d, d.diff(reflect.ValueOf(a), reflect.ValueOf(b), nil, opts)
} | [
"func",
"DeepDiff",
"(",
"a",
",",
"b",
"interface",
"{",
"}",
",",
"options",
"...",
"Option",
")",
"(",
"*",
"Diff",
",",
"bool",
")",
"{",
"d",
":=",
"newDiff",
"(",
")",
"\n",
"opts",
":=",
"&",
"opts",
"{",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"o",
".",
"apply",
"(",
"opts",
")",
"\n",
"}",
"\n",
"return",
"d",
",",
"d",
".",
"diff",
"(",
"reflect",
".",
"ValueOf",
"(",
"a",
")",
",",
"reflect",
".",
"ValueOf",
"(",
"b",
")",
",",
"nil",
",",
"opts",
")",
"\n",
"}"
] | // DeepDiff does a deep comparison and returns the results.
// If the field is time.Time, use Equal to compare | [
"DeepDiff",
"does",
"a",
"deep",
"comparison",
"and",
"returns",
"the",
"results",
".",
"If",
"the",
"field",
"is",
"time",
".",
"Time",
"use",
"Equal",
"to",
"compare"
] | b9e99b2f9263a86c71c1ca4507f34502448c58a4 | https://github.com/d4l3k/messagediff/blob/b9e99b2f9263a86c71c1ca4507f34502448c58a4/messagediff.go#L32-L39 |
5,089 | papertrail/go-tail | main.go | init | func init() {
flag.Int64VarP(&number, "number", "n", 10, "how many lines to return")
flag.BoolVarP(&follow, "follow", "f", false, "follow file changes")
flag.BoolVarP(&reopen, "reopen", "F", false, "implies -f and re-opens moved / truncated files")
} | go | func init() {
flag.Int64VarP(&number, "number", "n", 10, "how many lines to return")
flag.BoolVarP(&follow, "follow", "f", false, "follow file changes")
flag.BoolVarP(&reopen, "reopen", "F", false, "implies -f and re-opens moved / truncated files")
} | [
"func",
"init",
"(",
")",
"{",
"flag",
".",
"Int64VarP",
"(",
"&",
"number",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"10",
",",
"\"",
"\"",
")",
"\n",
"flag",
".",
"BoolVarP",
"(",
"&",
"follow",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"flag",
".",
"BoolVarP",
"(",
"&",
"reopen",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // "number" and "follow" are ignored for now, since the follower is the only behavior
// until reading the end of the file is implemented | [
"number",
"and",
"follow",
"are",
"ignored",
"for",
"now",
"since",
"the",
"follower",
"is",
"the",
"only",
"behavior",
"until",
"reading",
"the",
"end",
"of",
"the",
"file",
"is",
"implemented"
] | 973c153b04319fc4604d847b09861a5730cbbde2 | https://github.com/papertrail/go-tail/blob/973c153b04319fc4604d847b09861a5730cbbde2/main.go#L20-L24 |
5,090 | cnf/structhash | structhash.go | Version | func Version(h string) int {
if h == "" {
return -1
}
if h[0] != 'v' {
return -1
}
if spos := strings.IndexRune(h[1:], '_'); spos >= 0 {
n, e := strconv.Atoi(h[1 : spos+1])
if e != nil {
return -1
}
return n
}
return -1
} | go | func Version(h string) int {
if h == "" {
return -1
}
if h[0] != 'v' {
return -1
}
if spos := strings.IndexRune(h[1:], '_'); spos >= 0 {
n, e := strconv.Atoi(h[1 : spos+1])
if e != nil {
return -1
}
return n
}
return -1
} | [
"func",
"Version",
"(",
"h",
"string",
")",
"int",
"{",
"if",
"h",
"==",
"\"",
"\"",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"if",
"h",
"[",
"0",
"]",
"!=",
"'v'",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"if",
"spos",
":=",
"strings",
".",
"IndexRune",
"(",
"h",
"[",
"1",
":",
"]",
",",
"'_'",
")",
";",
"spos",
">=",
"0",
"{",
"n",
",",
"e",
":=",
"strconv",
".",
"Atoi",
"(",
"h",
"[",
"1",
":",
"spos",
"+",
"1",
"]",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // Version returns the version of the supplied hash as an integer
// or -1 on failure | [
"Version",
"returns",
"the",
"version",
"of",
"the",
"supplied",
"hash",
"as",
"an",
"integer",
"or",
"-",
"1",
"on",
"failure"
] | 62a607eb02243845670f25a61cbc2d394c1ede10 | https://github.com/cnf/structhash/blob/62a607eb02243845670f25a61cbc2d394c1ede10/structhash.go#L16-L31 |
5,091 | gocraft/health | stack/frame.go | NewFrame | func NewFrame(pc uintptr) Frame {
frame := Frame{ProgramCounter: pc}
if frame.Func() == nil {
return frame
}
frame.Package, frame.Name = packageAndName(frame.Func())
// pc -1 because the program counters we use are usually return addresses,
// and we want to show the line that corresponds to the function call
frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1)
frame.IsSystemPackage = isSystemPackage(frame.File, frame.Package)
return frame
} | go | func NewFrame(pc uintptr) Frame {
frame := Frame{ProgramCounter: pc}
if frame.Func() == nil {
return frame
}
frame.Package, frame.Name = packageAndName(frame.Func())
// pc -1 because the program counters we use are usually return addresses,
// and we want to show the line that corresponds to the function call
frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1)
frame.IsSystemPackage = isSystemPackage(frame.File, frame.Package)
return frame
} | [
"func",
"NewFrame",
"(",
"pc",
"uintptr",
")",
"Frame",
"{",
"frame",
":=",
"Frame",
"{",
"ProgramCounter",
":",
"pc",
"}",
"\n",
"if",
"frame",
".",
"Func",
"(",
")",
"==",
"nil",
"{",
"return",
"frame",
"\n",
"}",
"\n",
"frame",
".",
"Package",
",",
"frame",
".",
"Name",
"=",
"packageAndName",
"(",
"frame",
".",
"Func",
"(",
")",
")",
"\n\n",
"// pc -1 because the program counters we use are usually return addresses,",
"// and we want to show the line that corresponds to the function call",
"frame",
".",
"File",
",",
"frame",
".",
"LineNumber",
"=",
"frame",
".",
"Func",
"(",
")",
".",
"FileLine",
"(",
"pc",
"-",
"1",
")",
"\n",
"frame",
".",
"IsSystemPackage",
"=",
"isSystemPackage",
"(",
"frame",
".",
"File",
",",
"frame",
".",
"Package",
")",
"\n\n",
"return",
"frame",
"\n",
"}"
] | // NewFrame popoulates a stack frame object from the program counter. | [
"NewFrame",
"popoulates",
"a",
"stack",
"frame",
"object",
"from",
"the",
"program",
"counter",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/stack/frame.go#L22-L35 |
5,092 | gocraft/health | healthd/debouncer.go | debouncer | func debouncer(doit chan<- struct{}, needitdone <-chan struct{}, threshold time.Duration, sleepTime time.Duration) {
var oldestNeedItDone time.Time
for {
select {
case <-needitdone:
if oldestNeedItDone.IsZero() {
oldestNeedItDone = now()
}
default:
// This sleep time is the max error that we'll be off by.
time.Sleep(sleepTime)
}
if !oldestNeedItDone.IsZero() && (now().Sub(oldestNeedItDone) > threshold) {
doit <- struct{}{}
oldestNeedItDone = time.Time{} // Zero the object
}
}
} | go | func debouncer(doit chan<- struct{}, needitdone <-chan struct{}, threshold time.Duration, sleepTime time.Duration) {
var oldestNeedItDone time.Time
for {
select {
case <-needitdone:
if oldestNeedItDone.IsZero() {
oldestNeedItDone = now()
}
default:
// This sleep time is the max error that we'll be off by.
time.Sleep(sleepTime)
}
if !oldestNeedItDone.IsZero() && (now().Sub(oldestNeedItDone) > threshold) {
doit <- struct{}{}
oldestNeedItDone = time.Time{} // Zero the object
}
}
} | [
"func",
"debouncer",
"(",
"doit",
"chan",
"<-",
"struct",
"{",
"}",
",",
"needitdone",
"<-",
"chan",
"struct",
"{",
"}",
",",
"threshold",
"time",
".",
"Duration",
",",
"sleepTime",
"time",
".",
"Duration",
")",
"{",
"var",
"oldestNeedItDone",
"time",
".",
"Time",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"needitdone",
":",
"if",
"oldestNeedItDone",
".",
"IsZero",
"(",
")",
"{",
"oldestNeedItDone",
"=",
"now",
"(",
")",
"\n",
"}",
"\n",
"default",
":",
"// This sleep time is the max error that we'll be off by.",
"time",
".",
"Sleep",
"(",
"sleepTime",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"oldestNeedItDone",
".",
"IsZero",
"(",
")",
"&&",
"(",
"now",
"(",
")",
".",
"Sub",
"(",
"oldestNeedItDone",
")",
">",
"threshold",
")",
"{",
"doit",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"oldestNeedItDone",
"=",
"time",
".",
"Time",
"{",
"}",
"// Zero the object",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // A) don't fire more than every 2 seconds B) the time between an input and output should be at most 2 seconds | [
"A",
")",
"don",
"t",
"fire",
"more",
"than",
"every",
"2",
"seconds",
"B",
")",
"the",
"time",
"between",
"an",
"input",
"and",
"output",
"should",
"be",
"at",
"most",
"2",
"seconds"
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/healthd/debouncer.go#L8-L27 |
5,093 | gocraft/health | stack/stack.go | Stack | func (t *Trace) Stack() []byte {
buf := bytes.Buffer{}
for _, frame := range t.Frames() {
buf.WriteString(frame.String())
buf.WriteRune('\n')
}
return buf.Bytes()
} | go | func (t *Trace) Stack() []byte {
buf := bytes.Buffer{}
for _, frame := range t.Frames() {
buf.WriteString(frame.String())
buf.WriteRune('\n')
}
return buf.Bytes()
} | [
"func",
"(",
"t",
"*",
"Trace",
")",
"Stack",
"(",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"for",
"_",
",",
"frame",
":=",
"range",
"t",
".",
"Frames",
"(",
")",
"{",
"buf",
".",
"WriteString",
"(",
"frame",
".",
"String",
"(",
")",
")",
"\n",
"buf",
".",
"WriteRune",
"(",
"'\\n'",
")",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}"
] | // Stack returns a formatted callstack. | [
"Stack",
"returns",
"a",
"formatted",
"callstack",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/stack/stack.go#L38-L47 |
5,094 | gocraft/health | healthd/healthd.go | shouldStop | func (hd *HealthD) shouldStop() bool {
v := atomic.LoadInt64(&hd.stopFlag)
return v == 1
} | go | func (hd *HealthD) shouldStop() bool {
v := atomic.LoadInt64(&hd.stopFlag)
return v == 1
} | [
"func",
"(",
"hd",
"*",
"HealthD",
")",
"shouldStop",
"(",
")",
"bool",
"{",
"v",
":=",
"atomic",
".",
"LoadInt64",
"(",
"&",
"hd",
".",
"stopFlag",
")",
"\n",
"return",
"v",
"==",
"1",
"\n",
"}"
] | // shouldStop returns true if we've been flagged to stop | [
"shouldStop",
"returns",
"true",
"if",
"we",
"ve",
"been",
"flagged",
"to",
"stop"
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/healthd/healthd.go#L103-L106 |
5,095 | gocraft/health | healthd/healthd.go | poll | func (hd *HealthD) poll(responses chan *pollResponse) {
var wg sync.WaitGroup
for _, hs := range hd.hostStatus {
wg.Add(1)
go func(hs *HostStatus) {
defer wg.Done()
poll(hd.stream, hs.HostPort, responses)
}(hs)
}
wg.Wait()
responses <- nil
} | go | func (hd *HealthD) poll(responses chan *pollResponse) {
var wg sync.WaitGroup
for _, hs := range hd.hostStatus {
wg.Add(1)
go func(hs *HostStatus) {
defer wg.Done()
poll(hd.stream, hs.HostPort, responses)
}(hs)
}
wg.Wait()
responses <- nil
} | [
"func",
"(",
"hd",
"*",
"HealthD",
")",
"poll",
"(",
"responses",
"chan",
"*",
"pollResponse",
")",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"hs",
":=",
"range",
"hd",
".",
"hostStatus",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"hs",
"*",
"HostStatus",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"poll",
"(",
"hd",
".",
"stream",
",",
"hs",
".",
"HostPort",
",",
"responses",
")",
"\n",
"}",
"(",
"hs",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"responses",
"<-",
"nil",
"\n",
"}"
] | // poll is meant to be alled in a new goroutine.
// It will poll each managed host in a new goroutine.
// When everything has finished, it will send nil to responses to signal that we have all data. | [
"poll",
"is",
"meant",
"to",
"be",
"alled",
"in",
"a",
"new",
"goroutine",
".",
"It",
"will",
"poll",
"each",
"managed",
"host",
"in",
"a",
"new",
"goroutine",
".",
"When",
"everything",
"has",
"finished",
"it",
"will",
"send",
"nil",
"to",
"responses",
"to",
"signal",
"that",
"we",
"have",
"all",
"data",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/healthd/healthd.go#L161-L172 |
5,096 | gocraft/health | healthd/healthd.go | purge | func (agg *HealthD) purge() {
var threshold = agg.intervalDuration * 5 // NOTE: this is arbitrary.
for k, _ := range agg.hostAggregations {
if time.Since(k.Time) > threshold {
delete(agg.hostAggregations, k)
}
}
n := len(agg.intervalAggregations)
if n > agg.maxIntervals {
agg.intervalAggregations = agg.intervalAggregations[(n - agg.maxIntervals):]
}
} | go | func (agg *HealthD) purge() {
var threshold = agg.intervalDuration * 5 // NOTE: this is arbitrary.
for k, _ := range agg.hostAggregations {
if time.Since(k.Time) > threshold {
delete(agg.hostAggregations, k)
}
}
n := len(agg.intervalAggregations)
if n > agg.maxIntervals {
agg.intervalAggregations = agg.intervalAggregations[(n - agg.maxIntervals):]
}
} | [
"func",
"(",
"agg",
"*",
"HealthD",
")",
"purge",
"(",
")",
"{",
"var",
"threshold",
"=",
"agg",
".",
"intervalDuration",
"*",
"5",
"// NOTE: this is arbitrary.",
"\n",
"for",
"k",
",",
"_",
":=",
"range",
"agg",
".",
"hostAggregations",
"{",
"if",
"time",
".",
"Since",
"(",
"k",
".",
"Time",
")",
">",
"threshold",
"{",
"delete",
"(",
"agg",
".",
"hostAggregations",
",",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"n",
":=",
"len",
"(",
"agg",
".",
"intervalAggregations",
")",
"\n",
"if",
"n",
">",
"agg",
".",
"maxIntervals",
"{",
"agg",
".",
"intervalAggregations",
"=",
"agg",
".",
"intervalAggregations",
"[",
"(",
"n",
"-",
"agg",
".",
"maxIntervals",
")",
":",
"]",
"\n",
"}",
"\n",
"}"
] | // purge purges old hostAggregations older than 5 intervals | [
"purge",
"purges",
"old",
"hostAggregations",
"older",
"than",
"5",
"intervals"
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/healthd/healthd.go#L266-L278 |
5,097 | gocraft/health | interval_aggregation_clone.go | Clone | func (ia *IntervalAggregation) Clone() *IntervalAggregation {
dup := &IntervalAggregation{}
dup.IntervalStart = ia.IntervalStart
dup.SerialNumber = ia.SerialNumber
dup.aggregationMaps = *ia.aggregationMaps.Clone()
dup.Jobs = make(map[string]*JobAggregation)
for k, v := range ia.Jobs {
dup.Jobs[k] = v.Clone()
}
return dup
} | go | func (ia *IntervalAggregation) Clone() *IntervalAggregation {
dup := &IntervalAggregation{}
dup.IntervalStart = ia.IntervalStart
dup.SerialNumber = ia.SerialNumber
dup.aggregationMaps = *ia.aggregationMaps.Clone()
dup.Jobs = make(map[string]*JobAggregation)
for k, v := range ia.Jobs {
dup.Jobs[k] = v.Clone()
}
return dup
} | [
"func",
"(",
"ia",
"*",
"IntervalAggregation",
")",
"Clone",
"(",
")",
"*",
"IntervalAggregation",
"{",
"dup",
":=",
"&",
"IntervalAggregation",
"{",
"}",
"\n",
"dup",
".",
"IntervalStart",
"=",
"ia",
".",
"IntervalStart",
"\n",
"dup",
".",
"SerialNumber",
"=",
"ia",
".",
"SerialNumber",
"\n",
"dup",
".",
"aggregationMaps",
"=",
"*",
"ia",
".",
"aggregationMaps",
".",
"Clone",
"(",
")",
"\n\n",
"dup",
".",
"Jobs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"JobAggregation",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ia",
".",
"Jobs",
"{",
"dup",
".",
"Jobs",
"[",
"k",
"]",
"=",
"v",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"dup",
"\n",
"}"
] | // Clone does a deep clone of ia, duplicating all maps and whatnot. | [
"Clone",
"does",
"a",
"deep",
"clone",
"of",
"ia",
"duplicating",
"all",
"maps",
"and",
"whatnot",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/interval_aggregation_clone.go#L4-L16 |
5,098 | gocraft/health | cmd/healthtop/jobs.go | filterJobsByName | func filterJobsByName(resp *healthd.ApiResponseJobs, name string) {
filteredSlice := []*healthd.Job{}
for _, job := range resp.Jobs {
if strings.Contains(job.Name, name) {
filteredSlice = append(filteredSlice, job)
}
}
resp.Jobs = filteredSlice
} | go | func filterJobsByName(resp *healthd.ApiResponseJobs, name string) {
filteredSlice := []*healthd.Job{}
for _, job := range resp.Jobs {
if strings.Contains(job.Name, name) {
filteredSlice = append(filteredSlice, job)
}
}
resp.Jobs = filteredSlice
} | [
"func",
"filterJobsByName",
"(",
"resp",
"*",
"healthd",
".",
"ApiResponseJobs",
",",
"name",
"string",
")",
"{",
"filteredSlice",
":=",
"[",
"]",
"*",
"healthd",
".",
"Job",
"{",
"}",
"\n\n",
"for",
"_",
",",
"job",
":=",
"range",
"resp",
".",
"Jobs",
"{",
"if",
"strings",
".",
"Contains",
"(",
"job",
".",
"Name",
",",
"name",
")",
"{",
"filteredSlice",
"=",
"append",
"(",
"filteredSlice",
",",
"job",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"resp",
".",
"Jobs",
"=",
"filteredSlice",
"\n",
"}"
] | // Given the api response, remove any job entries that don't have 'name' in them. | [
"Given",
"the",
"api",
"response",
"remove",
"any",
"job",
"entries",
"that",
"don",
"t",
"have",
"name",
"in",
"them",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/cmd/healthtop/jobs.go#L96-L106 |
5,099 | gocraft/health | interval_aggregation_merge.go | Merge | func (ia *IntervalAggregation) Merge(intAgg *IntervalAggregation) {
ia.aggregationMaps.merge(&intAgg.aggregationMaps)
for k, v := range intAgg.Jobs {
if existingJob, ok := ia.Jobs[k]; ok {
existingJob.merge(v)
} else {
ia.Jobs[k] = v.Clone()
}
}
ia.SerialNumber++
} | go | func (ia *IntervalAggregation) Merge(intAgg *IntervalAggregation) {
ia.aggregationMaps.merge(&intAgg.aggregationMaps)
for k, v := range intAgg.Jobs {
if existingJob, ok := ia.Jobs[k]; ok {
existingJob.merge(v)
} else {
ia.Jobs[k] = v.Clone()
}
}
ia.SerialNumber++
} | [
"func",
"(",
"ia",
"*",
"IntervalAggregation",
")",
"Merge",
"(",
"intAgg",
"*",
"IntervalAggregation",
")",
"{",
"ia",
".",
"aggregationMaps",
".",
"merge",
"(",
"&",
"intAgg",
".",
"aggregationMaps",
")",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"intAgg",
".",
"Jobs",
"{",
"if",
"existingJob",
",",
"ok",
":=",
"ia",
".",
"Jobs",
"[",
"k",
"]",
";",
"ok",
"{",
"existingJob",
".",
"merge",
"(",
"v",
")",
"\n",
"}",
"else",
"{",
"ia",
".",
"Jobs",
"[",
"k",
"]",
"=",
"v",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ia",
".",
"SerialNumber",
"++",
"\n",
"}"
] | // Merge merges intAgg into ia, mutating ia.
// Requires that ia and intAgg are a fully valid with no nil maps. | [
"Merge",
"merges",
"intAgg",
"into",
"ia",
"mutating",
"ia",
".",
"Requires",
"that",
"ia",
"and",
"intAgg",
"are",
"a",
"fully",
"valid",
"with",
"no",
"nil",
"maps",
"."
] | 8675af27fef0dc5c973d0957f1b1b50ffac513f9 | https://github.com/gocraft/health/blob/8675af27fef0dc5c973d0957f1b1b50ffac513f9/interval_aggregation_merge.go#L5-L17 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.