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
|
---|---|---|---|---|---|---|---|---|---|---|---|
700 | appleboy/gofight | gofight.go | SetFileFromPath | func (rc *RequestConfig) SetFileFromPath(uploads []UploadFile, params ...H) *RequestConfig {
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
for _, f := range uploads {
reader := bytes.NewReader(f.Content)
if reader.Size() == 0 {
file, err := os.Open(f.Path)
if err != nil {
log.Fatal(err)
}
defer file.Close()
part, err := writer.CreateFormFile(f.Name, filepath.Base(f.Path))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(part, file)
if err != nil {
log.Fatal(err)
}
} else {
part, err := writer.CreateFormFile(f.Name, filepath.Base(f.Path))
if err != nil {
log.Fatal(err)
}
_, err = reader.WriteTo(part)
if err != nil {
log.Fatal(err)
}
}
}
if len(params) > 0 {
for key, val := range params[0] {
_ = writer.WriteField(key, val)
}
}
err := writer.Close()
if err != nil {
log.Fatal(err)
}
rc.ContentType = writer.FormDataContentType()
rc.Body = body.String()
return rc
} | go | func (rc *RequestConfig) SetFileFromPath(uploads []UploadFile, params ...H) *RequestConfig {
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
for _, f := range uploads {
reader := bytes.NewReader(f.Content)
if reader.Size() == 0 {
file, err := os.Open(f.Path)
if err != nil {
log.Fatal(err)
}
defer file.Close()
part, err := writer.CreateFormFile(f.Name, filepath.Base(f.Path))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(part, file)
if err != nil {
log.Fatal(err)
}
} else {
part, err := writer.CreateFormFile(f.Name, filepath.Base(f.Path))
if err != nil {
log.Fatal(err)
}
_, err = reader.WriteTo(part)
if err != nil {
log.Fatal(err)
}
}
}
if len(params) > 0 {
for key, val := range params[0] {
_ = writer.WriteField(key, val)
}
}
err := writer.Close()
if err != nil {
log.Fatal(err)
}
rc.ContentType = writer.FormDataContentType()
rc.Body = body.String()
return rc
} | [
"func",
"(",
"rc",
"*",
"RequestConfig",
")",
"SetFileFromPath",
"(",
"uploads",
"[",
"]",
"UploadFile",
",",
"params",
"...",
"H",
")",
"*",
"RequestConfig",
"{",
"body",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"writer",
":=",
"multipart",
".",
"NewWriter",
"(",
"body",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"uploads",
"{",
"reader",
":=",
"bytes",
".",
"NewReader",
"(",
"f",
".",
"Content",
")",
"\n",
"if",
"reader",
".",
"Size",
"(",
")",
"==",
"0",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"f",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"part",
",",
"err",
":=",
"writer",
".",
"CreateFormFile",
"(",
"f",
".",
"Name",
",",
"filepath",
".",
"Base",
"(",
"f",
".",
"Path",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"part",
",",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"part",
",",
"err",
":=",
"writer",
".",
"CreateFormFile",
"(",
"f",
".",
"Name",
",",
"filepath",
".",
"Base",
"(",
"f",
".",
"Path",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"reader",
".",
"WriteTo",
"(",
"part",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"params",
")",
">",
"0",
"{",
"for",
"key",
",",
"val",
":=",
"range",
"params",
"[",
"0",
"]",
"{",
"_",
"=",
"writer",
".",
"WriteField",
"(",
"key",
",",
"val",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"writer",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"rc",
".",
"ContentType",
"=",
"writer",
".",
"FormDataContentType",
"(",
")",
"\n",
"rc",
".",
"Body",
"=",
"body",
".",
"String",
"(",
")",
"\n\n",
"return",
"rc",
"\n",
"}"
] | // SetFileFromPath upload new file. | [
"SetFileFromPath",
"upload",
"new",
"file",
"."
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/gofight.go#L252-L300 |
701 | appleboy/gofight | gofight.go | SetQuery | func (rc *RequestConfig) SetQuery(query H) *RequestConfig {
f := make(url.Values)
for k, v := range query {
f.Set(k, v)
}
if strings.Contains(rc.Path, "?") {
rc.Path = rc.Path + "&" + f.Encode()
} else {
rc.Path = rc.Path + "?" + f.Encode()
}
return rc
} | go | func (rc *RequestConfig) SetQuery(query H) *RequestConfig {
f := make(url.Values)
for k, v := range query {
f.Set(k, v)
}
if strings.Contains(rc.Path, "?") {
rc.Path = rc.Path + "&" + f.Encode()
} else {
rc.Path = rc.Path + "?" + f.Encode()
}
return rc
} | [
"func",
"(",
"rc",
"*",
"RequestConfig",
")",
"SetQuery",
"(",
"query",
"H",
")",
"*",
"RequestConfig",
"{",
"f",
":=",
"make",
"(",
"url",
".",
"Values",
")",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"query",
"{",
"f",
".",
"Set",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"rc",
".",
"Path",
",",
"\"",
"\"",
")",
"{",
"rc",
".",
"Path",
"=",
"rc",
".",
"Path",
"+",
"\"",
"\"",
"+",
"f",
".",
"Encode",
"(",
")",
"\n",
"}",
"else",
"{",
"rc",
".",
"Path",
"=",
"rc",
".",
"Path",
"+",
"\"",
"\"",
"+",
"f",
".",
"Encode",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"rc",
"\n",
"}"
] | // SetQuery supply query string. | [
"SetQuery",
"supply",
"query",
"string",
"."
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/gofight.go#L303-L317 |
702 | appleboy/gofight | gofight.go | SetBody | func (rc *RequestConfig) SetBody(body string) *RequestConfig {
if len(body) > 0 {
rc.Body = body
}
return rc
} | go | func (rc *RequestConfig) SetBody(body string) *RequestConfig {
if len(body) > 0 {
rc.Body = body
}
return rc
} | [
"func",
"(",
"rc",
"*",
"RequestConfig",
")",
"SetBody",
"(",
"body",
"string",
")",
"*",
"RequestConfig",
"{",
"if",
"len",
"(",
"body",
")",
">",
"0",
"{",
"rc",
".",
"Body",
"=",
"body",
"\n",
"}",
"\n\n",
"return",
"rc",
"\n",
"}"
] | // SetBody supply raw body. | [
"SetBody",
"supply",
"raw",
"body",
"."
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/gofight.go#L320-L326 |
703 | appleboy/gofight | gofight.go | SetCookie | func (rc *RequestConfig) SetCookie(cookies H) *RequestConfig {
if len(cookies) > 0 {
rc.Cookies = cookies
}
return rc
} | go | func (rc *RequestConfig) SetCookie(cookies H) *RequestConfig {
if len(cookies) > 0 {
rc.Cookies = cookies
}
return rc
} | [
"func",
"(",
"rc",
"*",
"RequestConfig",
")",
"SetCookie",
"(",
"cookies",
"H",
")",
"*",
"RequestConfig",
"{",
"if",
"len",
"(",
"cookies",
")",
">",
"0",
"{",
"rc",
".",
"Cookies",
"=",
"cookies",
"\n",
"}",
"\n\n",
"return",
"rc",
"\n",
"}"
] | // SetCookie supply cookies what you defined. | [
"SetCookie",
"supply",
"cookies",
"what",
"you",
"defined",
"."
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/gofight.go#L329-L335 |
704 | appleboy/gofight | gofight.go | Run | func (rc *RequestConfig) Run(r http.Handler, response ResponseFunc) {
req, w := rc.initTest()
r.ServeHTTP(w, req)
response(w, req)
} | go | func (rc *RequestConfig) Run(r http.Handler, response ResponseFunc) {
req, w := rc.initTest()
r.ServeHTTP(w, req)
response(w, req)
} | [
"func",
"(",
"rc",
"*",
"RequestConfig",
")",
"Run",
"(",
"r",
"http",
".",
"Handler",
",",
"response",
"ResponseFunc",
")",
"{",
"req",
",",
"w",
":=",
"rc",
".",
"initTest",
"(",
")",
"\n",
"r",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
")",
"\n",
"response",
"(",
"w",
",",
"req",
")",
"\n",
"}"
] | // Run execute http request | [
"Run",
"execute",
"http",
"request"
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/gofight.go#L395-L399 |
705 | appleboy/gofight | example/mux.go | MuxEngine | func MuxEngine() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", muxHelloHandler)
return r
} | go | func MuxEngine() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", muxHelloHandler)
return r
} | [
"func",
"MuxEngine",
"(",
")",
"*",
"mux",
".",
"Router",
"{",
"r",
":=",
"mux",
".",
"NewRouter",
"(",
")",
"\n",
"r",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"muxHelloHandler",
")",
"\n\n",
"return",
"r",
"\n",
"}"
] | // MuxEngine is mux router. | [
"MuxEngine",
"is",
"mux",
"router",
"."
] | 9341751b2b3c62a14808c372ce615f2f543110a4 | https://github.com/appleboy/gofight/blob/9341751b2b3c62a14808c372ce615f2f543110a4/example/mux.go#L13-L18 |
706 | tidwall/finn | finn.go | fillOptions | func fillOptions(opts *Options) *Options {
if opts == nil {
opts = &Options{}
}
// copy and reassign the options
nopts := *opts
if nopts.LogOutput == nil {
nopts.LogOutput = os.Stderr
}
return &nopts
} | go | func fillOptions(opts *Options) *Options {
if opts == nil {
opts = &Options{}
}
// copy and reassign the options
nopts := *opts
if nopts.LogOutput == nil {
nopts.LogOutput = os.Stderr
}
return &nopts
} | [
"func",
"fillOptions",
"(",
"opts",
"*",
"Options",
")",
"*",
"Options",
"{",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"&",
"Options",
"{",
"}",
"\n",
"}",
"\n",
"// copy and reassign the options",
"nopts",
":=",
"*",
"opts",
"\n",
"if",
"nopts",
".",
"LogOutput",
"==",
"nil",
"{",
"nopts",
".",
"LogOutput",
"=",
"os",
".",
"Stderr",
"\n",
"}",
"\n",
"return",
"&",
"nopts",
"\n",
"}"
] | // fillOptions fills in default options | [
"fillOptions",
"fills",
"in",
"default",
"options"
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L154-L164 |
707 | tidwall/finn | finn.go | Close | func (n *Node) Close() error {
n.mu.Lock()
defer n.mu.Unlock()
// shutdown the raft, but do not handle the future error. :PPA:
if n.raft != nil {
n.raft.Shutdown().Error()
}
if n.trans != nil {
n.trans.Close()
}
// close the raft database
if n.store != nil {
n.store.Close()
}
n.closed = true
return nil
} | go | func (n *Node) Close() error {
n.mu.Lock()
defer n.mu.Unlock()
// shutdown the raft, but do not handle the future error. :PPA:
if n.raft != nil {
n.raft.Shutdown().Error()
}
if n.trans != nil {
n.trans.Close()
}
// close the raft database
if n.store != nil {
n.store.Close()
}
n.closed = true
return nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"Close",
"(",
")",
"error",
"{",
"n",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"n",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// shutdown the raft, but do not handle the future error. :PPA:",
"if",
"n",
".",
"raft",
"!=",
"nil",
"{",
"n",
".",
"raft",
".",
"Shutdown",
"(",
")",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"if",
"n",
".",
"trans",
"!=",
"nil",
"{",
"n",
".",
"trans",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"// close the raft database",
"if",
"n",
".",
"store",
"!=",
"nil",
"{",
"n",
".",
"store",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"n",
".",
"closed",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the node | [
"Close",
"closes",
"the",
"node"
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L409-L425 |
708 | tidwall/finn | finn.go | reqRaftJoin | func reqRaftJoin(join, raftAddr string) error {
resp, _, err := raftredcon.Do(join, nil, []byte("raftaddpeer"), []byte(raftAddr))
if err != nil {
return err
}
if string(resp) != "OK" {
return errors.New("invalid response")
}
return nil
} | go | func reqRaftJoin(join, raftAddr string) error {
resp, _, err := raftredcon.Do(join, nil, []byte("raftaddpeer"), []byte(raftAddr))
if err != nil {
return err
}
if string(resp) != "OK" {
return errors.New("invalid response")
}
return nil
} | [
"func",
"reqRaftJoin",
"(",
"join",
",",
"raftAddr",
"string",
")",
"error",
"{",
"resp",
",",
"_",
",",
"err",
":=",
"raftredcon",
".",
"Do",
"(",
"join",
",",
"nil",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"[",
"]",
"byte",
"(",
"raftAddr",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"string",
"(",
"resp",
")",
"!=",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // reqRaftJoin does a remote "RAFTJOIN" command at the specified address. | [
"reqRaftJoin",
"does",
"a",
"remote",
"RAFTJOIN",
"command",
"at",
"the",
"specified",
"address",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L505-L514 |
709 | tidwall/finn | finn.go | scanForErrors | func scanForErrors(buf []byte) [][]byte {
var res [][]byte
for len(buf) > 0 {
if buf[0] != '-' {
return nil
}
buf = buf[1:]
for i := 0; i < len(buf); i++ {
if buf[i] == '\n' && i > 0 && buf[i-1] == '\r' {
res = append(res, buf[:i-1])
buf = buf[i+1:]
break
}
}
}
return res
} | go | func scanForErrors(buf []byte) [][]byte {
var res [][]byte
for len(buf) > 0 {
if buf[0] != '-' {
return nil
}
buf = buf[1:]
for i := 0; i < len(buf); i++ {
if buf[i] == '\n' && i > 0 && buf[i-1] == '\r' {
res = append(res, buf[:i-1])
buf = buf[i+1:]
break
}
}
}
return res
} | [
"func",
"scanForErrors",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"var",
"res",
"[",
"]",
"[",
"]",
"byte",
"\n",
"for",
"len",
"(",
"buf",
")",
">",
"0",
"{",
"if",
"buf",
"[",
"0",
"]",
"!=",
"'-'",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"buf",
"=",
"buf",
"[",
"1",
":",
"]",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"buf",
")",
";",
"i",
"++",
"{",
"if",
"buf",
"[",
"i",
"]",
"==",
"'\\n'",
"&&",
"i",
">",
"0",
"&&",
"buf",
"[",
"i",
"-",
"1",
"]",
"==",
"'\\r'",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"buf",
"[",
":",
"i",
"-",
"1",
"]",
")",
"\n",
"buf",
"=",
"buf",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // scanForErrors returns pipeline errors. All messages must be errors | [
"scanForErrors",
"returns",
"pipeline",
"errors",
".",
"All",
"messages",
"must",
"be",
"errors"
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L517-L533 |
710 | tidwall/finn | finn.go | doCommand | func (n *Node) doCommand(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) == 0 {
return nil, nil
}
var val interface{}
var err error
switch strings.ToLower(string(cmd.Args[0])) {
default:
val, err = n.handler.Command((*nodeApplier)(n), conn, cmd)
if err == ErrDisabled {
err = ErrUnknownCommand
}
case "raftaddpeer":
val, err = n.doRaftAddPeer(conn, cmd)
case "raftremovepeer":
val, err = n.doRaftRemovePeer(conn, cmd)
case "raftleader":
val, err = n.doRaftLeader(conn, cmd)
case "raftsnapshot":
val, err = n.doRaftSnapshot(conn, cmd)
case "raftshrinklog":
val, err = n.doRaftShrinkLog(conn, cmd)
case "raftstate":
val, err = n.doRaftState(conn, cmd)
case "raftstats":
val, err = n.doRaftStats(conn, cmd)
case "raftpeers":
val, err = n.doRaftPeers(conn, cmd)
case "quit":
val, err = n.doQuit(conn, cmd)
case "ping":
val, err = n.doPing(conn, cmd)
}
if err != nil && conn != nil {
// it's possible that this was a pipelined response.
wr := redcon.BaseWriter(conn)
if wr != nil {
buf := wr.Buffer()
rerrs := scanForErrors(buf)
if len(rerrs) > 0 {
wr.SetBuffer(nil)
for _, rerr := range rerrs {
conn.WriteError(n.translateError(errors.New(string(rerr)), string(cmd.Args[0])))
}
}
}
conn.WriteError(n.translateError(err, string(cmd.Args[0])))
}
return val, err
} | go | func (n *Node) doCommand(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) == 0 {
return nil, nil
}
var val interface{}
var err error
switch strings.ToLower(string(cmd.Args[0])) {
default:
val, err = n.handler.Command((*nodeApplier)(n), conn, cmd)
if err == ErrDisabled {
err = ErrUnknownCommand
}
case "raftaddpeer":
val, err = n.doRaftAddPeer(conn, cmd)
case "raftremovepeer":
val, err = n.doRaftRemovePeer(conn, cmd)
case "raftleader":
val, err = n.doRaftLeader(conn, cmd)
case "raftsnapshot":
val, err = n.doRaftSnapshot(conn, cmd)
case "raftshrinklog":
val, err = n.doRaftShrinkLog(conn, cmd)
case "raftstate":
val, err = n.doRaftState(conn, cmd)
case "raftstats":
val, err = n.doRaftStats(conn, cmd)
case "raftpeers":
val, err = n.doRaftPeers(conn, cmd)
case "quit":
val, err = n.doQuit(conn, cmd)
case "ping":
val, err = n.doPing(conn, cmd)
}
if err != nil && conn != nil {
// it's possible that this was a pipelined response.
wr := redcon.BaseWriter(conn)
if wr != nil {
buf := wr.Buffer()
rerrs := scanForErrors(buf)
if len(rerrs) > 0 {
wr.SetBuffer(nil)
for _, rerr := range rerrs {
conn.WriteError(n.translateError(errors.New(string(rerr)), string(cmd.Args[0])))
}
}
}
conn.WriteError(n.translateError(err, string(cmd.Args[0])))
}
return val, err
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doCommand",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"var",
"val",
"interface",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"cmd",
".",
"Args",
"[",
"0",
"]",
")",
")",
"{",
"default",
":",
"val",
",",
"err",
"=",
"n",
".",
"handler",
".",
"Command",
"(",
"(",
"*",
"nodeApplier",
")",
"(",
"n",
")",
",",
"conn",
",",
"cmd",
")",
"\n",
"if",
"err",
"==",
"ErrDisabled",
"{",
"err",
"=",
"ErrUnknownCommand",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftAddPeer",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftRemovePeer",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftLeader",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftSnapshot",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftShrinkLog",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftState",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftStats",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doRaftPeers",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doQuit",
"(",
"conn",
",",
"cmd",
")",
"\n",
"case",
"\"",
"\"",
":",
"val",
",",
"err",
"=",
"n",
".",
"doPing",
"(",
"conn",
",",
"cmd",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"conn",
"!=",
"nil",
"{",
"// it's possible that this was a pipelined response.",
"wr",
":=",
"redcon",
".",
"BaseWriter",
"(",
"conn",
")",
"\n",
"if",
"wr",
"!=",
"nil",
"{",
"buf",
":=",
"wr",
".",
"Buffer",
"(",
")",
"\n",
"rerrs",
":=",
"scanForErrors",
"(",
"buf",
")",
"\n",
"if",
"len",
"(",
"rerrs",
")",
">",
"0",
"{",
"wr",
".",
"SetBuffer",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"rerr",
":=",
"range",
"rerrs",
"{",
"conn",
".",
"WriteError",
"(",
"n",
".",
"translateError",
"(",
"errors",
".",
"New",
"(",
"string",
"(",
"rerr",
")",
")",
",",
"string",
"(",
"cmd",
".",
"Args",
"[",
"0",
"]",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"conn",
".",
"WriteError",
"(",
"n",
".",
"translateError",
"(",
"err",
",",
"string",
"(",
"cmd",
".",
"Args",
"[",
"0",
"]",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"val",
",",
"err",
"\n",
"}"
] | // doCommand executes a client command which is processed through the raft pipeline. | [
"doCommand",
"executes",
"a",
"client",
"command",
"which",
"is",
"processed",
"through",
"the",
"raft",
"pipeline",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L551-L600 |
711 | tidwall/finn | finn.go | doPing | func (n *Node) doPing(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
switch len(cmd.Args) {
default:
return nil, ErrWrongNumberOfArguments
case 1:
conn.WriteString("PONG")
case 2:
conn.WriteBulk(cmd.Args[1])
}
return nil, nil
} | go | func (n *Node) doPing(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
switch len(cmd.Args) {
default:
return nil, ErrWrongNumberOfArguments
case 1:
conn.WriteString("PONG")
case 2:
conn.WriteBulk(cmd.Args[1])
}
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doPing",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"switch",
"len",
"(",
"cmd",
".",
"Args",
")",
"{",
"default",
":",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"case",
"1",
":",
"conn",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"case",
"2",
":",
"conn",
".",
"WriteBulk",
"(",
"cmd",
".",
"Args",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doPing handles a "PING" client command. | [
"doPing",
"handles",
"a",
"PING",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L603-L613 |
712 | tidwall/finn | finn.go | doRaftLeader | func (n *Node) doRaftLeader(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
leader := n.raft.Leader()
if leader == "" {
conn.WriteNull()
} else {
conn.WriteBulkString(leader)
}
return nil, nil
} | go | func (n *Node) doRaftLeader(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
leader := n.raft.Leader()
if leader == "" {
conn.WriteNull()
} else {
conn.WriteBulkString(leader)
}
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doRaftLeader",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"}",
"\n",
"leader",
":=",
"n",
".",
"raft",
".",
"Leader",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"",
"\"",
"{",
"conn",
".",
"WriteNull",
"(",
")",
"\n",
"}",
"else",
"{",
"conn",
".",
"WriteBulkString",
"(",
"leader",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doRaftLeader handles a "RAFTLEADER" client command. | [
"doRaftLeader",
"handles",
"a",
"RAFTLEADER",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L616-L627 |
713 | tidwall/finn | finn.go | doRaftSnapshot | func (n *Node) doRaftSnapshot(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
f := n.raft.Snapshot()
err := f.Error()
if err != nil {
conn.WriteError("ERR " + err.Error())
return nil, nil
}
conn.WriteString("OK")
return nil, nil
} | go | func (n *Node) doRaftSnapshot(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
f := n.raft.Snapshot()
err := f.Error()
if err != nil {
conn.WriteError("ERR " + err.Error())
return nil, nil
}
conn.WriteString("OK")
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doRaftSnapshot",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"}",
"\n",
"f",
":=",
"n",
".",
"raft",
".",
"Snapshot",
"(",
")",
"\n",
"err",
":=",
"f",
".",
"Error",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"WriteError",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"conn",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doRaftSnapshot handles a "RAFTSNAPSHOT" client command. | [
"doRaftSnapshot",
"handles",
"a",
"RAFTSNAPSHOT",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L630-L642 |
714 | tidwall/finn | finn.go | doRaftShrinkLog | func (n *Node) doRaftShrinkLog(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
if s, ok := n.store.(shrinkable); ok {
err := s.Shrink()
if err != nil {
conn.WriteError("ERR " + err.Error())
return nil, nil
}
conn.WriteString("OK")
return nil, nil
}
conn.WriteError("ERR log is not shrinkable")
return nil, nil
} | go | func (n *Node) doRaftShrinkLog(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
if s, ok := n.store.(shrinkable); ok {
err := s.Shrink()
if err != nil {
conn.WriteError("ERR " + err.Error())
return nil, nil
}
conn.WriteString("OK")
return nil, nil
}
conn.WriteError("ERR log is not shrinkable")
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doRaftShrinkLog",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"}",
"\n",
"if",
"s",
",",
"ok",
":=",
"n",
".",
"store",
".",
"(",
"shrinkable",
")",
";",
"ok",
"{",
"err",
":=",
"s",
".",
"Shrink",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"WriteError",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"conn",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"conn",
".",
"WriteError",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doRaftShrinkLog handles a "RAFTSHRINKLOG" client command. | [
"doRaftShrinkLog",
"handles",
"a",
"RAFTSHRINKLOG",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L649-L664 |
715 | tidwall/finn | finn.go | doRaftState | func (n *Node) doRaftState(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
conn.WriteBulkString(n.raft.State().String())
return nil, nil
} | go | func (n *Node) doRaftState(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 1 {
return nil, ErrWrongNumberOfArguments
}
conn.WriteBulkString(n.raft.State().String())
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doRaftState",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"}",
"\n",
"conn",
".",
"WriteBulkString",
"(",
"n",
".",
"raft",
".",
"State",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doRaftState handles a "RAFTSTATE" client command. | [
"doRaftState",
"handles",
"a",
"RAFTSTATE",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L667-L673 |
716 | tidwall/finn | finn.go | doQuit | func (n *Node) doQuit(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
conn.WriteString("OK")
conn.Close()
return nil, nil
} | go | func (n *Node) doQuit(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
conn.WriteString("OK")
conn.Close()
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doQuit",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"conn",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doQuit handles a "QUIT" client command. | [
"doQuit",
"handles",
"a",
"QUIT",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L722-L726 |
717 | tidwall/finn | finn.go | doRaftAddPeer | func (n *Node) doRaftAddPeer(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 2 {
return nil, ErrWrongNumberOfArguments
}
n.log.Noticef("Received add peer request from %v", string(cmd.Args[1]))
f := n.raft.AddPeer(string(cmd.Args[1]))
if f.Error() != nil {
return nil, f.Error()
}
n.log.Noticef("Node %v added successfully", string(cmd.Args[1]))
conn.WriteString("OK")
return nil, nil
} | go | func (n *Node) doRaftAddPeer(conn redcon.Conn, cmd redcon.Command) (interface{}, error) {
if len(cmd.Args) != 2 {
return nil, ErrWrongNumberOfArguments
}
n.log.Noticef("Received add peer request from %v", string(cmd.Args[1]))
f := n.raft.AddPeer(string(cmd.Args[1]))
if f.Error() != nil {
return nil, f.Error()
}
n.log.Noticef("Node %v added successfully", string(cmd.Args[1]))
conn.WriteString("OK")
return nil, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"doRaftAddPeer",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"ErrWrongNumberOfArguments",
"\n",
"}",
"\n",
"n",
".",
"log",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"string",
"(",
"cmd",
".",
"Args",
"[",
"1",
"]",
")",
")",
"\n",
"f",
":=",
"n",
".",
"raft",
".",
"AddPeer",
"(",
"string",
"(",
"cmd",
".",
"Args",
"[",
"1",
"]",
")",
")",
"\n",
"if",
"f",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"f",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"n",
".",
"log",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"string",
"(",
"cmd",
".",
"Args",
"[",
"1",
"]",
")",
")",
"\n",
"conn",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // doRaftAddPeer handles a "RAFTADDPEER address" client command. | [
"doRaftAddPeer",
"handles",
"a",
"RAFTADDPEER",
"address",
"client",
"command",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L729-L741 |
718 | tidwall/finn | finn.go | raftApplyCommand | func (n *Node) raftApplyCommand(cmd redcon.Command) (interface{}, error) {
f := n.raft.Apply(cmd.Raw, raftTimeout)
if err := f.Error(); err != nil {
return nil, err
}
// we check for the response to be an error and return it as such.
switch v := f.Response().(type) {
default:
return v, nil
case error:
return nil, v
}
} | go | func (n *Node) raftApplyCommand(cmd redcon.Command) (interface{}, error) {
f := n.raft.Apply(cmd.Raw, raftTimeout)
if err := f.Error(); err != nil {
return nil, err
}
// we check for the response to be an error and return it as such.
switch v := f.Response().(type) {
default:
return v, nil
case error:
return nil, v
}
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"raftApplyCommand",
"(",
"cmd",
"redcon",
".",
"Command",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"f",
":=",
"n",
".",
"raft",
".",
"Apply",
"(",
"cmd",
".",
"Raw",
",",
"raftTimeout",
")",
"\n",
"if",
"err",
":=",
"f",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// we check for the response to be an error and return it as such.",
"switch",
"v",
":=",
"f",
".",
"Response",
"(",
")",
".",
"(",
"type",
")",
"{",
"default",
":",
"return",
"v",
",",
"nil",
"\n",
"case",
"error",
":",
"return",
"nil",
",",
"v",
"\n",
"}",
"\n",
"}"
] | // raftApplyCommand encodes a series of args into a raft command and
// applies it to the index. | [
"raftApplyCommand",
"encodes",
"a",
"series",
"of",
"args",
"into",
"a",
"raft",
"command",
"and",
"applies",
"it",
"to",
"the",
"index",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L760-L772 |
719 | tidwall/finn | finn.go | Apply | func (m *nodeApplier) Apply(
conn redcon.Conn,
cmd redcon.Command,
mutate func() (interface{}, error),
respond func(interface{}) (interface{}, error),
) (interface{}, error) {
var val interface{}
var err error
if mutate == nil {
// no apply, just do a level guard.
if err := (*Node)(m).raftLevelGuard(); err != nil {
return nil, err
}
} else if conn == nil {
// this is happening on a follower node.
return mutate()
} else {
// this is happening on the leader node.
// apply the command to the raft log.
val, err = (*Node)(m).raftApplyCommand(cmd)
}
if err != nil {
return nil, err
}
// responde
return respond(val)
} | go | func (m *nodeApplier) Apply(
conn redcon.Conn,
cmd redcon.Command,
mutate func() (interface{}, error),
respond func(interface{}) (interface{}, error),
) (interface{}, error) {
var val interface{}
var err error
if mutate == nil {
// no apply, just do a level guard.
if err := (*Node)(m).raftLevelGuard(); err != nil {
return nil, err
}
} else if conn == nil {
// this is happening on a follower node.
return mutate()
} else {
// this is happening on the leader node.
// apply the command to the raft log.
val, err = (*Node)(m).raftApplyCommand(cmd)
}
if err != nil {
return nil, err
}
// responde
return respond(val)
} | [
"func",
"(",
"m",
"*",
"nodeApplier",
")",
"Apply",
"(",
"conn",
"redcon",
".",
"Conn",
",",
"cmd",
"redcon",
".",
"Command",
",",
"mutate",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
",",
"respond",
"func",
"(",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
",",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"val",
"interface",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"mutate",
"==",
"nil",
"{",
"// no apply, just do a level guard.",
"if",
"err",
":=",
"(",
"*",
"Node",
")",
"(",
"m",
")",
".",
"raftLevelGuard",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"conn",
"==",
"nil",
"{",
"// this is happening on a follower node.",
"return",
"mutate",
"(",
")",
"\n",
"}",
"else",
"{",
"// this is happening on the leader node.",
"// apply the command to the raft log.",
"val",
",",
"err",
"=",
"(",
"*",
"Node",
")",
"(",
"m",
")",
".",
"raftApplyCommand",
"(",
"cmd",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// responde",
"return",
"respond",
"(",
"val",
")",
"\n",
"}"
] | // Apply executes a command through raft.
// The mutate param should be set to nil for readonly commands.
// The repsond param is required and any response to conn happens here.
// The return value from mutate will be passed into the respond param. | [
"Apply",
"executes",
"a",
"command",
"through",
"raft",
".",
"The",
"mutate",
"param",
"should",
"be",
"set",
"to",
"nil",
"for",
"readonly",
"commands",
".",
"The",
"repsond",
"param",
"is",
"required",
"and",
"any",
"response",
"to",
"conn",
"happens",
"here",
".",
"The",
"return",
"value",
"from",
"mutate",
"will",
"be",
"passed",
"into",
"the",
"respond",
"param",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L825-L851 |
720 | tidwall/finn | finn.go | Apply | func (m *nodeFSM) Apply(l *raft.Log) interface{} {
if len(l.Data) == 0 {
// blank data
return nil
}
cmd, err := redcon.Parse(l.Data)
if err != nil {
return err
}
val, err := (*Node)(m).doCommand(nil, cmd)
if err != nil {
return err
}
return val
} | go | func (m *nodeFSM) Apply(l *raft.Log) interface{} {
if len(l.Data) == 0 {
// blank data
return nil
}
cmd, err := redcon.Parse(l.Data)
if err != nil {
return err
}
val, err := (*Node)(m).doCommand(nil, cmd)
if err != nil {
return err
}
return val
} | [
"func",
"(",
"m",
"*",
"nodeFSM",
")",
"Apply",
"(",
"l",
"*",
"raft",
".",
"Log",
")",
"interface",
"{",
"}",
"{",
"if",
"len",
"(",
"l",
".",
"Data",
")",
"==",
"0",
"{",
"// blank data",
"return",
"nil",
"\n",
"}",
"\n",
"cmd",
",",
"err",
":=",
"redcon",
".",
"Parse",
"(",
"l",
".",
"Data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"val",
",",
"err",
":=",
"(",
"*",
"Node",
")",
"(",
"m",
")",
".",
"doCommand",
"(",
"nil",
",",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"val",
"\n",
"}"
] | // Apply applies a Raft log entry to the key-value store. | [
"Apply",
"applies",
"a",
"Raft",
"log",
"entry",
"to",
"the",
"key",
"-",
"value",
"store",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L862-L876 |
721 | tidwall/finn | finn.go | Restore | func (m *nodeFSM) Restore(rc io.ReadCloser) error {
defer rc.Close()
return (*Node)(m).handler.Restore(rc)
} | go | func (m *nodeFSM) Restore(rc io.ReadCloser) error {
defer rc.Close()
return (*Node)(m).handler.Restore(rc)
} | [
"func",
"(",
"m",
"*",
"nodeFSM",
")",
"Restore",
"(",
"rc",
"io",
".",
"ReadCloser",
")",
"error",
"{",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n",
"return",
"(",
"*",
"Node",
")",
"(",
"m",
")",
".",
"handler",
".",
"Restore",
"(",
"rc",
")",
"\n",
"}"
] | // Restore stores the key-value store to a previous state. | [
"Restore",
"stores",
"the",
"key",
"-",
"value",
"store",
"to",
"a",
"previous",
"state",
"."
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/finn.go#L879-L882 |
722 | tidwall/finn | example/clone.go | Restore | func (kvm *Clone) Restore(rd io.Reader) error {
kvm.mu.Lock()
defer kvm.mu.Unlock()
data, err := ioutil.ReadAll(rd)
if err != nil {
return err
}
var keys map[string][]byte
if err := json.Unmarshal(data, &keys); err != nil {
return err
}
kvm.keys = keys
return nil
} | go | func (kvm *Clone) Restore(rd io.Reader) error {
kvm.mu.Lock()
defer kvm.mu.Unlock()
data, err := ioutil.ReadAll(rd)
if err != nil {
return err
}
var keys map[string][]byte
if err := json.Unmarshal(data, &keys); err != nil {
return err
}
kvm.keys = keys
return nil
} | [
"func",
"(",
"kvm",
"*",
"Clone",
")",
"Restore",
"(",
"rd",
"io",
".",
"Reader",
")",
"error",
"{",
"kvm",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"kvm",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"rd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"keys",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"kvm",
".",
"keys",
"=",
"keys",
"\n",
"return",
"nil",
"\n",
"}"
] | // Restore restores a snapshot | [
"Restore",
"restores",
"a",
"snapshot"
] | c62a564408323e14a093ce5c65c7c29d20952006 | https://github.com/tidwall/finn/blob/c62a564408323e14a093ce5c65c7c29d20952006/example/clone.go#L195-L208 |
723 | sanity-io/litter | mapper.go | consider | func (pm *pointerMap) consider(v reflect.Value) {
if v.Kind() == reflect.Invalid {
return
}
// fmt.Printf("Considering [%s] %#v\n\r", v.Type().String(), v.Interface())
if isPointerValue(v) && v.Pointer() != 0 { // pointer is 0 for unexported fields
// fmt.Printf("Ptr is %d\n\r", v.Pointer())
reused := pm.addPointerReturnTrueIfWasReused(v.Pointer())
if reused {
// No use descending inside this value, since it have been seen before and all its descendants
// have been considered
return
}
}
// Now descend into any children of this value
switch v.Kind() {
case reflect.Slice, reflect.Array:
numEntries := v.Len()
for i := 0; i < numEntries; i++ {
pm.consider(v.Index(i))
}
case reflect.Interface:
pm.consider(v.Elem())
case reflect.Ptr:
pm.consider(v.Elem())
case reflect.Map:
keys := v.MapKeys()
sort.Sort(mapKeySorter{
keys: keys,
options: &Config,
})
for _, key := range keys {
pm.consider(v.MapIndex(key))
}
case reflect.Struct:
numFields := v.NumField()
for i := 0; i < numFields; i++ {
pm.consider(v.Field(i))
}
}
} | go | func (pm *pointerMap) consider(v reflect.Value) {
if v.Kind() == reflect.Invalid {
return
}
// fmt.Printf("Considering [%s] %#v\n\r", v.Type().String(), v.Interface())
if isPointerValue(v) && v.Pointer() != 0 { // pointer is 0 for unexported fields
// fmt.Printf("Ptr is %d\n\r", v.Pointer())
reused := pm.addPointerReturnTrueIfWasReused(v.Pointer())
if reused {
// No use descending inside this value, since it have been seen before and all its descendants
// have been considered
return
}
}
// Now descend into any children of this value
switch v.Kind() {
case reflect.Slice, reflect.Array:
numEntries := v.Len()
for i := 0; i < numEntries; i++ {
pm.consider(v.Index(i))
}
case reflect.Interface:
pm.consider(v.Elem())
case reflect.Ptr:
pm.consider(v.Elem())
case reflect.Map:
keys := v.MapKeys()
sort.Sort(mapKeySorter{
keys: keys,
options: &Config,
})
for _, key := range keys {
pm.consider(v.MapIndex(key))
}
case reflect.Struct:
numFields := v.NumField()
for i := 0; i < numFields; i++ {
pm.consider(v.Field(i))
}
}
} | [
"func",
"(",
"pm",
"*",
"pointerMap",
")",
"consider",
"(",
"v",
"reflect",
".",
"Value",
")",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Invalid",
"{",
"return",
"\n",
"}",
"\n",
"// fmt.Printf(\"Considering [%s] %#v\\n\\r\", v.Type().String(), v.Interface())",
"if",
"isPointerValue",
"(",
"v",
")",
"&&",
"v",
".",
"Pointer",
"(",
")",
"!=",
"0",
"{",
"// pointer is 0 for unexported fields",
"// fmt.Printf(\"Ptr is %d\\n\\r\", v.Pointer())",
"reused",
":=",
"pm",
".",
"addPointerReturnTrueIfWasReused",
"(",
"v",
".",
"Pointer",
"(",
")",
")",
"\n",
"if",
"reused",
"{",
"// No use descending inside this value, since it have been seen before and all its descendants",
"// have been considered",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Now descend into any children of this value",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Array",
":",
"numEntries",
":=",
"v",
".",
"Len",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numEntries",
";",
"i",
"++",
"{",
"pm",
".",
"consider",
"(",
"v",
".",
"Index",
"(",
"i",
")",
")",
"\n",
"}",
"\n\n",
"case",
"reflect",
".",
"Interface",
":",
"pm",
".",
"consider",
"(",
"v",
".",
"Elem",
"(",
")",
")",
"\n\n",
"case",
"reflect",
".",
"Ptr",
":",
"pm",
".",
"consider",
"(",
"v",
".",
"Elem",
"(",
")",
")",
"\n\n",
"case",
"reflect",
".",
"Map",
":",
"keys",
":=",
"v",
".",
"MapKeys",
"(",
")",
"\n",
"sort",
".",
"Sort",
"(",
"mapKeySorter",
"{",
"keys",
":",
"keys",
",",
"options",
":",
"&",
"Config",
",",
"}",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"pm",
".",
"consider",
"(",
"v",
".",
"MapIndex",
"(",
"key",
")",
")",
"\n",
"}",
"\n\n",
"case",
"reflect",
".",
"Struct",
":",
"numFields",
":=",
"v",
".",
"NumField",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numFields",
";",
"i",
"++",
"{",
"pm",
".",
"consider",
"(",
"v",
".",
"Field",
"(",
"i",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Recursively consider v and each of its children, updating the map according to the
// semantics of MapReusedPointers | [
"Recursively",
"consider",
"v",
"and",
"each",
"of",
"its",
"children",
"updating",
"the",
"map",
"according",
"to",
"the",
"semantics",
"of",
"MapReusedPointers"
] | 01639073401d54f0f3120725e5110734550af82e | https://github.com/sanity-io/litter/blob/01639073401d54f0f3120725e5110734550af82e/mapper.go#L26-L71 |
724 | sanity-io/litter | dump.go | pointerNameFor | func (s *dumpState) pointerNameFor(v reflect.Value) (string, bool) {
if isPointerValue(v) {
ptr := v.Pointer()
for i, addr := range s.pointers {
if ptr == addr {
firstVisit := s.visitPointerAndCheckIfItIsTheFirstTime(ptr)
return fmt.Sprintf("p%d", i), firstVisit
}
}
}
return "", false
} | go | func (s *dumpState) pointerNameFor(v reflect.Value) (string, bool) {
if isPointerValue(v) {
ptr := v.Pointer()
for i, addr := range s.pointers {
if ptr == addr {
firstVisit := s.visitPointerAndCheckIfItIsTheFirstTime(ptr)
return fmt.Sprintf("p%d", i), firstVisit
}
}
}
return "", false
} | [
"func",
"(",
"s",
"*",
"dumpState",
")",
"pointerNameFor",
"(",
"v",
"reflect",
".",
"Value",
")",
"(",
"string",
",",
"bool",
")",
"{",
"if",
"isPointerValue",
"(",
"v",
")",
"{",
"ptr",
":=",
"v",
".",
"Pointer",
"(",
")",
"\n",
"for",
"i",
",",
"addr",
":=",
"range",
"s",
".",
"pointers",
"{",
"if",
"ptr",
"==",
"addr",
"{",
"firstVisit",
":=",
"s",
".",
"visitPointerAndCheckIfItIsTheFirstTime",
"(",
"ptr",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
",",
"firstVisit",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] | // registers that the value has been visited and checks to see if it is one of the
// pointers we will see multiple times. If it is, it returns a temporary name for this
// pointer. It also returns a boolean value indicating whether this is the first time
// this name is returned so the caller can decide whether the contents of the pointer
// has been dumped before or not. | [
"registers",
"that",
"the",
"value",
"has",
"been",
"visited",
"and",
"checks",
"to",
"see",
"if",
"it",
"is",
"one",
"of",
"the",
"pointers",
"we",
"will",
"see",
"multiple",
"times",
".",
"If",
"it",
"is",
"it",
"returns",
"a",
"temporary",
"name",
"for",
"this",
"pointer",
".",
"It",
"also",
"returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"this",
"is",
"the",
"first",
"time",
"this",
"name",
"is",
"returned",
"so",
"the",
"caller",
"can",
"decide",
"whether",
"the",
"contents",
"of",
"the",
"pointer",
"has",
"been",
"dumped",
"before",
"or",
"not",
"."
] | 01639073401d54f0f3120725e5110734550af82e | https://github.com/sanity-io/litter/blob/01639073401d54f0f3120725e5110734550af82e/dump.go#L382-L393 |
725 | minio/dsync | drwmutex.go | NewDRWMutex | func NewDRWMutex(name string, clnt *Dsync) *DRWMutex {
return &DRWMutex{
Name: name,
writeLocks: make([]string, clnt.dNodeCount),
clnt: clnt,
}
} | go | func NewDRWMutex(name string, clnt *Dsync) *DRWMutex {
return &DRWMutex{
Name: name,
writeLocks: make([]string, clnt.dNodeCount),
clnt: clnt,
}
} | [
"func",
"NewDRWMutex",
"(",
"name",
"string",
",",
"clnt",
"*",
"Dsync",
")",
"*",
"DRWMutex",
"{",
"return",
"&",
"DRWMutex",
"{",
"Name",
":",
"name",
",",
"writeLocks",
":",
"make",
"(",
"[",
"]",
"string",
",",
"clnt",
".",
"dNodeCount",
")",
",",
"clnt",
":",
"clnt",
",",
"}",
"\n",
"}"
] | // NewDRWMutex - initializes a new dsync RW mutex. | [
"NewDRWMutex",
"-",
"initializes",
"a",
"new",
"dsync",
"RW",
"mutex",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L73-L79 |
726 | minio/dsync | drwmutex.go | Lock | func (dm *DRWMutex) Lock(id, source string) {
isReadLock := false
dm.lockBlocking(drwMutexInfinite, id, source, isReadLock)
} | go | func (dm *DRWMutex) Lock(id, source string) {
isReadLock := false
dm.lockBlocking(drwMutexInfinite, id, source, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"Lock",
"(",
"id",
",",
"source",
"string",
")",
"{",
"isReadLock",
":=",
"false",
"\n",
"dm",
".",
"lockBlocking",
"(",
"drwMutexInfinite",
",",
"id",
",",
"source",
",",
"isReadLock",
")",
"\n",
"}"
] | // Lock holds a write lock on dm.
//
// If the lock is already in use, the calling go routine
// blocks until the mutex is available. | [
"Lock",
"holds",
"a",
"write",
"lock",
"on",
"dm",
".",
"If",
"the",
"lock",
"is",
"already",
"in",
"use",
"the",
"calling",
"go",
"routine",
"blocks",
"until",
"the",
"mutex",
"is",
"available",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L85-L89 |
727 | minio/dsync | drwmutex.go | GetLock | func (dm *DRWMutex) GetLock(id, source string, timeout time.Duration) (locked bool) {
isReadLock := false
return dm.lockBlocking(timeout, id, source, isReadLock)
} | go | func (dm *DRWMutex) GetLock(id, source string, timeout time.Duration) (locked bool) {
isReadLock := false
return dm.lockBlocking(timeout, id, source, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"GetLock",
"(",
"id",
",",
"source",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"locked",
"bool",
")",
"{",
"isReadLock",
":=",
"false",
"\n",
"return",
"dm",
".",
"lockBlocking",
"(",
"timeout",
",",
"id",
",",
"source",
",",
"isReadLock",
")",
"\n",
"}"
] | // GetLock tries to get a write lock on dm before the timeout elapses.
//
// If the lock is already in use, the calling go routine
// blocks until either the mutex becomes available and return success or
// more time has passed than the timeout value and return false. | [
"GetLock",
"tries",
"to",
"get",
"a",
"write",
"lock",
"on",
"dm",
"before",
"the",
"timeout",
"elapses",
".",
"If",
"the",
"lock",
"is",
"already",
"in",
"use",
"the",
"calling",
"go",
"routine",
"blocks",
"until",
"either",
"the",
"mutex",
"becomes",
"available",
"and",
"return",
"success",
"or",
"more",
"time",
"has",
"passed",
"than",
"the",
"timeout",
"value",
"and",
"return",
"false",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L96-L100 |
728 | minio/dsync | drwmutex.go | RLock | func (dm *DRWMutex) RLock(id, source string) {
isReadLock := true
dm.lockBlocking(drwMutexInfinite, id, source, isReadLock)
} | go | func (dm *DRWMutex) RLock(id, source string) {
isReadLock := true
dm.lockBlocking(drwMutexInfinite, id, source, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"RLock",
"(",
"id",
",",
"source",
"string",
")",
"{",
"isReadLock",
":=",
"true",
"\n",
"dm",
".",
"lockBlocking",
"(",
"drwMutexInfinite",
",",
"id",
",",
"source",
",",
"isReadLock",
")",
"\n",
"}"
] | // RLock holds a read lock on dm.
//
// If one or more read locks are already in use, it will grant another lock.
// Otherwise the calling go routine blocks until the mutex is available. | [
"RLock",
"holds",
"a",
"read",
"lock",
"on",
"dm",
".",
"If",
"one",
"or",
"more",
"read",
"locks",
"are",
"already",
"in",
"use",
"it",
"will",
"grant",
"another",
"lock",
".",
"Otherwise",
"the",
"calling",
"go",
"routine",
"blocks",
"until",
"the",
"mutex",
"is",
"available",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L106-L110 |
729 | minio/dsync | drwmutex.go | GetRLock | func (dm *DRWMutex) GetRLock(id, source string, timeout time.Duration) (locked bool) {
isReadLock := true
return dm.lockBlocking(timeout, id, source, isReadLock)
} | go | func (dm *DRWMutex) GetRLock(id, source string, timeout time.Duration) (locked bool) {
isReadLock := true
return dm.lockBlocking(timeout, id, source, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"GetRLock",
"(",
"id",
",",
"source",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"locked",
"bool",
")",
"{",
"isReadLock",
":=",
"true",
"\n",
"return",
"dm",
".",
"lockBlocking",
"(",
"timeout",
",",
"id",
",",
"source",
",",
"isReadLock",
")",
"\n",
"}"
] | // GetRLock tries to get a read lock on dm before the timeout elapses.
//
// If one or more read locks are already in use, it will grant another lock.
// Otherwise the calling go routine blocks until either the mutex becomes
// available and return success or more time has passed than the timeout
// value and return false. | [
"GetRLock",
"tries",
"to",
"get",
"a",
"read",
"lock",
"on",
"dm",
"before",
"the",
"timeout",
"elapses",
".",
"If",
"one",
"or",
"more",
"read",
"locks",
"are",
"already",
"in",
"use",
"it",
"will",
"grant",
"another",
"lock",
".",
"Otherwise",
"the",
"calling",
"go",
"routine",
"blocks",
"until",
"either",
"the",
"mutex",
"becomes",
"available",
"and",
"return",
"success",
"or",
"more",
"time",
"has",
"passed",
"than",
"the",
"timeout",
"value",
"and",
"return",
"false",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L118-L122 |
730 | minio/dsync | drwmutex.go | lockBlocking | func (dm *DRWMutex) lockBlocking(timeout time.Duration, id, source string, isReadLock bool) (locked bool) {
doneCh, start := make(chan struct{}), time.Now().UTC()
defer close(doneCh)
// Use incremental back-off algorithm for repeated attempts to acquire the lock
for range newRetryTimerSimple(doneCh) {
// Create temp array on stack.
locks := make([]string, dm.clnt.dNodeCount)
// Try to acquire the lock.
success := lock(dm.clnt, &locks, dm.Name, id, source, isReadLock)
if success {
dm.m.Lock()
defer dm.m.Unlock()
// If success, copy array to object
if isReadLock {
// Append new array of strings at the end
dm.readersLocks = append(dm.readersLocks, make([]string, dm.clnt.dNodeCount))
// and copy stack array into last spot
copy(dm.readersLocks[len(dm.readersLocks)-1], locks[:])
} else {
copy(dm.writeLocks, locks[:])
}
return true
}
if time.Now().UTC().Sub(start) >= timeout { // Are we past the timeout?
break
}
// Failed to acquire the lock on this attempt, incrementally wait
// for a longer back-off time and try again afterwards.
}
return false
} | go | func (dm *DRWMutex) lockBlocking(timeout time.Duration, id, source string, isReadLock bool) (locked bool) {
doneCh, start := make(chan struct{}), time.Now().UTC()
defer close(doneCh)
// Use incremental back-off algorithm for repeated attempts to acquire the lock
for range newRetryTimerSimple(doneCh) {
// Create temp array on stack.
locks := make([]string, dm.clnt.dNodeCount)
// Try to acquire the lock.
success := lock(dm.clnt, &locks, dm.Name, id, source, isReadLock)
if success {
dm.m.Lock()
defer dm.m.Unlock()
// If success, copy array to object
if isReadLock {
// Append new array of strings at the end
dm.readersLocks = append(dm.readersLocks, make([]string, dm.clnt.dNodeCount))
// and copy stack array into last spot
copy(dm.readersLocks[len(dm.readersLocks)-1], locks[:])
} else {
copy(dm.writeLocks, locks[:])
}
return true
}
if time.Now().UTC().Sub(start) >= timeout { // Are we past the timeout?
break
}
// Failed to acquire the lock on this attempt, incrementally wait
// for a longer back-off time and try again afterwards.
}
return false
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"lockBlocking",
"(",
"timeout",
"time",
".",
"Duration",
",",
"id",
",",
"source",
"string",
",",
"isReadLock",
"bool",
")",
"(",
"locked",
"bool",
")",
"{",
"doneCh",
",",
"start",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"defer",
"close",
"(",
"doneCh",
")",
"\n\n",
"// Use incremental back-off algorithm for repeated attempts to acquire the lock",
"for",
"range",
"newRetryTimerSimple",
"(",
"doneCh",
")",
"{",
"// Create temp array on stack.",
"locks",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
"\n\n",
"// Try to acquire the lock.",
"success",
":=",
"lock",
"(",
"dm",
".",
"clnt",
",",
"&",
"locks",
",",
"dm",
".",
"Name",
",",
"id",
",",
"source",
",",
"isReadLock",
")",
"\n",
"if",
"success",
"{",
"dm",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dm",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"// If success, copy array to object",
"if",
"isReadLock",
"{",
"// Append new array of strings at the end",
"dm",
".",
"readersLocks",
"=",
"append",
"(",
"dm",
".",
"readersLocks",
",",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
")",
"\n",
"// and copy stack array into last spot",
"copy",
"(",
"dm",
".",
"readersLocks",
"[",
"len",
"(",
"dm",
".",
"readersLocks",
")",
"-",
"1",
"]",
",",
"locks",
"[",
":",
"]",
")",
"\n",
"}",
"else",
"{",
"copy",
"(",
"dm",
".",
"writeLocks",
",",
"locks",
"[",
":",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Sub",
"(",
"start",
")",
">=",
"timeout",
"{",
"// Are we past the timeout?",
"break",
"\n",
"}",
"\n",
"// Failed to acquire the lock on this attempt, incrementally wait",
"// for a longer back-off time and try again afterwards.",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // lockBlocking will try to acquire either a read or a write lock
//
// The function will loop using a built-in timing randomized back-off
// algorithm until either the lock is acquired successfully or more
// time has elapsed than the timeout value. | [
"lockBlocking",
"will",
"try",
"to",
"acquire",
"either",
"a",
"read",
"or",
"a",
"write",
"lock",
"The",
"function",
"will",
"loop",
"using",
"a",
"built",
"-",
"in",
"timing",
"randomized",
"back",
"-",
"off",
"algorithm",
"until",
"either",
"the",
"lock",
"is",
"acquired",
"successfully",
"or",
"more",
"time",
"has",
"elapsed",
"than",
"the",
"timeout",
"value",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L129-L163 |
731 | minio/dsync | drwmutex.go | quorumMet | func quorumMet(locks *[]string, isReadLock bool, quorum, quorumReads int) bool {
count := 0
for _, uid := range *locks {
if isLocked(uid) {
count++
}
}
var metQuorum bool
if isReadLock {
metQuorum = count >= quorumReads
} else {
metQuorum = count >= quorum
}
return metQuorum
} | go | func quorumMet(locks *[]string, isReadLock bool, quorum, quorumReads int) bool {
count := 0
for _, uid := range *locks {
if isLocked(uid) {
count++
}
}
var metQuorum bool
if isReadLock {
metQuorum = count >= quorumReads
} else {
metQuorum = count >= quorum
}
return metQuorum
} | [
"func",
"quorumMet",
"(",
"locks",
"*",
"[",
"]",
"string",
",",
"isReadLock",
"bool",
",",
"quorum",
",",
"quorumReads",
"int",
")",
"bool",
"{",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"uid",
":=",
"range",
"*",
"locks",
"{",
"if",
"isLocked",
"(",
"uid",
")",
"{",
"count",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"metQuorum",
"bool",
"\n",
"if",
"isReadLock",
"{",
"metQuorum",
"=",
"count",
">=",
"quorumReads",
"\n",
"}",
"else",
"{",
"metQuorum",
"=",
"count",
">=",
"quorum",
"\n",
"}",
"\n\n",
"return",
"metQuorum",
"\n",
"}"
] | // quorumMet determines whether we have acquired the required quorum of underlying locks or not | [
"quorumMet",
"determines",
"whether",
"we",
"have",
"acquired",
"the",
"required",
"quorum",
"of",
"underlying",
"locks",
"or",
"not"
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L289-L306 |
732 | minio/dsync | drwmutex.go | releaseAll | func releaseAll(ds *Dsync, locks *[]string, lockName string, isReadLock bool) {
for lock := 0; lock < ds.dNodeCount; lock++ {
if isLocked((*locks)[lock]) {
sendRelease(ds, ds.rpcClnts[lock], lockName, (*locks)[lock], isReadLock)
(*locks)[lock] = ""
}
}
} | go | func releaseAll(ds *Dsync, locks *[]string, lockName string, isReadLock bool) {
for lock := 0; lock < ds.dNodeCount; lock++ {
if isLocked((*locks)[lock]) {
sendRelease(ds, ds.rpcClnts[lock], lockName, (*locks)[lock], isReadLock)
(*locks)[lock] = ""
}
}
} | [
"func",
"releaseAll",
"(",
"ds",
"*",
"Dsync",
",",
"locks",
"*",
"[",
"]",
"string",
",",
"lockName",
"string",
",",
"isReadLock",
"bool",
")",
"{",
"for",
"lock",
":=",
"0",
";",
"lock",
"<",
"ds",
".",
"dNodeCount",
";",
"lock",
"++",
"{",
"if",
"isLocked",
"(",
"(",
"*",
"locks",
")",
"[",
"lock",
"]",
")",
"{",
"sendRelease",
"(",
"ds",
",",
"ds",
".",
"rpcClnts",
"[",
"lock",
"]",
",",
"lockName",
",",
"(",
"*",
"locks",
")",
"[",
"lock",
"]",
",",
"isReadLock",
")",
"\n",
"(",
"*",
"locks",
")",
"[",
"lock",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // releaseAll releases all locks that are marked as locked | [
"releaseAll",
"releases",
"all",
"locks",
"that",
"are",
"marked",
"as",
"locked"
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L309-L316 |
733 | minio/dsync | drwmutex.go | Unlock | func (dm *DRWMutex) Unlock() {
// create temp array on stack
locks := make([]string, dm.clnt.dNodeCount)
{
dm.m.Lock()
defer dm.m.Unlock()
// Check if minimally a single bool is set in the writeLocks array
lockFound := false
for _, uid := range dm.writeLocks {
if isLocked(uid) {
lockFound = true
break
}
}
if !lockFound {
panic("Trying to Unlock() while no Lock() is active")
}
// Copy write locks to stack array
copy(locks, dm.writeLocks[:])
// Clear write locks array
dm.writeLocks = make([]string, dm.clnt.dNodeCount)
}
isReadLock := false
unlock(dm.clnt, locks, dm.Name, isReadLock)
} | go | func (dm *DRWMutex) Unlock() {
// create temp array on stack
locks := make([]string, dm.clnt.dNodeCount)
{
dm.m.Lock()
defer dm.m.Unlock()
// Check if minimally a single bool is set in the writeLocks array
lockFound := false
for _, uid := range dm.writeLocks {
if isLocked(uid) {
lockFound = true
break
}
}
if !lockFound {
panic("Trying to Unlock() while no Lock() is active")
}
// Copy write locks to stack array
copy(locks, dm.writeLocks[:])
// Clear write locks array
dm.writeLocks = make([]string, dm.clnt.dNodeCount)
}
isReadLock := false
unlock(dm.clnt, locks, dm.Name, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"Unlock",
"(",
")",
"{",
"// create temp array on stack",
"locks",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
"\n\n",
"{",
"dm",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dm",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check if minimally a single bool is set in the writeLocks array",
"lockFound",
":=",
"false",
"\n",
"for",
"_",
",",
"uid",
":=",
"range",
"dm",
".",
"writeLocks",
"{",
"if",
"isLocked",
"(",
"uid",
")",
"{",
"lockFound",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"lockFound",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Copy write locks to stack array",
"copy",
"(",
"locks",
",",
"dm",
".",
"writeLocks",
"[",
":",
"]",
")",
"\n",
"// Clear write locks array",
"dm",
".",
"writeLocks",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
"\n",
"}",
"\n\n",
"isReadLock",
":=",
"false",
"\n",
"unlock",
"(",
"dm",
".",
"clnt",
",",
"locks",
",",
"dm",
".",
"Name",
",",
"isReadLock",
")",
"\n",
"}"
] | // Unlock unlocks the write lock.
//
// It is a run-time error if dm is not locked on entry to Unlock. | [
"Unlock",
"unlocks",
"the",
"write",
"lock",
".",
"It",
"is",
"a",
"run",
"-",
"time",
"error",
"if",
"dm",
"is",
"not",
"locked",
"on",
"entry",
"to",
"Unlock",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L321-L350 |
734 | minio/dsync | drwmutex.go | RUnlock | func (dm *DRWMutex) RUnlock() {
// create temp array on stack
locks := make([]string, dm.clnt.dNodeCount)
{
dm.m.Lock()
defer dm.m.Unlock()
if len(dm.readersLocks) == 0 {
panic("Trying to RUnlock() while no RLock() is active")
}
// Copy out first element to release it first (FIFO)
copy(locks, dm.readersLocks[0][:])
// Drop first element from array
dm.readersLocks = dm.readersLocks[1:]
}
isReadLock := true
unlock(dm.clnt, locks, dm.Name, isReadLock)
} | go | func (dm *DRWMutex) RUnlock() {
// create temp array on stack
locks := make([]string, dm.clnt.dNodeCount)
{
dm.m.Lock()
defer dm.m.Unlock()
if len(dm.readersLocks) == 0 {
panic("Trying to RUnlock() while no RLock() is active")
}
// Copy out first element to release it first (FIFO)
copy(locks, dm.readersLocks[0][:])
// Drop first element from array
dm.readersLocks = dm.readersLocks[1:]
}
isReadLock := true
unlock(dm.clnt, locks, dm.Name, isReadLock)
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"RUnlock",
"(",
")",
"{",
"// create temp array on stack",
"locks",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
"\n\n",
"{",
"dm",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dm",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"dm",
".",
"readersLocks",
")",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Copy out first element to release it first (FIFO)",
"copy",
"(",
"locks",
",",
"dm",
".",
"readersLocks",
"[",
"0",
"]",
"[",
":",
"]",
")",
"\n",
"// Drop first element from array",
"dm",
".",
"readersLocks",
"=",
"dm",
".",
"readersLocks",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"isReadLock",
":=",
"true",
"\n",
"unlock",
"(",
"dm",
".",
"clnt",
",",
"locks",
",",
"dm",
".",
"Name",
",",
"isReadLock",
")",
"\n",
"}"
] | // RUnlock releases a read lock held on dm.
//
// It is a run-time error if dm is not locked on entry to RUnlock. | [
"RUnlock",
"releases",
"a",
"read",
"lock",
"held",
"on",
"dm",
".",
"It",
"is",
"a",
"run",
"-",
"time",
"error",
"if",
"dm",
"is",
"not",
"locked",
"on",
"entry",
"to",
"RUnlock",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L355-L374 |
735 | minio/dsync | drwmutex.go | ForceUnlock | func (dm *DRWMutex) ForceUnlock() {
{
dm.m.Lock()
defer dm.m.Unlock()
// Clear write locks array
dm.writeLocks = make([]string, dm.clnt.dNodeCount)
// Clear read locks array
dm.readersLocks = nil
}
for _, c := range dm.clnt.rpcClnts {
// broadcast lock release to all nodes that granted the lock
sendRelease(dm.clnt, c, dm.Name, "", false)
}
} | go | func (dm *DRWMutex) ForceUnlock() {
{
dm.m.Lock()
defer dm.m.Unlock()
// Clear write locks array
dm.writeLocks = make([]string, dm.clnt.dNodeCount)
// Clear read locks array
dm.readersLocks = nil
}
for _, c := range dm.clnt.rpcClnts {
// broadcast lock release to all nodes that granted the lock
sendRelease(dm.clnt, c, dm.Name, "", false)
}
} | [
"func",
"(",
"dm",
"*",
"DRWMutex",
")",
"ForceUnlock",
"(",
")",
"{",
"{",
"dm",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dm",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"// Clear write locks array",
"dm",
".",
"writeLocks",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"dm",
".",
"clnt",
".",
"dNodeCount",
")",
"\n",
"// Clear read locks array",
"dm",
".",
"readersLocks",
"=",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"dm",
".",
"clnt",
".",
"rpcClnts",
"{",
"// broadcast lock release to all nodes that granted the lock",
"sendRelease",
"(",
"dm",
".",
"clnt",
",",
"c",
",",
"dm",
".",
"Name",
",",
"\"",
"\"",
",",
"false",
")",
"\n",
"}",
"\n",
"}"
] | // ForceUnlock will forcefully clear a write or read lock. | [
"ForceUnlock",
"will",
"forcefully",
"clear",
"a",
"write",
"or",
"read",
"lock",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L391-L406 |
736 | minio/dsync | drwmutex.go | sendRelease | func sendRelease(ds *Dsync, c NetLocker, name, uid string, isReadLock bool) {
args := LockArgs{
UID: uid,
Resource: name,
ServerAddr: ds.rpcClnts[ds.ownNode].ServerAddr(),
ServiceEndpoint: ds.rpcClnts[ds.ownNode].ServiceEndpoint(),
}
if len(uid) == 0 {
if _, err := c.ForceUnlock(args); err != nil {
log("Unable to call ForceUnlock", err)
}
} else if isReadLock {
if _, err := c.RUnlock(args); err != nil {
log("Unable to call RUnlock", err)
}
} else {
if _, err := c.Unlock(args); err != nil {
log("Unable to call Unlock", err)
}
}
} | go | func sendRelease(ds *Dsync, c NetLocker, name, uid string, isReadLock bool) {
args := LockArgs{
UID: uid,
Resource: name,
ServerAddr: ds.rpcClnts[ds.ownNode].ServerAddr(),
ServiceEndpoint: ds.rpcClnts[ds.ownNode].ServiceEndpoint(),
}
if len(uid) == 0 {
if _, err := c.ForceUnlock(args); err != nil {
log("Unable to call ForceUnlock", err)
}
} else if isReadLock {
if _, err := c.RUnlock(args); err != nil {
log("Unable to call RUnlock", err)
}
} else {
if _, err := c.Unlock(args); err != nil {
log("Unable to call Unlock", err)
}
}
} | [
"func",
"sendRelease",
"(",
"ds",
"*",
"Dsync",
",",
"c",
"NetLocker",
",",
"name",
",",
"uid",
"string",
",",
"isReadLock",
"bool",
")",
"{",
"args",
":=",
"LockArgs",
"{",
"UID",
":",
"uid",
",",
"Resource",
":",
"name",
",",
"ServerAddr",
":",
"ds",
".",
"rpcClnts",
"[",
"ds",
".",
"ownNode",
"]",
".",
"ServerAddr",
"(",
")",
",",
"ServiceEndpoint",
":",
"ds",
".",
"rpcClnts",
"[",
"ds",
".",
"ownNode",
"]",
".",
"ServiceEndpoint",
"(",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"uid",
")",
"==",
"0",
"{",
"if",
"_",
",",
"err",
":=",
"c",
".",
"ForceUnlock",
"(",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isReadLock",
"{",
"if",
"_",
",",
"err",
":=",
"c",
".",
"RUnlock",
"(",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"_",
",",
"err",
":=",
"c",
".",
"Unlock",
"(",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // sendRelease sends a release message to a node that previously granted a lock | [
"sendRelease",
"sends",
"a",
"release",
"message",
"to",
"a",
"node",
"that",
"previously",
"granted",
"a",
"lock"
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/drwmutex.go#L409-L429 |
737 | minio/dsync | dsync.go | New | func New(rpcClnts []NetLocker, rpcOwnNode int) (*Dsync, error) {
if len(rpcClnts) < 2 {
return nil, errors.New("Dsync is not designed for less than 2 nodes")
} else if len(rpcClnts) > 32 {
return nil, errors.New("Dsync is not designed for more than 32 nodes")
}
if rpcOwnNode > len(rpcClnts) {
return nil, errors.New("Index for own node is too large")
}
ds := &Dsync{}
ds.dNodeCount = len(rpcClnts)
// With odd number of nodes, write and read quorum is basically the same
ds.dquorum = int(ds.dNodeCount/2) + 1
ds.dquorumReads = int(math.Ceil(float64(ds.dNodeCount) / 2.0))
ds.ownNode = rpcOwnNode
// Initialize node name and rpc path for each NetLocker object.
ds.rpcClnts = make([]NetLocker, ds.dNodeCount)
copy(ds.rpcClnts, rpcClnts)
return ds, nil
} | go | func New(rpcClnts []NetLocker, rpcOwnNode int) (*Dsync, error) {
if len(rpcClnts) < 2 {
return nil, errors.New("Dsync is not designed for less than 2 nodes")
} else if len(rpcClnts) > 32 {
return nil, errors.New("Dsync is not designed for more than 32 nodes")
}
if rpcOwnNode > len(rpcClnts) {
return nil, errors.New("Index for own node is too large")
}
ds := &Dsync{}
ds.dNodeCount = len(rpcClnts)
// With odd number of nodes, write and read quorum is basically the same
ds.dquorum = int(ds.dNodeCount/2) + 1
ds.dquorumReads = int(math.Ceil(float64(ds.dNodeCount) / 2.0))
ds.ownNode = rpcOwnNode
// Initialize node name and rpc path for each NetLocker object.
ds.rpcClnts = make([]NetLocker, ds.dNodeCount)
copy(ds.rpcClnts, rpcClnts)
return ds, nil
} | [
"func",
"New",
"(",
"rpcClnts",
"[",
"]",
"NetLocker",
",",
"rpcOwnNode",
"int",
")",
"(",
"*",
"Dsync",
",",
"error",
")",
"{",
"if",
"len",
"(",
"rpcClnts",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"rpcClnts",
")",
">",
"32",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"rpcOwnNode",
">",
"len",
"(",
"rpcClnts",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ds",
":=",
"&",
"Dsync",
"{",
"}",
"\n",
"ds",
".",
"dNodeCount",
"=",
"len",
"(",
"rpcClnts",
")",
"\n\n",
"// With odd number of nodes, write and read quorum is basically the same",
"ds",
".",
"dquorum",
"=",
"int",
"(",
"ds",
".",
"dNodeCount",
"/",
"2",
")",
"+",
"1",
"\n",
"ds",
".",
"dquorumReads",
"=",
"int",
"(",
"math",
".",
"Ceil",
"(",
"float64",
"(",
"ds",
".",
"dNodeCount",
")",
"/",
"2.0",
")",
")",
"\n",
"ds",
".",
"ownNode",
"=",
"rpcOwnNode",
"\n\n",
"// Initialize node name and rpc path for each NetLocker object.",
"ds",
".",
"rpcClnts",
"=",
"make",
"(",
"[",
"]",
"NetLocker",
",",
"ds",
".",
"dNodeCount",
")",
"\n",
"copy",
"(",
"ds",
".",
"rpcClnts",
",",
"rpcClnts",
")",
"\n\n",
"return",
"ds",
",",
"nil",
"\n",
"}"
] | // New - initializes a new dsync object with input rpcClnts. | [
"New",
"-",
"initializes",
"a",
"new",
"dsync",
"object",
"with",
"input",
"rpcClnts",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/dsync.go#L44-L68 |
738 | minio/dsync | chaos/net-rpc-client.go | newClient | func newClient(addr, endpoint string) *ReconnectRPCClient {
return &ReconnectRPCClient{
addr: addr,
endpoint: endpoint,
}
} | go | func newClient(addr, endpoint string) *ReconnectRPCClient {
return &ReconnectRPCClient{
addr: addr,
endpoint: endpoint,
}
} | [
"func",
"newClient",
"(",
"addr",
",",
"endpoint",
"string",
")",
"*",
"ReconnectRPCClient",
"{",
"return",
"&",
"ReconnectRPCClient",
"{",
"addr",
":",
"addr",
",",
"endpoint",
":",
"endpoint",
",",
"}",
"\n",
"}"
] | // newClient constructs a ReconnectRPCClient object with addr and endpoint initialized.
// It _doesn't_ connect to the remote endpoint. See Call method to see when the
// connect happens. | [
"newClient",
"constructs",
"a",
"ReconnectRPCClient",
"object",
"with",
"addr",
"and",
"endpoint",
"initialized",
".",
"It",
"_doesn",
"t_",
"connect",
"to",
"the",
"remote",
"endpoint",
".",
"See",
"Call",
"method",
"to",
"see",
"when",
"the",
"connect",
"happens",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/chaos/net-rpc-client.go#L37-L42 |
739 | minio/dsync | chaos/lock-rpc-server.go | RLock | func (l *lockServer) RLock(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
lrInfo := lockRequesterInfo{
writer: false,
serverAddr: args.ServerAddr,
rpcPath: args.ServiceEndpoint,
uid: args.UID,
timestamp: time.Now().UTC(),
timeLastCheck: time.Now().UTC(),
}
if lri, ok := l.lockMap[args.Resource]; ok {
if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock
l.lockMap[args.Resource] = append(l.lockMap[args.Resource], lrInfo)
}
} else { // No locks held on the given name, so claim (first) read lock
l.lockMap[args.Resource] = []lockRequesterInfo{lrInfo}
*reply = true
}
return nil
} | go | func (l *lockServer) RLock(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
lrInfo := lockRequesterInfo{
writer: false,
serverAddr: args.ServerAddr,
rpcPath: args.ServiceEndpoint,
uid: args.UID,
timestamp: time.Now().UTC(),
timeLastCheck: time.Now().UTC(),
}
if lri, ok := l.lockMap[args.Resource]; ok {
if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock
l.lockMap[args.Resource] = append(l.lockMap[args.Resource], lrInfo)
}
} else { // No locks held on the given name, so claim (first) read lock
l.lockMap[args.Resource] = []lockRequesterInfo{lrInfo}
*reply = true
}
return nil
} | [
"func",
"(",
"l",
"*",
"lockServer",
")",
"RLock",
"(",
"args",
"*",
"dsync",
".",
"LockArgs",
",",
"reply",
"*",
"bool",
")",
"error",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"lrInfo",
":=",
"lockRequesterInfo",
"{",
"writer",
":",
"false",
",",
"serverAddr",
":",
"args",
".",
"ServerAddr",
",",
"rpcPath",
":",
"args",
".",
"ServiceEndpoint",
",",
"uid",
":",
"args",
".",
"UID",
",",
"timestamp",
":",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
",",
"timeLastCheck",
":",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
",",
"}",
"\n",
"if",
"lri",
",",
"ok",
":=",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
";",
"ok",
"{",
"if",
"*",
"reply",
"=",
"!",
"isWriteLock",
"(",
"lri",
")",
";",
"*",
"reply",
"{",
"// Unless there is a write lock",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
"=",
"append",
"(",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
",",
"lrInfo",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// No locks held on the given name, so claim (first) read lock",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
"=",
"[",
"]",
"lockRequesterInfo",
"{",
"lrInfo",
"}",
"\n",
"*",
"reply",
"=",
"true",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RLock - rpc handler for read lock operation. | [
"RLock",
"-",
"rpc",
"handler",
"for",
"read",
"lock",
"operation",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/chaos/lock-rpc-server.go#L86-L106 |
740 | minio/dsync | chaos/lock-rpc-server.go | ForceUnlock | func (l *lockServer) ForceUnlock(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if len(args.UID) != 0 {
return fmt.Errorf("ForceUnlock called with non-empty UID: %s", args.UID)
}
if _, ok := l.lockMap[args.Resource]; ok { // Only clear lock when set
delete(l.lockMap, args.Resource) // Remove the lock (irrespective of write or read lock)
}
*reply = true
return nil
} | go | func (l *lockServer) ForceUnlock(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if len(args.UID) != 0 {
return fmt.Errorf("ForceUnlock called with non-empty UID: %s", args.UID)
}
if _, ok := l.lockMap[args.Resource]; ok { // Only clear lock when set
delete(l.lockMap, args.Resource) // Remove the lock (irrespective of write or read lock)
}
*reply = true
return nil
} | [
"func",
"(",
"l",
"*",
"lockServer",
")",
"ForceUnlock",
"(",
"args",
"*",
"dsync",
".",
"LockArgs",
",",
"reply",
"*",
"bool",
")",
"error",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"args",
".",
"UID",
")",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"args",
".",
"UID",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
";",
"ok",
"{",
"// Only clear lock when set",
"delete",
"(",
"l",
".",
"lockMap",
",",
"args",
".",
"Resource",
")",
"// Remove the lock (irrespective of write or read lock)",
"\n",
"}",
"\n",
"*",
"reply",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // ForceUnlock - rpc handler for force unlock operation. | [
"ForceUnlock",
"-",
"rpc",
"handler",
"for",
"force",
"unlock",
"operation",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/chaos/lock-rpc-server.go#L126-L137 |
741 | minio/dsync | chaos/lock-rpc-server.go | Expired | func (l *lockServer) Expired(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if lri, ok := l.lockMap[args.Resource]; ok {
// Check whether uid is still active for this name
for _, entry := range lri {
if entry.uid == args.UID {
*reply = false // When uid found, lock is still active so return not expired
return nil
}
}
}
// When we get here, lock is no longer active due to either args.Resource being absent from map
// or uid not found for given args.Resource
*reply = true
return nil
} | go | func (l *lockServer) Expired(args *dsync.LockArgs, reply *bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if lri, ok := l.lockMap[args.Resource]; ok {
// Check whether uid is still active for this name
for _, entry := range lri {
if entry.uid == args.UID {
*reply = false // When uid found, lock is still active so return not expired
return nil
}
}
}
// When we get here, lock is no longer active due to either args.Resource being absent from map
// or uid not found for given args.Resource
*reply = true
return nil
} | [
"func",
"(",
"l",
"*",
"lockServer",
")",
"Expired",
"(",
"args",
"*",
"dsync",
".",
"LockArgs",
",",
"reply",
"*",
"bool",
")",
"error",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"lri",
",",
"ok",
":=",
"l",
".",
"lockMap",
"[",
"args",
".",
"Resource",
"]",
";",
"ok",
"{",
"// Check whether uid is still active for this name",
"for",
"_",
",",
"entry",
":=",
"range",
"lri",
"{",
"if",
"entry",
".",
"uid",
"==",
"args",
".",
"UID",
"{",
"*",
"reply",
"=",
"false",
"// When uid found, lock is still active so return not expired",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// When we get here, lock is no longer active due to either args.Resource being absent from map",
"// or uid not found for given args.Resource",
"*",
"reply",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // Expired - rpc handler for expired lock status. | [
"Expired",
"-",
"rpc",
"handler",
"for",
"expired",
"lock",
"status",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/chaos/lock-rpc-server.go#L140-L156 |
742 | minio/dsync | retry.go | newRetryTimer | func newRetryTimer(unit time.Duration, cap time.Duration, doneCh chan struct{}) <-chan int {
return newRetryTimerWithJitter(unit, cap, MaxJitter, doneCh)
} | go | func newRetryTimer(unit time.Duration, cap time.Duration, doneCh chan struct{}) <-chan int {
return newRetryTimerWithJitter(unit, cap, MaxJitter, doneCh)
} | [
"func",
"newRetryTimer",
"(",
"unit",
"time",
".",
"Duration",
",",
"cap",
"time",
".",
"Duration",
",",
"doneCh",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"int",
"{",
"return",
"newRetryTimerWithJitter",
"(",
"unit",
",",
"cap",
",",
"MaxJitter",
",",
"doneCh",
")",
"\n",
"}"
] | // newRetryTimer creates a timer with exponentially increasing delays
// until the maximum retry attempts are reached. - this function provides
// resulting retry values to be of maximum jitter. | [
"newRetryTimer",
"creates",
"a",
"timer",
"with",
"exponentially",
"increasing",
"delays",
"until",
"the",
"maximum",
"retry",
"attempts",
"are",
"reached",
".",
"-",
"this",
"function",
"provides",
"resulting",
"retry",
"values",
"to",
"be",
"of",
"maximum",
"jitter",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/retry.go#L133-L135 |
743 | minio/dsync | examples/auth-locker/auth-lock-client.go | dial | func (rpcClient *ReconnectRPCClient) dial() (*rpc.Client, error) {
rpcClient.mutex.Lock()
defer rpcClient.mutex.Unlock()
// Nothing to do as we already have valid connection.
if rpcClient.netRPCClient != nil {
return rpcClient.netRPCClient, nil
}
// Dial with 3 seconds timeout.
conn, err := net.DialTimeout("tcp", rpcClient.serverAddr, defaultDialTimeout)
if err != nil {
// Print RPC connection errors that are worthy to display in log
switch err.(type) {
case x509.HostnameError:
log.Println("Unable to establish secure connection to", rpcClient.serverAddr)
log.Println("error:", err)
}
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: err,
}
}
io.WriteString(conn, "CONNECT "+rpcClient.serviceEndpoint+" HTTP/1.0\n\n")
// Require successful HTTP response before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
if err == nil && resp.Status == "200 Connected to Go RPC" {
netRPCClient := rpc.NewClient(conn)
if netRPCClient == nil {
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: fmt.Errorf("Unable to initialize new rpc.Client"),
}
}
rpcClient.netRPCClient = netRPCClient
return netRPCClient, nil
}
if err == nil {
err = errors.New("unexpected HTTP response: " + resp.Status)
}
conn.Close()
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: err,
}
} | go | func (rpcClient *ReconnectRPCClient) dial() (*rpc.Client, error) {
rpcClient.mutex.Lock()
defer rpcClient.mutex.Unlock()
// Nothing to do as we already have valid connection.
if rpcClient.netRPCClient != nil {
return rpcClient.netRPCClient, nil
}
// Dial with 3 seconds timeout.
conn, err := net.DialTimeout("tcp", rpcClient.serverAddr, defaultDialTimeout)
if err != nil {
// Print RPC connection errors that are worthy to display in log
switch err.(type) {
case x509.HostnameError:
log.Println("Unable to establish secure connection to", rpcClient.serverAddr)
log.Println("error:", err)
}
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: err,
}
}
io.WriteString(conn, "CONNECT "+rpcClient.serviceEndpoint+" HTTP/1.0\n\n")
// Require successful HTTP response before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
if err == nil && resp.Status == "200 Connected to Go RPC" {
netRPCClient := rpc.NewClient(conn)
if netRPCClient == nil {
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: fmt.Errorf("Unable to initialize new rpc.Client"),
}
}
rpcClient.netRPCClient = netRPCClient
return netRPCClient, nil
}
if err == nil {
err = errors.New("unexpected HTTP response: " + resp.Status)
}
conn.Close()
return nil, &net.OpError{
Op: "dial-http",
Net: rpcClient.serverAddr + " " + rpcClient.serviceEndpoint,
Addr: nil,
Err: err,
}
} | [
"func",
"(",
"rpcClient",
"*",
"ReconnectRPCClient",
")",
"dial",
"(",
")",
"(",
"*",
"rpc",
".",
"Client",
",",
"error",
")",
"{",
"rpcClient",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rpcClient",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"// Nothing to do as we already have valid connection.",
"if",
"rpcClient",
".",
"netRPCClient",
"!=",
"nil",
"{",
"return",
"rpcClient",
".",
"netRPCClient",
",",
"nil",
"\n",
"}",
"\n\n",
"// Dial with 3 seconds timeout.",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"\"",
"\"",
",",
"rpcClient",
".",
"serverAddr",
",",
"defaultDialTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Print RPC connection errors that are worthy to display in log",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"x509",
".",
"HostnameError",
":",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"rpcClient",
".",
"serverAddr",
")",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"&",
"net",
".",
"OpError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Net",
":",
"rpcClient",
".",
"serverAddr",
"+",
"\"",
"\"",
"+",
"rpcClient",
".",
"serviceEndpoint",
",",
"Addr",
":",
"nil",
",",
"Err",
":",
"err",
",",
"}",
"\n",
"}",
"\n\n",
"io",
".",
"WriteString",
"(",
"conn",
",",
"\"",
"\"",
"+",
"rpcClient",
".",
"serviceEndpoint",
"+",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"// Require successful HTTP response before switching to RPC protocol.",
"resp",
",",
"err",
":=",
"http",
".",
"ReadResponse",
"(",
"bufio",
".",
"NewReader",
"(",
"conn",
")",
",",
"&",
"http",
".",
"Request",
"{",
"Method",
":",
"\"",
"\"",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"resp",
".",
"Status",
"==",
"\"",
"\"",
"{",
"netRPCClient",
":=",
"rpc",
".",
"NewClient",
"(",
"conn",
")",
"\n",
"if",
"netRPCClient",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"net",
".",
"OpError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Net",
":",
"rpcClient",
".",
"serverAddr",
"+",
"\"",
"\"",
"+",
"rpcClient",
".",
"serviceEndpoint",
",",
"Addr",
":",
"nil",
",",
"Err",
":",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"}",
"\n\n",
"rpcClient",
".",
"netRPCClient",
"=",
"netRPCClient",
"\n\n",
"return",
"netRPCClient",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"&",
"net",
".",
"OpError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Net",
":",
"rpcClient",
".",
"serverAddr",
"+",
"\"",
"\"",
"+",
"rpcClient",
".",
"serviceEndpoint",
",",
"Addr",
":",
"nil",
",",
"Err",
":",
"err",
",",
"}",
"\n",
"}"
] | // dial tries to establish a connection to serverAddr in a safe manner.
// If there is a valid rpc.Cliemt, it returns that else creates a new one. | [
"dial",
"tries",
"to",
"establish",
"a",
"connection",
"to",
"serverAddr",
"in",
"a",
"safe",
"manner",
".",
"If",
"there",
"is",
"a",
"valid",
"rpc",
".",
"Cliemt",
"it",
"returns",
"that",
"else",
"creates",
"a",
"new",
"one",
"."
] | fb604afd87b2a095432c17af2dda742960ef111e | https://github.com/minio/dsync/blob/fb604afd87b2a095432c17af2dda742960ef111e/examples/auth-locker/auth-lock-client.go#L58-L115 |
744 | stripe/safesql | safesql.go | FuncHasQuery | func FuncHasQuery(sqlPackages sqlPackage, s *types.Signature) (offset int, ok bool) {
params := s.Params()
for i := 0; i < params.Len(); i++ {
v := params.At(i)
for _, paramName := range sqlPackages.paramNames {
if v.Name() == paramName {
return i, true
}
}
}
return 0, false
} | go | func FuncHasQuery(sqlPackages sqlPackage, s *types.Signature) (offset int, ok bool) {
params := s.Params()
for i := 0; i < params.Len(); i++ {
v := params.At(i)
for _, paramName := range sqlPackages.paramNames {
if v.Name() == paramName {
return i, true
}
}
}
return 0, false
} | [
"func",
"FuncHasQuery",
"(",
"sqlPackages",
"sqlPackage",
",",
"s",
"*",
"types",
".",
"Signature",
")",
"(",
"offset",
"int",
",",
"ok",
"bool",
")",
"{",
"params",
":=",
"s",
".",
"Params",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"params",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"v",
":=",
"params",
".",
"At",
"(",
"i",
")",
"\n",
"for",
"_",
",",
"paramName",
":=",
"range",
"sqlPackages",
".",
"paramNames",
"{",
"if",
"v",
".",
"Name",
"(",
")",
"==",
"paramName",
"{",
"return",
"i",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"0",
",",
"false",
"\n",
"}"
] | // FuncHasQuery returns the offset of the string parameter named "query", or
// none if no such parameter exists. | [
"FuncHasQuery",
"returns",
"the",
"offset",
"of",
"the",
"string",
"parameter",
"named",
"query",
"or",
"none",
"if",
"no",
"such",
"parameter",
"exists",
"."
] | cddf355596fe2dbae05b4b5f845b4a6e2fb4e818 | https://github.com/stripe/safesql/blob/cddf355596fe2dbae05b4b5f845b4a6e2fb4e818/safesql.go#L192-L203 |
745 | stripe/safesql | safesql.go | FindMains | func FindMains(p *loader.Program, s *ssa.Program) []*ssa.Package {
ips := p.InitialPackages()
mains := make([]*ssa.Package, 0, len(ips))
for _, info := range ips {
ssaPkg := s.Package(info.Pkg)
if ssaPkg.Func("main") != nil {
mains = append(mains, ssaPkg)
}
}
return mains
} | go | func FindMains(p *loader.Program, s *ssa.Program) []*ssa.Package {
ips := p.InitialPackages()
mains := make([]*ssa.Package, 0, len(ips))
for _, info := range ips {
ssaPkg := s.Package(info.Pkg)
if ssaPkg.Func("main") != nil {
mains = append(mains, ssaPkg)
}
}
return mains
} | [
"func",
"FindMains",
"(",
"p",
"*",
"loader",
".",
"Program",
",",
"s",
"*",
"ssa",
".",
"Program",
")",
"[",
"]",
"*",
"ssa",
".",
"Package",
"{",
"ips",
":=",
"p",
".",
"InitialPackages",
"(",
")",
"\n",
"mains",
":=",
"make",
"(",
"[",
"]",
"*",
"ssa",
".",
"Package",
",",
"0",
",",
"len",
"(",
"ips",
")",
")",
"\n",
"for",
"_",
",",
"info",
":=",
"range",
"ips",
"{",
"ssaPkg",
":=",
"s",
".",
"Package",
"(",
"info",
".",
"Pkg",
")",
"\n",
"if",
"ssaPkg",
".",
"Func",
"(",
"\"",
"\"",
")",
"!=",
"nil",
"{",
"mains",
"=",
"append",
"(",
"mains",
",",
"ssaPkg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"mains",
"\n",
"}"
] | // FindMains returns the set of all packages loaded into the given
// loader.Program which contain main functions | [
"FindMains",
"returns",
"the",
"set",
"of",
"all",
"packages",
"loaded",
"into",
"the",
"given",
"loader",
".",
"Program",
"which",
"contain",
"main",
"functions"
] | cddf355596fe2dbae05b4b5f845b4a6e2fb4e818 | https://github.com/stripe/safesql/blob/cddf355596fe2dbae05b4b5f845b4a6e2fb4e818/safesql.go#L207-L217 |
746 | stripe/safesql | safesql.go | FindNonConstCalls | func FindNonConstCalls(cg *callgraph.Graph, qms []*QueryMethod) []ssa.CallInstruction {
cg.DeleteSyntheticNodes()
// package database/sql has a couple helper functions which are thin
// wrappers around other sensitive functions. Instead of handling the
// general case by tracing down callsites of wrapper functions
// recursively, let's just whitelist the functions we're already
// tracking, since it happens to be good enough for our use case.
okFuncs := make(map[*ssa.Function]struct{}, len(qms))
for _, m := range qms {
okFuncs[m.SSA] = struct{}{}
}
bad := make([]ssa.CallInstruction, 0)
for _, m := range qms {
node := cg.CreateNode(m.SSA)
for _, edge := range node.In {
if _, ok := okFuncs[edge.Site.Parent()]; ok {
continue
}
isInternalSQLPkg := false
for _, pkg := range sqlPackages {
if pkg.packageName == edge.Caller.Func.Pkg.Pkg.Path() {
isInternalSQLPkg = true
break
}
}
if isInternalSQLPkg {
continue
}
cc := edge.Site.Common()
args := cc.Args
// The first parameter is occasionally the receiver.
if len(args) == m.ArgCount+1 {
args = args[1:]
} else if len(args) != m.ArgCount {
panic("arg count mismatch")
}
v := args[m.Param]
if _, ok := v.(*ssa.Const); !ok {
if inter, ok := v.(*ssa.MakeInterface); ok && types.IsInterface(v.(*ssa.MakeInterface).Type()) {
if inter.X.Referrers() == nil || inter.X.Type() != types.Typ[types.String] {
continue
}
}
bad = append(bad, edge.Site)
}
}
}
return bad
} | go | func FindNonConstCalls(cg *callgraph.Graph, qms []*QueryMethod) []ssa.CallInstruction {
cg.DeleteSyntheticNodes()
// package database/sql has a couple helper functions which are thin
// wrappers around other sensitive functions. Instead of handling the
// general case by tracing down callsites of wrapper functions
// recursively, let's just whitelist the functions we're already
// tracking, since it happens to be good enough for our use case.
okFuncs := make(map[*ssa.Function]struct{}, len(qms))
for _, m := range qms {
okFuncs[m.SSA] = struct{}{}
}
bad := make([]ssa.CallInstruction, 0)
for _, m := range qms {
node := cg.CreateNode(m.SSA)
for _, edge := range node.In {
if _, ok := okFuncs[edge.Site.Parent()]; ok {
continue
}
isInternalSQLPkg := false
for _, pkg := range sqlPackages {
if pkg.packageName == edge.Caller.Func.Pkg.Pkg.Path() {
isInternalSQLPkg = true
break
}
}
if isInternalSQLPkg {
continue
}
cc := edge.Site.Common()
args := cc.Args
// The first parameter is occasionally the receiver.
if len(args) == m.ArgCount+1 {
args = args[1:]
} else if len(args) != m.ArgCount {
panic("arg count mismatch")
}
v := args[m.Param]
if _, ok := v.(*ssa.Const); !ok {
if inter, ok := v.(*ssa.MakeInterface); ok && types.IsInterface(v.(*ssa.MakeInterface).Type()) {
if inter.X.Referrers() == nil || inter.X.Type() != types.Typ[types.String] {
continue
}
}
bad = append(bad, edge.Site)
}
}
}
return bad
} | [
"func",
"FindNonConstCalls",
"(",
"cg",
"*",
"callgraph",
".",
"Graph",
",",
"qms",
"[",
"]",
"*",
"QueryMethod",
")",
"[",
"]",
"ssa",
".",
"CallInstruction",
"{",
"cg",
".",
"DeleteSyntheticNodes",
"(",
")",
"\n\n",
"// package database/sql has a couple helper functions which are thin",
"// wrappers around other sensitive functions. Instead of handling the",
"// general case by tracing down callsites of wrapper functions",
"// recursively, let's just whitelist the functions we're already",
"// tracking, since it happens to be good enough for our use case.",
"okFuncs",
":=",
"make",
"(",
"map",
"[",
"*",
"ssa",
".",
"Function",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"qms",
")",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"qms",
"{",
"okFuncs",
"[",
"m",
".",
"SSA",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n\n",
"bad",
":=",
"make",
"(",
"[",
"]",
"ssa",
".",
"CallInstruction",
",",
"0",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"qms",
"{",
"node",
":=",
"cg",
".",
"CreateNode",
"(",
"m",
".",
"SSA",
")",
"\n",
"for",
"_",
",",
"edge",
":=",
"range",
"node",
".",
"In",
"{",
"if",
"_",
",",
"ok",
":=",
"okFuncs",
"[",
"edge",
".",
"Site",
".",
"Parent",
"(",
")",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"isInternalSQLPkg",
":=",
"false",
"\n",
"for",
"_",
",",
"pkg",
":=",
"range",
"sqlPackages",
"{",
"if",
"pkg",
".",
"packageName",
"==",
"edge",
".",
"Caller",
".",
"Func",
".",
"Pkg",
".",
"Pkg",
".",
"Path",
"(",
")",
"{",
"isInternalSQLPkg",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"isInternalSQLPkg",
"{",
"continue",
"\n",
"}",
"\n\n",
"cc",
":=",
"edge",
".",
"Site",
".",
"Common",
"(",
")",
"\n",
"args",
":=",
"cc",
".",
"Args",
"\n",
"// The first parameter is occasionally the receiver.",
"if",
"len",
"(",
"args",
")",
"==",
"m",
".",
"ArgCount",
"+",
"1",
"{",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"\n",
"}",
"else",
"if",
"len",
"(",
"args",
")",
"!=",
"m",
".",
"ArgCount",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"v",
":=",
"args",
"[",
"m",
".",
"Param",
"]",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"ssa",
".",
"Const",
")",
";",
"!",
"ok",
"{",
"if",
"inter",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"ssa",
".",
"MakeInterface",
")",
";",
"ok",
"&&",
"types",
".",
"IsInterface",
"(",
"v",
".",
"(",
"*",
"ssa",
".",
"MakeInterface",
")",
".",
"Type",
"(",
")",
")",
"{",
"if",
"inter",
".",
"X",
".",
"Referrers",
"(",
")",
"==",
"nil",
"||",
"inter",
".",
"X",
".",
"Type",
"(",
")",
"!=",
"types",
".",
"Typ",
"[",
"types",
".",
"String",
"]",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"bad",
"=",
"append",
"(",
"bad",
",",
"edge",
".",
"Site",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"bad",
"\n",
"}"
] | // FindNonConstCalls returns the set of callsites of the given set of methods
// for which the "query" parameter is not a compile-time constant. | [
"FindNonConstCalls",
"returns",
"the",
"set",
"of",
"callsites",
"of",
"the",
"given",
"set",
"of",
"methods",
"for",
"which",
"the",
"query",
"parameter",
"is",
"not",
"a",
"compile",
"-",
"time",
"constant",
"."
] | cddf355596fe2dbae05b4b5f845b4a6e2fb4e818 | https://github.com/stripe/safesql/blob/cddf355596fe2dbae05b4b5f845b4a6e2fb4e818/safesql.go#L231-L286 |
747 | stripe/safesql | safesql.go | FindPackage | func FindPackage(ctxt *build.Context, path, dir string, mode build.ImportMode) (*build.Package, error) {
if !useVendor {
return ctxt.Import(path, dir, mode)
}
// First, walk up the filesystem from dir looking for vendor directories
var vendorDir string
for tmp := dir; vendorDir == "" && tmp != "/"; tmp = filepath.Dir(tmp) {
dname := filepath.Join(tmp, "vendor", filepath.FromSlash(path))
fd, err := os.Open(dname)
if err != nil {
continue
}
// Directories are only valid if they contain at least one file
// with suffix ".go" (this also ensures that the file descriptor
// we have is in fact a directory)
names, err := fd.Readdirnames(-1)
if err != nil {
continue
}
for _, name := range names {
if strings.HasSuffix(name, ".go") {
vendorDir = filepath.ToSlash(dname)
break
}
}
}
if vendorDir != "" {
pkg, err := ctxt.ImportDir(vendorDir, mode)
if err != nil {
return nil, err
}
// Go tries to derive a valid import path for the package, but
// it's wrong (it includes "/vendor/"). Overwrite it here.
pkg.ImportPath = path
return pkg, nil
}
return ctxt.Import(path, dir, mode)
} | go | func FindPackage(ctxt *build.Context, path, dir string, mode build.ImportMode) (*build.Package, error) {
if !useVendor {
return ctxt.Import(path, dir, mode)
}
// First, walk up the filesystem from dir looking for vendor directories
var vendorDir string
for tmp := dir; vendorDir == "" && tmp != "/"; tmp = filepath.Dir(tmp) {
dname := filepath.Join(tmp, "vendor", filepath.FromSlash(path))
fd, err := os.Open(dname)
if err != nil {
continue
}
// Directories are only valid if they contain at least one file
// with suffix ".go" (this also ensures that the file descriptor
// we have is in fact a directory)
names, err := fd.Readdirnames(-1)
if err != nil {
continue
}
for _, name := range names {
if strings.HasSuffix(name, ".go") {
vendorDir = filepath.ToSlash(dname)
break
}
}
}
if vendorDir != "" {
pkg, err := ctxt.ImportDir(vendorDir, mode)
if err != nil {
return nil, err
}
// Go tries to derive a valid import path for the package, but
// it's wrong (it includes "/vendor/"). Overwrite it here.
pkg.ImportPath = path
return pkg, nil
}
return ctxt.Import(path, dir, mode)
} | [
"func",
"FindPackage",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"path",
",",
"dir",
"string",
",",
"mode",
"build",
".",
"ImportMode",
")",
"(",
"*",
"build",
".",
"Package",
",",
"error",
")",
"{",
"if",
"!",
"useVendor",
"{",
"return",
"ctxt",
".",
"Import",
"(",
"path",
",",
"dir",
",",
"mode",
")",
"\n",
"}",
"\n\n",
"// First, walk up the filesystem from dir looking for vendor directories",
"var",
"vendorDir",
"string",
"\n",
"for",
"tmp",
":=",
"dir",
";",
"vendorDir",
"==",
"\"",
"\"",
"&&",
"tmp",
"!=",
"\"",
"\"",
";",
"tmp",
"=",
"filepath",
".",
"Dir",
"(",
"tmp",
")",
"{",
"dname",
":=",
"filepath",
".",
"Join",
"(",
"tmp",
",",
"\"",
"\"",
",",
"filepath",
".",
"FromSlash",
"(",
"path",
")",
")",
"\n",
"fd",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"dname",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"// Directories are only valid if they contain at least one file",
"// with suffix \".go\" (this also ensures that the file descriptor",
"// we have is in fact a directory)",
"names",
",",
"err",
":=",
"fd",
".",
"Readdirnames",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"vendorDir",
"=",
"filepath",
".",
"ToSlash",
"(",
"dname",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"vendorDir",
"!=",
"\"",
"\"",
"{",
"pkg",
",",
"err",
":=",
"ctxt",
".",
"ImportDir",
"(",
"vendorDir",
",",
"mode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Go tries to derive a valid import path for the package, but",
"// it's wrong (it includes \"/vendor/\"). Overwrite it here.",
"pkg",
".",
"ImportPath",
"=",
"path",
"\n",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"ctxt",
".",
"Import",
"(",
"path",
",",
"dir",
",",
"mode",
")",
"\n",
"}"
] | // Deal with GO15VENDOREXPERIMENT | [
"Deal",
"with",
"GO15VENDOREXPERIMENT"
] | cddf355596fe2dbae05b4b5f845b4a6e2fb4e818 | https://github.com/stripe/safesql/blob/cddf355596fe2dbae05b4b5f845b4a6e2fb4e818/safesql.go#L289-L329 |
748 | rwcarlsen/goexif | exif/exif.go | IsShortReadTagValueError | func IsShortReadTagValueError(err error) bool {
de, ok := err.(decodeError)
if ok {
return de.cause == tiff.ErrShortReadTagValue
}
return false
} | go | func IsShortReadTagValueError(err error) bool {
de, ok := err.(decodeError)
if ok {
return de.cause == tiff.ErrShortReadTagValue
}
return false
} | [
"func",
"IsShortReadTagValueError",
"(",
"err",
"error",
")",
"bool",
"{",
"de",
",",
"ok",
":=",
"err",
".",
"(",
"decodeError",
")",
"\n",
"if",
"ok",
"{",
"return",
"de",
".",
"cause",
"==",
"tiff",
".",
"ErrShortReadTagValue",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsShortReadTagValueError identifies a ErrShortReadTagValue error. | [
"IsShortReadTagValueError",
"identifies",
"a",
"ErrShortReadTagValue",
"error",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L40-L46 |
749 | rwcarlsen/goexif | exif/exif.go | IsExifError | func IsExifError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isExif := te[loadExif]
return isExif
}
return false
} | go | func IsExifError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isExif := te[loadExif]
return isExif
}
return false
} | [
"func",
"IsExifError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"te",
",",
"ok",
":=",
"err",
".",
"(",
"tiffErrors",
")",
";",
"ok",
"{",
"_",
",",
"isExif",
":=",
"te",
"[",
"loadExif",
"]",
"\n",
"return",
"isExif",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsExifError reports whether the error happened while decoding the EXIF
// sub-IFD. | [
"IsExifError",
"reports",
"whether",
"the",
"error",
"happened",
"while",
"decoding",
"the",
"EXIF",
"sub",
"-",
"IFD",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L102-L108 |
750 | rwcarlsen/goexif | exif/exif.go | IsGPSError | func IsGPSError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isGPS := te[loadExif]
return isGPS
}
return false
} | go | func IsGPSError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isGPS := te[loadExif]
return isGPS
}
return false
} | [
"func",
"IsGPSError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"te",
",",
"ok",
":=",
"err",
".",
"(",
"tiffErrors",
")",
";",
"ok",
"{",
"_",
",",
"isGPS",
":=",
"te",
"[",
"loadExif",
"]",
"\n",
"return",
"isGPS",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsGPSError reports whether the error happened while decoding the GPS sub-IFD. | [
"IsGPSError",
"reports",
"whether",
"the",
"error",
"happened",
"while",
"decoding",
"the",
"GPS",
"sub",
"-",
"IFD",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L111-L117 |
751 | rwcarlsen/goexif | exif/exif.go | IsInteroperabilityError | func IsInteroperabilityError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isInterop := te[loadInteroperability]
return isInterop
}
return false
} | go | func IsInteroperabilityError(err error) bool {
if te, ok := err.(tiffErrors); ok {
_, isInterop := te[loadInteroperability]
return isInterop
}
return false
} | [
"func",
"IsInteroperabilityError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"te",
",",
"ok",
":=",
"err",
".",
"(",
"tiffErrors",
")",
";",
"ok",
"{",
"_",
",",
"isInterop",
":=",
"te",
"[",
"loadInteroperability",
"]",
"\n",
"return",
"isInterop",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsInteroperabilityError reports whether the error happened while decoding the
// Interoperability sub-IFD. | [
"IsInteroperabilityError",
"reports",
"whether",
"the",
"error",
"happened",
"while",
"decoding",
"the",
"Interoperability",
"sub",
"-",
"IFD",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L121-L127 |
752 | rwcarlsen/goexif | exif/exif.go | Parse | func (p *parser) Parse(x *Exif) error {
if len(x.Tiff.Dirs) == 0 {
return errors.New("Invalid exif data")
}
x.LoadTags(x.Tiff.Dirs[0], exifFields, false)
// thumbnails
if len(x.Tiff.Dirs) >= 2 {
x.LoadTags(x.Tiff.Dirs[1], thumbnailFields, false)
}
te := make(tiffErrors)
// recurse into exif, gps, and interop sub-IFDs
if err := loadSubDir(x, ExifIFDPointer, exifFields); err != nil {
te[loadExif] = err.Error()
}
if err := loadSubDir(x, GPSInfoIFDPointer, gpsFields); err != nil {
te[loadGPS] = err.Error()
}
if err := loadSubDir(x, InteroperabilityIFDPointer, interopFields); err != nil {
te[loadInteroperability] = err.Error()
}
if len(te) > 0 {
return te
}
return nil
} | go | func (p *parser) Parse(x *Exif) error {
if len(x.Tiff.Dirs) == 0 {
return errors.New("Invalid exif data")
}
x.LoadTags(x.Tiff.Dirs[0], exifFields, false)
// thumbnails
if len(x.Tiff.Dirs) >= 2 {
x.LoadTags(x.Tiff.Dirs[1], thumbnailFields, false)
}
te := make(tiffErrors)
// recurse into exif, gps, and interop sub-IFDs
if err := loadSubDir(x, ExifIFDPointer, exifFields); err != nil {
te[loadExif] = err.Error()
}
if err := loadSubDir(x, GPSInfoIFDPointer, gpsFields); err != nil {
te[loadGPS] = err.Error()
}
if err := loadSubDir(x, InteroperabilityIFDPointer, interopFields); err != nil {
te[loadInteroperability] = err.Error()
}
if len(te) > 0 {
return te
}
return nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"Parse",
"(",
"x",
"*",
"Exif",
")",
"error",
"{",
"if",
"len",
"(",
"x",
".",
"Tiff",
".",
"Dirs",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"x",
".",
"LoadTags",
"(",
"x",
".",
"Tiff",
".",
"Dirs",
"[",
"0",
"]",
",",
"exifFields",
",",
"false",
")",
"\n\n",
"// thumbnails",
"if",
"len",
"(",
"x",
".",
"Tiff",
".",
"Dirs",
")",
">=",
"2",
"{",
"x",
".",
"LoadTags",
"(",
"x",
".",
"Tiff",
".",
"Dirs",
"[",
"1",
"]",
",",
"thumbnailFields",
",",
"false",
")",
"\n",
"}",
"\n\n",
"te",
":=",
"make",
"(",
"tiffErrors",
")",
"\n\n",
"// recurse into exif, gps, and interop sub-IFDs",
"if",
"err",
":=",
"loadSubDir",
"(",
"x",
",",
"ExifIFDPointer",
",",
"exifFields",
")",
";",
"err",
"!=",
"nil",
"{",
"te",
"[",
"loadExif",
"]",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"loadSubDir",
"(",
"x",
",",
"GPSInfoIFDPointer",
",",
"gpsFields",
")",
";",
"err",
"!=",
"nil",
"{",
"te",
"[",
"loadGPS",
"]",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"loadSubDir",
"(",
"x",
",",
"InteroperabilityIFDPointer",
",",
"interopFields",
")",
";",
"err",
"!=",
"nil",
"{",
"te",
"[",
"loadInteroperability",
"]",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"te",
")",
">",
"0",
"{",
"return",
"te",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Parse reads data from the tiff data in x and populates the tags
// in x. If parsing a sub-IFD fails, the error is recorded and
// parsing continues with the remaining sub-IFDs. | [
"Parse",
"reads",
"data",
"from",
"the",
"tiff",
"data",
"in",
"x",
"and",
"populates",
"the",
"tags",
"in",
"x",
".",
"If",
"parsing",
"a",
"sub",
"-",
"IFD",
"fails",
"the",
"error",
"is",
"recorded",
"and",
"parsing",
"continues",
"with",
"the",
"remaining",
"sub",
"-",
"IFDs",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L146-L174 |
753 | rwcarlsen/goexif | exif/exif.go | Get | func (x *Exif) Get(name FieldName) (*tiff.Tag, error) {
if tg, ok := x.main[name]; ok {
return tg, nil
}
return nil, TagNotPresentError(name)
} | go | func (x *Exif) Get(name FieldName) (*tiff.Tag, error) {
if tg, ok := x.main[name]; ok {
return tg, nil
}
return nil, TagNotPresentError(name)
} | [
"func",
"(",
"x",
"*",
"Exif",
")",
"Get",
"(",
"name",
"FieldName",
")",
"(",
"*",
"tiff",
".",
"Tag",
",",
"error",
")",
"{",
"if",
"tg",
",",
"ok",
":=",
"x",
".",
"main",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"tg",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"TagNotPresentError",
"(",
"name",
")",
"\n",
"}"
] | // Get retrieves the EXIF tag for the given field name.
//
// If the tag is not known or not present, an error is returned. If the
// tag name is known, the error will be a TagNotPresentError. | [
"Get",
"retrieves",
"the",
"EXIF",
"tag",
"for",
"the",
"given",
"field",
"name",
".",
"If",
"the",
"tag",
"is",
"not",
"known",
"or",
"not",
"present",
"an",
"error",
"is",
"returned",
".",
"If",
"the",
"tag",
"name",
"is",
"known",
"the",
"error",
"will",
"be",
"a",
"TagNotPresentError",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L339-L344 |
754 | rwcarlsen/goexif | exif/exif.go | Walk | func (x *Exif) Walk(w Walker) error {
for name, tag := range x.main {
if err := w.Walk(name, tag); err != nil {
return err
}
}
return nil
} | go | func (x *Exif) Walk(w Walker) error {
for name, tag := range x.main {
if err := w.Walk(name, tag); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"x",
"*",
"Exif",
")",
"Walk",
"(",
"w",
"Walker",
")",
"error",
"{",
"for",
"name",
",",
"tag",
":=",
"range",
"x",
".",
"main",
"{",
"if",
"err",
":=",
"w",
".",
"Walk",
"(",
"name",
",",
"tag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Walk calls the Walk method of w with the name and tag for every non-nil
// EXIF field. If w aborts the walk with an error, that error is returned. | [
"Walk",
"calls",
"the",
"Walk",
"method",
"of",
"w",
"with",
"the",
"name",
"and",
"tag",
"for",
"every",
"non",
"-",
"nil",
"EXIF",
"field",
".",
"If",
"w",
"aborts",
"the",
"walk",
"with",
"an",
"error",
"that",
"error",
"is",
"returned",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L355-L362 |
755 | rwcarlsen/goexif | exif/exif.go | LatLong | func (x *Exif) LatLong() (lat, long float64, err error) {
// All calls of x.Get might return an TagNotPresentError
longTag, err := x.Get(FieldName("GPSLongitude"))
if err != nil {
return
}
ewTag, err := x.Get(FieldName("GPSLongitudeRef"))
if err != nil {
return
}
latTag, err := x.Get(FieldName("GPSLatitude"))
if err != nil {
return
}
nsTag, err := x.Get(FieldName("GPSLatitudeRef"))
if err != nil {
return
}
if long, err = tagDegrees(longTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
if lat, err = tagDegrees(latTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse latitude: %v", err)
}
ew, err := ewTag.StringVal()
if err == nil && ew == "W" {
long *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
ns, err := nsTag.StringVal()
if err == nil && ns == "S" {
lat *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
return lat, long, nil
} | go | func (x *Exif) LatLong() (lat, long float64, err error) {
// All calls of x.Get might return an TagNotPresentError
longTag, err := x.Get(FieldName("GPSLongitude"))
if err != nil {
return
}
ewTag, err := x.Get(FieldName("GPSLongitudeRef"))
if err != nil {
return
}
latTag, err := x.Get(FieldName("GPSLatitude"))
if err != nil {
return
}
nsTag, err := x.Get(FieldName("GPSLatitudeRef"))
if err != nil {
return
}
if long, err = tagDegrees(longTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
if lat, err = tagDegrees(latTag); err != nil {
return 0, 0, fmt.Errorf("Cannot parse latitude: %v", err)
}
ew, err := ewTag.StringVal()
if err == nil && ew == "W" {
long *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
ns, err := nsTag.StringVal()
if err == nil && ns == "S" {
lat *= -1.0
} else if err != nil {
return 0, 0, fmt.Errorf("Cannot parse longitude: %v", err)
}
return lat, long, nil
} | [
"func",
"(",
"x",
"*",
"Exif",
")",
"LatLong",
"(",
")",
"(",
"lat",
",",
"long",
"float64",
",",
"err",
"error",
")",
"{",
"// All calls of x.Get might return an TagNotPresentError",
"longTag",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"FieldName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ewTag",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"FieldName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"latTag",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"FieldName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nsTag",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"FieldName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"long",
",",
"err",
"=",
"tagDegrees",
"(",
"longTag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"lat",
",",
"err",
"=",
"tagDegrees",
"(",
"latTag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"ew",
",",
"err",
":=",
"ewTag",
".",
"StringVal",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"ew",
"==",
"\"",
"\"",
"{",
"long",
"*=",
"-",
"1.0",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"ns",
",",
"err",
":=",
"nsTag",
".",
"StringVal",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"ns",
"==",
"\"",
"\"",
"{",
"lat",
"*=",
"-",
"1.0",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"lat",
",",
"long",
",",
"nil",
"\n",
"}"
] | // LatLong returns the latitude and longitude of the photo and
// whether it was present. | [
"LatLong",
"returns",
"the",
"latitude",
"and",
"longitude",
"of",
"the",
"photo",
"and",
"whether",
"it",
"was",
"present",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L510-L547 |
756 | rwcarlsen/goexif | exif/exif.go | String | func (x *Exif) String() string {
var buf bytes.Buffer
for name, tag := range x.main {
fmt.Fprintf(&buf, "%s: %s\n", name, tag)
}
return buf.String()
} | go | func (x *Exif) String() string {
var buf bytes.Buffer
for name, tag := range x.main {
fmt.Fprintf(&buf, "%s: %s\n", name, tag)
}
return buf.String()
} | [
"func",
"(",
"x",
"*",
"Exif",
")",
"String",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"name",
",",
"tag",
":=",
"range",
"x",
".",
"main",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"name",
",",
"tag",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // String returns a pretty text representation of the decoded exif data. | [
"String",
"returns",
"a",
"pretty",
"text",
"representation",
"of",
"the",
"decoded",
"exif",
"data",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L550-L556 |
757 | rwcarlsen/goexif | exif/exif.go | JpegThumbnail | func (x *Exif) JpegThumbnail() ([]byte, error) {
offset, err := x.Get(ThumbJPEGInterchangeFormat)
if err != nil {
return nil, err
}
start, err := offset.Int(0)
if err != nil {
return nil, err
}
length, err := x.Get(ThumbJPEGInterchangeFormatLength)
if err != nil {
return nil, err
}
l, err := length.Int(0)
if err != nil {
return nil, err
}
return x.Raw[start : start+l], nil
} | go | func (x *Exif) JpegThumbnail() ([]byte, error) {
offset, err := x.Get(ThumbJPEGInterchangeFormat)
if err != nil {
return nil, err
}
start, err := offset.Int(0)
if err != nil {
return nil, err
}
length, err := x.Get(ThumbJPEGInterchangeFormatLength)
if err != nil {
return nil, err
}
l, err := length.Int(0)
if err != nil {
return nil, err
}
return x.Raw[start : start+l], nil
} | [
"func",
"(",
"x",
"*",
"Exif",
")",
"JpegThumbnail",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"offset",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"ThumbJPEGInterchangeFormat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"start",
",",
"err",
":=",
"offset",
".",
"Int",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"length",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"ThumbJPEGInterchangeFormatLength",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"l",
",",
"err",
":=",
"length",
".",
"Int",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"x",
".",
"Raw",
"[",
"start",
":",
"start",
"+",
"l",
"]",
",",
"nil",
"\n",
"}"
] | // JpegThumbnail returns the jpeg thumbnail if it exists. If it doesn't exist,
// TagNotPresentError will be returned | [
"JpegThumbnail",
"returns",
"the",
"jpeg",
"thumbnail",
"if",
"it",
"exists",
".",
"If",
"it",
"doesn",
"t",
"exist",
"TagNotPresentError",
"will",
"be",
"returned"
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L560-L580 |
758 | rwcarlsen/goexif | exif/exif.go | newAppSec | func newAppSec(marker byte, r io.Reader) (*appSec, error) {
br := bufio.NewReader(r)
app := &appSec{marker: marker}
var dataLen int
// seek to marker
for dataLen == 0 {
if _, err := br.ReadBytes(0xFF); err != nil {
return nil, err
}
c, err := br.ReadByte()
if err != nil {
return nil, err
} else if c != marker {
continue
}
dataLenBytes := make([]byte, 2)
for k, _ := range dataLenBytes {
c, err := br.ReadByte()
if err != nil {
return nil, err
}
dataLenBytes[k] = c
}
dataLen = int(binary.BigEndian.Uint16(dataLenBytes)) - 2
}
// read section data
nread := 0
for nread < dataLen {
s := make([]byte, dataLen-nread)
n, err := br.Read(s)
nread += n
if err != nil && nread < dataLen {
return nil, err
}
app.data = append(app.data, s[:n]...)
}
return app, nil
} | go | func newAppSec(marker byte, r io.Reader) (*appSec, error) {
br := bufio.NewReader(r)
app := &appSec{marker: marker}
var dataLen int
// seek to marker
for dataLen == 0 {
if _, err := br.ReadBytes(0xFF); err != nil {
return nil, err
}
c, err := br.ReadByte()
if err != nil {
return nil, err
} else if c != marker {
continue
}
dataLenBytes := make([]byte, 2)
for k, _ := range dataLenBytes {
c, err := br.ReadByte()
if err != nil {
return nil, err
}
dataLenBytes[k] = c
}
dataLen = int(binary.BigEndian.Uint16(dataLenBytes)) - 2
}
// read section data
nread := 0
for nread < dataLen {
s := make([]byte, dataLen-nread)
n, err := br.Read(s)
nread += n
if err != nil && nread < dataLen {
return nil, err
}
app.data = append(app.data, s[:n]...)
}
return app, nil
} | [
"func",
"newAppSec",
"(",
"marker",
"byte",
",",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"appSec",
",",
"error",
")",
"{",
"br",
":=",
"bufio",
".",
"NewReader",
"(",
"r",
")",
"\n",
"app",
":=",
"&",
"appSec",
"{",
"marker",
":",
"marker",
"}",
"\n",
"var",
"dataLen",
"int",
"\n\n",
"// seek to marker",
"for",
"dataLen",
"==",
"0",
"{",
"if",
"_",
",",
"err",
":=",
"br",
".",
"ReadBytes",
"(",
"0xFF",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"br",
".",
"ReadByte",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"else",
"if",
"c",
"!=",
"marker",
"{",
"continue",
"\n",
"}",
"\n\n",
"dataLenBytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
")",
"\n",
"for",
"k",
",",
"_",
":=",
"range",
"dataLenBytes",
"{",
"c",
",",
"err",
":=",
"br",
".",
"ReadByte",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dataLenBytes",
"[",
"k",
"]",
"=",
"c",
"\n",
"}",
"\n",
"dataLen",
"=",
"int",
"(",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"dataLenBytes",
")",
")",
"-",
"2",
"\n",
"}",
"\n\n",
"// read section data",
"nread",
":=",
"0",
"\n",
"for",
"nread",
"<",
"dataLen",
"{",
"s",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"dataLen",
"-",
"nread",
")",
"\n",
"n",
",",
"err",
":=",
"br",
".",
"Read",
"(",
"s",
")",
"\n",
"nread",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"nread",
"<",
"dataLen",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"app",
".",
"data",
"=",
"append",
"(",
"app",
".",
"data",
",",
"s",
"[",
":",
"n",
"]",
"...",
")",
"\n",
"}",
"\n",
"return",
"app",
",",
"nil",
"\n",
"}"
] | // newAppSec finds marker in r and returns the corresponding application data
// section. | [
"newAppSec",
"finds",
"marker",
"in",
"r",
"and",
"returns",
"the",
"corresponding",
"application",
"data",
"section",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L595-L635 |
759 | rwcarlsen/goexif | exif/exif.go | exifReader | func (app *appSec) exifReader() (*bytes.Reader, error) {
if len(app.data) < 6 {
return nil, errors.New("exif: failed to find exif intro marker")
}
// read/check for exif special mark
exif := app.data[:6]
if !bytes.Equal(exif, append([]byte("Exif"), 0x00, 0x00)) {
return nil, errors.New("exif: failed to find exif intro marker")
}
return bytes.NewReader(app.data[6:]), nil
} | go | func (app *appSec) exifReader() (*bytes.Reader, error) {
if len(app.data) < 6 {
return nil, errors.New("exif: failed to find exif intro marker")
}
// read/check for exif special mark
exif := app.data[:6]
if !bytes.Equal(exif, append([]byte("Exif"), 0x00, 0x00)) {
return nil, errors.New("exif: failed to find exif intro marker")
}
return bytes.NewReader(app.data[6:]), nil
} | [
"func",
"(",
"app",
"*",
"appSec",
")",
"exifReader",
"(",
")",
"(",
"*",
"bytes",
".",
"Reader",
",",
"error",
")",
"{",
"if",
"len",
"(",
"app",
".",
"data",
")",
"<",
"6",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// read/check for exif special mark",
"exif",
":=",
"app",
".",
"data",
"[",
":",
"6",
"]",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"exif",
",",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"0x00",
",",
"0x00",
")",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"bytes",
".",
"NewReader",
"(",
"app",
".",
"data",
"[",
"6",
":",
"]",
")",
",",
"nil",
"\n",
"}"
] | // exifReader returns a reader on this appSec with the read cursor advanced to
// the start of the exif's tiff encoded portion. | [
"exifReader",
"returns",
"a",
"reader",
"on",
"this",
"appSec",
"with",
"the",
"read",
"cursor",
"advanced",
"to",
"the",
"start",
"of",
"the",
"exif",
"s",
"tiff",
"encoded",
"portion",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/exif/exif.go#L644-L655 |
760 | rwcarlsen/goexif | tiff/tag.go | Rat | func (t *Tag) Rat(i int) (*big.Rat, error) {
n, d, err := t.Rat2(i)
if err != nil {
return nil, err
}
return big.NewRat(n, d), nil
} | go | func (t *Tag) Rat(i int) (*big.Rat, error) {
n, d, err := t.Rat2(i)
if err != nil {
return nil, err
}
return big.NewRat(n, d), nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"Rat",
"(",
"i",
"int",
")",
"(",
"*",
"big",
".",
"Rat",
",",
"error",
")",
"{",
"n",
",",
"d",
",",
"err",
":=",
"t",
".",
"Rat2",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"big",
".",
"NewRat",
"(",
"n",
",",
"d",
")",
",",
"nil",
"\n",
"}"
] | // Rat returns the tag's i'th value as a rational number. It returns a nil and
// an error if this tag's Format is not RatVal. It panics for zero deminators
// or if i is out of range. | [
"Rat",
"returns",
"the",
"tag",
"s",
"i",
"th",
"value",
"as",
"a",
"rational",
"number",
".",
"It",
"returns",
"a",
"nil",
"and",
"an",
"error",
"if",
"this",
"tag",
"s",
"Format",
"is",
"not",
"RatVal",
".",
"It",
"panics",
"for",
"zero",
"deminators",
"or",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L331-L337 |
761 | rwcarlsen/goexif | tiff/tag.go | Rat2 | func (t *Tag) Rat2(i int) (num, den int64, err error) {
if t.format != RatVal {
return 0, 0, t.typeErr(RatVal)
}
return t.ratVals[i][0], t.ratVals[i][1], nil
} | go | func (t *Tag) Rat2(i int) (num, den int64, err error) {
if t.format != RatVal {
return 0, 0, t.typeErr(RatVal)
}
return t.ratVals[i][0], t.ratVals[i][1], nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"Rat2",
"(",
"i",
"int",
")",
"(",
"num",
",",
"den",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"t",
".",
"format",
"!=",
"RatVal",
"{",
"return",
"0",
",",
"0",
",",
"t",
".",
"typeErr",
"(",
"RatVal",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"ratVals",
"[",
"i",
"]",
"[",
"0",
"]",
",",
"t",
".",
"ratVals",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"nil",
"\n",
"}"
] | // Rat2 returns the tag's i'th value as a rational number represented by a
// numerator-denominator pair. It returns an error if the tag's Format is not
// RatVal. It panics if i is out of range. | [
"Rat2",
"returns",
"the",
"tag",
"s",
"i",
"th",
"value",
"as",
"a",
"rational",
"number",
"represented",
"by",
"a",
"numerator",
"-",
"denominator",
"pair",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"tag",
"s",
"Format",
"is",
"not",
"RatVal",
".",
"It",
"panics",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L342-L347 |
762 | rwcarlsen/goexif | tiff/tag.go | Int64 | func (t *Tag) Int64(i int) (int64, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return t.intVals[i], nil
} | go | func (t *Tag) Int64(i int) (int64, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return t.intVals[i], nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"Int64",
"(",
"i",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"t",
".",
"format",
"!=",
"IntVal",
"{",
"return",
"0",
",",
"t",
".",
"typeErr",
"(",
"IntVal",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"intVals",
"[",
"i",
"]",
",",
"nil",
"\n",
"}"
] | // Int64 returns the tag's i'th value as an integer. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range. | [
"Int64",
"returns",
"the",
"tag",
"s",
"i",
"th",
"value",
"as",
"an",
"integer",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"tag",
"s",
"Format",
"is",
"not",
"IntVal",
".",
"It",
"panics",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L351-L356 |
763 | rwcarlsen/goexif | tiff/tag.go | Int | func (t *Tag) Int(i int) (int, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return int(t.intVals[i]), nil
} | go | func (t *Tag) Int(i int) (int, error) {
if t.format != IntVal {
return 0, t.typeErr(IntVal)
}
return int(t.intVals[i]), nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"Int",
"(",
"i",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"t",
".",
"format",
"!=",
"IntVal",
"{",
"return",
"0",
",",
"t",
".",
"typeErr",
"(",
"IntVal",
")",
"\n",
"}",
"\n",
"return",
"int",
"(",
"t",
".",
"intVals",
"[",
"i",
"]",
")",
",",
"nil",
"\n",
"}"
] | // Int returns the tag's i'th value as an integer. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range. | [
"Int",
"returns",
"the",
"tag",
"s",
"i",
"th",
"value",
"as",
"an",
"integer",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"tag",
"s",
"Format",
"is",
"not",
"IntVal",
".",
"It",
"panics",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L360-L365 |
764 | rwcarlsen/goexif | tiff/tag.go | Float | func (t *Tag) Float(i int) (float64, error) {
if t.format != FloatVal {
return 0, t.typeErr(FloatVal)
}
return t.floatVals[i], nil
} | go | func (t *Tag) Float(i int) (float64, error) {
if t.format != FloatVal {
return 0, t.typeErr(FloatVal)
}
return t.floatVals[i], nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"Float",
"(",
"i",
"int",
")",
"(",
"float64",
",",
"error",
")",
"{",
"if",
"t",
".",
"format",
"!=",
"FloatVal",
"{",
"return",
"0",
",",
"t",
".",
"typeErr",
"(",
"FloatVal",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"floatVals",
"[",
"i",
"]",
",",
"nil",
"\n",
"}"
] | // Float returns the tag's i'th value as a float. It returns an error if the
// tag's Format is not IntVal. It panics if i is out of range. | [
"Float",
"returns",
"the",
"tag",
"s",
"i",
"th",
"value",
"as",
"a",
"float",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"tag",
"s",
"Format",
"is",
"not",
"IntVal",
".",
"It",
"panics",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L369-L374 |
765 | rwcarlsen/goexif | tiff/tag.go | StringVal | func (t *Tag) StringVal() (string, error) {
if t.format != StringVal {
return "", t.typeErr(StringVal)
}
return t.strVal, nil
} | go | func (t *Tag) StringVal() (string, error) {
if t.format != StringVal {
return "", t.typeErr(StringVal)
}
return t.strVal, nil
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"StringVal",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"t",
".",
"format",
"!=",
"StringVal",
"{",
"return",
"\"",
"\"",
",",
"t",
".",
"typeErr",
"(",
"StringVal",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"strVal",
",",
"nil",
"\n",
"}"
] | // StringVal returns the tag's value as a string. It returns an error if the
// tag's Format is not StringVal. It panics if i is out of range. | [
"StringVal",
"returns",
"the",
"tag",
"s",
"value",
"as",
"a",
"string",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"tag",
"s",
"Format",
"is",
"not",
"StringVal",
".",
"It",
"panics",
"if",
"i",
"is",
"out",
"of",
"range",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L378-L383 |
766 | rwcarlsen/goexif | tiff/tag.go | String | func (t *Tag) String() string {
data, err := t.MarshalJSON()
if err != nil {
return "ERROR: " + err.Error()
}
if t.Count == 1 {
return strings.Trim(fmt.Sprintf("%s", data), "[]")
}
return fmt.Sprintf("%s", data)
} | go | func (t *Tag) String() string {
data, err := t.MarshalJSON()
if err != nil {
return "ERROR: " + err.Error()
}
if t.Count == 1 {
return strings.Trim(fmt.Sprintf("%s", data), "[]")
}
return fmt.Sprintf("%s", data)
} | [
"func",
"(",
"t",
"*",
"Tag",
")",
"String",
"(",
")",
"string",
"{",
"data",
",",
"err",
":=",
"t",
".",
"MarshalJSON",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"Count",
"==",
"1",
"{",
"return",
"strings",
".",
"Trim",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}"
] | // String returns a nicely formatted version of the tag. | [
"String",
"returns",
"a",
"nicely",
"formatted",
"version",
"of",
"the",
"tag",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tag.go#L386-L396 |
767 | rwcarlsen/goexif | tiff/tiff.go | Decode | func Decode(r io.Reader) (*Tiff, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.New("tiff: could not read data")
}
buf := bytes.NewReader(data)
t := new(Tiff)
// read byte order
bo := make([]byte, 2)
if _, err = io.ReadFull(buf, bo); err != nil {
return nil, errors.New("tiff: could not read tiff byte order")
}
if string(bo) == "II" {
t.Order = binary.LittleEndian
} else if string(bo) == "MM" {
t.Order = binary.BigEndian
} else {
return nil, errors.New("tiff: could not read tiff byte order")
}
// check for special tiff marker
var sp int16
err = binary.Read(buf, t.Order, &sp)
if err != nil || 42 != sp {
return nil, errors.New("tiff: could not find special tiff marker")
}
// load offset to first IFD
var offset int32
err = binary.Read(buf, t.Order, &offset)
if err != nil {
return nil, errors.New("tiff: could not read offset to first IFD")
}
// load IFD's
var d *Dir
prev := offset
for offset != 0 {
// seek to offset
_, err := buf.Seek(int64(offset), 0)
if err != nil {
return nil, errors.New("tiff: seek to IFD failed")
}
if buf.Len() == 0 {
return nil, errors.New("tiff: seek offset after EOF")
}
// load the dir
d, offset, err = DecodeDir(buf, t.Order)
if err != nil {
return nil, err
}
if offset == prev {
return nil, errors.New("tiff: recursive IFD")
}
prev = offset
t.Dirs = append(t.Dirs, d)
}
return t, nil
} | go | func Decode(r io.Reader) (*Tiff, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.New("tiff: could not read data")
}
buf := bytes.NewReader(data)
t := new(Tiff)
// read byte order
bo := make([]byte, 2)
if _, err = io.ReadFull(buf, bo); err != nil {
return nil, errors.New("tiff: could not read tiff byte order")
}
if string(bo) == "II" {
t.Order = binary.LittleEndian
} else if string(bo) == "MM" {
t.Order = binary.BigEndian
} else {
return nil, errors.New("tiff: could not read tiff byte order")
}
// check for special tiff marker
var sp int16
err = binary.Read(buf, t.Order, &sp)
if err != nil || 42 != sp {
return nil, errors.New("tiff: could not find special tiff marker")
}
// load offset to first IFD
var offset int32
err = binary.Read(buf, t.Order, &offset)
if err != nil {
return nil, errors.New("tiff: could not read offset to first IFD")
}
// load IFD's
var d *Dir
prev := offset
for offset != 0 {
// seek to offset
_, err := buf.Seek(int64(offset), 0)
if err != nil {
return nil, errors.New("tiff: seek to IFD failed")
}
if buf.Len() == 0 {
return nil, errors.New("tiff: seek offset after EOF")
}
// load the dir
d, offset, err = DecodeDir(buf, t.Order)
if err != nil {
return nil, err
}
if offset == prev {
return nil, errors.New("tiff: recursive IFD")
}
prev = offset
t.Dirs = append(t.Dirs, d)
}
return t, nil
} | [
"func",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Tiff",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n\n",
"t",
":=",
"new",
"(",
"Tiff",
")",
"\n\n",
"// read byte order",
"bo",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"buf",
",",
"bo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"string",
"(",
"bo",
")",
"==",
"\"",
"\"",
"{",
"t",
".",
"Order",
"=",
"binary",
".",
"LittleEndian",
"\n",
"}",
"else",
"if",
"string",
"(",
"bo",
")",
"==",
"\"",
"\"",
"{",
"t",
".",
"Order",
"=",
"binary",
".",
"BigEndian",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// check for special tiff marker",
"var",
"sp",
"int16",
"\n",
"err",
"=",
"binary",
".",
"Read",
"(",
"buf",
",",
"t",
".",
"Order",
",",
"&",
"sp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"42",
"!=",
"sp",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// load offset to first IFD",
"var",
"offset",
"int32",
"\n",
"err",
"=",
"binary",
".",
"Read",
"(",
"buf",
",",
"t",
".",
"Order",
",",
"&",
"offset",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// load IFD's",
"var",
"d",
"*",
"Dir",
"\n",
"prev",
":=",
"offset",
"\n",
"for",
"offset",
"!=",
"0",
"{",
"// seek to offset",
"_",
",",
"err",
":=",
"buf",
".",
"Seek",
"(",
"int64",
"(",
"offset",
")",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"buf",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// load the dir",
"d",
",",
"offset",
",",
"err",
"=",
"DecodeDir",
"(",
"buf",
",",
"t",
".",
"Order",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"offset",
"==",
"prev",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"prev",
"=",
"offset",
"\n\n",
"t",
".",
"Dirs",
"=",
"append",
"(",
"t",
".",
"Dirs",
",",
"d",
")",
"\n",
"}",
"\n\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // Decode parses tiff-encoded data from r and returns a Tiff struct that
// reflects the structure and content of the tiff data. The first read from r
// should be the first byte of the tiff-encoded data and not necessarily the
// first byte of an os.File object. | [
"Decode",
"parses",
"tiff",
"-",
"encoded",
"data",
"from",
"r",
"and",
"returns",
"a",
"Tiff",
"struct",
"that",
"reflects",
"the",
"structure",
"and",
"content",
"of",
"the",
"tiff",
"data",
".",
"The",
"first",
"read",
"from",
"r",
"should",
"be",
"the",
"first",
"byte",
"of",
"the",
"tiff",
"-",
"encoded",
"data",
"and",
"not",
"necessarily",
"the",
"first",
"byte",
"of",
"an",
"os",
".",
"File",
"object",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/tiff/tiff.go#L33-L98 |
768 | rwcarlsen/goexif | mknote/mknote.go | Parse | func (_ *canon) Parse(x *exif.Exif) error {
m, err := x.Get(exif.MakerNote)
if err != nil {
return nil
}
mk, err := x.Get(exif.Make)
if err != nil {
return nil
}
if val, err := mk.StringVal(); err != nil || val != "Canon" {
return nil
}
// Canon notes are a single IFD directory with no header.
// Reader offsets need to be w.r.t. the original tiff structure.
buf := bytes.NewReader(append(make([]byte, m.ValOffset), m.Val...))
buf.Seek(int64(m.ValOffset), 0)
mkNotesDir, _, err := tiff.DecodeDir(buf, x.Tiff.Order)
if err != nil {
return err
}
x.LoadTags(mkNotesDir, makerNoteCanonFields, false)
return nil
} | go | func (_ *canon) Parse(x *exif.Exif) error {
m, err := x.Get(exif.MakerNote)
if err != nil {
return nil
}
mk, err := x.Get(exif.Make)
if err != nil {
return nil
}
if val, err := mk.StringVal(); err != nil || val != "Canon" {
return nil
}
// Canon notes are a single IFD directory with no header.
// Reader offsets need to be w.r.t. the original tiff structure.
buf := bytes.NewReader(append(make([]byte, m.ValOffset), m.Val...))
buf.Seek(int64(m.ValOffset), 0)
mkNotesDir, _, err := tiff.DecodeDir(buf, x.Tiff.Order)
if err != nil {
return err
}
x.LoadTags(mkNotesDir, makerNoteCanonFields, false)
return nil
} | [
"func",
"(",
"_",
"*",
"canon",
")",
"Parse",
"(",
"x",
"*",
"exif",
".",
"Exif",
")",
"error",
"{",
"m",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"exif",
".",
"MakerNote",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"mk",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"exif",
".",
"Make",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"val",
",",
"err",
":=",
"mk",
".",
"StringVal",
"(",
")",
";",
"err",
"!=",
"nil",
"||",
"val",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Canon notes are a single IFD directory with no header.",
"// Reader offsets need to be w.r.t. the original tiff structure.",
"buf",
":=",
"bytes",
".",
"NewReader",
"(",
"append",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"m",
".",
"ValOffset",
")",
",",
"m",
".",
"Val",
"...",
")",
")",
"\n",
"buf",
".",
"Seek",
"(",
"int64",
"(",
"m",
".",
"ValOffset",
")",
",",
"0",
")",
"\n\n",
"mkNotesDir",
",",
"_",
",",
"err",
":=",
"tiff",
".",
"DecodeDir",
"(",
"buf",
",",
"x",
".",
"Tiff",
".",
"Order",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"x",
".",
"LoadTags",
"(",
"mkNotesDir",
",",
"makerNoteCanonFields",
",",
"false",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Parse decodes all Canon makernote data found in x and adds it to x. | [
"Parse",
"decodes",
"all",
"Canon",
"makernote",
"data",
"found",
"in",
"x",
"and",
"adds",
"it",
"to",
"x",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/mknote/mknote.go#L23-L49 |
769 | rwcarlsen/goexif | mknote/mknote.go | Parse | func (_ *nikonV3) Parse(x *exif.Exif) error {
m, err := x.Get(exif.MakerNote)
if err != nil {
return nil
} else if bytes.Compare(m.Val[:6], []byte("Nikon\000")) != 0 {
return nil
}
// Nikon v3 maker note is a self-contained IFD (offsets are relative
// to the start of the maker note)
mkNotes, err := tiff.Decode(bytes.NewReader(m.Val[10:]))
if err != nil {
return err
}
x.LoadTags(mkNotes.Dirs[0], makerNoteNikon3Fields, false)
return nil
} | go | func (_ *nikonV3) Parse(x *exif.Exif) error {
m, err := x.Get(exif.MakerNote)
if err != nil {
return nil
} else if bytes.Compare(m.Val[:6], []byte("Nikon\000")) != 0 {
return nil
}
// Nikon v3 maker note is a self-contained IFD (offsets are relative
// to the start of the maker note)
mkNotes, err := tiff.Decode(bytes.NewReader(m.Val[10:]))
if err != nil {
return err
}
x.LoadTags(mkNotes.Dirs[0], makerNoteNikon3Fields, false)
return nil
} | [
"func",
"(",
"_",
"*",
"nikonV3",
")",
"Parse",
"(",
"x",
"*",
"exif",
".",
"Exif",
")",
"error",
"{",
"m",
",",
"err",
":=",
"x",
".",
"Get",
"(",
"exif",
".",
"MakerNote",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"bytes",
".",
"Compare",
"(",
"m",
".",
"Val",
"[",
":",
"6",
"]",
",",
"[",
"]",
"byte",
"(",
"\"",
"\\000",
"\"",
")",
")",
"!=",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Nikon v3 maker note is a self-contained IFD (offsets are relative",
"// to the start of the maker note)",
"mkNotes",
",",
"err",
":=",
"tiff",
".",
"Decode",
"(",
"bytes",
".",
"NewReader",
"(",
"m",
".",
"Val",
"[",
"10",
":",
"]",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"x",
".",
"LoadTags",
"(",
"mkNotes",
".",
"Dirs",
"[",
"0",
"]",
",",
"makerNoteNikon3Fields",
",",
"false",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Parse decodes all Nikon makernote data found in x and adds it to x. | [
"Parse",
"decodes",
"all",
"Nikon",
"makernote",
"data",
"found",
"in",
"x",
"and",
"adds",
"it",
"to",
"x",
"."
] | 9e8deecbddbd4989a3e8d003684b783412b41e7a | https://github.com/rwcarlsen/goexif/blob/9e8deecbddbd4989a3e8d003684b783412b41e7a/mknote/mknote.go#L54-L70 |
770 | sendgrid/smtpapi-go | smtpapi.go | AddTo | func (h *SMTPAPIHeader) AddTo(email string) {
h.To = append(h.To, email)
} | go | func (h *SMTPAPIHeader) AddTo(email string) {
h.To = append(h.To, email)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddTo",
"(",
"email",
"string",
")",
"{",
"h",
".",
"To",
"=",
"append",
"(",
"h",
".",
"To",
",",
"email",
")",
"\n",
"}"
] | // AddTo appends a single email to the To header | [
"AddTo",
"appends",
"a",
"single",
"email",
"to",
"the",
"To",
"header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L41-L43 |
771 | sendgrid/smtpapi-go | smtpapi.go | AddTos | func (h *SMTPAPIHeader) AddTos(emails []string) {
for i := 0; i < len(emails); i++ {
h.AddTo(emails[i])
}
} | go | func (h *SMTPAPIHeader) AddTos(emails []string) {
for i := 0; i < len(emails); i++ {
h.AddTo(emails[i])
}
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddTos",
"(",
"emails",
"[",
"]",
"string",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"emails",
")",
";",
"i",
"++",
"{",
"h",
".",
"AddTo",
"(",
"emails",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // AddTos appends multiple emails to the To header | [
"AddTos",
"appends",
"multiple",
"emails",
"to",
"the",
"To",
"header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L46-L50 |
772 | sendgrid/smtpapi-go | smtpapi.go | AddSubstitution | func (h *SMTPAPIHeader) AddSubstitution(key, sub string) {
if h.Sub == nil {
h.Sub = make(map[string][]string)
}
h.Sub[key] = append(h.Sub[key], sub)
} | go | func (h *SMTPAPIHeader) AddSubstitution(key, sub string) {
if h.Sub == nil {
h.Sub = make(map[string][]string)
}
h.Sub[key] = append(h.Sub[key], sub)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddSubstitution",
"(",
"key",
",",
"sub",
"string",
")",
"{",
"if",
"h",
".",
"Sub",
"==",
"nil",
"{",
"h",
".",
"Sub",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}",
"\n",
"h",
".",
"Sub",
"[",
"key",
"]",
"=",
"append",
"(",
"h",
".",
"Sub",
"[",
"key",
"]",
",",
"sub",
")",
"\n",
"}"
] | // AddSubstitution adds a new substitution to a specific key | [
"AddSubstitution",
"adds",
"a",
"new",
"substitution",
"to",
"a",
"specific",
"key"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L58-L63 |
773 | sendgrid/smtpapi-go | smtpapi.go | AddSubstitutions | func (h *SMTPAPIHeader) AddSubstitutions(key string, subs []string) {
for i := 0; i < len(subs); i++ {
h.AddSubstitution(key, subs[i])
}
} | go | func (h *SMTPAPIHeader) AddSubstitutions(key string, subs []string) {
for i := 0; i < len(subs); i++ {
h.AddSubstitution(key, subs[i])
}
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddSubstitutions",
"(",
"key",
"string",
",",
"subs",
"[",
"]",
"string",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"subs",
")",
";",
"i",
"++",
"{",
"h",
".",
"AddSubstitution",
"(",
"key",
",",
"subs",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // AddSubstitutions adds a multiple substitutions to a specific key | [
"AddSubstitutions",
"adds",
"a",
"multiple",
"substitutions",
"to",
"a",
"specific",
"key"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L66-L70 |
774 | sendgrid/smtpapi-go | smtpapi.go | AddSection | func (h *SMTPAPIHeader) AddSection(section, value string) {
if h.Section == nil {
h.Section = make(map[string]string)
}
h.Section[section] = value
} | go | func (h *SMTPAPIHeader) AddSection(section, value string) {
if h.Section == nil {
h.Section = make(map[string]string)
}
h.Section[section] = value
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddSection",
"(",
"section",
",",
"value",
"string",
")",
"{",
"if",
"h",
".",
"Section",
"==",
"nil",
"{",
"h",
".",
"Section",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n",
"h",
".",
"Section",
"[",
"section",
"]",
"=",
"value",
"\n",
"}"
] | // AddSection sets the value for a specific section | [
"AddSection",
"sets",
"the",
"value",
"for",
"a",
"specific",
"section"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L78-L83 |
775 | sendgrid/smtpapi-go | smtpapi.go | AddCategory | func (h *SMTPAPIHeader) AddCategory(category string) {
h.Category = append(h.Category, category)
} | go | func (h *SMTPAPIHeader) AddCategory(category string) {
h.Category = append(h.Category, category)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddCategory",
"(",
"category",
"string",
")",
"{",
"h",
".",
"Category",
"=",
"append",
"(",
"h",
".",
"Category",
",",
"category",
")",
"\n",
"}"
] | // AddCategory adds a new category to the Category header | [
"AddCategory",
"adds",
"a",
"new",
"category",
"to",
"the",
"Category",
"header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L91-L93 |
776 | sendgrid/smtpapi-go | smtpapi.go | AddCategories | func (h *SMTPAPIHeader) AddCategories(categories []string) {
for i := 0; i < len(categories); i++ {
h.AddCategory(categories[i])
}
} | go | func (h *SMTPAPIHeader) AddCategories(categories []string) {
for i := 0; i < len(categories); i++ {
h.AddCategory(categories[i])
}
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddCategories",
"(",
"categories",
"[",
"]",
"string",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"categories",
")",
";",
"i",
"++",
"{",
"h",
".",
"AddCategory",
"(",
"categories",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // AddCategories adds multiple categories to the Category header | [
"AddCategories",
"adds",
"multiple",
"categories",
"to",
"the",
"Category",
"header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L96-L100 |
777 | sendgrid/smtpapi-go | smtpapi.go | AddASMGroupToDisplay | func (h *SMTPAPIHeader) AddASMGroupToDisplay(groupID int) {
h.ASMGroups = append(h.ASMGroups, groupID)
} | go | func (h *SMTPAPIHeader) AddASMGroupToDisplay(groupID int) {
h.ASMGroups = append(h.ASMGroups, groupID)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddASMGroupToDisplay",
"(",
"groupID",
"int",
")",
"{",
"h",
".",
"ASMGroups",
"=",
"append",
"(",
"h",
".",
"ASMGroups",
",",
"groupID",
")",
"\n",
"}"
] | // AddASMGroupToDisplay adds a new ASM group ID to be displayed | [
"AddASMGroupToDisplay",
"adds",
"a",
"new",
"ASM",
"group",
"ID",
"to",
"be",
"displayed"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L113-L115 |
778 | sendgrid/smtpapi-go | smtpapi.go | AddASMGroupsToDisplay | func (h *SMTPAPIHeader) AddASMGroupsToDisplay(groupIDs []int) {
for i := 0; i < len(groupIDs); i++ {
h.AddASMGroupToDisplay(groupIDs[i])
}
} | go | func (h *SMTPAPIHeader) AddASMGroupsToDisplay(groupIDs []int) {
for i := 0; i < len(groupIDs); i++ {
h.AddASMGroupToDisplay(groupIDs[i])
}
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddASMGroupsToDisplay",
"(",
"groupIDs",
"[",
"]",
"int",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"groupIDs",
")",
";",
"i",
"++",
"{",
"h",
".",
"AddASMGroupToDisplay",
"(",
"groupIDs",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // AddASMGroupsToDisplay adds multiple ASM group IDs to be displayed | [
"AddASMGroupsToDisplay",
"adds",
"multiple",
"ASM",
"group",
"IDs",
"to",
"be",
"displayed"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L118-L122 |
779 | sendgrid/smtpapi-go | smtpapi.go | AddUniqueArg | func (h *SMTPAPIHeader) AddUniqueArg(arg, value string) {
if h.UniqueArgs == nil {
h.UniqueArgs = make(map[string]string)
}
h.UniqueArgs[arg] = value
} | go | func (h *SMTPAPIHeader) AddUniqueArg(arg, value string) {
if h.UniqueArgs == nil {
h.UniqueArgs = make(map[string]string)
}
h.UniqueArgs[arg] = value
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddUniqueArg",
"(",
"arg",
",",
"value",
"string",
")",
"{",
"if",
"h",
".",
"UniqueArgs",
"==",
"nil",
"{",
"h",
".",
"UniqueArgs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n",
"h",
".",
"UniqueArgs",
"[",
"arg",
"]",
"=",
"value",
"\n",
"}"
] | // AddUniqueArg will set the value of a specific argument | [
"AddUniqueArg",
"will",
"set",
"the",
"value",
"of",
"a",
"specific",
"argument"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L130-L135 |
780 | sendgrid/smtpapi-go | smtpapi.go | AddFilter | func (h *SMTPAPIHeader) AddFilter(filter, setting string, value interface{}) {
if h.Filters == nil {
h.Filters = make(map[string]Filter)
}
if _, ok := h.Filters[filter]; !ok {
h.Filters[filter] = Filter{
Settings: make(map[string]interface{}),
}
}
h.Filters[filter].Settings[setting] = value
} | go | func (h *SMTPAPIHeader) AddFilter(filter, setting string, value interface{}) {
if h.Filters == nil {
h.Filters = make(map[string]Filter)
}
if _, ok := h.Filters[filter]; !ok {
h.Filters[filter] = Filter{
Settings: make(map[string]interface{}),
}
}
h.Filters[filter].Settings[setting] = value
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddFilter",
"(",
"filter",
",",
"setting",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"if",
"h",
".",
"Filters",
"==",
"nil",
"{",
"h",
".",
"Filters",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"Filter",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"h",
".",
"Filters",
"[",
"filter",
"]",
";",
"!",
"ok",
"{",
"h",
".",
"Filters",
"[",
"filter",
"]",
"=",
"Filter",
"{",
"Settings",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"}",
"\n",
"}",
"\n",
"h",
".",
"Filters",
"[",
"filter",
"]",
".",
"Settings",
"[",
"setting",
"]",
"=",
"value",
"\n",
"}"
] | // AddFilter will set the specific setting for a filter | [
"AddFilter",
"will",
"set",
"the",
"specific",
"setting",
"for",
"a",
"filter"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L143-L153 |
781 | sendgrid/smtpapi-go | smtpapi.go | SetFilter | func (h *SMTPAPIHeader) SetFilter(filter string, value *Filter) {
if h.Filters == nil {
h.Filters = make(map[string]Filter)
}
h.Filters[filter] = *value
} | go | func (h *SMTPAPIHeader) SetFilter(filter string, value *Filter) {
if h.Filters == nil {
h.Filters = make(map[string]Filter)
}
h.Filters[filter] = *value
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"SetFilter",
"(",
"filter",
"string",
",",
"value",
"*",
"Filter",
")",
"{",
"if",
"h",
".",
"Filters",
"==",
"nil",
"{",
"h",
".",
"Filters",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"Filter",
")",
"\n",
"}",
"\n",
"h",
".",
"Filters",
"[",
"filter",
"]",
"=",
"*",
"value",
"\n",
"}"
] | // SetFilter takes in a Filter struct with predetermined settings and sets it for such Filter key | [
"SetFilter",
"takes",
"in",
"a",
"Filter",
"struct",
"with",
"predetermined",
"settings",
"and",
"sets",
"it",
"for",
"such",
"Filter",
"key"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L156-L161 |
782 | sendgrid/smtpapi-go | smtpapi.go | AddSendEachAt | func (h *SMTPAPIHeader) AddSendEachAt(sendEachAt int64) {
h.SendEachAt = append(h.SendEachAt, sendEachAt)
} | go | func (h *SMTPAPIHeader) AddSendEachAt(sendEachAt int64) {
h.SendEachAt = append(h.SendEachAt, sendEachAt)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"AddSendEachAt",
"(",
"sendEachAt",
"int64",
")",
"{",
"h",
".",
"SendEachAt",
"=",
"append",
"(",
"h",
".",
"SendEachAt",
",",
"sendEachAt",
")",
"\n",
"}"
] | // AddSendEachAt takes in a timestamp and pushes it into a list Must match length of To emails | [
"AddSendEachAt",
"takes",
"in",
"a",
"timestamp",
"and",
"pushes",
"it",
"into",
"a",
"list",
"Must",
"match",
"length",
"of",
"To",
"emails"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L169-L171 |
783 | sendgrid/smtpapi-go | smtpapi.go | JSONString | func (h *SMTPAPIHeader) JSONString() (string, error) {
headers, e := json.Marshal(h)
return escapeUnicode(string(headers)), e
} | go | func (h *SMTPAPIHeader) JSONString() (string, error) {
headers, e := json.Marshal(h)
return escapeUnicode(string(headers)), e
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"JSONString",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"headers",
",",
"e",
":=",
"json",
".",
"Marshal",
"(",
"h",
")",
"\n",
"return",
"escapeUnicode",
"(",
"string",
"(",
"headers",
")",
")",
",",
"e",
"\n",
"}"
] | // JSONString returns the representation of the Header | [
"JSONString",
"returns",
"the",
"representation",
"of",
"the",
"Header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L208-L211 |
784 | sendgrid/smtpapi-go | smtpapi.go | Load | func (h *SMTPAPIHeader) Load(b []byte) error {
return json.Unmarshal(b, h)
} | go | func (h *SMTPAPIHeader) Load(b []byte) error {
return json.Unmarshal(b, h)
} | [
"func",
"(",
"h",
"*",
"SMTPAPIHeader",
")",
"Load",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"h",
")",
"\n",
"}"
] | // Load allows you to load a pre-formed x-smtpapi header | [
"Load",
"allows",
"you",
"to",
"load",
"a",
"pre",
"-",
"formed",
"x",
"-",
"smtpapi",
"header"
] | 19dcc8e7295405650578c35fb82557487b86488f | https://github.com/sendgrid/smtpapi-go/blob/19dcc8e7295405650578c35fb82557487b86488f/smtpapi.go#L214-L216 |
785 | go-chi/cors | cors.go | handlePreflight | func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
origin := r.Header.Get("Origin")
if r.Method != "OPTIONS" {
c.logf("Preflight aborted: %s!=OPTIONS", r.Method)
return
}
// Always set Vary headers
// see https://github.com/rs/cors/issues/10,
// https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
headers.Add("Vary", "Origin")
headers.Add("Vary", "Access-Control-Request-Method")
headers.Add("Vary", "Access-Control-Request-Headers")
if origin == "" {
c.logf("Preflight aborted: empty origin")
return
}
if !c.isOriginAllowed(r, origin) {
c.logf("Preflight aborted: origin '%s' not allowed", origin)
return
}
reqMethod := r.Header.Get("Access-Control-Request-Method")
if !c.isMethodAllowed(reqMethod) {
c.logf("Preflight aborted: method '%s' not allowed", reqMethod)
return
}
reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
if !c.areHeadersAllowed(reqHeaders) {
c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
return
}
headers.Set("Access-Control-Allow-Origin", origin)
// Spec says: Since the list of methods can be unbounded, simply returning the method indicated
// by Access-Control-Request-Method (if supported) can be enough
headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
if len(reqHeaders) > 0 {
// Spec says: Since the list of headers can be unbounded, simply returning supported headers
// from Access-Control-Request-Headers can be enough
headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
}
if c.allowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
if c.maxAge > 0 {
headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
}
c.logf("Preflight response headers: %v", headers)
} | go | func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
origin := r.Header.Get("Origin")
if r.Method != "OPTIONS" {
c.logf("Preflight aborted: %s!=OPTIONS", r.Method)
return
}
// Always set Vary headers
// see https://github.com/rs/cors/issues/10,
// https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
headers.Add("Vary", "Origin")
headers.Add("Vary", "Access-Control-Request-Method")
headers.Add("Vary", "Access-Control-Request-Headers")
if origin == "" {
c.logf("Preflight aborted: empty origin")
return
}
if !c.isOriginAllowed(r, origin) {
c.logf("Preflight aborted: origin '%s' not allowed", origin)
return
}
reqMethod := r.Header.Get("Access-Control-Request-Method")
if !c.isMethodAllowed(reqMethod) {
c.logf("Preflight aborted: method '%s' not allowed", reqMethod)
return
}
reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
if !c.areHeadersAllowed(reqHeaders) {
c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
return
}
headers.Set("Access-Control-Allow-Origin", origin)
// Spec says: Since the list of methods can be unbounded, simply returning the method indicated
// by Access-Control-Request-Method (if supported) can be enough
headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
if len(reqHeaders) > 0 {
// Spec says: Since the list of headers can be unbounded, simply returning supported headers
// from Access-Control-Request-Headers can be enough
headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
}
if c.allowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
if c.maxAge > 0 {
headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
}
c.logf("Preflight response headers: %v", headers)
} | [
"func",
"(",
"c",
"*",
"Cors",
")",
"handlePreflight",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"headers",
":=",
"w",
".",
"Header",
"(",
")",
"\n",
"origin",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Always set Vary headers",
"// see https://github.com/rs/cors/issues/10,",
"// https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001",
"headers",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"headers",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"headers",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"origin",
"==",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"isOriginAllowed",
"(",
"r",
",",
"origin",
")",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"origin",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"reqMethod",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"c",
".",
"isMethodAllowed",
"(",
"reqMethod",
")",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"reqMethod",
")",
"\n",
"return",
"\n",
"}",
"\n",
"reqHeaders",
":=",
"parseHeaderList",
"(",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"!",
"c",
".",
"areHeadersAllowed",
"(",
"reqHeaders",
")",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"reqHeaders",
")",
"\n",
"return",
"\n",
"}",
"\n",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"origin",
")",
"\n",
"// Spec says: Since the list of methods can be unbounded, simply returning the method indicated",
"// by Access-Control-Request-Method (if supported) can be enough",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"ToUpper",
"(",
"reqMethod",
")",
")",
"\n",
"if",
"len",
"(",
"reqHeaders",
")",
">",
"0",
"{",
"// Spec says: Since the list of headers can be unbounded, simply returning supported headers",
"// from Access-Control-Request-Headers can be enough",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"reqHeaders",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"allowCredentials",
"{",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"maxAge",
">",
"0",
"{",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"c",
".",
"maxAge",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"headers",
")",
"\n",
"}"
] | // handlePreflight handles pre-flight CORS requests | [
"handlePreflight",
"handles",
"pre",
"-",
"flight",
"CORS",
"requests"
] | 07727c846d14299758e54a275dd8c81353c01960 | https://github.com/go-chi/cors/blob/07727c846d14299758e54a275dd8c81353c01960/cors.go#L207-L258 |
786 | go-chi/cors | cors.go | handleActualRequest | func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
origin := r.Header.Get("Origin")
if r.Method == "OPTIONS" {
c.logf("Actual request no headers added: method == %s", r.Method)
return
}
// Always set Vary, see https://github.com/rs/cors/issues/10
headers.Add("Vary", "Origin")
if origin == "" {
c.logf("Actual request no headers added: missing origin")
return
}
if !c.isOriginAllowed(r, origin) {
c.logf("Actual request no headers added: origin '%s' not allowed", origin)
return
}
// Note that spec does define a way to specifically disallow a simple method like GET or
// POST. Access-Control-Allow-Methods is only used for pre-flight requests and the
// spec doesn't instruct to check the allowed methods for simple cross-origin requests.
// We think it's a nice feature to be able to have control on those methods though.
if !c.isMethodAllowed(r.Method) {
if c.log != nil {
c.logf("Actual request no headers added: method '%s' not allowed",
r.Method)
}
return
}
headers.Set("Access-Control-Allow-Origin", origin)
if len(c.exposedHeaders) > 0 {
headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", "))
}
if c.allowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
c.logf("Actual response added headers: %v", headers)
} | go | func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
origin := r.Header.Get("Origin")
if r.Method == "OPTIONS" {
c.logf("Actual request no headers added: method == %s", r.Method)
return
}
// Always set Vary, see https://github.com/rs/cors/issues/10
headers.Add("Vary", "Origin")
if origin == "" {
c.logf("Actual request no headers added: missing origin")
return
}
if !c.isOriginAllowed(r, origin) {
c.logf("Actual request no headers added: origin '%s' not allowed", origin)
return
}
// Note that spec does define a way to specifically disallow a simple method like GET or
// POST. Access-Control-Allow-Methods is only used for pre-flight requests and the
// spec doesn't instruct to check the allowed methods for simple cross-origin requests.
// We think it's a nice feature to be able to have control on those methods though.
if !c.isMethodAllowed(r.Method) {
if c.log != nil {
c.logf("Actual request no headers added: method '%s' not allowed",
r.Method)
}
return
}
headers.Set("Access-Control-Allow-Origin", origin)
if len(c.exposedHeaders) > 0 {
headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", "))
}
if c.allowCredentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
c.logf("Actual response added headers: %v", headers)
} | [
"func",
"(",
"c",
"*",
"Cors",
")",
"handleActualRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"headers",
":=",
"w",
".",
"Header",
"(",
")",
"\n",
"origin",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Always set Vary, see https://github.com/rs/cors/issues/10",
"headers",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"origin",
"==",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"isOriginAllowed",
"(",
"r",
",",
"origin",
")",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"origin",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Note that spec does define a way to specifically disallow a simple method like GET or",
"// POST. Access-Control-Allow-Methods is only used for pre-flight requests and the",
"// spec doesn't instruct to check the allowed methods for simple cross-origin requests.",
"// We think it's a nice feature to be able to have control on those methods though.",
"if",
"!",
"c",
".",
"isMethodAllowed",
"(",
"r",
".",
"Method",
")",
"{",
"if",
"c",
".",
"log",
"!=",
"nil",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"origin",
")",
"\n",
"if",
"len",
"(",
"c",
".",
"exposedHeaders",
")",
">",
"0",
"{",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"c",
".",
"exposedHeaders",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"allowCredentials",
"{",
"headers",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"c",
".",
"logf",
"(",
"\"",
"\"",
",",
"headers",
")",
"\n",
"}"
] | // handleActualRequest handles simple cross-origin requests, actual request or redirects | [
"handleActualRequest",
"handles",
"simple",
"cross",
"-",
"origin",
"requests",
"actual",
"request",
"or",
"redirects"
] | 07727c846d14299758e54a275dd8c81353c01960 | https://github.com/go-chi/cors/blob/07727c846d14299758e54a275dd8c81353c01960/cors.go#L261-L300 |
787 | go-chi/cors | cors.go | isOriginAllowed | func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
if c.allowOriginFunc != nil {
return c.allowOriginFunc(r, origin)
}
if c.allowedOriginsAll {
return true
}
origin = strings.ToLower(origin)
for _, o := range c.allowedOrigins {
if o == origin {
return true
}
}
for _, w := range c.allowedWOrigins {
if w.match(origin) {
return true
}
}
return false
} | go | func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
if c.allowOriginFunc != nil {
return c.allowOriginFunc(r, origin)
}
if c.allowedOriginsAll {
return true
}
origin = strings.ToLower(origin)
for _, o := range c.allowedOrigins {
if o == origin {
return true
}
}
for _, w := range c.allowedWOrigins {
if w.match(origin) {
return true
}
}
return false
} | [
"func",
"(",
"c",
"*",
"Cors",
")",
"isOriginAllowed",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"origin",
"string",
")",
"bool",
"{",
"if",
"c",
".",
"allowOriginFunc",
"!=",
"nil",
"{",
"return",
"c",
".",
"allowOriginFunc",
"(",
"r",
",",
"origin",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"allowedOriginsAll",
"{",
"return",
"true",
"\n",
"}",
"\n",
"origin",
"=",
"strings",
".",
"ToLower",
"(",
"origin",
")",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"c",
".",
"allowedOrigins",
"{",
"if",
"o",
"==",
"origin",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"c",
".",
"allowedWOrigins",
"{",
"if",
"w",
".",
"match",
"(",
"origin",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isOriginAllowed checks if a given origin is allowed to perform cross-domain requests
// on the endpoint | [
"isOriginAllowed",
"checks",
"if",
"a",
"given",
"origin",
"is",
"allowed",
"to",
"perform",
"cross",
"-",
"domain",
"requests",
"on",
"the",
"endpoint"
] | 07727c846d14299758e54a275dd8c81353c01960 | https://github.com/go-chi/cors/blob/07727c846d14299758e54a275dd8c81353c01960/cors.go#L311-L330 |
788 | go-chi/cors | cors.go | isMethodAllowed | func (c *Cors) isMethodAllowed(method string) bool {
if len(c.allowedMethods) == 0 {
// If no method allowed, always return false, even for preflight request
return false
}
method = strings.ToUpper(method)
if method == "OPTIONS" {
// Always allow preflight requests
return true
}
for _, m := range c.allowedMethods {
if m == method {
return true
}
}
return false
} | go | func (c *Cors) isMethodAllowed(method string) bool {
if len(c.allowedMethods) == 0 {
// If no method allowed, always return false, even for preflight request
return false
}
method = strings.ToUpper(method)
if method == "OPTIONS" {
// Always allow preflight requests
return true
}
for _, m := range c.allowedMethods {
if m == method {
return true
}
}
return false
} | [
"func",
"(",
"c",
"*",
"Cors",
")",
"isMethodAllowed",
"(",
"method",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"c",
".",
"allowedMethods",
")",
"==",
"0",
"{",
"// If no method allowed, always return false, even for preflight request",
"return",
"false",
"\n",
"}",
"\n",
"method",
"=",
"strings",
".",
"ToUpper",
"(",
"method",
")",
"\n",
"if",
"method",
"==",
"\"",
"\"",
"{",
"// Always allow preflight requests",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"c",
".",
"allowedMethods",
"{",
"if",
"m",
"==",
"method",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isMethodAllowed checks if a given method can be used as part of a cross-domain request
// on the endpoing | [
"isMethodAllowed",
"checks",
"if",
"a",
"given",
"method",
"can",
"be",
"used",
"as",
"part",
"of",
"a",
"cross",
"-",
"domain",
"request",
"on",
"the",
"endpoing"
] | 07727c846d14299758e54a275dd8c81353c01960 | https://github.com/go-chi/cors/blob/07727c846d14299758e54a275dd8c81353c01960/cors.go#L334-L350 |
789 | turnage/graw | reddit/loader.go | loadAgentFile | func loadAgentFile(filename string) (*redditproto.UserAgent, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
agent := &redditproto.UserAgent{}
return agent, proto.UnmarshalText(bytes.NewBuffer(buf).String(), agent)
} | go | func loadAgentFile(filename string) (*redditproto.UserAgent, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
agent := &redditproto.UserAgent{}
return agent, proto.UnmarshalText(bytes.NewBuffer(buf).String(), agent)
} | [
"func",
"loadAgentFile",
"(",
"filename",
"string",
")",
"(",
"*",
"redditproto",
".",
"UserAgent",
",",
"error",
")",
"{",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"agent",
":=",
"&",
"redditproto",
".",
"UserAgent",
"{",
"}",
"\n",
"return",
"agent",
",",
"proto",
".",
"UnmarshalText",
"(",
"bytes",
".",
"NewBuffer",
"(",
"buf",
")",
".",
"String",
"(",
")",
",",
"agent",
")",
"\n",
"}"
] | // loadAgentFile reads a user agent from a protobuffer file and returns it. | [
"loadAgentFile",
"reads",
"a",
"user",
"agent",
"from",
"a",
"protobuffer",
"file",
"and",
"returns",
"it",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/reddit/loader.go#L24-L32 |
790 | turnage/graw | streams/internal/monitor/monitor.go | New | func New(c Config) (Monitor, error) {
m := &monitor{
tip: []string{""},
path: c.Path,
scanner: c.Scanner,
sorter: c.Sorter,
}
if err := m.sync(); err != nil {
return nil, err
}
return m, nil
} | go | func New(c Config) (Monitor, error) {
m := &monitor{
tip: []string{""},
path: c.Path,
scanner: c.Scanner,
sorter: c.Sorter,
}
if err := m.sync(); err != nil {
return nil, err
}
return m, nil
} | [
"func",
"New",
"(",
"c",
"Config",
")",
"(",
"Monitor",
",",
"error",
")",
"{",
"m",
":=",
"&",
"monitor",
"{",
"tip",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"path",
":",
"c",
".",
"Path",
",",
"scanner",
":",
"c",
".",
"Scanner",
",",
"sorter",
":",
"c",
".",
"Sorter",
",",
"}",
"\n\n",
"if",
"err",
":=",
"m",
".",
"sync",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // New provides a monitor for the listing endpoint. | [
"New",
"provides",
"a",
"monitor",
"for",
"the",
"listing",
"endpoint",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L61-L74 |
791 | turnage/graw | streams/internal/monitor/monitor.go | Update | func (m *monitor) Update() (reddit.Harvest, error) {
if m.blanks > blankThreshold {
return reddit.Harvest{}, m.fixTip()
}
names, harvest, err := m.harvest(m.tip[0])
m.updateTip(names)
return harvest, err
} | go | func (m *monitor) Update() (reddit.Harvest, error) {
if m.blanks > blankThreshold {
return reddit.Harvest{}, m.fixTip()
}
names, harvest, err := m.harvest(m.tip[0])
m.updateTip(names)
return harvest, err
} | [
"func",
"(",
"m",
"*",
"monitor",
")",
"Update",
"(",
")",
"(",
"reddit",
".",
"Harvest",
",",
"error",
")",
"{",
"if",
"m",
".",
"blanks",
">",
"blankThreshold",
"{",
"return",
"reddit",
".",
"Harvest",
"{",
"}",
",",
"m",
".",
"fixTip",
"(",
")",
"\n",
"}",
"\n\n",
"names",
",",
"harvest",
",",
"err",
":=",
"m",
".",
"harvest",
"(",
"m",
".",
"tip",
"[",
"0",
"]",
")",
"\n",
"m",
".",
"updateTip",
"(",
"names",
")",
"\n",
"return",
"harvest",
",",
"err",
"\n",
"}"
] | // Update checks for new content at the monitored listing endpoint and forwards
// new content to the bot for processing. | [
"Update",
"checks",
"for",
"new",
"content",
"at",
"the",
"monitored",
"listing",
"endpoint",
"and",
"forwards",
"new",
"content",
"to",
"the",
"bot",
"for",
"processing",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L78-L86 |
792 | turnage/graw | streams/internal/monitor/monitor.go | harvest | func (m *monitor) harvest(ref string) ([]string, reddit.Harvest, error) {
h, err := m.scanner.Listing(m.path, ref)
return m.sorter.Sort(h), h, err
} | go | func (m *monitor) harvest(ref string) ([]string, reddit.Harvest, error) {
h, err := m.scanner.Listing(m.path, ref)
return m.sorter.Sort(h), h, err
} | [
"func",
"(",
"m",
"*",
"monitor",
")",
"harvest",
"(",
"ref",
"string",
")",
"(",
"[",
"]",
"string",
",",
"reddit",
".",
"Harvest",
",",
"error",
")",
"{",
"h",
",",
"err",
":=",
"m",
".",
"scanner",
".",
"Listing",
"(",
"m",
".",
"path",
",",
"ref",
")",
"\n",
"return",
"m",
".",
"sorter",
".",
"Sort",
"(",
"h",
")",
",",
"h",
",",
"err",
"\n",
"}"
] | // harvest fetches from the listing any posts after the given reference post,
// and returns those posts and a reverse chronologically sorted list of their
// names. | [
"harvest",
"fetches",
"from",
"the",
"listing",
"any",
"posts",
"after",
"the",
"given",
"reference",
"post",
"and",
"returns",
"those",
"posts",
"and",
"a",
"reverse",
"chronologically",
"sorted",
"list",
"of",
"their",
"names",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L91-L94 |
793 | turnage/graw | streams/internal/monitor/monitor.go | sync | func (m *monitor) sync() error {
names, _, err := m.harvest("")
if len(names) > 0 {
m.tip = names
} else {
m.tip = defaultTip
}
return err
} | go | func (m *monitor) sync() error {
names, _, err := m.harvest("")
if len(names) > 0 {
m.tip = names
} else {
m.tip = defaultTip
}
return err
} | [
"func",
"(",
"m",
"*",
"monitor",
")",
"sync",
"(",
")",
"error",
"{",
"names",
",",
"_",
",",
"err",
":=",
"m",
".",
"harvest",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"names",
")",
">",
"0",
"{",
"m",
".",
"tip",
"=",
"names",
"\n",
"}",
"else",
"{",
"m",
".",
"tip",
"=",
"defaultTip",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // sync fetches the current tip of a listing endpoint, so that grawbots crawling
// forward in time don't treat it as a new post, or reprocess it when restarted. | [
"sync",
"fetches",
"the",
"current",
"tip",
"of",
"a",
"listing",
"endpoint",
"so",
"that",
"grawbots",
"crawling",
"forward",
"in",
"time",
"don",
"t",
"treat",
"it",
"as",
"a",
"new",
"post",
"or",
"reprocess",
"it",
"when",
"restarted",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L98-L106 |
794 | turnage/graw | streams/internal/monitor/monitor.go | updateTip | func (m *monitor) updateTip(names []string) {
if len(names) > 0 {
m.blanks = 0
} else {
m.blanks++
}
m.tip = append(names, m.tip...)
if len(m.tip) > maxTipSize {
m.tip = m.tip[0:maxTipSize]
}
} | go | func (m *monitor) updateTip(names []string) {
if len(names) > 0 {
m.blanks = 0
} else {
m.blanks++
}
m.tip = append(names, m.tip...)
if len(m.tip) > maxTipSize {
m.tip = m.tip[0:maxTipSize]
}
} | [
"func",
"(",
"m",
"*",
"monitor",
")",
"updateTip",
"(",
"names",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"names",
")",
">",
"0",
"{",
"m",
".",
"blanks",
"=",
"0",
"\n",
"}",
"else",
"{",
"m",
".",
"blanks",
"++",
"\n",
"}",
"\n\n",
"m",
".",
"tip",
"=",
"append",
"(",
"names",
",",
"m",
".",
"tip",
"...",
")",
"\n",
"if",
"len",
"(",
"m",
".",
"tip",
")",
">",
"maxTipSize",
"{",
"m",
".",
"tip",
"=",
"m",
".",
"tip",
"[",
"0",
":",
"maxTipSize",
"]",
"\n",
"}",
"\n",
"}"
] | // updateTip updates the monitor's list of names from the endpoint listing it
// uses to keep track of its position in the monitored listing. | [
"updateTip",
"updates",
"the",
"monitor",
"s",
"list",
"of",
"names",
"from",
"the",
"endpoint",
"listing",
"it",
"uses",
"to",
"keep",
"track",
"of",
"its",
"position",
"in",
"the",
"monitored",
"listing",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L110-L121 |
795 | turnage/graw | streams/internal/monitor/monitor.go | fixTip | func (m *monitor) fixTip() error {
names, _, err := m.harvest(m.tip[len(m.tip)-1])
if err != nil {
return err
}
// If none of our backup tips were returned, most likely the last backup
// tip is dead and this check was meaningless.
if len(names) == 0 {
m.tip = m.tip[:len(m.tip)-1]
if len(m.tip) == 0 {
m.tip = defaultTip
}
return nil
}
// n^2 because your cycles don't matter to me & n <= maxTipSize
for i := 0; i < len(m.tip)-1; i++ {
alive := false
for _, n := range names {
if m.tip[i] == n {
alive = true
}
}
if !alive {
m.tip = append(m.tip[:i], m.tip[i+1:]...)
}
}
m.blanks = 0
return nil
} | go | func (m *monitor) fixTip() error {
names, _, err := m.harvest(m.tip[len(m.tip)-1])
if err != nil {
return err
}
// If none of our backup tips were returned, most likely the last backup
// tip is dead and this check was meaningless.
if len(names) == 0 {
m.tip = m.tip[:len(m.tip)-1]
if len(m.tip) == 0 {
m.tip = defaultTip
}
return nil
}
// n^2 because your cycles don't matter to me & n <= maxTipSize
for i := 0; i < len(m.tip)-1; i++ {
alive := false
for _, n := range names {
if m.tip[i] == n {
alive = true
}
}
if !alive {
m.tip = append(m.tip[:i], m.tip[i+1:]...)
}
}
m.blanks = 0
return nil
} | [
"func",
"(",
"m",
"*",
"monitor",
")",
"fixTip",
"(",
")",
"error",
"{",
"names",
",",
"_",
",",
"err",
":=",
"m",
".",
"harvest",
"(",
"m",
".",
"tip",
"[",
"len",
"(",
"m",
".",
"tip",
")",
"-",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If none of our backup tips were returned, most likely the last backup",
"// tip is dead and this check was meaningless.",
"if",
"len",
"(",
"names",
")",
"==",
"0",
"{",
"m",
".",
"tip",
"=",
"m",
".",
"tip",
"[",
":",
"len",
"(",
"m",
".",
"tip",
")",
"-",
"1",
"]",
"\n",
"if",
"len",
"(",
"m",
".",
"tip",
")",
"==",
"0",
"{",
"m",
".",
"tip",
"=",
"defaultTip",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// n^2 because your cycles don't matter to me & n <= maxTipSize",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"m",
".",
"tip",
")",
"-",
"1",
";",
"i",
"++",
"{",
"alive",
":=",
"false",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"names",
"{",
"if",
"m",
".",
"tip",
"[",
"i",
"]",
"==",
"n",
"{",
"alive",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"alive",
"{",
"m",
".",
"tip",
"=",
"append",
"(",
"m",
".",
"tip",
"[",
":",
"i",
"]",
",",
"m",
".",
"tip",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"m",
".",
"blanks",
"=",
"0",
"\n",
"return",
"nil",
"\n",
"}"
] | // fixTip checks all of the stored backup tips for health. If the post at the
// front has been deleted or caught in a spam filter, the feed will die and we
// will stop getting posts. This will adjust backward if a tip is dead and
// remove any other dead tips in the list. Returns whether the tip was broken. | [
"fixTip",
"checks",
"all",
"of",
"the",
"stored",
"backup",
"tips",
"for",
"health",
".",
"If",
"the",
"post",
"at",
"the",
"front",
"has",
"been",
"deleted",
"or",
"caught",
"in",
"a",
"spam",
"filter",
"the",
"feed",
"will",
"die",
"and",
"we",
"will",
"stop",
"getting",
"posts",
".",
"This",
"will",
"adjust",
"backward",
"if",
"a",
"tip",
"is",
"dead",
"and",
"remove",
"any",
"other",
"dead",
"tips",
"in",
"the",
"list",
".",
"Returns",
"whether",
"the",
"tip",
"was",
"broken",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/monitor/monitor.go#L127-L158 |
796 | turnage/graw | streams/internal/rsort/rsort.go | sortHarvest | func sortHarvest(h reddit.Harvest) []string {
things := merge(
postsAsThings(h.Posts),
commentsAsThings(h.Comments),
messagesAsThings(h.Messages),
)
sort.Sort(byCreationTime{things})
names := make([]string, len(things))
for i, t := range things {
names[i] = t.Name()
}
return names
} | go | func sortHarvest(h reddit.Harvest) []string {
things := merge(
postsAsThings(h.Posts),
commentsAsThings(h.Comments),
messagesAsThings(h.Messages),
)
sort.Sort(byCreationTime{things})
names := make([]string, len(things))
for i, t := range things {
names[i] = t.Name()
}
return names
} | [
"func",
"sortHarvest",
"(",
"h",
"reddit",
".",
"Harvest",
")",
"[",
"]",
"string",
"{",
"things",
":=",
"merge",
"(",
"postsAsThings",
"(",
"h",
".",
"Posts",
")",
",",
"commentsAsThings",
"(",
"h",
".",
"Comments",
")",
",",
"messagesAsThings",
"(",
"h",
".",
"Messages",
")",
",",
")",
"\n",
"sort",
".",
"Sort",
"(",
"byCreationTime",
"{",
"things",
"}",
")",
"\n\n",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"things",
")",
")",
"\n",
"for",
"i",
",",
"t",
":=",
"range",
"things",
"{",
"names",
"[",
"i",
"]",
"=",
"t",
".",
"Name",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"names",
"\n",
"}"
] | // sortHarvest returns the list of names of Reddit elements in a harvest sorted
// by creation time to the younger elements appear first in the slice. | [
"sortHarvest",
"returns",
"the",
"list",
"of",
"names",
"of",
"Reddit",
"elements",
"in",
"a",
"harvest",
"sorted",
"by",
"creation",
"time",
"to",
"the",
"younger",
"elements",
"appear",
"first",
"in",
"the",
"slice",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/streams/internal/rsort/rsort.go#L40-L54 |
797 | turnage/graw | reddit/data.go | IsTopLevel | func (c *Comment) IsTopLevel() bool {
parentType := strings.Split(c.ParentID, "_")[0]
return parentType == postKind
} | go | func (c *Comment) IsTopLevel() bool {
parentType := strings.Split(c.ParentID, "_")[0]
return parentType == postKind
} | [
"func",
"(",
"c",
"*",
"Comment",
")",
"IsTopLevel",
"(",
")",
"bool",
"{",
"parentType",
":=",
"strings",
".",
"Split",
"(",
"c",
".",
"ParentID",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
"\n",
"return",
"parentType",
"==",
"postKind",
"\n",
"}"
] | // IsTopLevel is true when the comment is a top level comment. | [
"IsTopLevel",
"is",
"true",
"when",
"the",
"comment",
"is",
"a",
"top",
"level",
"comment",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/reddit/data.go#L41-L44 |
798 | turnage/graw | scan.go | connectScanStreams | func connectScanStreams(
handler interface{},
sc reddit.Scanner,
c Config,
kill <-chan bool,
errs chan<- error,
) error {
if len(c.Subreddits) > 0 {
ph, ok := handler.(botfaces.PostHandler)
if !ok {
return postHandlerErr
}
if posts, err := streams.Subreddits(
sc,
kill,
errs,
c.Subreddits...,
); err != nil {
return err
} else {
go func() {
for p := range posts {
errs <- ph.Post(p)
}
}()
}
}
if len(c.SubredditComments) > 0 {
ch, ok := handler.(botfaces.CommentHandler)
if !ok {
return commentHandlerErr
}
if comments, err := streams.SubredditComments(
sc,
kill,
errs,
c.SubredditComments...,
); err != nil {
return err
} else {
go func() {
for c := range comments {
errs <- ch.Comment(c)
}
}()
}
}
if len(c.Users) > 0 {
uh, ok := handler.(botfaces.UserHandler)
if !ok {
return userHandlerErr
}
for _, user := range c.Users {
if posts, comments, err := streams.User(
sc,
kill,
errs,
user,
); err != nil {
return err
} else {
go func() {
for p := range posts {
errs <- uh.UserPost(p)
}
}()
go func() {
for c := range comments {
errs <- uh.UserComment(c)
}
}()
}
}
}
return nil
} | go | func connectScanStreams(
handler interface{},
sc reddit.Scanner,
c Config,
kill <-chan bool,
errs chan<- error,
) error {
if len(c.Subreddits) > 0 {
ph, ok := handler.(botfaces.PostHandler)
if !ok {
return postHandlerErr
}
if posts, err := streams.Subreddits(
sc,
kill,
errs,
c.Subreddits...,
); err != nil {
return err
} else {
go func() {
for p := range posts {
errs <- ph.Post(p)
}
}()
}
}
if len(c.SubredditComments) > 0 {
ch, ok := handler.(botfaces.CommentHandler)
if !ok {
return commentHandlerErr
}
if comments, err := streams.SubredditComments(
sc,
kill,
errs,
c.SubredditComments...,
); err != nil {
return err
} else {
go func() {
for c := range comments {
errs <- ch.Comment(c)
}
}()
}
}
if len(c.Users) > 0 {
uh, ok := handler.(botfaces.UserHandler)
if !ok {
return userHandlerErr
}
for _, user := range c.Users {
if posts, comments, err := streams.User(
sc,
kill,
errs,
user,
); err != nil {
return err
} else {
go func() {
for p := range posts {
errs <- uh.UserPost(p)
}
}()
go func() {
for c := range comments {
errs <- uh.UserComment(c)
}
}()
}
}
}
return nil
} | [
"func",
"connectScanStreams",
"(",
"handler",
"interface",
"{",
"}",
",",
"sc",
"reddit",
".",
"Scanner",
",",
"c",
"Config",
",",
"kill",
"<-",
"chan",
"bool",
",",
"errs",
"chan",
"<-",
"error",
",",
")",
"error",
"{",
"if",
"len",
"(",
"c",
".",
"Subreddits",
")",
">",
"0",
"{",
"ph",
",",
"ok",
":=",
"handler",
".",
"(",
"botfaces",
".",
"PostHandler",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"postHandlerErr",
"\n",
"}",
"\n\n",
"if",
"posts",
",",
"err",
":=",
"streams",
".",
"Subreddits",
"(",
"sc",
",",
"kill",
",",
"errs",
",",
"c",
".",
"Subreddits",
"...",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"p",
":=",
"range",
"posts",
"{",
"errs",
"<-",
"ph",
".",
"Post",
"(",
"p",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"c",
".",
"SubredditComments",
")",
">",
"0",
"{",
"ch",
",",
"ok",
":=",
"handler",
".",
"(",
"botfaces",
".",
"CommentHandler",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"commentHandlerErr",
"\n",
"}",
"\n\n",
"if",
"comments",
",",
"err",
":=",
"streams",
".",
"SubredditComments",
"(",
"sc",
",",
"kill",
",",
"errs",
",",
"c",
".",
"SubredditComments",
"...",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"c",
":=",
"range",
"comments",
"{",
"errs",
"<-",
"ch",
".",
"Comment",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"c",
".",
"Users",
")",
">",
"0",
"{",
"uh",
",",
"ok",
":=",
"handler",
".",
"(",
"botfaces",
".",
"UserHandler",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"userHandlerErr",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"user",
":=",
"range",
"c",
".",
"Users",
"{",
"if",
"posts",
",",
"comments",
",",
"err",
":=",
"streams",
".",
"User",
"(",
"sc",
",",
"kill",
",",
"errs",
",",
"user",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"p",
":=",
"range",
"posts",
"{",
"errs",
"<-",
"uh",
".",
"UserPost",
"(",
"p",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"c",
":=",
"range",
"comments",
"{",
"errs",
"<-",
"uh",
".",
"UserComment",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // connectScanStreams connects the streams a scanner can subscribe to to the
// handler. | [
"connectScanStreams",
"connects",
"the",
"streams",
"a",
"scanner",
"can",
"subscribe",
"to",
"to",
"the",
"handler",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/scan.go#L58-L139 |
799 | turnage/graw | reddit/script.go | NewScript | func NewScript(agent string, rate time.Duration) (Script, error) {
c, err := newClient(clientConfig{agent: agent})
r := newReaper(
reaperConfig{
client: c,
parser: newParser(),
hostname: "reddit.com",
reapSuffix: ".json",
tls: true,
rate: maxOf(rate, 2*time.Second),
},
)
return &script{
Lurker: newLurker(r),
Scanner: newScanner(r),
}, err
} | go | func NewScript(agent string, rate time.Duration) (Script, error) {
c, err := newClient(clientConfig{agent: agent})
r := newReaper(
reaperConfig{
client: c,
parser: newParser(),
hostname: "reddit.com",
reapSuffix: ".json",
tls: true,
rate: maxOf(rate, 2*time.Second),
},
)
return &script{
Lurker: newLurker(r),
Scanner: newScanner(r),
}, err
} | [
"func",
"NewScript",
"(",
"agent",
"string",
",",
"rate",
"time",
".",
"Duration",
")",
"(",
"Script",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"newClient",
"(",
"clientConfig",
"{",
"agent",
":",
"agent",
"}",
")",
"\n",
"r",
":=",
"newReaper",
"(",
"reaperConfig",
"{",
"client",
":",
"c",
",",
"parser",
":",
"newParser",
"(",
")",
",",
"hostname",
":",
"\"",
"\"",
",",
"reapSuffix",
":",
"\"",
"\"",
",",
"tls",
":",
"true",
",",
"rate",
":",
"maxOf",
"(",
"rate",
",",
"2",
"*",
"time",
".",
"Second",
")",
",",
"}",
",",
")",
"\n",
"return",
"&",
"script",
"{",
"Lurker",
":",
"newLurker",
"(",
"r",
")",
",",
"Scanner",
":",
"newScanner",
"(",
"r",
")",
",",
"}",
",",
"err",
"\n",
"}"
] | // NewScript returns a Script handle to Reddit's API which always sends the
// given agent in the user-agent header of its requests and makes requests with
// no less time between them than rate. The minimum respected value of rate is 2
// seconds, because Reddit's API rules cap logged out non-OAuth clients at 30
// requests per minute. | [
"NewScript",
"returns",
"a",
"Script",
"handle",
"to",
"Reddit",
"s",
"API",
"which",
"always",
"sends",
"the",
"given",
"agent",
"in",
"the",
"user",
"-",
"agent",
"header",
"of",
"its",
"requests",
"and",
"makes",
"requests",
"with",
"no",
"less",
"time",
"between",
"them",
"than",
"rate",
".",
"The",
"minimum",
"respected",
"value",
"of",
"rate",
"is",
"2",
"seconds",
"because",
"Reddit",
"s",
"API",
"rules",
"cap",
"logged",
"out",
"non",
"-",
"OAuth",
"clients",
"at",
"30",
"requests",
"per",
"minute",
"."
] | 3295929039f653fa7028de98b47e5abf51413322 | https://github.com/turnage/graw/blob/3295929039f653fa7028de98b47e5abf51413322/reddit/script.go#L23-L39 |
Subsets and Splits