id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
8,600
h2non/gock
response.go
SetHeaders
func (r *Response) SetHeaders(headers map[string]string) *Response { for key, value := range headers { r.Header.Add(key, value) } return r }
go
func (r *Response) SetHeaders(headers map[string]string) *Response { for key, value := range headers { r.Header.Add(key, value) } return r }
[ "func", "(", "r", "*", "Response", ")", "SetHeaders", "(", "headers", "map", "[", "string", "]", "string", ")", "*", "Response", "{", "for", "key", ",", "value", ":=", "range", "headers", "{", "r", ".", "Header", ".", "Add", "(", "key", ",", "value", ")", "\n", "}", "\n", "return", "r", "\n", "}" ]
// SetHeaders sets a map of header fields in the mock response.
[ "SetHeaders", "sets", "a", "map", "of", "header", "fields", "in", "the", "mock", "response", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L89-L94
8,601
h2non/gock
response.go
Body
func (r *Response) Body(body io.Reader) *Response { r.BodyBuffer, r.Error = ioutil.ReadAll(body) return r }
go
func (r *Response) Body(body io.Reader) *Response { r.BodyBuffer, r.Error = ioutil.ReadAll(body) return r }
[ "func", "(", "r", "*", "Response", ")", "Body", "(", "body", "io", ".", "Reader", ")", "*", "Response", "{", "r", ".", "BodyBuffer", ",", "r", ".", "Error", "=", "ioutil", ".", "ReadAll", "(", "body", ")", "\n", "return", "r", "\n", "}" ]
// Body sets the HTTP response body to be used.
[ "Body", "sets", "the", "HTTP", "response", "body", "to", "be", "used", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L97-L100
8,602
h2non/gock
response.go
BodyString
func (r *Response) BodyString(body string) *Response { r.BodyBuffer = []byte(body) return r }
go
func (r *Response) BodyString(body string) *Response { r.BodyBuffer = []byte(body) return r }
[ "func", "(", "r", "*", "Response", ")", "BodyString", "(", "body", "string", ")", "*", "Response", "{", "r", ".", "BodyBuffer", "=", "[", "]", "byte", "(", "body", ")", "\n", "return", "r", "\n", "}" ]
// BodyString defines the response body as string.
[ "BodyString", "defines", "the", "response", "body", "as", "string", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L103-L106
8,603
h2non/gock
response.go
JSON
func (r *Response) JSON(data interface{}) *Response { r.Header.Set("Content-Type", "application/json") r.BodyBuffer, r.Error = readAndDecode(data, "json") return r }
go
func (r *Response) JSON(data interface{}) *Response { r.Header.Set("Content-Type", "application/json") r.BodyBuffer, r.Error = readAndDecode(data, "json") return r }
[ "func", "(", "r", "*", "Response", ")", "JSON", "(", "data", "interface", "{", "}", ")", "*", "Response", "{", "r", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "r", ".", "BodyBuffer", ",", "r", ".", "Error", "=", "readAndDecode", "(", "data", ",", "\"", "\"", ")", "\n", "return", "r", "\n", "}" ]
// JSON defines the response body based on a JSON based input.
[ "JSON", "defines", "the", "response", "body", "based", "on", "a", "JSON", "based", "input", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L116-L120
8,604
h2non/gock
response.go
SetError
func (r *Response) SetError(err error) *Response { r.Error = err return r }
go
func (r *Response) SetError(err error) *Response { r.Error = err return r }
[ "func", "(", "r", "*", "Response", ")", "SetError", "(", "err", "error", ")", "*", "Response", "{", "r", ".", "Error", "=", "err", "\n", "return", "r", "\n", "}" ]
// SetError defines the response simulated error.
[ "SetError", "defines", "the", "response", "simulated", "error", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L130-L133
8,605
h2non/gock
response.go
Delay
func (r *Response) Delay(delay time.Duration) *Response { r.ResponseDelay = delay return r }
go
func (r *Response) Delay(delay time.Duration) *Response { r.ResponseDelay = delay return r }
[ "func", "(", "r", "*", "Response", ")", "Delay", "(", "delay", "time", ".", "Duration", ")", "*", "Response", "{", "r", ".", "ResponseDelay", "=", "delay", "\n", "return", "r", "\n", "}" ]
// Delay defines the response simulated delay. // This feature is still experimental and will be improved in the future.
[ "Delay", "defines", "the", "response", "simulated", "delay", ".", "This", "feature", "is", "still", "experimental", "and", "will", "be", "improved", "in", "the", "future", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L137-L140
8,606
h2non/gock
response.go
Map
func (r *Response) Map(fn MapResponseFunc) *Response { r.Mappers = append(r.Mappers, fn) return r }
go
func (r *Response) Map(fn MapResponseFunc) *Response { r.Mappers = append(r.Mappers, fn) return r }
[ "func", "(", "r", "*", "Response", ")", "Map", "(", "fn", "MapResponseFunc", ")", "*", "Response", "{", "r", ".", "Mappers", "=", "append", "(", "r", ".", "Mappers", ",", "fn", ")", "\n", "return", "r", "\n", "}" ]
// Map adds a new response mapper function to map http.Response before the matching process.
[ "Map", "adds", "a", "new", "response", "mapper", "function", "to", "map", "http", ".", "Response", "before", "the", "matching", "process", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/response.go#L143-L146
8,607
h2non/gock
gock.go
New
func New(uri string) *Request { Intercept() res := NewResponse() req := NewRequest() req.URLStruct, res.Error = url.Parse(normalizeURI(uri)) // Create the new mock expectation exp := NewMock(req, res) Register(exp) return req }
go
func New(uri string) *Request { Intercept() res := NewResponse() req := NewRequest() req.URLStruct, res.Error = url.Parse(normalizeURI(uri)) // Create the new mock expectation exp := NewMock(req, res) Register(exp) return req }
[ "func", "New", "(", "uri", "string", ")", "*", "Request", "{", "Intercept", "(", ")", "\n\n", "res", ":=", "NewResponse", "(", ")", "\n", "req", ":=", "NewRequest", "(", ")", "\n", "req", ".", "URLStruct", ",", "res", ".", "Error", "=", "url", ".", "Parse", "(", "normalizeURI", "(", "uri", ")", ")", "\n\n", "// Create the new mock expectation", "exp", ":=", "NewMock", "(", "req", ",", "res", ")", "\n", "Register", "(", "exp", ")", "\n\n", "return", "req", "\n", "}" ]
// New creates and registers a new HTTP mock with // default settings and returns the Request DSL for HTTP mock // definition and set up.
[ "New", "creates", "and", "registers", "a", "new", "HTTP", "mock", "with", "default", "settings", "and", "returns", "the", "Request", "DSL", "for", "HTTP", "mock", "definition", "and", "set", "up", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/gock.go#L39-L51
8,608
h2non/gock
gock.go
RestoreClient
func RestoreClient(cli *http.Client) { trans, ok := cli.Transport.(*Transport) if !ok { return } cli.Transport = trans.Transport }
go
func RestoreClient(cli *http.Client) { trans, ok := cli.Transport.(*Transport) if !ok { return } cli.Transport = trans.Transport }
[ "func", "RestoreClient", "(", "cli", "*", "http", ".", "Client", ")", "{", "trans", ",", "ok", ":=", "cli", ".", "Transport", ".", "(", "*", "Transport", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "cli", ".", "Transport", "=", "trans", ".", "Transport", "\n", "}" ]
// RestoreClient allows the developer to disable and restore the // original transport in the given http.Client.
[ "RestoreClient", "allows", "the", "developer", "to", "disable", "and", "restore", "the", "original", "transport", "in", "the", "given", "http", ".", "Client", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/gock.go#L82-L88
8,609
h2non/gock
gock.go
Observe
func Observe(fn ObserverFunc) { mutex.Lock() defer mutex.Unlock() config.Observer = fn }
go
func Observe(fn ObserverFunc) { mutex.Lock() defer mutex.Unlock() config.Observer = fn }
[ "func", "Observe", "(", "fn", "ObserverFunc", ")", "{", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mutex", ".", "Unlock", "(", ")", "\n", "config", ".", "Observer", "=", "fn", "\n", "}" ]
// Observe provides a hook to support inspection of the request and matched mock
[ "Observe", "provides", "a", "hook", "to", "support", "inspection", "of", "the", "request", "and", "matched", "mock" ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/gock.go#L112-L116
8,610
h2non/gock
gock.go
NetworkingFilter
func NetworkingFilter(fn FilterRequestFunc) { mutex.Lock() defer mutex.Unlock() config.NetworkingFilters = append(config.NetworkingFilters, fn) }
go
func NetworkingFilter(fn FilterRequestFunc) { mutex.Lock() defer mutex.Unlock() config.NetworkingFilters = append(config.NetworkingFilters, fn) }
[ "func", "NetworkingFilter", "(", "fn", "FilterRequestFunc", ")", "{", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mutex", ".", "Unlock", "(", ")", "\n", "config", ".", "NetworkingFilters", "=", "append", "(", "config", ".", "NetworkingFilters", ",", "fn", ")", "\n", "}" ]
// NetworkingFilter determines if an http.Request should be triggered or not.
[ "NetworkingFilter", "determines", "if", "an", "http", ".", "Request", "should", "be", "triggered", "or", "not", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/gock.go#L133-L137
8,611
h2non/gock
mock.go
NewMock
func NewMock(req *Request, res *Response) *Mocker { mock := &Mocker{ request: req, response: res, matcher: DefaultMatcher, } res.Mock = mock req.Mock = mock req.Response = res return mock }
go
func NewMock(req *Request, res *Response) *Mocker { mock := &Mocker{ request: req, response: res, matcher: DefaultMatcher, } res.Mock = mock req.Mock = mock req.Response = res return mock }
[ "func", "NewMock", "(", "req", "*", "Request", ",", "res", "*", "Response", ")", "*", "Mocker", "{", "mock", ":=", "&", "Mocker", "{", "request", ":", "req", ",", "response", ":", "res", ",", "matcher", ":", "DefaultMatcher", ",", "}", "\n", "res", ".", "Mock", "=", "mock", "\n", "req", ".", "Mock", "=", "mock", "\n", "req", ".", "Response", "=", "res", "\n", "return", "mock", "\n", "}" ]
// NewMock creates a new HTTP mock based on the given request and response instances. // It's mostly used internally.
[ "NewMock", "creates", "a", "new", "HTTP", "mock", "based", "on", "the", "given", "request", "and", "response", "instances", ".", "It", "s", "mostly", "used", "internally", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/mock.go#L54-L64
8,612
h2non/gock
mock.go
Done
func (m *Mocker) Done() bool { m.mutex.Lock() defer m.mutex.Unlock() return m.disabled || (!m.request.Persisted && m.request.Counter == 0) }
go
func (m *Mocker) Done() bool { m.mutex.Lock() defer m.mutex.Unlock() return m.disabled || (!m.request.Persisted && m.request.Counter == 0) }
[ "func", "(", "m", "*", "Mocker", ")", "Done", "(", ")", "bool", "{", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "m", ".", "disabled", "||", "(", "!", "m", ".", "request", ".", "Persisted", "&&", "m", ".", "request", ".", "Counter", "==", "0", ")", "\n", "}" ]
// Done returns true in case that the current mock // instance is disabled and therefore must be removed.
[ "Done", "returns", "true", "in", "case", "that", "the", "current", "mock", "instance", "is", "disabled", "and", "therefore", "must", "be", "removed", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/mock.go#L73-L77
8,613
h2non/gock
mock.go
Match
func (m *Mocker) Match(req *http.Request) (bool, error) { if m.disabled { return false, nil } // Filter for _, filter := range m.request.Filters { if !filter(req) { return false, nil } } // Map for _, mapper := range m.request.Mappers { if treq := mapper(req); treq != nil { req = treq } } // Match matches, err := m.matcher.Match(req, m.request) if matches { m.decrement() } return matches, err }
go
func (m *Mocker) Match(req *http.Request) (bool, error) { if m.disabled { return false, nil } // Filter for _, filter := range m.request.Filters { if !filter(req) { return false, nil } } // Map for _, mapper := range m.request.Mappers { if treq := mapper(req); treq != nil { req = treq } } // Match matches, err := m.matcher.Match(req, m.request) if matches { m.decrement() } return matches, err }
[ "func", "(", "m", "*", "Mocker", ")", "Match", "(", "req", "*", "http", ".", "Request", ")", "(", "bool", ",", "error", ")", "{", "if", "m", ".", "disabled", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// Filter", "for", "_", ",", "filter", ":=", "range", "m", ".", "request", ".", "Filters", "{", "if", "!", "filter", "(", "req", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// Map", "for", "_", ",", "mapper", ":=", "range", "m", ".", "request", ".", "Mappers", "{", "if", "treq", ":=", "mapper", "(", "req", ")", ";", "treq", "!=", "nil", "{", "req", "=", "treq", "\n", "}", "\n", "}", "\n\n", "// Match", "matches", ",", "err", ":=", "m", ".", "matcher", ".", "Match", "(", "req", ",", "m", ".", "request", ")", "\n", "if", "matches", "{", "m", ".", "decrement", "(", ")", "\n", "}", "\n\n", "return", "matches", ",", "err", "\n", "}" ]
// Match matches the given http.Request with the current Request // mock expectation, returning true if matches.
[ "Match", "matches", "the", "given", "http", ".", "Request", "with", "the", "current", "Request", "mock", "expectation", "returning", "true", "if", "matches", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/mock.go#L93-L119
8,614
h2non/gock
mock.go
decrement
func (m *Mocker) decrement() { if m.request.Persisted { return } m.mutex.Lock() defer m.mutex.Unlock() m.request.Counter-- if m.request.Counter == 0 { m.disabled = true } }
go
func (m *Mocker) decrement() { if m.request.Persisted { return } m.mutex.Lock() defer m.mutex.Unlock() m.request.Counter-- if m.request.Counter == 0 { m.disabled = true } }
[ "func", "(", "m", "*", "Mocker", ")", "decrement", "(", ")", "{", "if", "m", ".", "request", ".", "Persisted", "{", "return", "\n", "}", "\n\n", "m", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "m", ".", "request", ".", "Counter", "--", "\n", "if", "m", ".", "request", ".", "Counter", "==", "0", "{", "m", ".", "disabled", "=", "true", "\n", "}", "\n", "}" ]
// decrement decrements the current mock Request counter.
[ "decrement", "decrements", "the", "current", "mock", "Request", "counter", "." ]
090e9d9644e4961e7084159b80b64ebca1497299
https://github.com/h2non/gock/blob/090e9d9644e4961e7084159b80b64ebca1497299/mock.go#L134-L146
8,615
posener/complete
predict_files.go
PredictFilesSet
func PredictFilesSet(files []string) PredictFunc { return func(a Args) (prediction []string) { // add all matching files to prediction for _, f := range files { f = fixPathForm(a.Last, f) // test matching of file to the argument if match.File(f, a.Last) { prediction = append(prediction, f) } } return } }
go
func PredictFilesSet(files []string) PredictFunc { return func(a Args) (prediction []string) { // add all matching files to prediction for _, f := range files { f = fixPathForm(a.Last, f) // test matching of file to the argument if match.File(f, a.Last) { prediction = append(prediction, f) } } return } }
[ "func", "PredictFilesSet", "(", "files", "[", "]", "string", ")", "PredictFunc", "{", "return", "func", "(", "a", "Args", ")", "(", "prediction", "[", "]", "string", ")", "{", "// add all matching files to prediction", "for", "_", ",", "f", ":=", "range", "files", "{", "f", "=", "fixPathForm", "(", "a", ".", "Last", ",", "f", ")", "\n\n", "// test matching of file to the argument", "if", "match", ".", "File", "(", "f", ",", "a", ".", "Last", ")", "{", "prediction", "=", "append", "(", "prediction", ",", "f", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}", "\n", "}" ]
// PredictFilesSet predict according to file rules to a given set of file names
[ "PredictFilesSet", "predict", "according", "to", "file", "rules", "to", "a", "given", "set", "of", "file", "names" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/predict_files.go#L66-L79
8,616
posener/complete
match/file.go
File
func File(file, prefix string) bool { // special case for current directory completion if file == "./" && (prefix == "." || prefix == "") { return true } if prefix == "." && strings.HasPrefix(file, ".") { return true } file = strings.TrimPrefix(file, "./") prefix = strings.TrimPrefix(prefix, "./") return strings.HasPrefix(file, prefix) }
go
func File(file, prefix string) bool { // special case for current directory completion if file == "./" && (prefix == "." || prefix == "") { return true } if prefix == "." && strings.HasPrefix(file, ".") { return true } file = strings.TrimPrefix(file, "./") prefix = strings.TrimPrefix(prefix, "./") return strings.HasPrefix(file, prefix) }
[ "func", "File", "(", "file", ",", "prefix", "string", ")", "bool", "{", "// special case for current directory completion", "if", "file", "==", "\"", "\"", "&&", "(", "prefix", "==", "\"", "\"", "||", "prefix", "==", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "if", "prefix", "==", "\"", "\"", "&&", "strings", ".", "HasPrefix", "(", "file", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n\n", "file", "=", "strings", ".", "TrimPrefix", "(", "file", ",", "\"", "\"", ")", "\n", "prefix", "=", "strings", ".", "TrimPrefix", "(", "prefix", ",", "\"", "\"", ")", "\n\n", "return", "strings", ".", "HasPrefix", "(", "file", ",", "prefix", ")", "\n", "}" ]
// File returns true if prefix can match the file
[ "File", "returns", "true", "if", "prefix", "can", "match", "the", "file" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/match/file.go#L6-L19
8,617
posener/complete
args.go
Directory
func (a Args) Directory() string { if info, err := os.Stat(a.Last); err == nil && info.IsDir() { return fixPathForm(a.Last, a.Last) } dir := filepath.Dir(a.Last) if info, err := os.Stat(dir); err != nil || !info.IsDir() { return "./" } return fixPathForm(a.Last, dir) }
go
func (a Args) Directory() string { if info, err := os.Stat(a.Last); err == nil && info.IsDir() { return fixPathForm(a.Last, a.Last) } dir := filepath.Dir(a.Last) if info, err := os.Stat(dir); err != nil || !info.IsDir() { return "./" } return fixPathForm(a.Last, dir) }
[ "func", "(", "a", "Args", ")", "Directory", "(", ")", "string", "{", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "a", ".", "Last", ")", ";", "err", "==", "nil", "&&", "info", ".", "IsDir", "(", ")", "{", "return", "fixPathForm", "(", "a", ".", "Last", ",", "a", ".", "Last", ")", "\n", "}", "\n", "dir", ":=", "filepath", ".", "Dir", "(", "a", ".", "Last", ")", "\n", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "dir", ")", ";", "err", "!=", "nil", "||", "!", "info", ".", "IsDir", "(", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fixPathForm", "(", "a", ".", "Last", ",", "dir", ")", "\n", "}" ]
// Directory gives the directory of the current written // last argument if it represents a file name being written. // in case that it is not, we fall back to the current directory.
[ "Directory", "gives", "the", "directory", "of", "the", "current", "written", "last", "argument", "if", "it", "represents", "a", "file", "name", "being", "written", ".", "in", "case", "that", "it", "is", "not", "we", "fall", "back", "to", "the", "current", "directory", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/args.go#L31-L40
8,618
posener/complete
gocomplete/pkgs.go
predictPackages
func predictPackages(a complete.Args) (prediction []string) { prediction = []string{a.Last} lastPrediction := "" for len(prediction) == 1 && (lastPrediction == "" || lastPrediction != prediction[0]) { // if only one prediction, predict files within this prediction, // for example, if the user entered 'pk' and we have a package named 'pkg', // which is the only package prefixed with 'pk', we will automatically go one // level deeper and give the user the 'pkg' and all the nested packages within // that package. lastPrediction = prediction[0] a.Last = prediction[0] prediction = predictLocalAndSystem(a) } return }
go
func predictPackages(a complete.Args) (prediction []string) { prediction = []string{a.Last} lastPrediction := "" for len(prediction) == 1 && (lastPrediction == "" || lastPrediction != prediction[0]) { // if only one prediction, predict files within this prediction, // for example, if the user entered 'pk' and we have a package named 'pkg', // which is the only package prefixed with 'pk', we will automatically go one // level deeper and give the user the 'pkg' and all the nested packages within // that package. lastPrediction = prediction[0] a.Last = prediction[0] prediction = predictLocalAndSystem(a) } return }
[ "func", "predictPackages", "(", "a", "complete", ".", "Args", ")", "(", "prediction", "[", "]", "string", ")", "{", "prediction", "=", "[", "]", "string", "{", "a", ".", "Last", "}", "\n", "lastPrediction", ":=", "\"", "\"", "\n", "for", "len", "(", "prediction", ")", "==", "1", "&&", "(", "lastPrediction", "==", "\"", "\"", "||", "lastPrediction", "!=", "prediction", "[", "0", "]", ")", "{", "// if only one prediction, predict files within this prediction,", "// for example, if the user entered 'pk' and we have a package named 'pkg',", "// which is the only package prefixed with 'pk', we will automatically go one", "// level deeper and give the user the 'pkg' and all the nested packages within", "// that package.", "lastPrediction", "=", "prediction", "[", "0", "]", "\n", "a", ".", "Last", "=", "prediction", "[", "0", "]", "\n", "prediction", "=", "predictLocalAndSystem", "(", "a", ")", "\n", "}", "\n", "return", "\n", "}" ]
// predictPackages completes packages in the directory pointed by a.Last // and packages that are one level below that package.
[ "predictPackages", "completes", "packages", "in", "the", "directory", "pointed", "by", "a", ".", "Last", "and", "packages", "that", "are", "one", "level", "below", "that", "package", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/gocomplete/pkgs.go#L16-L30
8,619
posener/complete
gocomplete/pkgs.go
listPackages
func listPackages(dir string) (directories []string) { // add subdirectories files, err := ioutil.ReadDir(dir) if err != nil { complete.Log("failed reading directory %s: %s", dir, err) return } // build paths array paths := make([]string, 0, len(files)+1) for _, f := range files { if f.IsDir() { paths = append(paths, filepath.Join(dir, f.Name())) } } paths = append(paths, dir) // import packages according to given paths for _, p := range paths { pkg, err := build.ImportDir(p, 0) if err != nil { complete.Log("failed importing directory %s: %s", p, err) continue } directories = append(directories, pkg.Dir) } return }
go
func listPackages(dir string) (directories []string) { // add subdirectories files, err := ioutil.ReadDir(dir) if err != nil { complete.Log("failed reading directory %s: %s", dir, err) return } // build paths array paths := make([]string, 0, len(files)+1) for _, f := range files { if f.IsDir() { paths = append(paths, filepath.Join(dir, f.Name())) } } paths = append(paths, dir) // import packages according to given paths for _, p := range paths { pkg, err := build.ImportDir(p, 0) if err != nil { complete.Log("failed importing directory %s: %s", p, err) continue } directories = append(directories, pkg.Dir) } return }
[ "func", "listPackages", "(", "dir", "string", ")", "(", "directories", "[", "]", "string", ")", "{", "// add subdirectories", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "complete", ".", "Log", "(", "\"", "\"", ",", "dir", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// build paths array", "paths", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "files", ")", "+", "1", ")", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "if", "f", ".", "IsDir", "(", ")", "{", "paths", "=", "append", "(", "paths", ",", "filepath", ".", "Join", "(", "dir", ",", "f", ".", "Name", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "paths", "=", "append", "(", "paths", ",", "dir", ")", "\n\n", "// import packages according to given paths", "for", "_", ",", "p", ":=", "range", "paths", "{", "pkg", ",", "err", ":=", "build", ".", "ImportDir", "(", "p", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "complete", ".", "Log", "(", "\"", "\"", ",", "p", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "directories", "=", "append", "(", "directories", ",", "pkg", ".", "Dir", ")", "\n", "}", "\n", "return", "\n", "}" ]
// listPackages looks in current pointed dir and in all it's direct sub-packages // and return a list of paths to go packages.
[ "listPackages", "looks", "in", "current", "pointed", "dir", "and", "in", "all", "it", "s", "direct", "sub", "-", "packages", "and", "return", "a", "list", "of", "paths", "to", "go", "packages", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/gocomplete/pkgs.go#L44-L71
8,620
posener/complete
complete.go
Run
func (c *Complete) Run() bool { c.AddFlags(nil) flag.Parse() return c.Complete() }
go
func (c *Complete) Run() bool { c.AddFlags(nil) flag.Parse() return c.Complete() }
[ "func", "(", "c", "*", "Complete", ")", "Run", "(", ")", "bool", "{", "c", ".", "AddFlags", "(", "nil", ")", "\n", "flag", ".", "Parse", "(", ")", "\n", "return", "c", ".", "Complete", "(", ")", "\n", "}" ]
// Run runs the completion and add installation flags beforehand. // The flags are added to the main flag CommandLine variable.
[ "Run", "runs", "the", "completion", "and", "add", "installation", "flags", "beforehand", ".", "The", "flags", "are", "added", "to", "the", "main", "flag", "CommandLine", "variable", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/complete.go#L42-L46
8,621
posener/complete
command.go
Predict
func (c *Command) Predict(a Args) []string { options, _ := c.predict(a) return options }
go
func (c *Command) Predict(a Args) []string { options, _ := c.predict(a) return options }
[ "func", "(", "c", "*", "Command", ")", "Predict", "(", "a", "Args", ")", "[", "]", "string", "{", "options", ",", "_", ":=", "c", ".", "predict", "(", "a", ")", "\n", "return", "options", "\n", "}" ]
// Predict returns all possible predictions for args according to the command struct
[ "Predict", "returns", "all", "possible", "predictions", "for", "args", "according", "to", "the", "command", "struct" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/command.go#L26-L29
8,622
posener/complete
command.go
Predict
func (c Commands) Predict(a Args) (prediction []string) { for sub := range c { prediction = append(prediction, sub) } return }
go
func (c Commands) Predict(a Args) (prediction []string) { for sub := range c { prediction = append(prediction, sub) } return }
[ "func", "(", "c", "Commands", ")", "Predict", "(", "a", "Args", ")", "(", "prediction", "[", "]", "string", ")", "{", "for", "sub", ":=", "range", "c", "{", "prediction", "=", "append", "(", "prediction", ",", "sub", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Predict completion of sub command names names according to command line arguments
[ "Predict", "completion", "of", "sub", "command", "names", "names", "according", "to", "command", "line", "arguments" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/command.go#L35-L40
8,623
posener/complete
command.go
Predict
func (f Flags) Predict(a Args) (prediction []string) { for flag := range f { // If the flag starts with a hyphen, we avoid emitting the prediction // unless the last typed arg contains a hyphen as well. flagHyphenStart := len(flag) != 0 && flag[0] == '-' lastHyphenStart := len(a.Last) != 0 && a.Last[0] == '-' if flagHyphenStart && !lastHyphenStart { continue } prediction = append(prediction, flag) } return }
go
func (f Flags) Predict(a Args) (prediction []string) { for flag := range f { // If the flag starts with a hyphen, we avoid emitting the prediction // unless the last typed arg contains a hyphen as well. flagHyphenStart := len(flag) != 0 && flag[0] == '-' lastHyphenStart := len(a.Last) != 0 && a.Last[0] == '-' if flagHyphenStart && !lastHyphenStart { continue } prediction = append(prediction, flag) } return }
[ "func", "(", "f", "Flags", ")", "Predict", "(", "a", "Args", ")", "(", "prediction", "[", "]", "string", ")", "{", "for", "flag", ":=", "range", "f", "{", "// If the flag starts with a hyphen, we avoid emitting the prediction", "// unless the last typed arg contains a hyphen as well.", "flagHyphenStart", ":=", "len", "(", "flag", ")", "!=", "0", "&&", "flag", "[", "0", "]", "==", "'-'", "\n", "lastHyphenStart", ":=", "len", "(", "a", ".", "Last", ")", "!=", "0", "&&", "a", ".", "Last", "[", "0", "]", "==", "'-'", "\n", "if", "flagHyphenStart", "&&", "!", "lastHyphenStart", "{", "continue", "\n", "}", "\n", "prediction", "=", "append", "(", "prediction", ",", "flag", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Predict completion of flags names according to command line arguments
[ "Predict", "completion", "of", "flags", "names", "according", "to", "command", "line", "arguments" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/command.go#L46-L58
8,624
posener/complete
command.go
predict
func (c *Command) predict(a Args) (options []string, only bool) { // search sub commands for predictions first subCommandFound := false for i, arg := range a.Completed { if cmd, ok := c.Sub[arg]; ok { subCommandFound = true // recursive call for sub command options, only = cmd.predict(a.from(i)) if only { return } // We matched so stop searching. Continuing to search can accidentally // match a subcommand with current set of commands, see issue #46. break } } // if last completed word is a global flag that we need to complete if predictor, ok := c.GlobalFlags[a.LastCompleted]; ok && predictor != nil { Log("Predicting according to global flag %s", a.LastCompleted) return predictor.Predict(a), true } options = append(options, c.GlobalFlags.Predict(a)...) // if a sub command was entered, we won't add the parent command // completions and we return here. if subCommandFound { return } // if last completed word is a command flag that we need to complete if predictor, ok := c.Flags[a.LastCompleted]; ok && predictor != nil { Log("Predicting according to flag %s", a.LastCompleted) return predictor.Predict(a), true } options = append(options, c.Sub.Predict(a)...) options = append(options, c.Flags.Predict(a)...) if c.Args != nil { options = append(options, c.Args.Predict(a)...) } return }
go
func (c *Command) predict(a Args) (options []string, only bool) { // search sub commands for predictions first subCommandFound := false for i, arg := range a.Completed { if cmd, ok := c.Sub[arg]; ok { subCommandFound = true // recursive call for sub command options, only = cmd.predict(a.from(i)) if only { return } // We matched so stop searching. Continuing to search can accidentally // match a subcommand with current set of commands, see issue #46. break } } // if last completed word is a global flag that we need to complete if predictor, ok := c.GlobalFlags[a.LastCompleted]; ok && predictor != nil { Log("Predicting according to global flag %s", a.LastCompleted) return predictor.Predict(a), true } options = append(options, c.GlobalFlags.Predict(a)...) // if a sub command was entered, we won't add the parent command // completions and we return here. if subCommandFound { return } // if last completed word is a command flag that we need to complete if predictor, ok := c.Flags[a.LastCompleted]; ok && predictor != nil { Log("Predicting according to flag %s", a.LastCompleted) return predictor.Predict(a), true } options = append(options, c.Sub.Predict(a)...) options = append(options, c.Flags.Predict(a)...) if c.Args != nil { options = append(options, c.Args.Predict(a)...) } return }
[ "func", "(", "c", "*", "Command", ")", "predict", "(", "a", "Args", ")", "(", "options", "[", "]", "string", ",", "only", "bool", ")", "{", "// search sub commands for predictions first", "subCommandFound", ":=", "false", "\n", "for", "i", ",", "arg", ":=", "range", "a", ".", "Completed", "{", "if", "cmd", ",", "ok", ":=", "c", ".", "Sub", "[", "arg", "]", ";", "ok", "{", "subCommandFound", "=", "true", "\n\n", "// recursive call for sub command", "options", ",", "only", "=", "cmd", ".", "predict", "(", "a", ".", "from", "(", "i", ")", ")", "\n", "if", "only", "{", "return", "\n", "}", "\n\n", "// We matched so stop searching. Continuing to search can accidentally", "// match a subcommand with current set of commands, see issue #46.", "break", "\n", "}", "\n", "}", "\n\n", "// if last completed word is a global flag that we need to complete", "if", "predictor", ",", "ok", ":=", "c", ".", "GlobalFlags", "[", "a", ".", "LastCompleted", "]", ";", "ok", "&&", "predictor", "!=", "nil", "{", "Log", "(", "\"", "\"", ",", "a", ".", "LastCompleted", ")", "\n", "return", "predictor", ".", "Predict", "(", "a", ")", ",", "true", "\n", "}", "\n\n", "options", "=", "append", "(", "options", ",", "c", ".", "GlobalFlags", ".", "Predict", "(", "a", ")", "...", ")", "\n\n", "// if a sub command was entered, we won't add the parent command", "// completions and we return here.", "if", "subCommandFound", "{", "return", "\n", "}", "\n\n", "// if last completed word is a command flag that we need to complete", "if", "predictor", ",", "ok", ":=", "c", ".", "Flags", "[", "a", ".", "LastCompleted", "]", ";", "ok", "&&", "predictor", "!=", "nil", "{", "Log", "(", "\"", "\"", ",", "a", ".", "LastCompleted", ")", "\n", "return", "predictor", ".", "Predict", "(", "a", ")", ",", "true", "\n", "}", "\n\n", "options", "=", "append", "(", "options", ",", "c", ".", "Sub", ".", "Predict", "(", "a", ")", "...", ")", "\n", "options", "=", "append", "(", "options", ",", "c", ".", "Flags", ".", "Predict", "(", "a", ")", "...", ")", "\n", "if", "c", ".", "Args", "!=", "nil", "{", "options", "=", "append", "(", "options", ",", "c", ".", "Args", ".", "Predict", "(", "a", ")", "...", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// predict options // only is set to true if no more options are allowed to be returned // those are in cases of special flag that has specific completion arguments, // and other flags or sub commands can't come after it.
[ "predict", "options", "only", "is", "set", "to", "true", "if", "no", "more", "options", "are", "allowed", "to", "be", "returned", "those", "are", "in", "cases", "of", "special", "flag", "that", "has", "specific", "completion", "arguments", "and", "other", "flags", "or", "sub", "commands", "can", "t", "come", "after", "it", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/command.go#L64-L111
8,625
posener/complete
utils.go
fixPathForm
func fixPathForm(last string, file string) string { // get wording directory for relative name workDir, err := os.Getwd() if err != nil { return file } abs, err := filepath.Abs(file) if err != nil { return file } // if last is absolute, return path as absolute if filepath.IsAbs(last) { return fixDirPath(abs) } rel, err := filepath.Rel(workDir, abs) if err != nil { return file } // fix ./ prefix of path if rel != "." && strings.HasPrefix(last, ".") { rel = "./" + rel } return fixDirPath(rel) }
go
func fixPathForm(last string, file string) string { // get wording directory for relative name workDir, err := os.Getwd() if err != nil { return file } abs, err := filepath.Abs(file) if err != nil { return file } // if last is absolute, return path as absolute if filepath.IsAbs(last) { return fixDirPath(abs) } rel, err := filepath.Rel(workDir, abs) if err != nil { return file } // fix ./ prefix of path if rel != "." && strings.HasPrefix(last, ".") { rel = "./" + rel } return fixDirPath(rel) }
[ "func", "fixPathForm", "(", "last", "string", ",", "file", "string", ")", "string", "{", "// get wording directory for relative name", "workDir", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "file", "\n", "}", "\n\n", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "file", "\n", "}", "\n\n", "// if last is absolute, return path as absolute", "if", "filepath", ".", "IsAbs", "(", "last", ")", "{", "return", "fixDirPath", "(", "abs", ")", "\n", "}", "\n\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "workDir", ",", "abs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "file", "\n", "}", "\n\n", "// fix ./ prefix of path", "if", "rel", "!=", "\"", "\"", "&&", "strings", ".", "HasPrefix", "(", "last", ",", "\"", "\"", ")", "{", "rel", "=", "\"", "\"", "+", "rel", "\n", "}", "\n\n", "return", "fixDirPath", "(", "rel", ")", "\n", "}" ]
// fixPathForm changes a file name to a relative name
[ "fixPathForm", "changes", "a", "file", "name", "to", "a", "relative", "name" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/utils.go#L10-L38
8,626
posener/complete
cmd/cmd.go
Run
func (f *CLI) Run() bool { err := f.validate() if err != nil { os.Stderr.WriteString(err.Error() + "\n") os.Exit(1) } switch { case f.install: f.prompt() err = install.Install(f.Name) case f.uninstall: f.prompt() err = install.Uninstall(f.Name) default: // non of the action flags matched, // returning false should make the real program execute return false } if err != nil { fmt.Printf("%s failed! %s\n", f.action(), err) os.Exit(3) } fmt.Println("Done!") return true }
go
func (f *CLI) Run() bool { err := f.validate() if err != nil { os.Stderr.WriteString(err.Error() + "\n") os.Exit(1) } switch { case f.install: f.prompt() err = install.Install(f.Name) case f.uninstall: f.prompt() err = install.Uninstall(f.Name) default: // non of the action flags matched, // returning false should make the real program execute return false } if err != nil { fmt.Printf("%s failed! %s\n", f.action(), err) os.Exit(3) } fmt.Println("Done!") return true }
[ "func", "(", "f", "*", "CLI", ")", "Run", "(", ")", "bool", "{", "err", ":=", "f", ".", "validate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Stderr", ".", "WriteString", "(", "err", ".", "Error", "(", ")", "+", "\"", "\\n", "\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "switch", "{", "case", "f", ".", "install", ":", "f", ".", "prompt", "(", ")", "\n", "err", "=", "install", ".", "Install", "(", "f", ".", "Name", ")", "\n", "case", "f", ".", "uninstall", ":", "f", ".", "prompt", "(", ")", "\n", "err", "=", "install", ".", "Uninstall", "(", "f", ".", "Name", ")", "\n", "default", ":", "// non of the action flags matched,", "// returning false should make the real program execute", "return", "false", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "f", ".", "action", "(", ")", ",", "err", ")", "\n", "os", ".", "Exit", "(", "3", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "true", "\n", "}" ]
// Run is used when running complete in command line mode. // this is used when the complete is not completing words, but to // install it or uninstall it.
[ "Run", "is", "used", "when", "running", "complete", "in", "command", "line", "mode", ".", "this", "is", "used", "when", "the", "complete", "is", "not", "completing", "words", "but", "to", "install", "it", "or", "uninstall", "it", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/cmd/cmd.go#L33-L59
8,627
posener/complete
cmd/cmd.go
prompt
func (f *CLI) prompt() { defer fmt.Println(f.action() + "ing...") if f.yes { return } fmt.Printf("%s completion for %s? ", f.action(), f.Name) var answer string fmt.Scanln(&answer) switch strings.ToLower(answer) { case "y", "yes": return default: fmt.Println("Cancelling...") os.Exit(1) } }
go
func (f *CLI) prompt() { defer fmt.Println(f.action() + "ing...") if f.yes { return } fmt.Printf("%s completion for %s? ", f.action(), f.Name) var answer string fmt.Scanln(&answer) switch strings.ToLower(answer) { case "y", "yes": return default: fmt.Println("Cancelling...") os.Exit(1) } }
[ "func", "(", "f", "*", "CLI", ")", "prompt", "(", ")", "{", "defer", "fmt", ".", "Println", "(", "f", ".", "action", "(", ")", "+", "\"", "\"", ")", "\n", "if", "f", ".", "yes", "{", "return", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "f", ".", "action", "(", ")", ",", "f", ".", "Name", ")", "\n", "var", "answer", "string", "\n", "fmt", ".", "Scanln", "(", "&", "answer", ")", "\n\n", "switch", "strings", ".", "ToLower", "(", "answer", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "\n", "default", ":", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}" ]
// prompt use for approval // exit if approval was not given
[ "prompt", "use", "for", "approval", "exit", "if", "approval", "was", "not", "given" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/cmd/cmd.go#L63-L79
8,628
posener/complete
cmd/cmd.go
AddFlags
func (f *CLI) AddFlags(flags *flag.FlagSet) { if flags == nil { flags = flag.CommandLine } if f.InstallName == "" { f.InstallName = defaultInstallName } if f.UninstallName == "" { f.UninstallName = defaultUninstallName } if flags.Lookup(f.InstallName) == nil { flags.BoolVar(&f.install, f.InstallName, false, fmt.Sprintf("Install completion for %s command", f.Name)) } if flags.Lookup(f.UninstallName) == nil { flags.BoolVar(&f.uninstall, f.UninstallName, false, fmt.Sprintf("Uninstall completion for %s command", f.Name)) } if flags.Lookup("y") == nil { flags.BoolVar(&f.yes, "y", false, "Don't prompt user for typing 'yes' when installing completion") } }
go
func (f *CLI) AddFlags(flags *flag.FlagSet) { if flags == nil { flags = flag.CommandLine } if f.InstallName == "" { f.InstallName = defaultInstallName } if f.UninstallName == "" { f.UninstallName = defaultUninstallName } if flags.Lookup(f.InstallName) == nil { flags.BoolVar(&f.install, f.InstallName, false, fmt.Sprintf("Install completion for %s command", f.Name)) } if flags.Lookup(f.UninstallName) == nil { flags.BoolVar(&f.uninstall, f.UninstallName, false, fmt.Sprintf("Uninstall completion for %s command", f.Name)) } if flags.Lookup("y") == nil { flags.BoolVar(&f.yes, "y", false, "Don't prompt user for typing 'yes' when installing completion") } }
[ "func", "(", "f", "*", "CLI", ")", "AddFlags", "(", "flags", "*", "flag", ".", "FlagSet", ")", "{", "if", "flags", "==", "nil", "{", "flags", "=", "flag", ".", "CommandLine", "\n", "}", "\n\n", "if", "f", ".", "InstallName", "==", "\"", "\"", "{", "f", ".", "InstallName", "=", "defaultInstallName", "\n", "}", "\n", "if", "f", ".", "UninstallName", "==", "\"", "\"", "{", "f", ".", "UninstallName", "=", "defaultUninstallName", "\n", "}", "\n\n", "if", "flags", ".", "Lookup", "(", "f", ".", "InstallName", ")", "==", "nil", "{", "flags", ".", "BoolVar", "(", "&", "f", ".", "install", ",", "f", ".", "InstallName", ",", "false", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Name", ")", ")", "\n", "}", "\n", "if", "flags", ".", "Lookup", "(", "f", ".", "UninstallName", ")", "==", "nil", "{", "flags", ".", "BoolVar", "(", "&", "f", ".", "uninstall", ",", "f", ".", "UninstallName", ",", "false", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Name", ")", ")", "\n", "}", "\n", "if", "flags", ".", "Lookup", "(", "\"", "\"", ")", "==", "nil", "{", "flags", ".", "BoolVar", "(", "&", "f", ".", "yes", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// AddFlags adds the CLI flags to the flag set. // If flags is nil, the default command line flags will be taken. // Pass non-empty strings as installName and uninstallName to override the default // flag names.
[ "AddFlags", "adds", "the", "CLI", "flags", "to", "the", "flag", "set", ".", "If", "flags", "is", "nil", "the", "default", "command", "line", "flags", "will", "be", "taken", ".", "Pass", "non", "-", "empty", "strings", "as", "installName", "and", "uninstallName", "to", "override", "the", "default", "flag", "names", "." ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/cmd/cmd.go#L85-L108
8,629
posener/complete
cmd/cmd.go
validate
func (f *CLI) validate() error { if f.install && f.uninstall { return errors.New("Install and uninstall are mutually exclusive") } return nil }
go
func (f *CLI) validate() error { if f.install && f.uninstall { return errors.New("Install and uninstall are mutually exclusive") } return nil }
[ "func", "(", "f", "*", "CLI", ")", "validate", "(", ")", "error", "{", "if", "f", ".", "install", "&&", "f", ".", "uninstall", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validate the CLI
[ "validate", "the", "CLI" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/cmd/cmd.go#L111-L116
8,630
posener/complete
predict.go
PredictOr
func PredictOr(predictors ...Predictor) Predictor { return PredictFunc(func(a Args) (prediction []string) { for _, p := range predictors { if p == nil { continue } prediction = append(prediction, p.Predict(a)...) } return }) }
go
func PredictOr(predictors ...Predictor) Predictor { return PredictFunc(func(a Args) (prediction []string) { for _, p := range predictors { if p == nil { continue } prediction = append(prediction, p.Predict(a)...) } return }) }
[ "func", "PredictOr", "(", "predictors", "...", "Predictor", ")", "Predictor", "{", "return", "PredictFunc", "(", "func", "(", "a", "Args", ")", "(", "prediction", "[", "]", "string", ")", "{", "for", "_", ",", "p", ":=", "range", "predictors", "{", "if", "p", "==", "nil", "{", "continue", "\n", "}", "\n", "prediction", "=", "append", "(", "prediction", ",", "p", ".", "Predict", "(", "a", ")", "...", ")", "\n", "}", "\n", "return", "\n", "}", ")", "\n", "}" ]
// PredictOr unions two predicate functions, so that the result predicate // returns the union of their predication
[ "PredictOr", "unions", "two", "predicate", "functions", "so", "that", "the", "result", "predicate", "returns", "the", "union", "of", "their", "predication" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/predict.go#L11-L21
8,631
posener/complete
predict.go
Predict
func (p PredictFunc) Predict(a Args) []string { if p == nil { return nil } return p(a) }
go
func (p PredictFunc) Predict(a Args) []string { if p == nil { return nil } return p(a) }
[ "func", "(", "p", "PredictFunc", ")", "Predict", "(", "a", "Args", ")", "[", "]", "string", "{", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "p", "(", "a", ")", "\n", "}" ]
// Predict invokes the predict function and implements the Predictor interface
[ "Predict", "invokes", "the", "predict", "function", "and", "implements", "the", "Predictor", "interface" ]
af07aa5181b38e3fa57d053328e44aaa27da5999
https://github.com/posener/complete/blob/af07aa5181b38e3fa57d053328e44aaa27da5999/predict.go#L29-L34
8,632
dghubble/sling
sling.go
New
func New() *Sling { return &Sling{ httpClient: http.DefaultClient, method: "GET", header: make(http.Header), queryStructs: make([]interface{}, 0), responseDecoder: jsonDecoder{}, } }
go
func New() *Sling { return &Sling{ httpClient: http.DefaultClient, method: "GET", header: make(http.Header), queryStructs: make([]interface{}, 0), responseDecoder: jsonDecoder{}, } }
[ "func", "New", "(", ")", "*", "Sling", "{", "return", "&", "Sling", "{", "httpClient", ":", "http", ".", "DefaultClient", ",", "method", ":", "\"", "\"", ",", "header", ":", "make", "(", "http", ".", "Header", ")", ",", "queryStructs", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ")", ",", "responseDecoder", ":", "jsonDecoder", "{", "}", ",", "}", "\n", "}" ]
// New returns a new Sling with an http DefaultClient.
[ "New", "returns", "a", "new", "Sling", "with", "an", "http", "DefaultClient", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L44-L52
8,633
dghubble/sling
sling.go
Client
func (s *Sling) Client(httpClient *http.Client) *Sling { if httpClient == nil { return s.Doer(http.DefaultClient) } return s.Doer(httpClient) }
go
func (s *Sling) Client(httpClient *http.Client) *Sling { if httpClient == nil { return s.Doer(http.DefaultClient) } return s.Doer(httpClient) }
[ "func", "(", "s", "*", "Sling", ")", "Client", "(", "httpClient", "*", "http", ".", "Client", ")", "*", "Sling", "{", "if", "httpClient", "==", "nil", "{", "return", "s", ".", "Doer", "(", "http", ".", "DefaultClient", ")", "\n", "}", "\n", "return", "s", ".", "Doer", "(", "httpClient", ")", "\n", "}" ]
// Http Client // Client sets the http Client used to do requests. If a nil client is given, // the http.DefaultClient will be used.
[ "Http", "Client", "Client", "sets", "the", "http", "Client", "used", "to", "do", "requests", ".", "If", "a", "nil", "client", "is", "given", "the", "http", ".", "DefaultClient", "will", "be", "used", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L87-L92
8,634
dghubble/sling
sling.go
Doer
func (s *Sling) Doer(doer Doer) *Sling { if doer == nil { s.httpClient = http.DefaultClient } else { s.httpClient = doer } return s }
go
func (s *Sling) Doer(doer Doer) *Sling { if doer == nil { s.httpClient = http.DefaultClient } else { s.httpClient = doer } return s }
[ "func", "(", "s", "*", "Sling", ")", "Doer", "(", "doer", "Doer", ")", "*", "Sling", "{", "if", "doer", "==", "nil", "{", "s", ".", "httpClient", "=", "http", ".", "DefaultClient", "\n", "}", "else", "{", "s", ".", "httpClient", "=", "doer", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Doer sets the custom Doer implementation used to do requests. // If a nil client is given, the http.DefaultClient will be used.
[ "Doer", "sets", "the", "custom", "Doer", "implementation", "used", "to", "do", "requests", ".", "If", "a", "nil", "client", "is", "given", "the", "http", ".", "DefaultClient", "will", "be", "used", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L96-L103
8,635
dghubble/sling
sling.go
Head
func (s *Sling) Head(pathURL string) *Sling { s.method = "HEAD" return s.Path(pathURL) }
go
func (s *Sling) Head(pathURL string) *Sling { s.method = "HEAD" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Head", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Method // Head sets the Sling method to HEAD and sets the given pathURL.
[ "Method", "Head", "sets", "the", "Sling", "method", "to", "HEAD", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L108-L111
8,636
dghubble/sling
sling.go
Get
func (s *Sling) Get(pathURL string) *Sling { s.method = "GET" return s.Path(pathURL) }
go
func (s *Sling) Get(pathURL string) *Sling { s.method = "GET" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Get", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Get sets the Sling method to GET and sets the given pathURL.
[ "Get", "sets", "the", "Sling", "method", "to", "GET", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L114-L117
8,637
dghubble/sling
sling.go
Post
func (s *Sling) Post(pathURL string) *Sling { s.method = "POST" return s.Path(pathURL) }
go
func (s *Sling) Post(pathURL string) *Sling { s.method = "POST" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Post", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Post sets the Sling method to POST and sets the given pathURL.
[ "Post", "sets", "the", "Sling", "method", "to", "POST", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L120-L123
8,638
dghubble/sling
sling.go
Put
func (s *Sling) Put(pathURL string) *Sling { s.method = "PUT" return s.Path(pathURL) }
go
func (s *Sling) Put(pathURL string) *Sling { s.method = "PUT" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Put", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Put sets the Sling method to PUT and sets the given pathURL.
[ "Put", "sets", "the", "Sling", "method", "to", "PUT", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L126-L129
8,639
dghubble/sling
sling.go
Patch
func (s *Sling) Patch(pathURL string) *Sling { s.method = "PATCH" return s.Path(pathURL) }
go
func (s *Sling) Patch(pathURL string) *Sling { s.method = "PATCH" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Patch", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Patch sets the Sling method to PATCH and sets the given pathURL.
[ "Patch", "sets", "the", "Sling", "method", "to", "PATCH", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L132-L135
8,640
dghubble/sling
sling.go
Delete
func (s *Sling) Delete(pathURL string) *Sling { s.method = "DELETE" return s.Path(pathURL) }
go
func (s *Sling) Delete(pathURL string) *Sling { s.method = "DELETE" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Delete", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Delete sets the Sling method to DELETE and sets the given pathURL.
[ "Delete", "sets", "the", "Sling", "method", "to", "DELETE", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L138-L141
8,641
dghubble/sling
sling.go
Options
func (s *Sling) Options(pathURL string) *Sling { s.method = "OPTIONS" return s.Path(pathURL) }
go
func (s *Sling) Options(pathURL string) *Sling { s.method = "OPTIONS" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Options", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Options sets the Sling method to OPTIONS and sets the given pathURL.
[ "Options", "sets", "the", "Sling", "method", "to", "OPTIONS", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L144-L147
8,642
dghubble/sling
sling.go
Trace
func (s *Sling) Trace(pathURL string) *Sling { s.method = "TRACE" return s.Path(pathURL) }
go
func (s *Sling) Trace(pathURL string) *Sling { s.method = "TRACE" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Trace", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Trace sets the Sling method to TRACE and sets the given pathURL.
[ "Trace", "sets", "the", "Sling", "method", "to", "TRACE", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L150-L153
8,643
dghubble/sling
sling.go
Connect
func (s *Sling) Connect(pathURL string) *Sling { s.method = "CONNECT" return s.Path(pathURL) }
go
func (s *Sling) Connect(pathURL string) *Sling { s.method = "CONNECT" return s.Path(pathURL) }
[ "func", "(", "s", "*", "Sling", ")", "Connect", "(", "pathURL", "string", ")", "*", "Sling", "{", "s", ".", "method", "=", "\"", "\"", "\n", "return", "s", ".", "Path", "(", "pathURL", ")", "\n", "}" ]
// Connect sets the Sling method to CONNECT and sets the given pathURL.
[ "Connect", "sets", "the", "Sling", "method", "to", "CONNECT", "and", "sets", "the", "given", "pathURL", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L156-L159
8,644
dghubble/sling
sling.go
Add
func (s *Sling) Add(key, value string) *Sling { s.header.Add(key, value) return s }
go
func (s *Sling) Add(key, value string) *Sling { s.header.Add(key, value) return s }
[ "func", "(", "s", "*", "Sling", ")", "Add", "(", "key", ",", "value", "string", ")", "*", "Sling", "{", "s", ".", "header", ".", "Add", "(", "key", ",", "value", ")", "\n", "return", "s", "\n", "}" ]
// Header // Add adds the key, value pair in Headers, appending values for existing keys // to the key's values. Header keys are canonicalized.
[ "Header", "Add", "adds", "the", "key", "value", "pair", "in", "Headers", "appending", "values", "for", "existing", "keys", "to", "the", "key", "s", "values", ".", "Header", "keys", "are", "canonicalized", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L165-L168
8,645
dghubble/sling
sling.go
Set
func (s *Sling) Set(key, value string) *Sling { s.header.Set(key, value) return s }
go
func (s *Sling) Set(key, value string) *Sling { s.header.Set(key, value) return s }
[ "func", "(", "s", "*", "Sling", ")", "Set", "(", "key", ",", "value", "string", ")", "*", "Sling", "{", "s", ".", "header", ".", "Set", "(", "key", ",", "value", ")", "\n", "return", "s", "\n", "}" ]
// Set sets the key, value pair in Headers, replacing existing values // associated with key. Header keys are canonicalized.
[ "Set", "sets", "the", "key", "value", "pair", "in", "Headers", "replacing", "existing", "values", "associated", "with", "key", ".", "Header", "keys", "are", "canonicalized", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L172-L175
8,646
dghubble/sling
sling.go
SetBasicAuth
func (s *Sling) SetBasicAuth(username, password string) *Sling { return s.Set("Authorization", "Basic "+basicAuth(username, password)) }
go
func (s *Sling) SetBasicAuth(username, password string) *Sling { return s.Set("Authorization", "Basic "+basicAuth(username, password)) }
[ "func", "(", "s", "*", "Sling", ")", "SetBasicAuth", "(", "username", ",", "password", "string", ")", "*", "Sling", "{", "return", "s", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", "+", "basicAuth", "(", "username", ",", "password", ")", ")", "\n", "}" ]
// SetBasicAuth sets the Authorization header to use HTTP Basic Authentication // with the provided username and password. With HTTP Basic Authentication // the provided username and password are not encrypted.
[ "SetBasicAuth", "sets", "the", "Authorization", "header", "to", "use", "HTTP", "Basic", "Authentication", "with", "the", "provided", "username", "and", "password", ".", "With", "HTTP", "Basic", "Authentication", "the", "provided", "username", "and", "password", "are", "not", "encrypted", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L180-L182
8,647
dghubble/sling
sling.go
Base
func (s *Sling) Base(rawURL string) *Sling { s.rawURL = rawURL return s }
go
func (s *Sling) Base(rawURL string) *Sling { s.rawURL = rawURL return s }
[ "func", "(", "s", "*", "Sling", ")", "Base", "(", "rawURL", "string", ")", "*", "Sling", "{", "s", ".", "rawURL", "=", "rawURL", "\n", "return", "s", "\n", "}" ]
// Url // Base sets the rawURL. If you intend to extend the url with Path, // baseUrl should be specified with a trailing slash.
[ "Url", "Base", "sets", "the", "rawURL", ".", "If", "you", "intend", "to", "extend", "the", "url", "with", "Path", "baseUrl", "should", "be", "specified", "with", "a", "trailing", "slash", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L195-L198
8,648
dghubble/sling
sling.go
Path
func (s *Sling) Path(path string) *Sling { baseURL, baseErr := url.Parse(s.rawURL) pathURL, pathErr := url.Parse(path) if baseErr == nil && pathErr == nil { s.rawURL = baseURL.ResolveReference(pathURL).String() return s } return s }
go
func (s *Sling) Path(path string) *Sling { baseURL, baseErr := url.Parse(s.rawURL) pathURL, pathErr := url.Parse(path) if baseErr == nil && pathErr == nil { s.rawURL = baseURL.ResolveReference(pathURL).String() return s } return s }
[ "func", "(", "s", "*", "Sling", ")", "Path", "(", "path", "string", ")", "*", "Sling", "{", "baseURL", ",", "baseErr", ":=", "url", ".", "Parse", "(", "s", ".", "rawURL", ")", "\n", "pathURL", ",", "pathErr", ":=", "url", ".", "Parse", "(", "path", ")", "\n", "if", "baseErr", "==", "nil", "&&", "pathErr", "==", "nil", "{", "s", ".", "rawURL", "=", "baseURL", ".", "ResolveReference", "(", "pathURL", ")", ".", "String", "(", ")", "\n", "return", "s", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Path extends the rawURL with the given path by resolving the reference to // an absolute URL. If parsing errors occur, the rawURL is left unmodified.
[ "Path", "extends", "the", "rawURL", "with", "the", "given", "path", "by", "resolving", "the", "reference", "to", "an", "absolute", "URL", ".", "If", "parsing", "errors", "occur", "the", "rawURL", "is", "left", "unmodified", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L202-L210
8,649
dghubble/sling
sling.go
BodyProvider
func (s *Sling) BodyProvider(body BodyProvider) *Sling { if body == nil { return s } s.bodyProvider = body ct := body.ContentType() if ct != "" { s.Set(contentType, ct) } return s }
go
func (s *Sling) BodyProvider(body BodyProvider) *Sling { if body == nil { return s } s.bodyProvider = body ct := body.ContentType() if ct != "" { s.Set(contentType, ct) } return s }
[ "func", "(", "s", "*", "Sling", ")", "BodyProvider", "(", "body", "BodyProvider", ")", "*", "Sling", "{", "if", "body", "==", "nil", "{", "return", "s", "\n", "}", "\n", "s", ".", "bodyProvider", "=", "body", "\n\n", "ct", ":=", "body", ".", "ContentType", "(", ")", "\n", "if", "ct", "!=", "\"", "\"", "{", "s", ".", "Set", "(", "contentType", ",", "ct", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// BodyProvider sets the Sling's body provider.
[ "BodyProvider", "sets", "the", "Sling", "s", "body", "provider", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L238-L250
8,650
dghubble/sling
sling.go
Request
func (s *Sling) Request() (*http.Request, error) { reqURL, err := url.Parse(s.rawURL) if err != nil { return nil, err } err = addQueryStructs(reqURL, s.queryStructs) if err != nil { return nil, err } var body io.Reader if s.bodyProvider != nil { body, err = s.bodyProvider.Body() if err != nil { return nil, err } } req, err := http.NewRequest(s.method, reqURL.String(), body) if err != nil { return nil, err } addHeaders(req, s.header) return req, err }
go
func (s *Sling) Request() (*http.Request, error) { reqURL, err := url.Parse(s.rawURL) if err != nil { return nil, err } err = addQueryStructs(reqURL, s.queryStructs) if err != nil { return nil, err } var body io.Reader if s.bodyProvider != nil { body, err = s.bodyProvider.Body() if err != nil { return nil, err } } req, err := http.NewRequest(s.method, reqURL.String(), body) if err != nil { return nil, err } addHeaders(req, s.header) return req, err }
[ "func", "(", "s", "*", "Sling", ")", "Request", "(", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "reqURL", ",", "err", ":=", "url", ".", "Parse", "(", "s", ".", "rawURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "addQueryStructs", "(", "reqURL", ",", "s", ".", "queryStructs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "body", "io", ".", "Reader", "\n", "if", "s", ".", "bodyProvider", "!=", "nil", "{", "body", ",", "err", "=", "s", ".", "bodyProvider", ".", "Body", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "s", ".", "method", ",", "reqURL", ".", "String", "(", ")", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addHeaders", "(", "req", ",", "s", ".", "header", ")", "\n", "return", "req", ",", "err", "\n", "}" ]
// Requests // Request returns a new http.Request created with the Sling properties. // Returns any errors parsing the rawURL, encoding query structs, encoding // the body, or creating the http.Request.
[ "Requests", "Request", "returns", "a", "new", "http", ".", "Request", "created", "with", "the", "Sling", "properties", ".", "Returns", "any", "errors", "parsing", "the", "rawURL", "encoding", "query", "structs", "encoding", "the", "body", "or", "creating", "the", "http", ".", "Request", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L279-L303
8,651
dghubble/sling
sling.go
addQueryStructs
func addQueryStructs(reqURL *url.URL, queryStructs []interface{}) error { urlValues, err := url.ParseQuery(reqURL.RawQuery) if err != nil { return err } // encodes query structs into a url.Values map and merges maps for _, queryStruct := range queryStructs { queryValues, err := goquery.Values(queryStruct) if err != nil { return err } for key, values := range queryValues { for _, value := range values { urlValues.Add(key, value) } } } // url.Values format to a sorted "url encoded" string, e.g. "key=val&foo=bar" reqURL.RawQuery = urlValues.Encode() return nil }
go
func addQueryStructs(reqURL *url.URL, queryStructs []interface{}) error { urlValues, err := url.ParseQuery(reqURL.RawQuery) if err != nil { return err } // encodes query structs into a url.Values map and merges maps for _, queryStruct := range queryStructs { queryValues, err := goquery.Values(queryStruct) if err != nil { return err } for key, values := range queryValues { for _, value := range values { urlValues.Add(key, value) } } } // url.Values format to a sorted "url encoded" string, e.g. "key=val&foo=bar" reqURL.RawQuery = urlValues.Encode() return nil }
[ "func", "addQueryStructs", "(", "reqURL", "*", "url", ".", "URL", ",", "queryStructs", "[", "]", "interface", "{", "}", ")", "error", "{", "urlValues", ",", "err", ":=", "url", ".", "ParseQuery", "(", "reqURL", ".", "RawQuery", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// encodes query structs into a url.Values map and merges maps", "for", "_", ",", "queryStruct", ":=", "range", "queryStructs", "{", "queryValues", ",", "err", ":=", "goquery", ".", "Values", "(", "queryStruct", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "key", ",", "values", ":=", "range", "queryValues", "{", "for", "_", ",", "value", ":=", "range", "values", "{", "urlValues", ".", "Add", "(", "key", ",", "value", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "// url.Values format to a sorted \"url encoded\" string, e.g. \"key=val&foo=bar\"", "reqURL", ".", "RawQuery", "=", "urlValues", ".", "Encode", "(", ")", "\n", "return", "nil", "\n", "}" ]
// addQueryStructs parses url tagged query structs using go-querystring to // encode them to url.Values and format them onto the url.RawQuery. Any // query parsing or encoding errors are returned.
[ "addQueryStructs", "parses", "url", "tagged", "query", "structs", "using", "go", "-", "querystring", "to", "encode", "them", "to", "url", ".", "Values", "and", "format", "them", "onto", "the", "url", ".", "RawQuery", ".", "Any", "query", "parsing", "or", "encoding", "errors", "are", "returned", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L308-L328
8,652
dghubble/sling
sling.go
addHeaders
func addHeaders(req *http.Request, header http.Header) { for key, values := range header { for _, value := range values { req.Header.Add(key, value) } } }
go
func addHeaders(req *http.Request, header http.Header) { for key, values := range header { for _, value := range values { req.Header.Add(key, value) } } }
[ "func", "addHeaders", "(", "req", "*", "http", ".", "Request", ",", "header", "http", ".", "Header", ")", "{", "for", "key", ",", "values", ":=", "range", "header", "{", "for", "_", ",", "value", ":=", "range", "values", "{", "req", ".", "Header", ".", "Add", "(", "key", ",", "value", ")", "\n", "}", "\n", "}", "\n", "}" ]
// addHeaders adds the key, value pairs from the given http.Header to the // request. Values for existing keys are appended to the keys values.
[ "addHeaders", "adds", "the", "key", "value", "pairs", "from", "the", "given", "http", ".", "Header", "to", "the", "request", ".", "Values", "for", "existing", "keys", "are", "appended", "to", "the", "keys", "values", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L332-L338
8,653
dghubble/sling
sling.go
ResponseDecoder
func (s *Sling) ResponseDecoder(decoder ResponseDecoder) *Sling { if decoder == nil { return s } s.responseDecoder = decoder return s }
go
func (s *Sling) ResponseDecoder(decoder ResponseDecoder) *Sling { if decoder == nil { return s } s.responseDecoder = decoder return s }
[ "func", "(", "s", "*", "Sling", ")", "ResponseDecoder", "(", "decoder", "ResponseDecoder", ")", "*", "Sling", "{", "if", "decoder", "==", "nil", "{", "return", "s", "\n", "}", "\n", "s", ".", "responseDecoder", "=", "decoder", "\n", "return", "s", "\n", "}" ]
// Sending // ResponseDecoder sets the Sling's response decoder.
[ "Sending", "ResponseDecoder", "sets", "the", "Sling", "s", "response", "decoder", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/sling.go#L343-L349
8,654
dghubble/sling
response.go
Decode
func (d jsonDecoder) Decode(resp *http.Response, v interface{}) error { return json.NewDecoder(resp.Body).Decode(v) }
go
func (d jsonDecoder) Decode(resp *http.Response, v interface{}) error { return json.NewDecoder(resp.Body).Decode(v) }
[ "func", "(", "d", "jsonDecoder", ")", "Decode", "(", "resp", "*", "http", ".", "Response", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "v", ")", "\n", "}" ]
// Decode decodes the Response Body into the value pointed to by v. // Caller must provide a non-nil v and close the resp.Body.
[ "Decode", "decodes", "the", "Response", "Body", "into", "the", "value", "pointed", "to", "by", "v", ".", "Caller", "must", "provide", "a", "non", "-", "nil", "v", "and", "close", "the", "resp", ".", "Body", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/response.go#L20-L22
8,655
dghubble/sling
examples/github.go
NewIssueService
func NewIssueService(httpClient *http.Client) *IssueService { return &IssueService{ sling: sling.New().Client(httpClient).Base(baseURL), } }
go
func NewIssueService(httpClient *http.Client) *IssueService { return &IssueService{ sling: sling.New().Client(httpClient).Base(baseURL), } }
[ "func", "NewIssueService", "(", "httpClient", "*", "http", ".", "Client", ")", "*", "IssueService", "{", "return", "&", "IssueService", "{", "sling", ":", "sling", ".", "New", "(", ")", ".", "Client", "(", "httpClient", ")", ".", "Base", "(", "baseURL", ")", ",", "}", "\n", "}" ]
// NewIssueService returns a new IssueService.
[ "NewIssueService", "returns", "a", "new", "IssueService", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/examples/github.go#L73-L77
8,656
dghubble/sling
examples/github.go
List
func (s *IssueService) List(params *IssueListParams) ([]Issue, *http.Response, error) { issues := new([]Issue) githubError := new(GithubError) resp, err := s.sling.New().Path("issues").QueryStruct(params).Receive(issues, githubError) if err == nil { err = githubError } return *issues, resp, err }
go
func (s *IssueService) List(params *IssueListParams) ([]Issue, *http.Response, error) { issues := new([]Issue) githubError := new(GithubError) resp, err := s.sling.New().Path("issues").QueryStruct(params).Receive(issues, githubError) if err == nil { err = githubError } return *issues, resp, err }
[ "func", "(", "s", "*", "IssueService", ")", "List", "(", "params", "*", "IssueListParams", ")", "(", "[", "]", "Issue", ",", "*", "http", ".", "Response", ",", "error", ")", "{", "issues", ":=", "new", "(", "[", "]", "Issue", ")", "\n", "githubError", ":=", "new", "(", "GithubError", ")", "\n", "resp", ",", "err", ":=", "s", ".", "sling", ".", "New", "(", ")", ".", "Path", "(", "\"", "\"", ")", ".", "QueryStruct", "(", "params", ")", ".", "Receive", "(", "issues", ",", "githubError", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "githubError", "\n", "}", "\n", "return", "*", "issues", ",", "resp", ",", "err", "\n", "}" ]
// List returns the authenticated user's issues across repos and orgs.
[ "List", "returns", "the", "authenticated", "user", "s", "issues", "across", "repos", "and", "orgs", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/examples/github.go#L80-L88
8,657
dghubble/sling
examples/github.go
ListByRepo
func (s *IssueService) ListByRepo(owner, repo string, params *IssueListParams) ([]Issue, *http.Response, error) { issues := new([]Issue) githubError := new(GithubError) path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) resp, err := s.sling.New().Get(path).QueryStruct(params).Receive(issues, githubError) if err == nil { err = githubError } return *issues, resp, err }
go
func (s *IssueService) ListByRepo(owner, repo string, params *IssueListParams) ([]Issue, *http.Response, error) { issues := new([]Issue) githubError := new(GithubError) path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) resp, err := s.sling.New().Get(path).QueryStruct(params).Receive(issues, githubError) if err == nil { err = githubError } return *issues, resp, err }
[ "func", "(", "s", "*", "IssueService", ")", "ListByRepo", "(", "owner", ",", "repo", "string", ",", "params", "*", "IssueListParams", ")", "(", "[", "]", "Issue", ",", "*", "http", ".", "Response", ",", "error", ")", "{", "issues", ":=", "new", "(", "[", "]", "Issue", ")", "\n", "githubError", ":=", "new", "(", "GithubError", ")", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "owner", ",", "repo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "sling", ".", "New", "(", ")", ".", "Get", "(", "path", ")", ".", "QueryStruct", "(", "params", ")", ".", "Receive", "(", "issues", ",", "githubError", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "githubError", "\n", "}", "\n", "return", "*", "issues", ",", "resp", ",", "err", "\n", "}" ]
// ListByRepo returns a repository's issues.
[ "ListByRepo", "returns", "a", "repository", "s", "issues", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/examples/github.go#L91-L100
8,658
dghubble/sling
examples/github.go
Create
func (s *IssueService) Create(owner, repo string, issueBody *IssueRequest) (*Issue, *http.Response, error) { issue := new(Issue) githubError := new(GithubError) path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) resp, err := s.sling.New().Post(path).BodyJSON(issueBody).Receive(issue, githubError) if err == nil { err = githubError } return issue, resp, err }
go
func (s *IssueService) Create(owner, repo string, issueBody *IssueRequest) (*Issue, *http.Response, error) { issue := new(Issue) githubError := new(GithubError) path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) resp, err := s.sling.New().Post(path).BodyJSON(issueBody).Receive(issue, githubError) if err == nil { err = githubError } return issue, resp, err }
[ "func", "(", "s", "*", "IssueService", ")", "Create", "(", "owner", ",", "repo", "string", ",", "issueBody", "*", "IssueRequest", ")", "(", "*", "Issue", ",", "*", "http", ".", "Response", ",", "error", ")", "{", "issue", ":=", "new", "(", "Issue", ")", "\n", "githubError", ":=", "new", "(", "GithubError", ")", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "owner", ",", "repo", ")", "\n", "resp", ",", "err", ":=", "s", ".", "sling", ".", "New", "(", ")", ".", "Post", "(", "path", ")", ".", "BodyJSON", "(", "issueBody", ")", ".", "Receive", "(", "issue", ",", "githubError", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "githubError", "\n", "}", "\n", "return", "issue", ",", "resp", ",", "err", "\n", "}" ]
// Create creates a new issue on the specified repository.
[ "Create", "creates", "a", "new", "issue", "on", "the", "specified", "repository", "." ]
22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2
https://github.com/dghubble/sling/blob/22538d0bac4e8b6337114fccfdfeb6d1ad0ef2d2/examples/github.go#L103-L112
8,659
cespare/xxhash
xxhash_other.go
Sum64
func Sum64(b []byte) uint64 { // A simpler version would be // d := New() // d.Write(b) // return d.Sum64() // but this is faster, particularly for small inputs. n := len(b) var h uint64 if n >= 32 { v1 := prime1v + prime2 v2 := prime2 v3 := uint64(0) v4 := -prime1v for len(b) >= 32 { v1 = round(v1, u64(b[0:8:len(b)])) v2 = round(v2, u64(b[8:16:len(b)])) v3 = round(v3, u64(b[16:24:len(b)])) v4 = round(v4, u64(b[24:32:len(b)])) b = b[32:len(b):len(b)] } h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) h = mergeRound(h, v1) h = mergeRound(h, v2) h = mergeRound(h, v3) h = mergeRound(h, v4) } else { h = prime5 } h += uint64(n) i, end := 0, len(b) for ; i+8 <= end; i += 8 { k1 := round(0, u64(b[i:i+8:len(b)])) h ^= k1 h = rol27(h)*prime1 + prime4 } if i+4 <= end { h ^= uint64(u32(b[i:i+4:len(b)])) * prime1 h = rol23(h)*prime2 + prime3 i += 4 } for ; i < end; i++ { h ^= uint64(b[i]) * prime5 h = rol11(h) * prime1 } h ^= h >> 33 h *= prime2 h ^= h >> 29 h *= prime3 h ^= h >> 32 return h }
go
func Sum64(b []byte) uint64 { // A simpler version would be // d := New() // d.Write(b) // return d.Sum64() // but this is faster, particularly for small inputs. n := len(b) var h uint64 if n >= 32 { v1 := prime1v + prime2 v2 := prime2 v3 := uint64(0) v4 := -prime1v for len(b) >= 32 { v1 = round(v1, u64(b[0:8:len(b)])) v2 = round(v2, u64(b[8:16:len(b)])) v3 = round(v3, u64(b[16:24:len(b)])) v4 = round(v4, u64(b[24:32:len(b)])) b = b[32:len(b):len(b)] } h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) h = mergeRound(h, v1) h = mergeRound(h, v2) h = mergeRound(h, v3) h = mergeRound(h, v4) } else { h = prime5 } h += uint64(n) i, end := 0, len(b) for ; i+8 <= end; i += 8 { k1 := round(0, u64(b[i:i+8:len(b)])) h ^= k1 h = rol27(h)*prime1 + prime4 } if i+4 <= end { h ^= uint64(u32(b[i:i+4:len(b)])) * prime1 h = rol23(h)*prime2 + prime3 i += 4 } for ; i < end; i++ { h ^= uint64(b[i]) * prime5 h = rol11(h) * prime1 } h ^= h >> 33 h *= prime2 h ^= h >> 29 h *= prime3 h ^= h >> 32 return h }
[ "func", "Sum64", "(", "b", "[", "]", "byte", ")", "uint64", "{", "// A simpler version would be", "// d := New()", "// d.Write(b)", "// return d.Sum64()", "// but this is faster, particularly for small inputs.", "n", ":=", "len", "(", "b", ")", "\n", "var", "h", "uint64", "\n\n", "if", "n", ">=", "32", "{", "v1", ":=", "prime1v", "+", "prime2", "\n", "v2", ":=", "prime2", "\n", "v3", ":=", "uint64", "(", "0", ")", "\n", "v4", ":=", "-", "prime1v", "\n", "for", "len", "(", "b", ")", ">=", "32", "{", "v1", "=", "round", "(", "v1", ",", "u64", "(", "b", "[", "0", ":", "8", ":", "len", "(", "b", ")", "]", ")", ")", "\n", "v2", "=", "round", "(", "v2", ",", "u64", "(", "b", "[", "8", ":", "16", ":", "len", "(", "b", ")", "]", ")", ")", "\n", "v3", "=", "round", "(", "v3", ",", "u64", "(", "b", "[", "16", ":", "24", ":", "len", "(", "b", ")", "]", ")", ")", "\n", "v4", "=", "round", "(", "v4", ",", "u64", "(", "b", "[", "24", ":", "32", ":", "len", "(", "b", ")", "]", ")", ")", "\n", "b", "=", "b", "[", "32", ":", "len", "(", "b", ")", ":", "len", "(", "b", ")", "]", "\n", "}", "\n", "h", "=", "rol1", "(", "v1", ")", "+", "rol7", "(", "v2", ")", "+", "rol12", "(", "v3", ")", "+", "rol18", "(", "v4", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v1", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v2", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v3", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v4", ")", "\n", "}", "else", "{", "h", "=", "prime5", "\n", "}", "\n\n", "h", "+=", "uint64", "(", "n", ")", "\n\n", "i", ",", "end", ":=", "0", ",", "len", "(", "b", ")", "\n", "for", ";", "i", "+", "8", "<=", "end", ";", "i", "+=", "8", "{", "k1", ":=", "round", "(", "0", ",", "u64", "(", "b", "[", "i", ":", "i", "+", "8", ":", "len", "(", "b", ")", "]", ")", ")", "\n", "h", "^=", "k1", "\n", "h", "=", "rol27", "(", "h", ")", "*", "prime1", "+", "prime4", "\n", "}", "\n", "if", "i", "+", "4", "<=", "end", "{", "h", "^=", "uint64", "(", "u32", "(", "b", "[", "i", ":", "i", "+", "4", ":", "len", "(", "b", ")", "]", ")", ")", "*", "prime1", "\n", "h", "=", "rol23", "(", "h", ")", "*", "prime2", "+", "prime3", "\n", "i", "+=", "4", "\n", "}", "\n", "for", ";", "i", "<", "end", ";", "i", "++", "{", "h", "^=", "uint64", "(", "b", "[", "i", "]", ")", "*", "prime5", "\n", "h", "=", "rol11", "(", "h", ")", "*", "prime1", "\n", "}", "\n\n", "h", "^=", "h", ">>", "33", "\n", "h", "*=", "prime2", "\n", "h", "^=", "h", ">>", "29", "\n", "h", "*=", "prime3", "\n", "h", "^=", "h", ">>", "32", "\n\n", "return", "h", "\n", "}" ]
// Sum64 computes the 64-bit xxHash digest of b.
[ "Sum64", "computes", "the", "64", "-", "bit", "xxHash", "digest", "of", "b", "." ]
3767db7a7e183c0ad3395680d460d0b61534ae7b
https://github.com/cespare/xxhash/blob/3767db7a7e183c0ad3395680d460d0b61534ae7b/xxhash_other.go#L6-L62
8,660
cespare/xxhash
xxhash.go
Reset
func (d *Digest) Reset() { d.v1 = prime1v + prime2 d.v2 = prime2 d.v3 = 0 d.v4 = -prime1v d.total = 0 d.n = 0 }
go
func (d *Digest) Reset() { d.v1 = prime1v + prime2 d.v2 = prime2 d.v3 = 0 d.v4 = -prime1v d.total = 0 d.n = 0 }
[ "func", "(", "d", "*", "Digest", ")", "Reset", "(", ")", "{", "d", ".", "v1", "=", "prime1v", "+", "prime2", "\n", "d", ".", "v2", "=", "prime2", "\n", "d", ".", "v3", "=", "0", "\n", "d", ".", "v4", "=", "-", "prime1v", "\n", "d", ".", "total", "=", "0", "\n", "d", ".", "n", "=", "0", "\n", "}" ]
// Reset clears the Digest's state so that it can be reused.
[ "Reset", "clears", "the", "Digest", "s", "state", "so", "that", "it", "can", "be", "reused", "." ]
3767db7a7e183c0ad3395680d460d0b61534ae7b
https://github.com/cespare/xxhash/blob/3767db7a7e183c0ad3395680d460d0b61534ae7b/xxhash.go#L52-L59
8,661
cespare/xxhash
xxhash.go
Sum
func (d *Digest) Sum(b []byte) []byte { s := d.Sum64() return append( b, byte(s>>56), byte(s>>48), byte(s>>40), byte(s>>32), byte(s>>24), byte(s>>16), byte(s>>8), byte(s), ) }
go
func (d *Digest) Sum(b []byte) []byte { s := d.Sum64() return append( b, byte(s>>56), byte(s>>48), byte(s>>40), byte(s>>32), byte(s>>24), byte(s>>16), byte(s>>8), byte(s), ) }
[ "func", "(", "d", "*", "Digest", ")", "Sum", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "s", ":=", "d", ".", "Sum64", "(", ")", "\n", "return", "append", "(", "b", ",", "byte", "(", "s", ">>", "56", ")", ",", "byte", "(", "s", ">>", "48", ")", ",", "byte", "(", "s", ">>", "40", ")", ",", "byte", "(", "s", ">>", "32", ")", ",", "byte", "(", "s", ">>", "24", ")", ",", "byte", "(", "s", ">>", "16", ")", ",", "byte", "(", "s", ">>", "8", ")", ",", "byte", "(", "s", ")", ",", ")", "\n", "}" ]
// Sum appends the current hash to b and returns the resulting slice.
[ "Sum", "appends", "the", "current", "hash", "to", "b", "and", "returns", "the", "resulting", "slice", "." ]
3767db7a7e183c0ad3395680d460d0b61534ae7b
https://github.com/cespare/xxhash/blob/3767db7a7e183c0ad3395680d460d0b61534ae7b/xxhash.go#L104-L117
8,662
cespare/xxhash
xxhash.go
Sum64
func (d *Digest) Sum64() uint64 { var h uint64 if d.total >= 32 { v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) h = mergeRound(h, v1) h = mergeRound(h, v2) h = mergeRound(h, v3) h = mergeRound(h, v4) } else { h = d.v3 + prime5 } h += d.total i, end := 0, d.n for ; i+8 <= end; i += 8 { k1 := round(0, u64(d.mem[i:i+8])) h ^= k1 h = rol27(h)*prime1 + prime4 } if i+4 <= end { h ^= uint64(u32(d.mem[i:i+4])) * prime1 h = rol23(h)*prime2 + prime3 i += 4 } for i < end { h ^= uint64(d.mem[i]) * prime5 h = rol11(h) * prime1 i++ } h ^= h >> 33 h *= prime2 h ^= h >> 29 h *= prime3 h ^= h >> 32 return h }
go
func (d *Digest) Sum64() uint64 { var h uint64 if d.total >= 32 { v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) h = mergeRound(h, v1) h = mergeRound(h, v2) h = mergeRound(h, v3) h = mergeRound(h, v4) } else { h = d.v3 + prime5 } h += d.total i, end := 0, d.n for ; i+8 <= end; i += 8 { k1 := round(0, u64(d.mem[i:i+8])) h ^= k1 h = rol27(h)*prime1 + prime4 } if i+4 <= end { h ^= uint64(u32(d.mem[i:i+4])) * prime1 h = rol23(h)*prime2 + prime3 i += 4 } for i < end { h ^= uint64(d.mem[i]) * prime5 h = rol11(h) * prime1 i++ } h ^= h >> 33 h *= prime2 h ^= h >> 29 h *= prime3 h ^= h >> 32 return h }
[ "func", "(", "d", "*", "Digest", ")", "Sum64", "(", ")", "uint64", "{", "var", "h", "uint64", "\n\n", "if", "d", ".", "total", ">=", "32", "{", "v1", ",", "v2", ",", "v3", ",", "v4", ":=", "d", ".", "v1", ",", "d", ".", "v2", ",", "d", ".", "v3", ",", "d", ".", "v4", "\n", "h", "=", "rol1", "(", "v1", ")", "+", "rol7", "(", "v2", ")", "+", "rol12", "(", "v3", ")", "+", "rol18", "(", "v4", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v1", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v2", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v3", ")", "\n", "h", "=", "mergeRound", "(", "h", ",", "v4", ")", "\n", "}", "else", "{", "h", "=", "d", ".", "v3", "+", "prime5", "\n", "}", "\n\n", "h", "+=", "d", ".", "total", "\n\n", "i", ",", "end", ":=", "0", ",", "d", ".", "n", "\n", "for", ";", "i", "+", "8", "<=", "end", ";", "i", "+=", "8", "{", "k1", ":=", "round", "(", "0", ",", "u64", "(", "d", ".", "mem", "[", "i", ":", "i", "+", "8", "]", ")", ")", "\n", "h", "^=", "k1", "\n", "h", "=", "rol27", "(", "h", ")", "*", "prime1", "+", "prime4", "\n", "}", "\n", "if", "i", "+", "4", "<=", "end", "{", "h", "^=", "uint64", "(", "u32", "(", "d", ".", "mem", "[", "i", ":", "i", "+", "4", "]", ")", ")", "*", "prime1", "\n", "h", "=", "rol23", "(", "h", ")", "*", "prime2", "+", "prime3", "\n", "i", "+=", "4", "\n", "}", "\n", "for", "i", "<", "end", "{", "h", "^=", "uint64", "(", "d", ".", "mem", "[", "i", "]", ")", "*", "prime5", "\n", "h", "=", "rol11", "(", "h", ")", "*", "prime1", "\n", "i", "++", "\n", "}", "\n\n", "h", "^=", "h", ">>", "33", "\n", "h", "*=", "prime2", "\n", "h", "^=", "h", ">>", "29", "\n", "h", "*=", "prime3", "\n", "h", "^=", "h", ">>", "32", "\n\n", "return", "h", "\n", "}" ]
// Sum64 returns the current hash.
[ "Sum64", "returns", "the", "current", "hash", "." ]
3767db7a7e183c0ad3395680d460d0b61534ae7b
https://github.com/cespare/xxhash/blob/3767db7a7e183c0ad3395680d460d0b61534ae7b/xxhash.go#L120-L160
8,663
throttled/throttled
deprecated.go
RateLimit
func RateLimit(q Quota, vary *VaryBy, store GCRAStore) *Throttler { count, period := q.Quota() if count < 1 { count = 1 } if period <= 0 { period = time.Second } rate := Rate{period: period / time.Duration(count)} limiter, err := NewGCRARateLimiter(store, RateQuota{rate, count - 1}) // This panic in unavoidable because the original interface does // not support returning an error. if err != nil { panic(err) } return &Throttler{ HTTPRateLimiter{ RateLimiter: limiter, VaryBy: vary, }, } }
go
func RateLimit(q Quota, vary *VaryBy, store GCRAStore) *Throttler { count, period := q.Quota() if count < 1 { count = 1 } if period <= 0 { period = time.Second } rate := Rate{period: period / time.Duration(count)} limiter, err := NewGCRARateLimiter(store, RateQuota{rate, count - 1}) // This panic in unavoidable because the original interface does // not support returning an error. if err != nil { panic(err) } return &Throttler{ HTTPRateLimiter{ RateLimiter: limiter, VaryBy: vary, }, } }
[ "func", "RateLimit", "(", "q", "Quota", ",", "vary", "*", "VaryBy", ",", "store", "GCRAStore", ")", "*", "Throttler", "{", "count", ",", "period", ":=", "q", ".", "Quota", "(", ")", "\n\n", "if", "count", "<", "1", "{", "count", "=", "1", "\n", "}", "\n", "if", "period", "<=", "0", "{", "period", "=", "time", ".", "Second", "\n", "}", "\n\n", "rate", ":=", "Rate", "{", "period", ":", "period", "/", "time", ".", "Duration", "(", "count", ")", "}", "\n", "limiter", ",", "err", ":=", "NewGCRARateLimiter", "(", "store", ",", "RateQuota", "{", "rate", ",", "count", "-", "1", "}", ")", "\n\n", "// This panic in unavoidable because the original interface does", "// not support returning an error.", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "Throttler", "{", "HTTPRateLimiter", "{", "RateLimiter", ":", "limiter", ",", "VaryBy", ":", "vary", ",", "}", ",", "}", "\n", "}" ]
// DEPRECATED. RateLimit creates a Throttler that conforms to the given // rate limits
[ "DEPRECATED", ".", "RateLimit", "creates", "a", "Throttler", "that", "conforms", "to", "the", "given", "rate", "limits" ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/deprecated.go#L43-L68
8,664
throttled/throttled
store/redigostore/redigostore.go
getConn
func (r *RedigoStore) getConn() (redis.Conn, error) { conn := r.pool.Get() // Select the specified database if r.db > 0 { if _, err := redis.String(conn.Do("SELECT", r.db)); err != nil { conn.Close() return nil, err } } return conn, nil }
go
func (r *RedigoStore) getConn() (redis.Conn, error) { conn := r.pool.Get() // Select the specified database if r.db > 0 { if _, err := redis.String(conn.Do("SELECT", r.db)); err != nil { conn.Close() return nil, err } } return conn, nil }
[ "func", "(", "r", "*", "RedigoStore", ")", "getConn", "(", ")", "(", "redis", ".", "Conn", ",", "error", ")", "{", "conn", ":=", "r", ".", "pool", ".", "Get", "(", ")", "\n\n", "// Select the specified database", "if", "r", ".", "db", ">", "0", "{", "if", "_", ",", "err", ":=", "redis", ".", "String", "(", "conn", ".", "Do", "(", "\"", "\"", ",", "r", ".", "db", ")", ")", ";", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// Select the specified database index.
[ "Select", "the", "specified", "database", "index", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/redigostore/redigostore.go#L156-L168
8,665
throttled/throttled
rate.go
RateLimit
func (g *GCRARateLimiter) RateLimit(key string, quantity int) (bool, RateLimitResult, error) { var tat, newTat, now time.Time var ttl time.Duration rlc := RateLimitResult{Limit: g.limit, RetryAfter: -1} limited := false i := 0 for { var err error var tatVal int64 var updated bool // tat refers to the theoretical arrival time that would be expected // from equally spaced requests at exactly the rate limit. tatVal, now, err = g.store.GetWithTime(key) if err != nil { return false, rlc, err } if tatVal == -1 { tat = now } else { tat = time.Unix(0, tatVal) } increment := time.Duration(quantity) * g.emissionInterval if now.After(tat) { newTat = now.Add(increment) } else { newTat = tat.Add(increment) } // Block the request if the next permitted time is in the future allowAt := newTat.Add(-(g.delayVariationTolerance)) if diff := now.Sub(allowAt); diff < 0 { if increment <= g.delayVariationTolerance { rlc.RetryAfter = -diff } ttl = tat.Sub(now) limited = true break } ttl = newTat.Sub(now) if tatVal == -1 { updated, err = g.store.SetIfNotExistsWithTTL(key, newTat.UnixNano(), ttl) } else { updated, err = g.store.CompareAndSwapWithTTL(key, tatVal, newTat.UnixNano(), ttl) } if err != nil { return false, rlc, err } if updated { break } i++ if i > maxCASAttempts { return false, rlc, fmt.Errorf( "Failed to store updated rate limit data for key %s after %d attempts", key, i, ) } } next := g.delayVariationTolerance - ttl if next > -g.emissionInterval { rlc.Remaining = int(next / g.emissionInterval) } rlc.ResetAfter = ttl return limited, rlc, nil }
go
func (g *GCRARateLimiter) RateLimit(key string, quantity int) (bool, RateLimitResult, error) { var tat, newTat, now time.Time var ttl time.Duration rlc := RateLimitResult{Limit: g.limit, RetryAfter: -1} limited := false i := 0 for { var err error var tatVal int64 var updated bool // tat refers to the theoretical arrival time that would be expected // from equally spaced requests at exactly the rate limit. tatVal, now, err = g.store.GetWithTime(key) if err != nil { return false, rlc, err } if tatVal == -1 { tat = now } else { tat = time.Unix(0, tatVal) } increment := time.Duration(quantity) * g.emissionInterval if now.After(tat) { newTat = now.Add(increment) } else { newTat = tat.Add(increment) } // Block the request if the next permitted time is in the future allowAt := newTat.Add(-(g.delayVariationTolerance)) if diff := now.Sub(allowAt); diff < 0 { if increment <= g.delayVariationTolerance { rlc.RetryAfter = -diff } ttl = tat.Sub(now) limited = true break } ttl = newTat.Sub(now) if tatVal == -1 { updated, err = g.store.SetIfNotExistsWithTTL(key, newTat.UnixNano(), ttl) } else { updated, err = g.store.CompareAndSwapWithTTL(key, tatVal, newTat.UnixNano(), ttl) } if err != nil { return false, rlc, err } if updated { break } i++ if i > maxCASAttempts { return false, rlc, fmt.Errorf( "Failed to store updated rate limit data for key %s after %d attempts", key, i, ) } } next := g.delayVariationTolerance - ttl if next > -g.emissionInterval { rlc.Remaining = int(next / g.emissionInterval) } rlc.ResetAfter = ttl return limited, rlc, nil }
[ "func", "(", "g", "*", "GCRARateLimiter", ")", "RateLimit", "(", "key", "string", ",", "quantity", "int", ")", "(", "bool", ",", "RateLimitResult", ",", "error", ")", "{", "var", "tat", ",", "newTat", ",", "now", "time", ".", "Time", "\n", "var", "ttl", "time", ".", "Duration", "\n", "rlc", ":=", "RateLimitResult", "{", "Limit", ":", "g", ".", "limit", ",", "RetryAfter", ":", "-", "1", "}", "\n", "limited", ":=", "false", "\n\n", "i", ":=", "0", "\n", "for", "{", "var", "err", "error", "\n", "var", "tatVal", "int64", "\n", "var", "updated", "bool", "\n\n", "// tat refers to the theoretical arrival time that would be expected", "// from equally spaced requests at exactly the rate limit.", "tatVal", ",", "now", ",", "err", "=", "g", ".", "store", ".", "GetWithTime", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "rlc", ",", "err", "\n", "}", "\n\n", "if", "tatVal", "==", "-", "1", "{", "tat", "=", "now", "\n", "}", "else", "{", "tat", "=", "time", ".", "Unix", "(", "0", ",", "tatVal", ")", "\n", "}", "\n\n", "increment", ":=", "time", ".", "Duration", "(", "quantity", ")", "*", "g", ".", "emissionInterval", "\n", "if", "now", ".", "After", "(", "tat", ")", "{", "newTat", "=", "now", ".", "Add", "(", "increment", ")", "\n", "}", "else", "{", "newTat", "=", "tat", ".", "Add", "(", "increment", ")", "\n", "}", "\n\n", "// Block the request if the next permitted time is in the future", "allowAt", ":=", "newTat", ".", "Add", "(", "-", "(", "g", ".", "delayVariationTolerance", ")", ")", "\n", "if", "diff", ":=", "now", ".", "Sub", "(", "allowAt", ")", ";", "diff", "<", "0", "{", "if", "increment", "<=", "g", ".", "delayVariationTolerance", "{", "rlc", ".", "RetryAfter", "=", "-", "diff", "\n", "}", "\n", "ttl", "=", "tat", ".", "Sub", "(", "now", ")", "\n", "limited", "=", "true", "\n", "break", "\n", "}", "\n\n", "ttl", "=", "newTat", ".", "Sub", "(", "now", ")", "\n\n", "if", "tatVal", "==", "-", "1", "{", "updated", ",", "err", "=", "g", ".", "store", ".", "SetIfNotExistsWithTTL", "(", "key", ",", "newTat", ".", "UnixNano", "(", ")", ",", "ttl", ")", "\n", "}", "else", "{", "updated", ",", "err", "=", "g", ".", "store", ".", "CompareAndSwapWithTTL", "(", "key", ",", "tatVal", ",", "newTat", ".", "UnixNano", "(", ")", ",", "ttl", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "rlc", ",", "err", "\n", "}", "\n", "if", "updated", "{", "break", "\n", "}", "\n\n", "i", "++", "\n", "if", "i", ">", "maxCASAttempts", "{", "return", "false", ",", "rlc", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "i", ",", ")", "\n", "}", "\n", "}", "\n\n", "next", ":=", "g", ".", "delayVariationTolerance", "-", "ttl", "\n", "if", "next", ">", "-", "g", ".", "emissionInterval", "{", "rlc", ".", "Remaining", "=", "int", "(", "next", "/", "g", ".", "emissionInterval", ")", "\n", "}", "\n", "rlc", ".", "ResetAfter", "=", "ttl", "\n\n", "return", "limited", ",", "rlc", ",", "nil", "\n", "}" ]
// RateLimit checks whether a particular key has exceeded a rate // limit. It also returns a RateLimitResult to provide additional // information about the state of the RateLimiter. // // If the rate limit has not been exceeded, the underlying storage is // updated by the supplied quantity. For example, a quantity of 1 // might be used to rate limit a single request while a greater // quantity could rate limit based on the size of a file upload in // megabytes. If quantity is 0, no update is performed allowing you // to "peek" at the state of the RateLimiter for a given key.
[ "RateLimit", "checks", "whether", "a", "particular", "key", "has", "exceeded", "a", "rate", "limit", ".", "It", "also", "returns", "a", "RateLimitResult", "to", "provide", "additional", "information", "about", "the", "state", "of", "the", "RateLimiter", ".", "If", "the", "rate", "limit", "has", "not", "been", "exceeded", "the", "underlying", "storage", "is", "updated", "by", "the", "supplied", "quantity", ".", "For", "example", "a", "quantity", "of", "1", "might", "be", "used", "to", "rate", "limit", "a", "single", "request", "while", "a", "greater", "quantity", "could", "rate", "limit", "based", "on", "the", "size", "of", "a", "file", "upload", "in", "megabytes", ".", "If", "quantity", "is", "0", "no", "update", "is", "performed", "allowing", "you", "to", "peek", "at", "the", "state", "of", "the", "RateLimiter", "for", "a", "given", "key", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/rate.go#L168-L242
8,666
throttled/throttled
http.go
RateLimit
func (t *HTTPRateLimiter) RateLimit(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if t.RateLimiter == nil { t.error(w, r, errors.New("You must set a RateLimiter on HTTPRateLimiter")) } var k string if t.VaryBy != nil { k = t.VaryBy.Key(r) } limited, context, err := t.RateLimiter.RateLimit(k, 1) if err != nil { t.error(w, r, err) return } setRateLimitHeaders(w, context) if !limited { h.ServeHTTP(w, r) } else { dh := t.DeniedHandler if dh == nil { dh = DefaultDeniedHandler } dh.ServeHTTP(w, r) } }) }
go
func (t *HTTPRateLimiter) RateLimit(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if t.RateLimiter == nil { t.error(w, r, errors.New("You must set a RateLimiter on HTTPRateLimiter")) } var k string if t.VaryBy != nil { k = t.VaryBy.Key(r) } limited, context, err := t.RateLimiter.RateLimit(k, 1) if err != nil { t.error(w, r, err) return } setRateLimitHeaders(w, context) if !limited { h.ServeHTTP(w, r) } else { dh := t.DeniedHandler if dh == nil { dh = DefaultDeniedHandler } dh.ServeHTTP(w, r) } }) }
[ "func", "(", "t", "*", "HTTPRateLimiter", ")", "RateLimit", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "t", ".", "RateLimiter", "==", "nil", "{", "t", ".", "error", "(", "w", ",", "r", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "var", "k", "string", "\n", "if", "t", ".", "VaryBy", "!=", "nil", "{", "k", "=", "t", ".", "VaryBy", ".", "Key", "(", "r", ")", "\n", "}", "\n\n", "limited", ",", "context", ",", "err", ":=", "t", ".", "RateLimiter", ".", "RateLimit", "(", "k", ",", "1", ")", "\n\n", "if", "err", "!=", "nil", "{", "t", ".", "error", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "setRateLimitHeaders", "(", "w", ",", "context", ")", "\n\n", "if", "!", "limited", "{", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "else", "{", "dh", ":=", "t", ".", "DeniedHandler", "\n", "if", "dh", "==", "nil", "{", "dh", "=", "DefaultDeniedHandler", "\n", "}", "\n", "dh", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// RateLimit wraps an http.Handler to limit incoming requests. // Requests that are not limited will be passed to the handler // unchanged. Limited requests will be passed to the DeniedHandler. // X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and // Retry-After headers will be written to the response based on the // values in the RateLimitResult.
[ "RateLimit", "wraps", "an", "http", ".", "Handler", "to", "limit", "incoming", "requests", ".", "Requests", "that", "are", "not", "limited", "will", "be", "passed", "to", "the", "handler", "unchanged", ".", "Limited", "requests", "will", "be", "passed", "to", "the", "DeniedHandler", ".", "X", "-", "RateLimit", "-", "Limit", "X", "-", "RateLimit", "-", "Remaining", "X", "-", "RateLimit", "-", "Reset", "and", "Retry", "-", "After", "headers", "will", "be", "written", "to", "the", "response", "based", "on", "the", "values", "in", "the", "RateLimitResult", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/http.go#L52-L82
8,667
throttled/throttled
store/memstore/memstore.go
GetWithTime
func (ms *MemStore) GetWithTime(key string) (int64, time.Time, error) { now := time.Now() valP, ok := ms.get(key, false) if !ok { return -1, now, nil } return atomic.LoadInt64(valP), now, nil }
go
func (ms *MemStore) GetWithTime(key string) (int64, time.Time, error) { now := time.Now() valP, ok := ms.get(key, false) if !ok { return -1, now, nil } return atomic.LoadInt64(valP), now, nil }
[ "func", "(", "ms", "*", "MemStore", ")", "GetWithTime", "(", "key", "string", ")", "(", "int64", ",", "time", ".", "Time", ",", "error", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "valP", ",", "ok", ":=", "ms", ".", "get", "(", "key", ",", "false", ")", "\n\n", "if", "!", "ok", "{", "return", "-", "1", ",", "now", ",", "nil", "\n", "}", "\n\n", "return", "atomic", ".", "LoadInt64", "(", "valP", ")", ",", "now", ",", "nil", "\n", "}" ]
// GetWithTime returns the value of the key if it is in the store or // -1 if it does not exist. It also returns the current local time on // the machine.
[ "GetWithTime", "returns", "the", "value", "of", "the", "key", "if", "it", "is", "in", "the", "store", "or", "-", "1", "if", "it", "does", "not", "exist", ".", "It", "also", "returns", "the", "current", "local", "time", "on", "the", "machine", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/memstore/memstore.go#L50-L59
8,668
throttled/throttled
store/memstore/memstore.go
SetIfNotExistsWithTTL
func (ms *MemStore) SetIfNotExistsWithTTL(key string, value int64, _ time.Duration) (bool, error) { _, ok := ms.get(key, false) if ok { return false, nil } ms.Lock() defer ms.Unlock() _, ok = ms.get(key, true) if ok { return false, nil } // Store a pointer to a new instance so that the caller // can't mutate the value after setting v := value if ms.keys != nil { ms.keys.Add(key, &v) } else { ms.m[key] = &v } return true, nil }
go
func (ms *MemStore) SetIfNotExistsWithTTL(key string, value int64, _ time.Duration) (bool, error) { _, ok := ms.get(key, false) if ok { return false, nil } ms.Lock() defer ms.Unlock() _, ok = ms.get(key, true) if ok { return false, nil } // Store a pointer to a new instance so that the caller // can't mutate the value after setting v := value if ms.keys != nil { ms.keys.Add(key, &v) } else { ms.m[key] = &v } return true, nil }
[ "func", "(", "ms", "*", "MemStore", ")", "SetIfNotExistsWithTTL", "(", "key", "string", ",", "value", "int64", ",", "_", "time", ".", "Duration", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "ok", ":=", "ms", ".", "get", "(", "key", ",", "false", ")", "\n\n", "if", "ok", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "ms", ".", "Lock", "(", ")", "\n", "defer", "ms", ".", "Unlock", "(", ")", "\n\n", "_", ",", "ok", "=", "ms", ".", "get", "(", "key", ",", "true", ")", "\n\n", "if", "ok", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// Store a pointer to a new instance so that the caller", "// can't mutate the value after setting", "v", ":=", "value", "\n\n", "if", "ms", ".", "keys", "!=", "nil", "{", "ms", ".", "keys", ".", "Add", "(", "key", ",", "&", "v", ")", "\n", "}", "else", "{", "ms", ".", "m", "[", "key", "]", "=", "&", "v", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// SetIfNotExistsWithTTL sets the value of key only if it is not // already set in the store it returns whether a new value was set. It // ignores the ttl.
[ "SetIfNotExistsWithTTL", "sets", "the", "value", "of", "key", "only", "if", "it", "is", "not", "already", "set", "in", "the", "store", "it", "returns", "whether", "a", "new", "value", "was", "set", ".", "It", "ignores", "the", "ttl", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/memstore/memstore.go#L64-L91
8,669
throttled/throttled
store/memstore/memstore.go
CompareAndSwapWithTTL
func (ms *MemStore) CompareAndSwapWithTTL(key string, old, new int64, _ time.Duration) (bool, error) { valP, ok := ms.get(key, false) if !ok { return false, nil } return atomic.CompareAndSwapInt64(valP, old, new), nil }
go
func (ms *MemStore) CompareAndSwapWithTTL(key string, old, new int64, _ time.Duration) (bool, error) { valP, ok := ms.get(key, false) if !ok { return false, nil } return atomic.CompareAndSwapInt64(valP, old, new), nil }
[ "func", "(", "ms", "*", "MemStore", ")", "CompareAndSwapWithTTL", "(", "key", "string", ",", "old", ",", "new", "int64", ",", "_", "time", ".", "Duration", ")", "(", "bool", ",", "error", ")", "{", "valP", ",", "ok", ":=", "ms", ".", "get", "(", "key", ",", "false", ")", "\n\n", "if", "!", "ok", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "return", "atomic", ".", "CompareAndSwapInt64", "(", "valP", ",", "old", ",", "new", ")", ",", "nil", "\n", "}" ]
// CompareAndSwapWithTTL atomically compares the value at key to the // old value. If it matches, it sets it to the new value and returns // true. Otherwise, it returns false. If the key does not exist in the // store, it returns false with no error. It ignores the ttl.
[ "CompareAndSwapWithTTL", "atomically", "compares", "the", "value", "at", "key", "to", "the", "old", "value", ".", "If", "it", "matches", "it", "sets", "it", "to", "the", "new", "value", "and", "returns", "true", ".", "Otherwise", "it", "returns", "false", ".", "If", "the", "key", "does", "not", "exist", "in", "the", "store", "it", "returns", "false", "with", "no", "error", ".", "It", "ignores", "the", "ttl", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/memstore/memstore.go#L97-L105
8,670
throttled/throttled
varyby.go
Key
func (vb *VaryBy) Key(r *http.Request) string { var buf bytes.Buffer if vb == nil { return "" // Special case for no vary-by option } if vb.Custom != nil { // A custom key generator is specified return vb.Custom(r) } sep := vb.Separator if sep == "" { sep = "\n" // Separator defaults to newline } if vb.RemoteAddr && len(r.RemoteAddr) > 0 { // RemoteAddr usually looks something like `IP:port`. For example, // `[::]:1234`. However, it seems to occasionally degenerately appear // as just IP (or other), so be conservative with how we extract it. index := strings.LastIndex(r.RemoteAddr, ":") var ip string if index == -1 { ip = r.RemoteAddr } else { ip = r.RemoteAddr[:index] } buf.WriteString(strings.ToLower(ip) + sep) } if vb.Method { buf.WriteString(strings.ToLower(r.Method) + sep) } for _, h := range vb.Headers { buf.WriteString(strings.ToLower(r.Header.Get(h)) + sep) } if vb.Path { buf.WriteString(r.URL.Path + sep) } for _, p := range vb.Params { buf.WriteString(r.FormValue(p) + sep) } for _, c := range vb.Cookies { ck, err := r.Cookie(c) if err == nil { buf.WriteString(ck.Value) } buf.WriteString(sep) // Write the separator anyway, whether or not the cookie exists } return buf.String() }
go
func (vb *VaryBy) Key(r *http.Request) string { var buf bytes.Buffer if vb == nil { return "" // Special case for no vary-by option } if vb.Custom != nil { // A custom key generator is specified return vb.Custom(r) } sep := vb.Separator if sep == "" { sep = "\n" // Separator defaults to newline } if vb.RemoteAddr && len(r.RemoteAddr) > 0 { // RemoteAddr usually looks something like `IP:port`. For example, // `[::]:1234`. However, it seems to occasionally degenerately appear // as just IP (or other), so be conservative with how we extract it. index := strings.LastIndex(r.RemoteAddr, ":") var ip string if index == -1 { ip = r.RemoteAddr } else { ip = r.RemoteAddr[:index] } buf.WriteString(strings.ToLower(ip) + sep) } if vb.Method { buf.WriteString(strings.ToLower(r.Method) + sep) } for _, h := range vb.Headers { buf.WriteString(strings.ToLower(r.Header.Get(h)) + sep) } if vb.Path { buf.WriteString(r.URL.Path + sep) } for _, p := range vb.Params { buf.WriteString(r.FormValue(p) + sep) } for _, c := range vb.Cookies { ck, err := r.Cookie(c) if err == nil { buf.WriteString(ck.Value) } buf.WriteString(sep) // Write the separator anyway, whether or not the cookie exists } return buf.String() }
[ "func", "(", "vb", "*", "VaryBy", ")", "Key", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "if", "vb", "==", "nil", "{", "return", "\"", "\"", "// Special case for no vary-by option", "\n", "}", "\n", "if", "vb", ".", "Custom", "!=", "nil", "{", "// A custom key generator is specified", "return", "vb", ".", "Custom", "(", "r", ")", "\n", "}", "\n", "sep", ":=", "vb", ".", "Separator", "\n", "if", "sep", "==", "\"", "\"", "{", "sep", "=", "\"", "\\n", "\"", "// Separator defaults to newline", "\n", "}", "\n", "if", "vb", ".", "RemoteAddr", "&&", "len", "(", "r", ".", "RemoteAddr", ")", ">", "0", "{", "// RemoteAddr usually looks something like `IP:port`. For example,", "// `[::]:1234`. However, it seems to occasionally degenerately appear", "// as just IP (or other), so be conservative with how we extract it.", "index", ":=", "strings", ".", "LastIndex", "(", "r", ".", "RemoteAddr", ",", "\"", "\"", ")", "\n\n", "var", "ip", "string", "\n", "if", "index", "==", "-", "1", "{", "ip", "=", "r", ".", "RemoteAddr", "\n", "}", "else", "{", "ip", "=", "r", ".", "RemoteAddr", "[", ":", "index", "]", "\n", "}", "\n\n", "buf", ".", "WriteString", "(", "strings", ".", "ToLower", "(", "ip", ")", "+", "sep", ")", "\n", "}", "\n", "if", "vb", ".", "Method", "{", "buf", ".", "WriteString", "(", "strings", ".", "ToLower", "(", "r", ".", "Method", ")", "+", "sep", ")", "\n", "}", "\n", "for", "_", ",", "h", ":=", "range", "vb", ".", "Headers", "{", "buf", ".", "WriteString", "(", "strings", ".", "ToLower", "(", "r", ".", "Header", ".", "Get", "(", "h", ")", ")", "+", "sep", ")", "\n", "}", "\n", "if", "vb", ".", "Path", "{", "buf", ".", "WriteString", "(", "r", ".", "URL", ".", "Path", "+", "sep", ")", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "vb", ".", "Params", "{", "buf", ".", "WriteString", "(", "r", ".", "FormValue", "(", "p", ")", "+", "sep", ")", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "vb", ".", "Cookies", "{", "ck", ",", "err", ":=", "r", ".", "Cookie", "(", "c", ")", "\n", "if", "err", "==", "nil", "{", "buf", ".", "WriteString", "(", "ck", ".", "Value", ")", "\n", "}", "\n", "buf", ".", "WriteString", "(", "sep", ")", "// Write the separator anyway, whether or not the cookie exists", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Key returns the key for this request based on the criteria defined by the VaryBy struct.
[ "Key", "returns", "the", "key", "for", "this", "request", "based", "on", "the", "criteria", "defined", "by", "the", "VaryBy", "struct", "." ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/varyby.go#L41-L90
8,671
throttled/throttled
store/deprecated.go
NewMemStore
func NewMemStore(maxKeys int) *memstore.MemStore { st, err := memstore.New(maxKeys) if err != nil { // As of this writing, `lru.New` can only return an error if you pass // maxKeys <= 0 so this should never occur. panic(err) } return st }
go
func NewMemStore(maxKeys int) *memstore.MemStore { st, err := memstore.New(maxKeys) if err != nil { // As of this writing, `lru.New` can only return an error if you pass // maxKeys <= 0 so this should never occur. panic(err) } return st }
[ "func", "NewMemStore", "(", "maxKeys", "int", ")", "*", "memstore", ".", "MemStore", "{", "st", ",", "err", ":=", "memstore", ".", "New", "(", "maxKeys", ")", "\n", "if", "err", "!=", "nil", "{", "// As of this writing, `lru.New` can only return an error if you pass", "// maxKeys <= 0 so this should never occur.", "panic", "(", "err", ")", "\n", "}", "\n", "return", "st", "\n", "}" ]
// DEPRECATED. NewMemStore is a compatible alias for mem.New
[ "DEPRECATED", ".", "NewMemStore", "is", "a", "compatible", "alias", "for", "mem", ".", "New" ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/deprecated.go#L12-L20
8,672
throttled/throttled
store/deprecated.go
NewRedisStore
func NewRedisStore(pool *redis.Pool, keyPrefix string, db int) *redigostore.RedigoStore { st, err := redigostore.New(pool, keyPrefix, db) if err != nil { // As of this writing, creating a Redis store never returns an error // so this should be safe while providing some ability to return errors // in the future. panic(err) } return st }
go
func NewRedisStore(pool *redis.Pool, keyPrefix string, db int) *redigostore.RedigoStore { st, err := redigostore.New(pool, keyPrefix, db) if err != nil { // As of this writing, creating a Redis store never returns an error // so this should be safe while providing some ability to return errors // in the future. panic(err) } return st }
[ "func", "NewRedisStore", "(", "pool", "*", "redis", ".", "Pool", ",", "keyPrefix", "string", ",", "db", "int", ")", "*", "redigostore", ".", "RedigoStore", "{", "st", ",", "err", ":=", "redigostore", ".", "New", "(", "pool", ",", "keyPrefix", ",", "db", ")", "\n", "if", "err", "!=", "nil", "{", "// As of this writing, creating a Redis store never returns an error", "// so this should be safe while providing some ability to return errors", "// in the future.", "panic", "(", "err", ")", "\n", "}", "\n", "return", "st", "\n", "}" ]
// DEPRECATED. NewMemStore is a compatible alias for redis.New
[ "DEPRECATED", ".", "NewMemStore", "is", "a", "compatible", "alias", "for", "redis", ".", "New" ]
def5708c45a0d2b2b9a3604521f3164e227d2c83
https://github.com/throttled/throttled/blob/def5708c45a0d2b2b9a3604521f3164e227d2c83/store/deprecated.go#L23-L32
8,673
getsentry/raven-go
exception.go
NewException
func NewException(err error, stacktrace *Stacktrace) *Exception { msg := err.Error() ex := &Exception{ Stacktrace: stacktrace, Value: msg, Type: reflect.TypeOf(err).String(), } if m := errorMsgPattern.FindStringSubmatch(msg); m != nil { ex.Module, ex.Value = m[1], m[2] } return ex }
go
func NewException(err error, stacktrace *Stacktrace) *Exception { msg := err.Error() ex := &Exception{ Stacktrace: stacktrace, Value: msg, Type: reflect.TypeOf(err).String(), } if m := errorMsgPattern.FindStringSubmatch(msg); m != nil { ex.Module, ex.Value = m[1], m[2] } return ex }
[ "func", "NewException", "(", "err", "error", ",", "stacktrace", "*", "Stacktrace", ")", "*", "Exception", "{", "msg", ":=", "err", ".", "Error", "(", ")", "\n", "ex", ":=", "&", "Exception", "{", "Stacktrace", ":", "stacktrace", ",", "Value", ":", "msg", ",", "Type", ":", "reflect", ".", "TypeOf", "(", "err", ")", ".", "String", "(", ")", ",", "}", "\n", "if", "m", ":=", "errorMsgPattern", ".", "FindStringSubmatch", "(", "msg", ")", ";", "m", "!=", "nil", "{", "ex", ".", "Module", ",", "ex", ".", "Value", "=", "m", "[", "1", "]", ",", "m", "[", "2", "]", "\n", "}", "\n", "return", "ex", "\n", "}" ]
// NewException constructs an Exception using provided Error and Stacktrace
[ "NewException", "constructs", "an", "Exception", "using", "provided", "Error", "and", "Stacktrace" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/exception.go#L11-L22
8,674
getsentry/raven-go
exception.go
Culprit
func (e *Exception) Culprit() string { if e.Stacktrace == nil { return "" } return e.Stacktrace.Culprit() }
go
func (e *Exception) Culprit() string { if e.Stacktrace == nil { return "" } return e.Stacktrace.Culprit() }
[ "func", "(", "e", "*", "Exception", ")", "Culprit", "(", ")", "string", "{", "if", "e", ".", "Stacktrace", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "e", ".", "Stacktrace", ".", "Culprit", "(", ")", "\n", "}" ]
// Culprit tries to read top-most error message from Exception's stacktrace
[ "Culprit", "tries", "to", "read", "top", "-", "most", "error", "message", "from", "Exception", "s", "stacktrace" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/exception.go#L39-L44
8,675
getsentry/raven-go
errors.go
WrapWithExtra
func WrapWithExtra(err error, extraInfo map[string]interface{}) error { return &errWrappedWithExtra{ err: err, extraInfo: extraInfo, } }
go
func WrapWithExtra(err error, extraInfo map[string]interface{}) error { return &errWrappedWithExtra{ err: err, extraInfo: extraInfo, } }
[ "func", "WrapWithExtra", "(", "err", "error", ",", "extraInfo", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "return", "&", "errWrappedWithExtra", "{", "err", ":", "err", ",", "extraInfo", ":", "extraInfo", ",", "}", "\n", "}" ]
// WrapWithExtra adds extra data to an error before reporting to Sentry
[ "WrapWithExtra", "adds", "extra", "data", "to", "an", "error", "before", "reporting", "to", "Sentry" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/errors.go#L29-L34
8,676
getsentry/raven-go
errors.go
extractExtra
func extractExtra(err error) Extra { extra := Extra{} currentErr := err for currentErr != nil { if errWithExtra, ok := currentErr.(errWithJustExtra); ok { for k, v := range errWithExtra.ExtraInfo() { extra[k] = v } } if errWithCause, ok := currentErr.(causer); ok { currentErr = errWithCause.Cause() } else { currentErr = nil } } return extra }
go
func extractExtra(err error) Extra { extra := Extra{} currentErr := err for currentErr != nil { if errWithExtra, ok := currentErr.(errWithJustExtra); ok { for k, v := range errWithExtra.ExtraInfo() { extra[k] = v } } if errWithCause, ok := currentErr.(causer); ok { currentErr = errWithCause.Cause() } else { currentErr = nil } } return extra }
[ "func", "extractExtra", "(", "err", "error", ")", "Extra", "{", "extra", ":=", "Extra", "{", "}", "\n\n", "currentErr", ":=", "err", "\n", "for", "currentErr", "!=", "nil", "{", "if", "errWithExtra", ",", "ok", ":=", "currentErr", ".", "(", "errWithJustExtra", ")", ";", "ok", "{", "for", "k", ",", "v", ":=", "range", "errWithExtra", ".", "ExtraInfo", "(", ")", "{", "extra", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "if", "errWithCause", ",", "ok", ":=", "currentErr", ".", "(", "causer", ")", ";", "ok", "{", "currentErr", "=", "errWithCause", ".", "Cause", "(", ")", "\n", "}", "else", "{", "currentErr", "=", "nil", "\n", "}", "\n", "}", "\n\n", "return", "extra", "\n", "}" ]
// Iteratively fetches all the Extra data added to an error, // and it's underlying errors. Extra data defined first is // respected, and is not overridden when extracting.
[ "Iteratively", "fetches", "all", "the", "Extra", "data", "added", "to", "an", "error", "and", "it", "s", "underlying", "errors", ".", "Extra", "data", "defined", "first", "is", "respected", "and", "is", "not", "overridden", "when", "extracting", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/errors.go#L51-L70
8,677
getsentry/raven-go
stacktrace.go
Culprit
func (s *Stacktrace) Culprit() string { for i := len(s.Frames) - 1; i >= 0; i-- { frame := s.Frames[i] if frame.InApp == true && frame.Module != "" && frame.Function != "" { return frame.Module + "." + frame.Function } } return "" }
go
func (s *Stacktrace) Culprit() string { for i := len(s.Frames) - 1; i >= 0; i-- { frame := s.Frames[i] if frame.InApp == true && frame.Module != "" && frame.Function != "" { return frame.Module + "." + frame.Function } } return "" }
[ "func", "(", "s", "*", "Stacktrace", ")", "Culprit", "(", ")", "string", "{", "for", "i", ":=", "len", "(", "s", ".", "Frames", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "frame", ":=", "s", ".", "Frames", "[", "i", "]", "\n", "if", "frame", ".", "InApp", "==", "true", "&&", "frame", ".", "Module", "!=", "\"", "\"", "&&", "frame", ".", "Function", "!=", "\"", "\"", "{", "return", "frame", ".", "Module", "+", "\"", "\"", "+", "frame", ".", "Function", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Culprit iterates through stacktrace frames and returns first in-app frame's information
[ "Culprit", "iterates", "through", "stacktrace", "frames", "and", "returns", "first", "in", "-", "app", "frame", "s", "information" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L28-L36
8,678
getsentry/raven-go
stacktrace.go
NewStacktrace
func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace { var frames []*StacktraceFrame callerPcs := make([]uintptr, 100) numCallers := runtime.Callers(skip+2, callerPcs) // If there are no callers, the entire stacktrace is nil if numCallers == 0 { return nil } callersFrames := runtime.CallersFrames(callerPcs) for { fr, more := callersFrames.Next() frame := NewStacktraceFrame(fr.PC, fr.Function, fr.File, fr.Line, context, appPackagePrefixes) if frame != nil { frames = append(frames, frame) } if !more { break } } // If there are no frames, the entire stacktrace is nil if len(frames) == 0 { return nil } // Optimize the path where there's only 1 frame if len(frames) == 1 { return &Stacktrace{frames} } // Sentry wants the frames with the oldest first, so reverse them for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 { frames[i], frames[j] = frames[j], frames[i] } return &Stacktrace{frames} }
go
func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace { var frames []*StacktraceFrame callerPcs := make([]uintptr, 100) numCallers := runtime.Callers(skip+2, callerPcs) // If there are no callers, the entire stacktrace is nil if numCallers == 0 { return nil } callersFrames := runtime.CallersFrames(callerPcs) for { fr, more := callersFrames.Next() frame := NewStacktraceFrame(fr.PC, fr.Function, fr.File, fr.Line, context, appPackagePrefixes) if frame != nil { frames = append(frames, frame) } if !more { break } } // If there are no frames, the entire stacktrace is nil if len(frames) == 0 { return nil } // Optimize the path where there's only 1 frame if len(frames) == 1 { return &Stacktrace{frames} } // Sentry wants the frames with the oldest first, so reverse them for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 { frames[i], frames[j] = frames[j], frames[i] } return &Stacktrace{frames} }
[ "func", "NewStacktrace", "(", "skip", "int", ",", "context", "int", ",", "appPackagePrefixes", "[", "]", "string", ")", "*", "Stacktrace", "{", "var", "frames", "[", "]", "*", "StacktraceFrame", "\n\n", "callerPcs", ":=", "make", "(", "[", "]", "uintptr", ",", "100", ")", "\n", "numCallers", ":=", "runtime", ".", "Callers", "(", "skip", "+", "2", ",", "callerPcs", ")", "\n\n", "// If there are no callers, the entire stacktrace is nil", "if", "numCallers", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "callersFrames", ":=", "runtime", ".", "CallersFrames", "(", "callerPcs", ")", "\n\n", "for", "{", "fr", ",", "more", ":=", "callersFrames", ".", "Next", "(", ")", "\n", "frame", ":=", "NewStacktraceFrame", "(", "fr", ".", "PC", ",", "fr", ".", "Function", ",", "fr", ".", "File", ",", "fr", ".", "Line", ",", "context", ",", "appPackagePrefixes", ")", "\n", "if", "frame", "!=", "nil", "{", "frames", "=", "append", "(", "frames", ",", "frame", ")", "\n", "}", "\n", "if", "!", "more", "{", "break", "\n", "}", "\n", "}", "\n", "// If there are no frames, the entire stacktrace is nil", "if", "len", "(", "frames", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "// Optimize the path where there's only 1 frame", "if", "len", "(", "frames", ")", "==", "1", "{", "return", "&", "Stacktrace", "{", "frames", "}", "\n", "}", "\n", "// Sentry wants the frames with the oldest first, so reverse them", "for", "i", ",", "j", ":=", "0", ",", "len", "(", "frames", ")", "-", "1", ";", "i", "<", "j", ";", "i", ",", "j", "=", "i", "+", "1", ",", "j", "-", "1", "{", "frames", "[", "i", "]", ",", "frames", "[", "j", "]", "=", "frames", "[", "j", "]", ",", "frames", "[", "i", "]", "\n", "}", "\n", "return", "&", "Stacktrace", "{", "frames", "}", "\n", "}" ]
// NewStacktrace intializes and populates a new stacktrace, skipping skip frames. // // context is the number of surrounding lines that should be included for context. // Setting context to 3 would try to get seven lines. Setting context to -1 returns // one line with no surrounding context, and 0 returns no context. // // appPackagePrefixes is a list of prefixes used to check whether a package should // be considered "in app".
[ "NewStacktrace", "intializes", "and", "populates", "a", "new", "stacktrace", "skipping", "skip", "frames", ".", "context", "is", "the", "number", "of", "surrounding", "lines", "that", "should", "be", "included", "for", "context", ".", "Setting", "context", "to", "3", "would", "try", "to", "get", "seven", "lines", ".", "Setting", "context", "to", "-", "1", "returns", "one", "line", "with", "no", "surrounding", "context", "and", "0", "returns", "no", "context", ".", "appPackagePrefixes", "is", "a", "list", "of", "prefixes", "used", "to", "check", "whether", "a", "package", "should", "be", "considered", "in", "app", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L94-L130
8,679
getsentry/raven-go
stacktrace.go
NewStacktraceFrame
func NewStacktraceFrame(pc uintptr, fName, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame { frame := &StacktraceFrame{AbsolutePath: file, Filename: trimPath(file), Lineno: line} frame.Module, frame.Function = functionName(fName) frame.InApp = isInAppFrame(*frame, appPackagePrefixes) // `runtime.goexit` is effectively a placeholder that comes from // runtime/asm_amd64.s and is meaningless. if frame.Module == "runtime" && frame.Function == "goexit" { return nil } if context > 0 { contextLines, lineIdx := sourceCodeLoader.Load(file, line, context) if len(contextLines) > 0 { for i, line := range contextLines { switch { case i < lineIdx: frame.PreContext = append(frame.PreContext, string(line)) case i == lineIdx: frame.ContextLine = string(line) default: frame.PostContext = append(frame.PostContext, string(line)) } } } } else if context == -1 { contextLine, _ := sourceCodeLoader.Load(file, line, 0) if len(contextLine) > 0 { frame.ContextLine = string(contextLine[0]) } } return frame }
go
func NewStacktraceFrame(pc uintptr, fName, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame { frame := &StacktraceFrame{AbsolutePath: file, Filename: trimPath(file), Lineno: line} frame.Module, frame.Function = functionName(fName) frame.InApp = isInAppFrame(*frame, appPackagePrefixes) // `runtime.goexit` is effectively a placeholder that comes from // runtime/asm_amd64.s and is meaningless. if frame.Module == "runtime" && frame.Function == "goexit" { return nil } if context > 0 { contextLines, lineIdx := sourceCodeLoader.Load(file, line, context) if len(contextLines) > 0 { for i, line := range contextLines { switch { case i < lineIdx: frame.PreContext = append(frame.PreContext, string(line)) case i == lineIdx: frame.ContextLine = string(line) default: frame.PostContext = append(frame.PostContext, string(line)) } } } } else if context == -1 { contextLine, _ := sourceCodeLoader.Load(file, line, 0) if len(contextLine) > 0 { frame.ContextLine = string(contextLine[0]) } } return frame }
[ "func", "NewStacktraceFrame", "(", "pc", "uintptr", ",", "fName", ",", "file", "string", ",", "line", ",", "context", "int", ",", "appPackagePrefixes", "[", "]", "string", ")", "*", "StacktraceFrame", "{", "frame", ":=", "&", "StacktraceFrame", "{", "AbsolutePath", ":", "file", ",", "Filename", ":", "trimPath", "(", "file", ")", ",", "Lineno", ":", "line", "}", "\n", "frame", ".", "Module", ",", "frame", ".", "Function", "=", "functionName", "(", "fName", ")", "\n", "frame", ".", "InApp", "=", "isInAppFrame", "(", "*", "frame", ",", "appPackagePrefixes", ")", "\n\n", "// `runtime.goexit` is effectively a placeholder that comes from", "// runtime/asm_amd64.s and is meaningless.", "if", "frame", ".", "Module", "==", "\"", "\"", "&&", "frame", ".", "Function", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "if", "context", ">", "0", "{", "contextLines", ",", "lineIdx", ":=", "sourceCodeLoader", ".", "Load", "(", "file", ",", "line", ",", "context", ")", "\n", "if", "len", "(", "contextLines", ")", ">", "0", "{", "for", "i", ",", "line", ":=", "range", "contextLines", "{", "switch", "{", "case", "i", "<", "lineIdx", ":", "frame", ".", "PreContext", "=", "append", "(", "frame", ".", "PreContext", ",", "string", "(", "line", ")", ")", "\n", "case", "i", "==", "lineIdx", ":", "frame", ".", "ContextLine", "=", "string", "(", "line", ")", "\n", "default", ":", "frame", ".", "PostContext", "=", "append", "(", "frame", ".", "PostContext", ",", "string", "(", "line", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "context", "==", "-", "1", "{", "contextLine", ",", "_", ":=", "sourceCodeLoader", ".", "Load", "(", "file", ",", "line", ",", "0", ")", "\n", "if", "len", "(", "contextLine", ")", ">", "0", "{", "frame", ".", "ContextLine", "=", "string", "(", "contextLine", "[", "0", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "frame", "\n", "}" ]
// NewStacktraceFrame builds a single frame using data returned from runtime.Caller. // // context is the number of surrounding lines that should be included for context. // Setting context to 3 would try to get seven lines. Setting context to -1 returns // one line with no surrounding context, and 0 returns no context. // // appPackagePrefixes is a list of prefixes used to check whether a package should // be considered "in app".
[ "NewStacktraceFrame", "builds", "a", "single", "frame", "using", "data", "returned", "from", "runtime", ".", "Caller", ".", "context", "is", "the", "number", "of", "surrounding", "lines", "that", "should", "be", "included", "for", "context", ".", "Setting", "context", "to", "3", "would", "try", "to", "get", "seven", "lines", ".", "Setting", "context", "to", "-", "1", "returns", "one", "line", "with", "no", "surrounding", "context", "and", "0", "returns", "no", "context", ".", "appPackagePrefixes", "is", "a", "list", "of", "prefixes", "used", "to", "check", "whether", "a", "package", "should", "be", "considered", "in", "app", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L140-L173
8,680
getsentry/raven-go
stacktrace.go
isInAppFrame
func isInAppFrame(frame StacktraceFrame, appPackagePrefixes []string) bool { if frame.Module == "main" { return true } for _, prefix := range appPackagePrefixes { if strings.HasPrefix(frame.Module, prefix) && !strings.Contains(frame.Module, "vendor") && !strings.Contains(frame.Module, "third_party") { return true } } return false }
go
func isInAppFrame(frame StacktraceFrame, appPackagePrefixes []string) bool { if frame.Module == "main" { return true } for _, prefix := range appPackagePrefixes { if strings.HasPrefix(frame.Module, prefix) && !strings.Contains(frame.Module, "vendor") && !strings.Contains(frame.Module, "third_party") { return true } } return false }
[ "func", "isInAppFrame", "(", "frame", "StacktraceFrame", ",", "appPackagePrefixes", "[", "]", "string", ")", "bool", "{", "if", "frame", ".", "Module", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "prefix", ":=", "range", "appPackagePrefixes", "{", "if", "strings", ".", "HasPrefix", "(", "frame", ".", "Module", ",", "prefix", ")", "&&", "!", "strings", ".", "Contains", "(", "frame", ".", "Module", ",", "\"", "\"", ")", "&&", "!", "strings", ".", "Contains", "(", "frame", ".", "Module", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Determines whether frame should be marked as InApp
[ "Determines", "whether", "frame", "should", "be", "marked", "as", "InApp" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L176-L186
8,681
getsentry/raven-go
stacktrace.go
functionName
func functionName(fName string) (pack string, name string) { name = fName // We get this: // runtime/debug.*T·ptrmethod // and want this: // pack = runtime/debug // name = *T.ptrmethod if idx := strings.LastIndex(name, "."); idx != -1 { pack = name[:idx] name = name[idx+1:] } name = strings.Replace(name, "·", ".", -1) return }
go
func functionName(fName string) (pack string, name string) { name = fName // We get this: // runtime/debug.*T·ptrmethod // and want this: // pack = runtime/debug // name = *T.ptrmethod if idx := strings.LastIndex(name, "."); idx != -1 { pack = name[:idx] name = name[idx+1:] } name = strings.Replace(name, "·", ".", -1) return }
[ "func", "functionName", "(", "fName", "string", ")", "(", "pack", "string", ",", "name", "string", ")", "{", "name", "=", "fName", "\n", "// We get this:", "//\truntime/debug.*T·ptrmethod", "// and want this:", "// pack = runtime/debug", "//\tname = *T.ptrmethod", "if", "idx", ":=", "strings", ".", "LastIndex", "(", "name", ",", "\"", "\"", ")", ";", "idx", "!=", "-", "1", "{", "pack", "=", "name", "[", ":", "idx", "]", "\n", "name", "=", "name", "[", "idx", "+", "1", ":", "]", "\n", "}", "\n", "name", "=", "strings", ".", "Replace", "(", "name", ",", "\"", ",", " ", ".", ",", " ", "1", ")", "", "\n", "return", "\n", "}" ]
// Retrieve the name of the package and function containing the PC.
[ "Retrieve", "the", "name", "of", "the", "package", "and", "function", "containing", "the", "PC", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L189-L202
8,682
getsentry/raven-go
stacktrace.go
trimPath
func trimPath(filename string) string { for _, prefix := range trimPaths { if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) { return trimmed } } return filename }
go
func trimPath(filename string) string { for _, prefix := range trimPaths { if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) { return trimmed } } return filename }
[ "func", "trimPath", "(", "filename", "string", ")", "string", "{", "for", "_", ",", "prefix", ":=", "range", "trimPaths", "{", "if", "trimmed", ":=", "strings", ".", "TrimPrefix", "(", "filename", ",", "prefix", ")", ";", "len", "(", "trimmed", ")", "<", "len", "(", "filename", ")", "{", "return", "trimmed", "\n", "}", "\n", "}", "\n", "return", "filename", "\n", "}" ]
// Try to trim the GOROOT or GOPATH prefix off of a filename
[ "Try", "to", "trim", "the", "GOROOT", "or", "GOPATH", "prefix", "off", "of", "a", "filename" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/stacktrace.go#L265-L272
8,683
getsentry/raven-go
client.go
MarshalJSON
func (timestamp Timestamp) MarshalJSON() ([]byte, error) { return []byte(time.Time(timestamp).UTC().Format(timestampFormat)), nil }
go
func (timestamp Timestamp) MarshalJSON() ([]byte, error) { return []byte(time.Time(timestamp).UTC().Format(timestampFormat)), nil }
[ "func", "(", "timestamp", "Timestamp", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "time", ".", "Time", "(", "timestamp", ")", ".", "UTC", "(", ")", ".", "Format", "(", "timestampFormat", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON returns the JSON encoding of a timestamp
[ "MarshalJSON", "returns", "the", "JSON", "encoding", "of", "a", "timestamp" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L64-L66
8,684
getsentry/raven-go
client.go
UnmarshalJSON
func (timestamp *Timestamp) UnmarshalJSON(data []byte) error { t, err := time.Parse(timestampFormat, string(data)) if err != nil { return err } *timestamp = Timestamp(t) return nil }
go
func (timestamp *Timestamp) UnmarshalJSON(data []byte) error { t, err := time.Parse(timestampFormat, string(data)) if err != nil { return err } *timestamp = Timestamp(t) return nil }
[ "func", "(", "timestamp", "*", "Timestamp", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "t", ",", "err", ":=", "time", ".", "Parse", "(", "timestampFormat", ",", "string", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "timestamp", "=", "Timestamp", "(", "t", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON sets timestamp to parsed JSON data
[ "UnmarshalJSON", "sets", "timestamp", "to", "parsed", "JSON", "data" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L69-L77
8,685
getsentry/raven-go
client.go
Format
func (timestamp Timestamp) Format(format string) string { t := time.Time(timestamp) return t.Format(format) }
go
func (timestamp Timestamp) Format(format string) string { t := time.Time(timestamp) return t.Format(format) }
[ "func", "(", "timestamp", "Timestamp", ")", "Format", "(", "format", "string", ")", "string", "{", "t", ":=", "time", ".", "Time", "(", "timestamp", ")", "\n", "return", "t", ".", "Format", "(", "format", ")", "\n", "}" ]
// Format return timestamp in configured timestampFormat
[ "Format", "return", "timestamp", "in", "configured", "timestampFormat" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L80-L83
8,686
getsentry/raven-go
client.go
MarshalJSON
func (t *Tag) MarshalJSON() ([]byte, error) { return json.Marshal([2]string{t.Key, t.Value}) }
go
func (t *Tag) MarshalJSON() ([]byte, error) { return json.Marshal([2]string{t.Key, t.Value}) }
[ "func", "(", "t", "*", "Tag", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "[", "2", "]", "string", "{", "t", ".", "Key", ",", "t", ".", "Value", "}", ")", "\n", "}" ]
// MarshalJSON returns the JSON encoding of a tag
[ "MarshalJSON", "returns", "the", "JSON", "encoding", "of", "a", "tag" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L120-L122
8,687
getsentry/raven-go
client.go
UnmarshalJSON
func (t *Tag) UnmarshalJSON(data []byte) error { var tag [2]string if err := json.Unmarshal(data, &tag); err != nil { return err } *t = Tag{tag[0], tag[1]} return nil }
go
func (t *Tag) UnmarshalJSON(data []byte) error { var tag [2]string if err := json.Unmarshal(data, &tag); err != nil { return err } *t = Tag{tag[0], tag[1]} return nil }
[ "func", "(", "t", "*", "Tag", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "tag", "[", "2", "]", "string", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "tag", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "t", "=", "Tag", "{", "tag", "[", "0", "]", ",", "tag", "[", "1", "]", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON sets tag to parsed JSON data
[ "UnmarshalJSON", "sets", "tag", "to", "parsed", "JSON", "data" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L125-L132
8,688
getsentry/raven-go
client.go
UnmarshalJSON
func (t *Tags) UnmarshalJSON(data []byte) error { var tags []Tag switch data[0] { case '[': // Unmarshal into []Tag if err := json.Unmarshal(data, &tags); err != nil { return err } case '{': // Unmarshal into map[string]string tagMap := make(map[string]string) if err := json.Unmarshal(data, &tagMap); err != nil { return err } // Convert to []Tag for k, v := range tagMap { tags = append(tags, Tag{k, v}) } default: return ErrUnableToUnmarshalJSON } *t = tags return nil }
go
func (t *Tags) UnmarshalJSON(data []byte) error { var tags []Tag switch data[0] { case '[': // Unmarshal into []Tag if err := json.Unmarshal(data, &tags); err != nil { return err } case '{': // Unmarshal into map[string]string tagMap := make(map[string]string) if err := json.Unmarshal(data, &tagMap); err != nil { return err } // Convert to []Tag for k, v := range tagMap { tags = append(tags, Tag{k, v}) } default: return ErrUnableToUnmarshalJSON } *t = tags return nil }
[ "func", "(", "t", "*", "Tags", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "tags", "[", "]", "Tag", "\n\n", "switch", "data", "[", "0", "]", "{", "case", "'['", ":", "// Unmarshal into []Tag", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "tags", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "'{'", ":", "// Unmarshal into map[string]string", "tagMap", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "tagMap", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Convert to []Tag", "for", "k", ",", "v", ":=", "range", "tagMap", "{", "tags", "=", "append", "(", "tags", ",", "Tag", "{", "k", ",", "v", "}", ")", "\n", "}", "\n", "default", ":", "return", "ErrUnableToUnmarshalJSON", "\n", "}", "\n\n", "*", "t", "=", "tags", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON sets tags to parsed JSON data
[ "UnmarshalJSON", "sets", "tags", "to", "parsed", "JSON", "data" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L135-L161
8,689
getsentry/raven-go
client.go
NewPacket
func NewPacket(message string, interfaces ...Interface) *Packet { extra := Extra{} setExtraDefaults(extra) return &Packet{ Message: message, Interfaces: interfaces, Extra: extra, } }
go
func NewPacket(message string, interfaces ...Interface) *Packet { extra := Extra{} setExtraDefaults(extra) return &Packet{ Message: message, Interfaces: interfaces, Extra: extra, } }
[ "func", "NewPacket", "(", "message", "string", ",", "interfaces", "...", "Interface", ")", "*", "Packet", "{", "extra", ":=", "Extra", "{", "}", "\n", "setExtraDefaults", "(", "extra", ")", "\n", "return", "&", "Packet", "{", "Message", ":", "message", ",", "Interfaces", ":", "interfaces", ",", "Extra", ":", "extra", ",", "}", "\n", "}" ]
// NewPacket constructs a packet with the specified message and interfaces.
[ "NewPacket", "constructs", "a", "packet", "with", "the", "specified", "message", "and", "interfaces", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L190-L198
8,690
getsentry/raven-go
client.go
NewPacketWithExtra
func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet { if extra == nil { extra = Extra{} } setExtraDefaults(extra) return &Packet{ Message: message, Interfaces: interfaces, Extra: extra, } }
go
func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet { if extra == nil { extra = Extra{} } setExtraDefaults(extra) return &Packet{ Message: message, Interfaces: interfaces, Extra: extra, } }
[ "func", "NewPacketWithExtra", "(", "message", "string", ",", "extra", "Extra", ",", "interfaces", "...", "Interface", ")", "*", "Packet", "{", "if", "extra", "==", "nil", "{", "extra", "=", "Extra", "{", "}", "\n", "}", "\n", "setExtraDefaults", "(", "extra", ")", "\n\n", "return", "&", "Packet", "{", "Message", ":", "message", ",", "Interfaces", ":", "interfaces", ",", "Extra", ":", "extra", ",", "}", "\n", "}" ]
// NewPacketWithExtra constructs a packet with the specified message, extra information, and interfaces.
[ "NewPacketWithExtra", "constructs", "a", "packet", "with", "the", "specified", "message", "extra", "information", "and", "interfaces", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L201-L212
8,691
getsentry/raven-go
client.go
AddTags
func (packet *Packet) AddTags(tags map[string]string) { for k, v := range tags { packet.Tags = append(packet.Tags, Tag{k, v}) } }
go
func (packet *Packet) AddTags(tags map[string]string) { for k, v := range tags { packet.Tags = append(packet.Tags, Tag{k, v}) } }
[ "func", "(", "packet", "*", "Packet", ")", "AddTags", "(", "tags", "map", "[", "string", "]", "string", ")", "{", "for", "k", ",", "v", ":=", "range", "tags", "{", "packet", ".", "Tags", "=", "append", "(", "packet", ".", "Tags", ",", "Tag", "{", "k", ",", "v", "}", ")", "\n", "}", "\n", "}" ]
// AddTags appends new tags to the existing ones
[ "AddTags", "appends", "new", "tags", "to", "the", "existing", "ones" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L266-L270
8,692
getsentry/raven-go
client.go
JSON
func (packet *Packet) JSON() ([]byte, error) { packetJSON, err := json.Marshal(packet) if err != nil { return nil, err } interfaces := make(map[string]Interface, len(packet.Interfaces)) for _, inter := range packet.Interfaces { if inter != nil { interfaces[inter.Class()] = inter } } if len(interfaces) > 0 { interfaceJSON, err := json.Marshal(interfaces) if err != nil { return nil, err } packetJSON[len(packetJSON)-1] = ',' packetJSON = append(packetJSON, interfaceJSON[1:]...) } return packetJSON, nil }
go
func (packet *Packet) JSON() ([]byte, error) { packetJSON, err := json.Marshal(packet) if err != nil { return nil, err } interfaces := make(map[string]Interface, len(packet.Interfaces)) for _, inter := range packet.Interfaces { if inter != nil { interfaces[inter.Class()] = inter } } if len(interfaces) > 0 { interfaceJSON, err := json.Marshal(interfaces) if err != nil { return nil, err } packetJSON[len(packetJSON)-1] = ',' packetJSON = append(packetJSON, interfaceJSON[1:]...) } return packetJSON, nil }
[ "func", "(", "packet", "*", "Packet", ")", "JSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "packetJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "interfaces", ":=", "make", "(", "map", "[", "string", "]", "Interface", ",", "len", "(", "packet", ".", "Interfaces", ")", ")", "\n", "for", "_", ",", "inter", ":=", "range", "packet", ".", "Interfaces", "{", "if", "inter", "!=", "nil", "{", "interfaces", "[", "inter", ".", "Class", "(", ")", "]", "=", "inter", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "interfaces", ")", ">", "0", "{", "interfaceJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "interfaces", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "packetJSON", "[", "len", "(", "packetJSON", ")", "-", "1", "]", "=", "','", "\n", "packetJSON", "=", "append", "(", "packetJSON", ",", "interfaceJSON", "[", "1", ":", "]", "...", ")", "\n", "}", "\n\n", "return", "packetJSON", ",", "nil", "\n", "}" ]
// JSON encodes packet into JSON format that will be sent to the server
[ "JSON", "encodes", "packet", "into", "JSON", "format", "that", "will", "be", "sent", "to", "the", "server" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L286-L309
8,693
getsentry/raven-go
client.go
interfaces
func (c *context) interfaces() []Interface { len, i := 0, 0 if c.user != nil { len++ } if c.http != nil { len++ } interfaces := make([]Interface, len) if c.user != nil { interfaces[i] = c.user i++ } if c.http != nil { interfaces[i] = c.http } return interfaces }
go
func (c *context) interfaces() []Interface { len, i := 0, 0 if c.user != nil { len++ } if c.http != nil { len++ } interfaces := make([]Interface, len) if c.user != nil { interfaces[i] = c.user i++ } if c.http != nil { interfaces[i] = c.http } return interfaces }
[ "func", "(", "c", "*", "context", ")", "interfaces", "(", ")", "[", "]", "Interface", "{", "len", ",", "i", ":=", "0", ",", "0", "\n", "if", "c", ".", "user", "!=", "nil", "{", "len", "++", "\n", "}", "\n", "if", "c", ".", "http", "!=", "nil", "{", "len", "++", "\n", "}", "\n", "interfaces", ":=", "make", "(", "[", "]", "Interface", ",", "len", ")", "\n", "if", "c", ".", "user", "!=", "nil", "{", "interfaces", "[", "i", "]", "=", "c", ".", "user", "\n", "i", "++", "\n", "}", "\n", "if", "c", ".", "http", "!=", "nil", "{", "interfaces", "[", "i", "]", "=", "c", ".", "http", "\n", "}", "\n", "return", "interfaces", "\n", "}" ]
// Return a list of interfaces to be used in appending with the rest
[ "Return", "a", "list", "of", "interfaces", "to", "be", "used", "in", "appending", "with", "the", "rest" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L334-L351
8,694
getsentry/raven-go
client.go
New
func New(dsn string) (*Client, error) { client := newClient(nil) return client, client.SetDSN(dsn) }
go
func New(dsn string) (*Client, error) { client := newClient(nil) return client, client.SetDSN(dsn) }
[ "func", "New", "(", "dsn", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "client", ":=", "newClient", "(", "nil", ")", "\n", "return", "client", ",", "client", ".", "SetDSN", "(", "dsn", ")", "\n", "}" ]
// New constructs a new Sentry client instance
[ "New", "constructs", "a", "new", "Sentry", "client", "instance" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L398-L401
8,695
getsentry/raven-go
client.go
NewWithTags
func NewWithTags(dsn string, tags map[string]string) (*Client, error) { client := newClient(tags) return client, client.SetDSN(dsn) }
go
func NewWithTags(dsn string, tags map[string]string) (*Client, error) { client := newClient(tags) return client, client.SetDSN(dsn) }
[ "func", "NewWithTags", "(", "dsn", "string", ",", "tags", "map", "[", "string", "]", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "client", ":=", "newClient", "(", "tags", ")", "\n", "return", "client", ",", "client", ".", "SetDSN", "(", "dsn", ")", "\n", "}" ]
// NewWithTags constructs a new Sentry client instance with default tags.
[ "NewWithTags", "constructs", "a", "new", "Sentry", "client", "instance", "with", "default", "tags", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L404-L407
8,696
getsentry/raven-go
client.go
SetIgnoreErrors
func (client *Client) SetIgnoreErrors(errs []string) error { joinedRegexp := strings.Join(errs, "|") r, err := regexp.Compile(joinedRegexp) if err != nil { return fmt.Errorf("raven: failed to compile regexp %q for %q: %v", joinedRegexp, errs, err) } client.mu.Lock() client.ignoreErrorsRegexp = r client.mu.Unlock() return nil }
go
func (client *Client) SetIgnoreErrors(errs []string) error { joinedRegexp := strings.Join(errs, "|") r, err := regexp.Compile(joinedRegexp) if err != nil { return fmt.Errorf("raven: failed to compile regexp %q for %q: %v", joinedRegexp, errs, err) } client.mu.Lock() client.ignoreErrorsRegexp = r client.mu.Unlock() return nil }
[ "func", "(", "client", "*", "Client", ")", "SetIgnoreErrors", "(", "errs", "[", "]", "string", ")", "error", "{", "joinedRegexp", ":=", "strings", ".", "Join", "(", "errs", ",", "\"", "\"", ")", "\n", "r", ",", "err", ":=", "regexp", ".", "Compile", "(", "joinedRegexp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "joinedRegexp", ",", "errs", ",", "err", ")", "\n", "}", "\n\n", "client", ".", "mu", ".", "Lock", "(", ")", "\n", "client", ".", "ignoreErrorsRegexp", "=", "r", "\n", "client", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// SetIgnoreErrors updates ignoreErrors config on given client
[ "SetIgnoreErrors", "updates", "ignoreErrors", "config", "on", "given", "client" ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L460-L471
8,697
getsentry/raven-go
client.go
SetDSN
func (client *Client) SetDSN(dsn string) error { if dsn == "" { return nil } client.mu.Lock() defer client.mu.Unlock() uri, err := url.Parse(dsn) if err != nil { return err } if uri.User == nil { return ErrMissingUser } publicKey := uri.User.Username() secretKey, hasSecretKey := uri.User.Password() uri.User = nil if idx := strings.LastIndex(uri.Path, "/"); idx != -1 { client.projectID = uri.Path[idx+1:] uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/" } if client.projectID == "" { return ErrMissingProjectID } client.url = uri.String() if hasSecretKey { client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey) } else { client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s", publicKey) } return nil }
go
func (client *Client) SetDSN(dsn string) error { if dsn == "" { return nil } client.mu.Lock() defer client.mu.Unlock() uri, err := url.Parse(dsn) if err != nil { return err } if uri.User == nil { return ErrMissingUser } publicKey := uri.User.Username() secretKey, hasSecretKey := uri.User.Password() uri.User = nil if idx := strings.LastIndex(uri.Path, "/"); idx != -1 { client.projectID = uri.Path[idx+1:] uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/" } if client.projectID == "" { return ErrMissingProjectID } client.url = uri.String() if hasSecretKey { client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey) } else { client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s", publicKey) } return nil }
[ "func", "(", "client", "*", "Client", ")", "SetDSN", "(", "dsn", "string", ")", "error", "{", "if", "dsn", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "client", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "client", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "uri", ",", "err", ":=", "url", ".", "Parse", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "uri", ".", "User", "==", "nil", "{", "return", "ErrMissingUser", "\n", "}", "\n", "publicKey", ":=", "uri", ".", "User", ".", "Username", "(", ")", "\n", "secretKey", ",", "hasSecretKey", ":=", "uri", ".", "User", ".", "Password", "(", ")", "\n", "uri", ".", "User", "=", "nil", "\n\n", "if", "idx", ":=", "strings", ".", "LastIndex", "(", "uri", ".", "Path", ",", "\"", "\"", ")", ";", "idx", "!=", "-", "1", "{", "client", ".", "projectID", "=", "uri", ".", "Path", "[", "idx", "+", "1", ":", "]", "\n", "uri", ".", "Path", "=", "uri", ".", "Path", "[", ":", "idx", "+", "1", "]", "+", "\"", "\"", "+", "client", ".", "projectID", "+", "\"", "\"", "\n", "}", "\n", "if", "client", ".", "projectID", "==", "\"", "\"", "{", "return", "ErrMissingProjectID", "\n", "}", "\n\n", "client", ".", "url", "=", "uri", ".", "String", "(", ")", "\n\n", "if", "hasSecretKey", "{", "client", ".", "authHeader", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "publicKey", ",", "secretKey", ")", "\n", "}", "else", "{", "client", ".", "authHeader", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "publicKey", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetDSN updates a client with a new DSN. It safe to call after and // concurrently with calls to Report and Send.
[ "SetDSN", "updates", "a", "client", "with", "a", "new", "DSN", ".", "It", "safe", "to", "call", "after", "and", "concurrently", "with", "calls", "to", "Report", "and", "Send", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L486-L523
8,698
getsentry/raven-go
client.go
SetRelease
func (client *Client) SetRelease(release string) { client.mu.Lock() defer client.mu.Unlock() client.release = release }
go
func (client *Client) SetRelease(release string) { client.mu.Lock() defer client.mu.Unlock() client.release = release }
[ "func", "(", "client", "*", "Client", ")", "SetRelease", "(", "release", "string", ")", "{", "client", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "client", ".", "mu", ".", "Unlock", "(", ")", "\n", "client", ".", "release", "=", "release", "\n", "}" ]
// SetRelease sets the "release" tag.
[ "SetRelease", "sets", "the", "release", "tag", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L529-L533
8,699
getsentry/raven-go
client.go
SetEnvironment
func (client *Client) SetEnvironment(environment string) { client.mu.Lock() defer client.mu.Unlock() client.environment = environment }
go
func (client *Client) SetEnvironment(environment string) { client.mu.Lock() defer client.mu.Unlock() client.environment = environment }
[ "func", "(", "client", "*", "Client", ")", "SetEnvironment", "(", "environment", "string", ")", "{", "client", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "client", ".", "mu", ".", "Unlock", "(", ")", "\n", "client", ".", "environment", "=", "environment", "\n", "}" ]
// SetEnvironment sets the "environment" tag.
[ "SetEnvironment", "sets", "the", "environment", "tag", "." ]
919484f041ea21e7e27be291cee1d6af7bc98864
https://github.com/getsentry/raven-go/blob/919484f041ea21e7e27be291cee1d6af7bc98864/client.go#L536-L540