id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
151,600 | vulcand/vulcan | circuitbreaker/cbreaker.go | ProcessRequest | func (c *CircuitBreaker) ProcessRequest(r request.Request) (*http.Response, error) {
if c.isStandby() {
c.markToRecordMetrics(r)
return nil, nil
}
// Circuit breaker is in tripped or recovering state
c.m.Lock()
defer c.m.Unlock()
log.Infof("%v is in error handling state", c)
switch c.state {
case stateStandby:
// other goroutine has set it to standby state
return nil, nil
case stateTripped:
if c.tm.UtcNow().Before(c.until) {
return c.fallback.ProcessRequest(r)
}
// We have been in active state enough, enter recovering state
c.setRecovering()
fallthrough
case stateRecovering:
// We have been in recovering state enough, enter standby
if c.tm.UtcNow().After(c.until) {
// instructs ProcessResponse() to record metrics for this request
c.markToRecordMetrics(r)
c.setState(stateStandby, c.tm.UtcNow())
return nil, nil
}
if c.rc.allowRequest() {
// instructs ProcessResponse() to record metrics for this request
c.markToRecordMetrics(r)
return nil, nil
}
return c.fallback.ProcessRequest(r)
}
return nil, nil
} | go | func (c *CircuitBreaker) ProcessRequest(r request.Request) (*http.Response, error) {
if c.isStandby() {
c.markToRecordMetrics(r)
return nil, nil
}
// Circuit breaker is in tripped or recovering state
c.m.Lock()
defer c.m.Unlock()
log.Infof("%v is in error handling state", c)
switch c.state {
case stateStandby:
// other goroutine has set it to standby state
return nil, nil
case stateTripped:
if c.tm.UtcNow().Before(c.until) {
return c.fallback.ProcessRequest(r)
}
// We have been in active state enough, enter recovering state
c.setRecovering()
fallthrough
case stateRecovering:
// We have been in recovering state enough, enter standby
if c.tm.UtcNow().After(c.until) {
// instructs ProcessResponse() to record metrics for this request
c.markToRecordMetrics(r)
c.setState(stateStandby, c.tm.UtcNow())
return nil, nil
}
if c.rc.allowRequest() {
// instructs ProcessResponse() to record metrics for this request
c.markToRecordMetrics(r)
return nil, nil
}
return c.fallback.ProcessRequest(r)
}
return nil, nil
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"ProcessRequest",
"(",
"r",
"request",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"c",
".",
"isStandby",
"(",
")",
"{",
"c",
".",
"markToRecordMetrics",
"(",
"r"... | // ProcessRequest is called on every request to the endpoint. CircuitBreaker uses this feature
// to intercept the request if it's in Tripped state or slowly start passing the requests to endpoint
// if it's in the recovering state | [
"ProcessRequest",
"is",
"called",
"on",
"every",
"request",
"to",
"the",
"endpoint",
".",
"CircuitBreaker",
"uses",
"this",
"feature",
"to",
"intercept",
"the",
"request",
"if",
"it",
"s",
"in",
"Tripped",
"state",
"or",
"slowly",
"start",
"passing",
"the",
... | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/circuitbreaker/cbreaker.go#L156-L196 |
151,601 | vulcand/vulcan | circuitbreaker/cbreaker.go | setTripped | func (c *CircuitBreaker) setTripped(e endpoint.Endpoint) bool {
c.m.Lock()
defer c.m.Unlock()
if c.state == stateTripped {
log.Infof("%v skip set tripped", c)
return false
}
c.setState(stateTripped, c.tm.UtcNow().Add(c.o.FallbackDuration))
c.resetStats(e)
return true
} | go | func (c *CircuitBreaker) setTripped(e endpoint.Endpoint) bool {
c.m.Lock()
defer c.m.Unlock()
if c.state == stateTripped {
log.Infof("%v skip set tripped", c)
return false
}
c.setState(stateTripped, c.tm.UtcNow().Add(c.o.FallbackDuration))
c.resetStats(e)
return true
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"setTripped",
"(",
"e",
"endpoint",
".",
"Endpoint",
")",
"bool",
"{",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"state",
"... | // setTripped sets state only when current state is not tripped already | [
"setTripped",
"sets",
"state",
"only",
"when",
"current",
"state",
"is",
"not",
"tripped",
"already"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/circuitbreaker/cbreaker.go#L243-L255 |
151,602 | vulcand/vulcan | metrics/counter.go | NewRollingCounter | func NewRollingCounter(buckets int, resolution time.Duration, timeProvider timetools.TimeProvider) (*RollingCounter, error) {
if buckets <= 0 {
return nil, fmt.Errorf("Buckets should be >= 0")
}
if resolution < time.Second {
return nil, fmt.Errorf("Resolution should be larger than a second")
}
return &RollingCounter{
resolution: resolution,
timeProvider: timeProvider,
values: make([]int, buckets),
lastBucket: -1,
}, nil
} | go | func NewRollingCounter(buckets int, resolution time.Duration, timeProvider timetools.TimeProvider) (*RollingCounter, error) {
if buckets <= 0 {
return nil, fmt.Errorf("Buckets should be >= 0")
}
if resolution < time.Second {
return nil, fmt.Errorf("Resolution should be larger than a second")
}
return &RollingCounter{
resolution: resolution,
timeProvider: timeProvider,
values: make([]int, buckets),
lastBucket: -1,
}, nil
} | [
"func",
"NewRollingCounter",
"(",
"buckets",
"int",
",",
"resolution",
"time",
".",
"Duration",
",",
"timeProvider",
"timetools",
".",
"TimeProvider",
")",
"(",
"*",
"RollingCounter",
",",
"error",
")",
"{",
"if",
"buckets",
"<=",
"0",
"{",
"return",
"nil",
... | // NewRollingCounter creates a counter with fixed amount of buckets that are rotated every resolition period.
// E.g. 10 buckets with 1 second means that every new second the bucket is refreshed, so it maintains 10 second rolling window. | [
"NewRollingCounter",
"creates",
"a",
"counter",
"with",
"fixed",
"amount",
"of",
"buckets",
"that",
"are",
"rotated",
"every",
"resolition",
"period",
".",
"E",
".",
"g",
".",
"10",
"buckets",
"with",
"1",
"second",
"means",
"that",
"every",
"new",
"second",... | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/metrics/counter.go#L25-L39 |
151,603 | vulcand/vulcan | netutils/netutils.go | CopyHeaders | func CopyHeaders(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
} | go | func CopyHeaders(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
} | [
"func",
"CopyHeaders",
"(",
"dst",
",",
"src",
"http",
".",
"Header",
")",
"{",
"for",
"k",
",",
"vv",
":=",
"range",
"src",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vv",
"{",
"dst",
".",
"Add",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"... | // Copies http headers from source to destination
// does not overide, but adds multiple headers | [
"Copies",
"http",
"headers",
"from",
"source",
"to",
"destination",
"does",
"not",
"overide",
"but",
"adds",
"multiple",
"headers"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/netutils/netutils.go#L56-L62 |
151,604 | vulcand/vulcan | netutils/netutils.go | RemoveHeaders | func RemoveHeaders(names []string, headers http.Header) {
for _, h := range names {
headers.Del(h)
}
} | go | func RemoveHeaders(names []string, headers http.Header) {
for _, h := range names {
headers.Del(h)
}
} | [
"func",
"RemoveHeaders",
"(",
"names",
"[",
"]",
"string",
",",
"headers",
"http",
".",
"Header",
")",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"names",
"{",
"headers",
".",
"Del",
"(",
"h",
")",
"\n",
"}",
"\n",
"}"
] | // Removes the header with the given names from the headers map | [
"Removes",
"the",
"header",
"with",
"the",
"given",
"names",
"from",
"the",
"headers",
"map"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/netutils/netutils.go#L76-L80 |
151,605 | vulcand/vulcan | netutils/netutils.go | ParseUrl | func ParseUrl(inUrl string) (*url.URL, error) {
parsedUrl, err := url.Parse(inUrl)
if err != nil {
return nil, err
}
if parsedUrl.Host == "" || parsedUrl.Scheme == "" {
return nil, fmt.Errorf("Empty Url is not allowed")
}
return parsedUrl, nil
} | go | func ParseUrl(inUrl string) (*url.URL, error) {
parsedUrl, err := url.Parse(inUrl)
if err != nil {
return nil, err
}
if parsedUrl.Host == "" || parsedUrl.Scheme == "" {
return nil, fmt.Errorf("Empty Url is not allowed")
}
return parsedUrl, nil
} | [
"func",
"ParseUrl",
"(",
"inUrl",
"string",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"parsedUrl",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"inUrl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
... | // Standard parse url is very generous,
// parseUrl wrapper makes it more strict
// and demands scheme and host to be set | [
"Standard",
"parse",
"url",
"is",
"very",
"generous",
"parseUrl",
"wrapper",
"makes",
"it",
"more",
"strict",
"and",
"demands",
"scheme",
"and",
"host",
"to",
"be",
"set"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/netutils/netutils.go#L93-L103 |
151,606 | vulcand/vulcan | proxy.go | ServeHTTP | func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := p.proxyRequest(w, r)
if err == nil {
return
}
switch e := err.(type) {
case *errors.RedirectError:
// In case if it's redirect error, try the request one more time, but with different URL
r.URL = e.URL
r.Host = e.URL.Host
r.RequestURI = e.URL.String()
if err := p.proxyRequest(w, r); err != nil {
p.replyError(err, w, r)
}
default:
p.replyError(err, w, r)
}
} | go | func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := p.proxyRequest(w, r)
if err == nil {
return
}
switch e := err.(type) {
case *errors.RedirectError:
// In case if it's redirect error, try the request one more time, but with different URL
r.URL = e.URL
r.Host = e.URL.Host
r.RequestURI = e.URL.String()
if err := p.proxyRequest(w, r); err != nil {
p.replyError(err, w, r)
}
default:
p.replyError(err, w, r)
}
} | [
"func",
"(",
"p",
"*",
"Proxy",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"err",
":=",
"p",
".",
"proxyRequest",
"(",
"w",
",",
"r",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"re... | // Accepts requests, round trips it to the endpoint, and writes back the response. | [
"Accepts",
"requests",
"round",
"trips",
"it",
"to",
"the",
"endpoint",
"and",
"writes",
"back",
"the",
"response",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/proxy.go#L32-L50 |
151,607 | vulcand/vulcan | proxy.go | NewProxyWithOptions | func NewProxyWithOptions(router route.Router, o Options) (*Proxy, error) {
o, err := validateOptions(o)
if err != nil {
return nil, err
}
p := &Proxy{
options: o,
router: router,
}
return p, nil
} | go | func NewProxyWithOptions(router route.Router, o Options) (*Proxy, error) {
o, err := validateOptions(o)
if err != nil {
return nil, err
}
p := &Proxy{
options: o,
router: router,
}
return p, nil
} | [
"func",
"NewProxyWithOptions",
"(",
"router",
"route",
".",
"Router",
",",
"o",
"Options",
")",
"(",
"*",
"Proxy",
",",
"error",
")",
"{",
"o",
",",
"err",
":=",
"validateOptions",
"(",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // Creates reverse proxy that acts like http request handler | [
"Creates",
"reverse",
"proxy",
"that",
"acts",
"like",
"http",
"request",
"handler"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/proxy.go#L58-L69 |
151,608 | vulcand/vulcan | proxy.go | proxyRequest | func (p *Proxy) proxyRequest(w http.ResponseWriter, r *http.Request) error {
// Create a unique request with sequential ids that will be passed to all interfaces.
req := request.NewBaseRequest(r, atomic.AddInt64(&p.lastRequestId, 1), nil)
location, err := p.router.Route(req)
if err != nil {
return err
}
// Router could not find a matching location, we can do nothing else.
if location == nil {
log.Errorf("%s failed to route", req)
return errors.FromStatus(http.StatusBadGateway)
}
response, err := location.RoundTrip(req)
if response != nil {
netutils.CopyHeaders(w.Header(), response.Header)
w.WriteHeader(response.StatusCode)
io.Copy(w, response.Body)
response.Body.Close()
return nil
} else {
return err
}
} | go | func (p *Proxy) proxyRequest(w http.ResponseWriter, r *http.Request) error {
// Create a unique request with sequential ids that will be passed to all interfaces.
req := request.NewBaseRequest(r, atomic.AddInt64(&p.lastRequestId, 1), nil)
location, err := p.router.Route(req)
if err != nil {
return err
}
// Router could not find a matching location, we can do nothing else.
if location == nil {
log.Errorf("%s failed to route", req)
return errors.FromStatus(http.StatusBadGateway)
}
response, err := location.RoundTrip(req)
if response != nil {
netutils.CopyHeaders(w.Header(), response.Header)
w.WriteHeader(response.StatusCode)
io.Copy(w, response.Body)
response.Body.Close()
return nil
} else {
return err
}
} | [
"func",
"(",
"p",
"*",
"Proxy",
")",
"proxyRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// Create a unique request with sequential ids that will be passed to all interfaces.",
"req",
":=",
"request",
"... | // Round trips the request to the selected location and writes back the response | [
"Round",
"trips",
"the",
"request",
"to",
"the",
"selected",
"location",
"and",
"writes",
"back",
"the",
"response"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/proxy.go#L76-L101 |
151,609 | vulcand/vulcan | proxy.go | replyError | func (p *Proxy) replyError(err error, w http.ResponseWriter, req *http.Request) {
proxyError := convertError(err)
statusCode, body, contentType := p.options.ErrorFormatter.Format(proxyError)
w.Header().Set("Content-Type", contentType)
if proxyError.Headers() != nil {
netutils.CopyHeaders(w.Header(), proxyError.Headers())
}
w.WriteHeader(statusCode)
w.Write(body)
} | go | func (p *Proxy) replyError(err error, w http.ResponseWriter, req *http.Request) {
proxyError := convertError(err)
statusCode, body, contentType := p.options.ErrorFormatter.Format(proxyError)
w.Header().Set("Content-Type", contentType)
if proxyError.Headers() != nil {
netutils.CopyHeaders(w.Header(), proxyError.Headers())
}
w.WriteHeader(statusCode)
w.Write(body)
} | [
"func",
"(",
"p",
"*",
"Proxy",
")",
"replyError",
"(",
"err",
"error",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"proxyError",
":=",
"convertError",
"(",
"err",
")",
"\n",
"statusCode",
",",
"body",
... | // replyError is a helper function that takes error and replies with HTTP compatible error to the client. | [
"replyError",
"is",
"a",
"helper",
"function",
"that",
"takes",
"error",
"and",
"replies",
"with",
"HTTP",
"compatible",
"error",
"to",
"the",
"client",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/proxy.go#L104-L113 |
151,610 | vulcand/vulcan | threshold/threshold.go | ResponseCode | func ResponseCode() RequestToInt {
return func(r request.Request) int {
attempts := len(r.GetAttempts())
if attempts == 0 {
return 0
}
lastResponse := r.GetAttempts()[attempts-1].GetResponse()
if lastResponse == nil {
return 0
}
return lastResponse.StatusCode
}
} | go | func ResponseCode() RequestToInt {
return func(r request.Request) int {
attempts := len(r.GetAttempts())
if attempts == 0 {
return 0
}
lastResponse := r.GetAttempts()[attempts-1].GetResponse()
if lastResponse == nil {
return 0
}
return lastResponse.StatusCode
}
} | [
"func",
"ResponseCode",
"(",
")",
"RequestToInt",
"{",
"return",
"func",
"(",
"r",
"request",
".",
"Request",
")",
"int",
"{",
"attempts",
":=",
"len",
"(",
"r",
".",
"GetAttempts",
"(",
")",
")",
"\n",
"if",
"attempts",
"==",
"0",
"{",
"return",
"0"... | // ResponseCode returns mapper of the request to the last response code, returns 0 if there was no response code. | [
"ResponseCode",
"returns",
"mapper",
"of",
"the",
"request",
"to",
"the",
"last",
"response",
"code",
"returns",
"0",
"if",
"there",
"was",
"no",
"response",
"code",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L47-L59 |
151,611 | vulcand/vulcan | threshold/threshold.go | OR | func OR(fns ...Predicate) Predicate {
return func(req request.Request) bool {
for _, fn := range fns {
if fn(req) {
return true
}
}
return false
}
} | go | func OR(fns ...Predicate) Predicate {
return func(req request.Request) bool {
for _, fn := range fns {
if fn(req) {
return true
}
}
return false
}
} | [
"func",
"OR",
"(",
"fns",
"...",
"Predicate",
")",
"Predicate",
"{",
"return",
"func",
"(",
"req",
"request",
".",
"Request",
")",
"bool",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"{",
"if",
"fn",
"(",
"req",
")",
"{",
"return",
"true",
... | // OR returns predicate by joining the passed predicates with logical 'or' | [
"OR",
"returns",
"predicate",
"by",
"joining",
"the",
"passed",
"predicates",
"with",
"logical",
"or"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L82-L91 |
151,612 | vulcand/vulcan | threshold/threshold.go | NOT | func NOT(p Predicate) Predicate {
return func(r request.Request) bool {
return !p(r)
}
} | go | func NOT(p Predicate) Predicate {
return func(r request.Request) bool {
return !p(r)
}
} | [
"func",
"NOT",
"(",
"p",
"Predicate",
")",
"Predicate",
"{",
"return",
"func",
"(",
"r",
"request",
".",
"Request",
")",
"bool",
"{",
"return",
"!",
"p",
"(",
"r",
")",
"\n",
"}",
"\n",
"}"
] | // NOT creates negation of the passed predicate | [
"NOT",
"creates",
"negation",
"of",
"the",
"passed",
"predicate"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L94-L98 |
151,613 | vulcand/vulcan | threshold/threshold.go | EQ | func EQ(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToString:
return stringEQ(mapper, value)
case RequestToInt:
return intEQ(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | go | func EQ(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToString:
return stringEQ(mapper, value)
case RequestToInt:
return intEQ(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | [
"func",
"EQ",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"RequestToString",
":",
"return",
"stringEQ",
"(",
... | // EQ returns predicate that tests for equality of the value of the mapper and the constant | [
"EQ",
"returns",
"predicate",
"that",
"tests",
"for",
"equality",
"of",
"the",
"value",
"of",
"the",
"mapper",
"and",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L101-L109 |
151,614 | vulcand/vulcan | threshold/threshold.go | NEQ | func NEQ(m interface{}, value interface{}) (Predicate, error) {
p, err := EQ(m, value)
if err != nil {
return nil, err
}
return NOT(p), nil
} | go | func NEQ(m interface{}, value interface{}) (Predicate, error) {
p, err := EQ(m, value)
if err != nil {
return nil, err
}
return NOT(p), nil
} | [
"func",
"NEQ",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"EQ",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // NEQ returns predicate that tests for inequality of the value of the mapper and the constant | [
"NEQ",
"returns",
"predicate",
"that",
"tests",
"for",
"inequality",
"of",
"the",
"value",
"of",
"the",
"mapper",
"and",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L112-L118 |
151,615 | vulcand/vulcan | threshold/threshold.go | LT | func LT(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intLT(mapper, value)
case RequestToFloat64:
return float64LT(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | go | func LT(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intLT(mapper, value)
case RequestToFloat64:
return float64LT(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | [
"func",
"LT",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"RequestToInt",
":",
"return",
"intLT",
"(",
"mapp... | // LT returns predicate that tests that value of the mapper function is less than the constant | [
"LT",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"less",
"than",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L121-L129 |
151,616 | vulcand/vulcan | threshold/threshold.go | GT | func GT(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intGT(mapper, value)
case RequestToFloat64:
return float64GT(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | go | func GT(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intGT(mapper, value)
case RequestToFloat64:
return float64GT(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | [
"func",
"GT",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"RequestToInt",
":",
"return",
"intGT",
"(",
"mapp... | // GT returns predicate that tests that value of the mapper function is greater than the constant | [
"GT",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"greater",
"than",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L132-L140 |
151,617 | vulcand/vulcan | threshold/threshold.go | LE | func LE(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intLE(mapper, value)
case RequestToFloat64:
return float64LE(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | go | func LE(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intLE(mapper, value)
case RequestToFloat64:
return float64LE(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | [
"func",
"LE",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"RequestToInt",
":",
"return",
"intLE",
"(",
"mapp... | // LE returns predicate that tests that value of the mapper function is less than or equal to the constant | [
"LE",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L143-L151 |
151,618 | vulcand/vulcan | threshold/threshold.go | GE | func GE(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intGE(mapper, value)
case RequestToFloat64:
return float64GE(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | go | func GE(m interface{}, value interface{}) (Predicate, error) {
switch mapper := m.(type) {
case RequestToInt:
return intGE(mapper, value)
case RequestToFloat64:
return float64GE(mapper, value)
}
return nil, fmt.Errorf("unsupported argument: %T", m)
} | [
"func",
"GE",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"Predicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"RequestToInt",
":",
"return",
"intGE",
"(",
"mapp... | // GE returns predicate that tests that value of the mapper function is greater than or equal to the constant | [
"GE",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"constant"
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/threshold/threshold.go#L154-L162 |
151,619 | vulcand/vulcan | limit/tokenbucket/tokenlimiter.go | NewLimiter | func NewLimiter(defaultRates *RateSet, capacity int, mapper limit.MapperFn, configMapper ConfigMapperFn, clock timetools.TimeProvider) (*TokenLimiter, error) {
if defaultRates == nil || len(defaultRates.m) == 0 {
return nil, fmt.Errorf("Provide default rates")
}
if mapper == nil {
return nil, fmt.Errorf("Provide mapper function")
}
// Set default values for optional fields.
if capacity <= 0 {
capacity = DefaultCapacity
}
if clock == nil {
clock = &timetools.RealTime{}
}
bucketSets, err := ttlmap.NewMapWithProvider(DefaultCapacity, clock)
if err != nil {
return nil, err
}
return &TokenLimiter{
defaultRates: defaultRates,
mapper: mapper,
configMapper: configMapper,
clock: clock,
bucketSets: bucketSets,
}, nil
} | go | func NewLimiter(defaultRates *RateSet, capacity int, mapper limit.MapperFn, configMapper ConfigMapperFn, clock timetools.TimeProvider) (*TokenLimiter, error) {
if defaultRates == nil || len(defaultRates.m) == 0 {
return nil, fmt.Errorf("Provide default rates")
}
if mapper == nil {
return nil, fmt.Errorf("Provide mapper function")
}
// Set default values for optional fields.
if capacity <= 0 {
capacity = DefaultCapacity
}
if clock == nil {
clock = &timetools.RealTime{}
}
bucketSets, err := ttlmap.NewMapWithProvider(DefaultCapacity, clock)
if err != nil {
return nil, err
}
return &TokenLimiter{
defaultRates: defaultRates,
mapper: mapper,
configMapper: configMapper,
clock: clock,
bucketSets: bucketSets,
}, nil
} | [
"func",
"NewLimiter",
"(",
"defaultRates",
"*",
"RateSet",
",",
"capacity",
"int",
",",
"mapper",
"limit",
".",
"MapperFn",
",",
"configMapper",
"ConfigMapperFn",
",",
"clock",
"timetools",
".",
"TimeProvider",
")",
"(",
"*",
"TokenLimiter",
",",
"error",
")",... | // NewLimiter constructs a `TokenLimiter` middleware instance. | [
"NewLimiter",
"constructs",
"a",
"TokenLimiter",
"middleware",
"instance",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/tokenbucket/tokenlimiter.go#L68-L96 |
151,620 | vulcand/vulcan | limit/tokenbucket/tokenlimiter.go | DefaultRates | func (tl *TokenLimiter) DefaultRates() *RateSet {
defaultRates := NewRateSet()
for _, r := range tl.defaultRates.m {
defaultRates.Add(r.period, r.average, r.burst)
}
return defaultRates
} | go | func (tl *TokenLimiter) DefaultRates() *RateSet {
defaultRates := NewRateSet()
for _, r := range tl.defaultRates.m {
defaultRates.Add(r.period, r.average, r.burst)
}
return defaultRates
} | [
"func",
"(",
"tl",
"*",
"TokenLimiter",
")",
"DefaultRates",
"(",
")",
"*",
"RateSet",
"{",
"defaultRates",
":=",
"NewRateSet",
"(",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"tl",
".",
"defaultRates",
".",
"m",
"{",
"defaultRates",
".",
"Add",
... | // DefaultRates returns the default rate set of the limiter. The only reason to
// Provide this method is to facilitate testing. | [
"DefaultRates",
"returns",
"the",
"default",
"rate",
"set",
"of",
"the",
"limiter",
".",
"The",
"only",
"reason",
"to",
"Provide",
"this",
"method",
"is",
"to",
"facilitate",
"testing",
"."
] | 68da62480270a5267400baa37587e8c9d451faa3 | https://github.com/vulcand/vulcan/blob/68da62480270a5267400baa37587e8c9d451faa3/limit/tokenbucket/tokenlimiter.go#L100-L106 |
151,621 | gravitational/version | version.go | Print | func Print() {
payload, err := json.Marshal(Get())
if err != nil {
panic(err)
}
fmt.Printf("%s", payload)
} | go | func Print() {
payload, err := json.Marshal(Get())
if err != nil {
panic(err)
}
fmt.Printf("%s", payload)
} | [
"func",
"Print",
"(",
")",
"{",
"payload",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"Get",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
",",
"paylo... | // Print prints build version in default format. | [
"Print",
"prints",
"build",
"version",
"in",
"default",
"format",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/version.go#L45-L51 |
151,622 | gravitational/version | cmd/linkflags/main.go | getVersionInfo | func getVersionInfo(pkg string) (*version.Info, error) {
git := newGit(pkg)
commitID, err := git.commitID()
if err != nil {
return nil, fmt.Errorf("failed to obtain git commit ID: %v\n", err)
}
treeState, err := git.treeState()
if err != nil {
return nil, fmt.Errorf("failed to determine git tree state: %v\n", err)
}
tag, err := git.tag(commitID)
if err != nil {
tag = ""
}
if tag != "" {
tag = semverify(tag)
if treeState == dirty {
tag = tag + "-" + string(treeState)
}
}
return &version.Info{
Version: tag,
GitCommit: commitID,
GitTreeState: string(treeState),
}, nil
} | go | func getVersionInfo(pkg string) (*version.Info, error) {
git := newGit(pkg)
commitID, err := git.commitID()
if err != nil {
return nil, fmt.Errorf("failed to obtain git commit ID: %v\n", err)
}
treeState, err := git.treeState()
if err != nil {
return nil, fmt.Errorf("failed to determine git tree state: %v\n", err)
}
tag, err := git.tag(commitID)
if err != nil {
tag = ""
}
if tag != "" {
tag = semverify(tag)
if treeState == dirty {
tag = tag + "-" + string(treeState)
}
}
return &version.Info{
Version: tag,
GitCommit: commitID,
GitTreeState: string(treeState),
}, nil
} | [
"func",
"getVersionInfo",
"(",
"pkg",
"string",
")",
"(",
"*",
"version",
".",
"Info",
",",
"error",
")",
"{",
"git",
":=",
"newGit",
"(",
"pkg",
")",
"\n",
"commitID",
",",
"err",
":=",
"git",
".",
"commitID",
"(",
")",
"\n",
"if",
"err",
"!=",
... | // getVersionInfo collects the build version information for package pkg. | [
"getVersionInfo",
"collects",
"the",
"build",
"version",
"information",
"for",
"package",
"pkg",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/cmd/linkflags/main.go#L125-L150 |
151,623 | gravitational/version | cmd/linkflags/main.go | goToolVersion | func goToolVersion() (toolVersion, error) {
goTool := &tool.T{Cmd: "go"}
out, err := goTool.Exec("version")
if err != nil {
return toolVersionUnknown, err
}
build := strings.Split(out, " ")
if len(build) > 2 {
return parseToolVersion(build[2]), nil
}
return toolVersionUnknown, nil
} | go | func goToolVersion() (toolVersion, error) {
goTool := &tool.T{Cmd: "go"}
out, err := goTool.Exec("version")
if err != nil {
return toolVersionUnknown, err
}
build := strings.Split(out, " ")
if len(build) > 2 {
return parseToolVersion(build[2]), nil
}
return toolVersionUnknown, nil
} | [
"func",
"goToolVersion",
"(",
")",
"(",
"toolVersion",
",",
"error",
")",
"{",
"goTool",
":=",
"&",
"tool",
".",
"T",
"{",
"Cmd",
":",
"\"",
"\"",
"}",
"\n",
"out",
",",
"err",
":=",
"goTool",
".",
"Exec",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err... | // goToolVersion determines the version of the `go tool`. | [
"goToolVersion",
"determines",
"the",
"version",
"of",
"the",
"go",
"tool",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/cmd/linkflags/main.go#L153-L164 |
151,624 | gravitational/version | cmd/linkflags/main.go | parseToolVersion | func parseToolVersion(version string) toolVersion {
match := goVersionPattern.FindStringSubmatch(version)
if len(match) > 2 {
// After a successful match, match[1] and match[2] are integers
major := mustAtoi(match[1])
minor := mustAtoi(match[2])
return toolVersion(major*10 + minor)
}
return toolVersionUnknown
} | go | func parseToolVersion(version string) toolVersion {
match := goVersionPattern.FindStringSubmatch(version)
if len(match) > 2 {
// After a successful match, match[1] and match[2] are integers
major := mustAtoi(match[1])
minor := mustAtoi(match[2])
return toolVersion(major*10 + minor)
}
return toolVersionUnknown
} | [
"func",
"parseToolVersion",
"(",
"version",
"string",
")",
"toolVersion",
"{",
"match",
":=",
"goVersionPattern",
".",
"FindStringSubmatch",
"(",
"version",
")",
"\n",
"if",
"len",
"(",
"match",
")",
">",
"2",
"{",
"// After a successful match, match[1] and match[2]... | // parseToolVersion translates a string version of the form 'go1.4.3' to a numeric value 14. | [
"parseToolVersion",
"translates",
"a",
"string",
"version",
"of",
"the",
"form",
"go1",
".",
"4",
".",
"3",
"to",
"a",
"numeric",
"value",
"14",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/cmd/linkflags/main.go#L167-L176 |
151,625 | gravitational/version | cmd/linkflags/main.go | semverify | func semverify(version string) string {
match := semverPattern.FindStringSubmatch(version)
if match != nil && len(match) == 6 {
// replace the last component of the semver (which is always 0 in our versioning scheme)
// with the number of commits since the last tag
return fmt.Sprintf("%v.%v.%v+%v", match[1], match[2], match[4], match[5])
}
return version
} | go | func semverify(version string) string {
match := semverPattern.FindStringSubmatch(version)
if match != nil && len(match) == 6 {
// replace the last component of the semver (which is always 0 in our versioning scheme)
// with the number of commits since the last tag
return fmt.Sprintf("%v.%v.%v+%v", match[1], match[2], match[4], match[5])
}
return version
} | [
"func",
"semverify",
"(",
"version",
"string",
")",
"string",
"{",
"match",
":=",
"semverPattern",
".",
"FindStringSubmatch",
"(",
"version",
")",
"\n",
"if",
"match",
"!=",
"nil",
"&&",
"len",
"(",
"match",
")",
"==",
"6",
"{",
"// replace the last componen... | // semverify transforms the output of `git describe` to be semver-compliant. | [
"semverify",
"transforms",
"the",
"output",
"of",
"git",
"describe",
"to",
"be",
"semver",
"-",
"compliant",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/cmd/linkflags/main.go#L228-L236 |
151,626 | gravitational/version | cmd/linkflags/main.go | mustAtoi | func mustAtoi(value string) int {
result, err := strconv.Atoi(value)
if err != nil {
panic(err)
}
return result
} | go | func mustAtoi(value string) int {
result, err := strconv.Atoi(value)
if err != nil {
panic(err)
}
return result
} | [
"func",
"mustAtoi",
"(",
"value",
"string",
")",
"int",
"{",
"result",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // mustAtoi converts value to an integer.
// It panics if the value does not represent a valid integer. | [
"mustAtoi",
"converts",
"value",
"to",
"an",
"integer",
".",
"It",
"panics",
"if",
"the",
"value",
"does",
"not",
"represent",
"a",
"valid",
"integer",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/cmd/linkflags/main.go#L240-L246 |
151,627 | gravitational/version | pkg/tool/tool.go | Exec | func (r *T) Exec(args ...string) (string, error) {
args = append(r.Args[:], args...)
return r.RawExec(args...)
} | go | func (r *T) Exec(args ...string) (string, error) {
args = append(r.Args[:], args...)
return r.RawExec(args...)
} | [
"func",
"(",
"r",
"*",
"T",
")",
"Exec",
"(",
"args",
"...",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"args",
"=",
"append",
"(",
"r",
".",
"Args",
"[",
":",
"]",
",",
"args",
"...",
")",
"\n",
"return",
"r",
".",
"RawExec",
"(",... | // exec executes a given command specified with args prepending a set of fixed arguments.
// Otherwise behaves exactly as rawExec | [
"exec",
"executes",
"a",
"given",
"command",
"specified",
"with",
"args",
"prepending",
"a",
"set",
"of",
"fixed",
"arguments",
".",
"Otherwise",
"behaves",
"exactly",
"as",
"rawExec"
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/pkg/tool/tool.go#L45-L48 |
151,628 | gravitational/version | pkg/tool/tool.go | RawExec | func (r *T) RawExec(args ...string) (string, error) {
out, err := exec.Command(r.Cmd, args...).CombinedOutput()
if err == nil {
out = bytes.TrimSpace(out)
}
if err != nil {
err = &Error{
Tool: r.Cmd,
Output: out,
Err: err,
}
}
return string(out), err
} | go | func (r *T) RawExec(args ...string) (string, error) {
out, err := exec.Command(r.Cmd, args...).CombinedOutput()
if err == nil {
out = bytes.TrimSpace(out)
}
if err != nil {
err = &Error{
Tool: r.Cmd,
Output: out,
Err: err,
}
}
return string(out), err
} | [
"func",
"(",
"r",
"*",
"T",
")",
"RawExec",
"(",
"args",
"...",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"r",
".",
"Cmd",
",",
"args",
"...",
")",
".",
"CombinedOutput",
"(",
")... | // RawExec executes a given command specified with args and returns the output
// with whitespace trimmed. | [
"RawExec",
"executes",
"a",
"given",
"command",
"specified",
"with",
"args",
"and",
"returns",
"the",
"output",
"with",
"whitespace",
"trimmed",
"."
] | 95d33ece5ce1a00844c874822496682f353f3003 | https://github.com/gravitational/version/blob/95d33ece5ce1a00844c874822496682f353f3003/pkg/tool/tool.go#L52-L65 |
151,629 | foize/go.fifo | fifo.go | Len | func (q *Queue) Len() (length int) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// copy q.count and return length
length = q.count
return length
} | go | func (q *Queue) Len() (length int) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// copy q.count and return length
length = q.count
return length
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Len",
"(",
")",
"(",
"length",
"int",
")",
"{",
"// locking to make Queue thread-safe",
"q",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"// copy q.count an... | // Return the number of items in the queue | [
"Return",
"the",
"number",
"of",
"items",
"in",
"the",
"queue"
] | 3a04cfeec12143459af4c62b147b365e950051c9 | https://github.com/foize/go.fifo/blob/3a04cfeec12143459af4c62b147b365e950051c9/fifo.go#L41-L49 |
151,630 | foize/go.fifo | fifo.go | Add | func (q *Queue) Add(item interface{}) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// check if item is valid
if item == nil {
panic("can not add nil item to fifo queue")
}
// if the tail chunk is full, create a new one and add it to the queue.
if q.tail.last >= chunkSize {
q.tail.next = new(chunk)
q.tail = q.tail.next
}
// add item to the tail chunk at the last position
q.tail.items[q.tail.last] = item
q.tail.last++
q.count++
} | go | func (q *Queue) Add(item interface{}) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// check if item is valid
if item == nil {
panic("can not add nil item to fifo queue")
}
// if the tail chunk is full, create a new one and add it to the queue.
if q.tail.last >= chunkSize {
q.tail.next = new(chunk)
q.tail = q.tail.next
}
// add item to the tail chunk at the last position
q.tail.items[q.tail.last] = item
q.tail.last++
q.count++
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Add",
"(",
"item",
"interface",
"{",
"}",
")",
"{",
"// locking to make Queue thread-safe",
"q",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"// check if it... | // Add an item to the end of the queue | [
"Add",
"an",
"item",
"to",
"the",
"end",
"of",
"the",
"queue"
] | 3a04cfeec12143459af4c62b147b365e950051c9 | https://github.com/foize/go.fifo/blob/3a04cfeec12143459af4c62b147b365e950051c9/fifo.go#L52-L72 |
151,631 | foize/go.fifo | fifo.go | Next | func (q *Queue) Next() (item interface{}) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// Return nil if there are no items to return
if q.count == 0 {
return nil
}
// FIXME: why would this check be required?
if q.head.first >= q.head.last {
return nil
}
// Get item from queue
item = q.head.items[q.head.first]
// increment first position and decrement queue item count
q.head.first++
q.count--
if q.head.first >= q.head.last {
// we're at the end of this chunk and we should do some maintainance
// if there are no follow up chunks then reset the current one so it can be used again.
if q.count == 0 {
q.head.first = 0
q.head.last = 0
q.head.next = nil
} else {
// set queue's head chunk to the next chunk
// old head will fall out of scope and be GC-ed
q.head = q.head.next
}
}
// return the retrieved item
return item
} | go | func (q *Queue) Next() (item interface{}) {
// locking to make Queue thread-safe
q.lock.Lock()
defer q.lock.Unlock()
// Return nil if there are no items to return
if q.count == 0 {
return nil
}
// FIXME: why would this check be required?
if q.head.first >= q.head.last {
return nil
}
// Get item from queue
item = q.head.items[q.head.first]
// increment first position and decrement queue item count
q.head.first++
q.count--
if q.head.first >= q.head.last {
// we're at the end of this chunk and we should do some maintainance
// if there are no follow up chunks then reset the current one so it can be used again.
if q.count == 0 {
q.head.first = 0
q.head.last = 0
q.head.next = nil
} else {
// set queue's head chunk to the next chunk
// old head will fall out of scope and be GC-ed
q.head = q.head.next
}
}
// return the retrieved item
return item
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Next",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
")",
"{",
"// locking to make Queue thread-safe",
"q",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
... | // Remove the item at the head of the queue and return it.
// Returns nil when there are no items left in queue. | [
"Remove",
"the",
"item",
"at",
"the",
"head",
"of",
"the",
"queue",
"and",
"return",
"it",
".",
"Returns",
"nil",
"when",
"there",
"are",
"no",
"items",
"left",
"in",
"queue",
"."
] | 3a04cfeec12143459af4c62b147b365e950051c9 | https://github.com/foize/go.fifo/blob/3a04cfeec12143459af4c62b147b365e950051c9/fifo.go#L76-L113 |
151,632 | dogtools/dog | parse.go | Parse | func Parse(p []byte) (dtasks Dogtasks, err error) {
var tasks []*taskYAML
err = yaml.Unmarshal(p, &tasks)
if err != nil {
return
}
for _, parsedTask := range tasks {
if _, ok := dtasks.Tasks[parsedTask.Name]; ok {
err = fmt.Errorf("Duplicated task name %s", parsedTask.Name)
return
} else if !validTaskName(parsedTask.Name) {
err = fmt.Errorf("Invalid name for task %s", parsedTask.Name)
return
} else {
task := &Task{
Name: parsedTask.Name,
Description: parsedTask.Description,
Code: parsedTask.Code,
Runner: parsedTask.Runner,
Workdir: parsedTask.Workdir,
Register: parsedTask.Register,
}
// convert pre-tasks, post-tasks and environment variables
// into []string
if task.Pre, err = parseStringSlice(parsedTask.Pre); err != nil {
return
}
if task.Post, err = parseStringSlice(parsedTask.Post); err != nil {
return
}
if task.Env, err = parseStringSlice(parsedTask.Env); err != nil {
return
}
// set default runner if not specified
if task.Runner == "" {
task.Runner = DefaultRunner
}
if dtasks.Tasks == nil {
dtasks.Tasks = make(map[string]*Task)
}
dtasks.Tasks[task.Name] = task
}
}
// validate resulting dogtasks object
err = dtasks.Validate()
return
} | go | func Parse(p []byte) (dtasks Dogtasks, err error) {
var tasks []*taskYAML
err = yaml.Unmarshal(p, &tasks)
if err != nil {
return
}
for _, parsedTask := range tasks {
if _, ok := dtasks.Tasks[parsedTask.Name]; ok {
err = fmt.Errorf("Duplicated task name %s", parsedTask.Name)
return
} else if !validTaskName(parsedTask.Name) {
err = fmt.Errorf("Invalid name for task %s", parsedTask.Name)
return
} else {
task := &Task{
Name: parsedTask.Name,
Description: parsedTask.Description,
Code: parsedTask.Code,
Runner: parsedTask.Runner,
Workdir: parsedTask.Workdir,
Register: parsedTask.Register,
}
// convert pre-tasks, post-tasks and environment variables
// into []string
if task.Pre, err = parseStringSlice(parsedTask.Pre); err != nil {
return
}
if task.Post, err = parseStringSlice(parsedTask.Post); err != nil {
return
}
if task.Env, err = parseStringSlice(parsedTask.Env); err != nil {
return
}
// set default runner if not specified
if task.Runner == "" {
task.Runner = DefaultRunner
}
if dtasks.Tasks == nil {
dtasks.Tasks = make(map[string]*Task)
}
dtasks.Tasks[task.Name] = task
}
}
// validate resulting dogtasks object
err = dtasks.Validate()
return
} | [
"func",
"Parse",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"dtasks",
"Dogtasks",
",",
"err",
"error",
")",
"{",
"var",
"tasks",
"[",
"]",
"*",
"taskYAML",
"\n\n",
"err",
"=",
"yaml",
".",
"Unmarshal",
"(",
"p",
",",
"&",
"tasks",
")",
"\n",
"if",
"... | // Parse accepts a slice of bytes and parses it following the Dogfile Spec. | [
"Parse",
"accepts",
"a",
"slice",
"of",
"bytes",
"and",
"parses",
"it",
"following",
"the",
"Dogfile",
"Spec",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L61-L114 |
151,633 | dogtools/dog | parse.go | parseStringSlice | func parseStringSlice(str interface{}) ([]string, error) {
switch h := str.(type) {
case string:
return []string{h}, nil
case []interface{}:
s := make([]string, len(h))
for i, hook := range h {
sHook, ok := hook.(string)
if !ok {
return nil, ErrMalformedStringArray
}
s[i] = sHook
}
return s, nil
case nil:
return []string{}, nil
default:
return nil, ErrMalformedStringArray
}
} | go | func parseStringSlice(str interface{}) ([]string, error) {
switch h := str.(type) {
case string:
return []string{h}, nil
case []interface{}:
s := make([]string, len(h))
for i, hook := range h {
sHook, ok := hook.(string)
if !ok {
return nil, ErrMalformedStringArray
}
s[i] = sHook
}
return s, nil
case nil:
return []string{}, nil
default:
return nil, ErrMalformedStringArray
}
} | [
"func",
"parseStringSlice",
"(",
"str",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"switch",
"h",
":=",
"str",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"[",
"]",
"string",
"{",
"h",
"}",
",",
... | // parseStringSlice takes an interface from a pre, post or env field
// and returns a slice of strings representing the found values. | [
"parseStringSlice",
"takes",
"an",
"interface",
"from",
"a",
"pre",
"post",
"or",
"env",
"field",
"and",
"returns",
"a",
"slice",
"of",
"strings",
"representing",
"the",
"found",
"values",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L118-L137 |
151,634 | dogtools/dog | parse.go | ParseFromDisk | func ParseFromDisk(dir string) (dtasks Dogtasks, err error) {
if dir == "" {
dir = "."
}
dir, err = filepath.Abs(dir)
if err != nil {
return
}
dtasks.Files, err = FindDogfiles(dir)
if err != nil {
return
}
if len(dtasks.Files) == 0 {
err = ErrNoDogfile
return
}
dtasks.Path, err = filepath.Abs(filepath.Dir(dtasks.Files[0]))
if err != nil {
return
}
// iterate over every found file
for _, file := range dtasks.Files {
var fileData []byte
var d Dogtasks
fileData, err = ioutil.ReadFile(file)
if err != nil {
return
}
// parse file
d, err = Parse(fileData)
if err != nil {
return
}
// add parsed tasks to main dogfile
for _, t := range d.Tasks {
if dtasks.Tasks == nil {
dtasks.Tasks = make(map[string]*Task)
}
if t.Workdir == "" {
t.Workdir = dtasks.Path
} else {
t.Workdir, err = filepath.Abs(t.Workdir)
if err != nil {
return
}
}
dtasks.Tasks[t.Name] = t
}
}
// validate resulting dogfile
err = dtasks.Validate()
return
} | go | func ParseFromDisk(dir string) (dtasks Dogtasks, err error) {
if dir == "" {
dir = "."
}
dir, err = filepath.Abs(dir)
if err != nil {
return
}
dtasks.Files, err = FindDogfiles(dir)
if err != nil {
return
}
if len(dtasks.Files) == 0 {
err = ErrNoDogfile
return
}
dtasks.Path, err = filepath.Abs(filepath.Dir(dtasks.Files[0]))
if err != nil {
return
}
// iterate over every found file
for _, file := range dtasks.Files {
var fileData []byte
var d Dogtasks
fileData, err = ioutil.ReadFile(file)
if err != nil {
return
}
// parse file
d, err = Parse(fileData)
if err != nil {
return
}
// add parsed tasks to main dogfile
for _, t := range d.Tasks {
if dtasks.Tasks == nil {
dtasks.Tasks = make(map[string]*Task)
}
if t.Workdir == "" {
t.Workdir = dtasks.Path
} else {
t.Workdir, err = filepath.Abs(t.Workdir)
if err != nil {
return
}
}
dtasks.Tasks[t.Name] = t
}
}
// validate resulting dogfile
err = dtasks.Validate()
return
} | [
"func",
"ParseFromDisk",
"(",
"dir",
"string",
")",
"(",
"dtasks",
"Dogtasks",
",",
"err",
"error",
")",
"{",
"if",
"dir",
"==",
"\"",
"\"",
"{",
"dir",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"dir",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"dir",... | // ParseFromDisk finds a Dogfile in disk and parses it. | [
"ParseFromDisk",
"finds",
"a",
"Dogfile",
"in",
"disk",
"and",
"parses",
"it",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L140-L199 |
151,635 | dogtools/dog | parse.go | Validate | func (dtasks *Dogtasks) Validate() error {
for _, t := range dtasks.Tasks {
if !validTaskName(t.Name) {
return fmt.Errorf("Invalid name for task %s", t.Name)
}
if _, err := NewTaskChain(*dtasks, t.Name); err != nil {
return err
}
}
return nil
} | go | func (dtasks *Dogtasks) Validate() error {
for _, t := range dtasks.Tasks {
if !validTaskName(t.Name) {
return fmt.Errorf("Invalid name for task %s", t.Name)
}
if _, err := NewTaskChain(*dtasks, t.Name); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"dtasks",
"*",
"Dogtasks",
")",
"Validate",
"(",
")",
"error",
"{",
"for",
"_",
",",
"t",
":=",
"range",
"dtasks",
".",
"Tasks",
"{",
"if",
"!",
"validTaskName",
"(",
"t",
".",
"Name",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"... | // Validate checks that all tasks in a Dogfile are valid.
//
// It checks if any task has a non standard name and also if the
// resulting task chain of each of them have an undesired cycle. | [
"Validate",
"checks",
"that",
"all",
"tasks",
"in",
"a",
"Dogfile",
"are",
"valid",
".",
"It",
"checks",
"if",
"any",
"task",
"has",
"a",
"non",
"standard",
"name",
"and",
"also",
"if",
"the",
"resulting",
"task",
"chain",
"of",
"each",
"of",
"them",
"... | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L205-L218 |
151,636 | dogtools/dog | parse.go | FindDogfiles | func FindDogfiles(p string) ([]string, error) {
var dogfilePaths []string
currentPath, err := filepath.Abs(p)
if err != nil {
return nil, err
}
for {
var files []os.FileInfo
files, err = ioutil.ReadDir(currentPath)
if err != nil {
return nil, err
}
for _, file := range files {
if validDogfileName(file.Name()) {
dogfilePath := path.Join(currentPath, file.Name())
dogfilePaths = append(dogfilePaths, dogfilePath)
}
}
if len(dogfilePaths) > 0 {
return dogfilePaths, nil
}
nextPath := path.Dir(currentPath)
if nextPath == currentPath {
return dogfilePaths, nil
}
currentPath = nextPath
}
} | go | func FindDogfiles(p string) ([]string, error) {
var dogfilePaths []string
currentPath, err := filepath.Abs(p)
if err != nil {
return nil, err
}
for {
var files []os.FileInfo
files, err = ioutil.ReadDir(currentPath)
if err != nil {
return nil, err
}
for _, file := range files {
if validDogfileName(file.Name()) {
dogfilePath := path.Join(currentPath, file.Name())
dogfilePaths = append(dogfilePaths, dogfilePath)
}
}
if len(dogfilePaths) > 0 {
return dogfilePaths, nil
}
nextPath := path.Dir(currentPath)
if nextPath == currentPath {
return dogfilePaths, nil
}
currentPath = nextPath
}
} | [
"func",
"FindDogfiles",
"(",
"p",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"dogfilePaths",
"[",
"]",
"string",
"\n\n",
"currentPath",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"n... | // FindDogfiles finds Dogfiles in disk for a given path.
//
// It traverses directories until it finds one containing Dogfiles.
// If such a directory is found, the function returns the full path
// for each valid Dogfile in that directory. | [
"FindDogfiles",
"finds",
"Dogfiles",
"in",
"disk",
"for",
"a",
"given",
"path",
".",
"It",
"traverses",
"directories",
"until",
"it",
"finds",
"one",
"containing",
"Dogfiles",
".",
"If",
"such",
"a",
"directory",
"is",
"found",
"the",
"function",
"returns",
... | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L225-L257 |
151,637 | dogtools/dog | parse.go | validDogfileName | func validDogfileName(name string) bool {
var match bool
match, err := regexp.MatchString("^(dog|🐕).*\\.(yml|yaml)$", name)
if err != nil {
return false
}
return match
} | go | func validDogfileName(name string) bool {
var match bool
match, err := regexp.MatchString("^(dog|🐕).*\\.(yml|yaml)$", name)
if err != nil {
return false
}
return match
} | [
"func",
"validDogfileName",
"(",
"name",
"string",
")",
"bool",
"{",
"var",
"match",
"bool",
"\n",
"match",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"\"",
"(y",
"n",
"a",
"e)",
"",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
... | // validDogfileName checks if a Dogfile name is valid as defined
// by the Dogfile Spec. | [
"validDogfileName",
"checks",
"if",
"a",
"Dogfile",
"name",
"is",
"valid",
"as",
"defined",
"by",
"the",
"Dogfile",
"Spec",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L261-L268 |
151,638 | dogtools/dog | parse.go | validTaskName | func validTaskName(name string) bool {
var match bool
match, err := regexp.MatchString("^[a-z0-9]+(-[a-z0-9]+)*$", name)
if err != nil {
return false
}
return match
} | go | func validTaskName(name string) bool {
var match bool
match, err := regexp.MatchString("^[a-z0-9]+(-[a-z0-9]+)*$", name)
if err != nil {
return false
}
return match
} | [
"func",
"validTaskName",
"(",
"name",
"string",
")",
"bool",
"{",
"var",
"match",
"bool",
"\n",
"match",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
... | // validTaskName checks if a task name is valid as defined
// by the Dogfile Spec. | [
"validTaskName",
"checks",
"if",
"a",
"task",
"name",
"is",
"valid",
"as",
"defined",
"by",
"the",
"Dogfile",
"Spec",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/parse.go#L272-L279 |
151,639 | dogtools/dog | chain.go | NewTaskChain | func NewTaskChain(dtasks Dogtasks, task string) (taskChain TaskChain, err error) {
err = taskChain.generate(dtasks, task)
if err != nil {
return
}
return
} | go | func NewTaskChain(dtasks Dogtasks, task string) (taskChain TaskChain, err error) {
err = taskChain.generate(dtasks, task)
if err != nil {
return
}
return
} | [
"func",
"NewTaskChain",
"(",
"dtasks",
"Dogtasks",
",",
"task",
"string",
")",
"(",
"taskChain",
"TaskChain",
",",
"err",
"error",
")",
"{",
"err",
"=",
"taskChain",
".",
"generate",
"(",
"dtasks",
",",
"task",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // NewTaskChain creates the task chain for a specific dogfile and task. | [
"NewTaskChain",
"creates",
"the",
"task",
"chain",
"for",
"a",
"specific",
"dogfile",
"and",
"task",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/chain.go#L29-L35 |
151,640 | dogtools/dog | chain.go | generate | func (taskChain *TaskChain) generate(dtasks Dogtasks, task string) error {
t, found := dtasks.Tasks[task]
if !found {
return fmt.Errorf("Task %q does not exist", task)
}
// Cycle detection
for i := 0; i < len(taskChain.Tasks); i++ {
if taskChain.Tasks[i].Name == task {
if len(taskChain.Tasks[i].Pre) > 0 || len(taskChain.Tasks[i].Post) > 0 {
return ErrCycleInTaskChain
}
}
}
// Iterate over pre-tasks
if err := addToChain(taskChain, dtasks, t.Pre); err != nil {
return err
}
// Add current task to chain
taskChain.Tasks = append(taskChain.Tasks, *t)
// Iterate over post-tasks
if err := addToChain(taskChain, dtasks, t.Post); err != nil {
return err
}
return nil
} | go | func (taskChain *TaskChain) generate(dtasks Dogtasks, task string) error {
t, found := dtasks.Tasks[task]
if !found {
return fmt.Errorf("Task %q does not exist", task)
}
// Cycle detection
for i := 0; i < len(taskChain.Tasks); i++ {
if taskChain.Tasks[i].Name == task {
if len(taskChain.Tasks[i].Pre) > 0 || len(taskChain.Tasks[i].Post) > 0 {
return ErrCycleInTaskChain
}
}
}
// Iterate over pre-tasks
if err := addToChain(taskChain, dtasks, t.Pre); err != nil {
return err
}
// Add current task to chain
taskChain.Tasks = append(taskChain.Tasks, *t)
// Iterate over post-tasks
if err := addToChain(taskChain, dtasks, t.Post); err != nil {
return err
}
return nil
} | [
"func",
"(",
"taskChain",
"*",
"TaskChain",
")",
"generate",
"(",
"dtasks",
"Dogtasks",
",",
"task",
"string",
")",
"error",
"{",
"t",
",",
"found",
":=",
"dtasks",
".",
"Tasks",
"[",
"task",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"fmt",
".",
... | // Generate recursively iterates over all tasks, including pre and post tasks for
// each of them, and adds all of them into a task chain. | [
"Generate",
"recursively",
"iterates",
"over",
"all",
"tasks",
"including",
"pre",
"and",
"post",
"tasks",
"for",
"each",
"of",
"them",
"and",
"adds",
"all",
"of",
"them",
"into",
"a",
"task",
"chain",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/chain.go#L39-L68 |
151,641 | dogtools/dog | chain.go | addToChain | func addToChain(taskChain *TaskChain, dtasks Dogtasks, tasks []string) error {
for _, name := range tasks {
t, found := dtasks.Tasks[name]
if !found {
return fmt.Errorf("Task %q does not exist", name)
}
if err := taskChain.generate(dtasks, t.Name); err != nil {
return err
}
}
return nil
} | go | func addToChain(taskChain *TaskChain, dtasks Dogtasks, tasks []string) error {
for _, name := range tasks {
t, found := dtasks.Tasks[name]
if !found {
return fmt.Errorf("Task %q does not exist", name)
}
if err := taskChain.generate(dtasks, t.Name); err != nil {
return err
}
}
return nil
} | [
"func",
"addToChain",
"(",
"taskChain",
"*",
"TaskChain",
",",
"dtasks",
"Dogtasks",
",",
"tasks",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"name",
":=",
"range",
"tasks",
"{",
"t",
",",
"found",
":=",
"dtasks",
".",
"Tasks",
"[",
"nam... | // addToChain adds found tasks into the task chain. | [
"addToChain",
"adds",
"found",
"tasks",
"into",
"the",
"task",
"chain",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/chain.go#L71-L84 |
151,642 | dogtools/dog | chain.go | Run | func (taskChain *TaskChain) Run(stdout, stderr io.Writer) error {
var startTime time.Time
var registers []string
for _, t := range taskChain.Tasks {
var err error
var runner run.Runner
register := new(bytes.Buffer)
exitStatus := 0
env := append(t.Env, registers...)
switch t.Runner {
case "sh":
runner, err = run.NewShRunner(t.Code, t.Workdir, env)
case "bash":
runner, err = run.NewBashRunner(t.Code, t.Workdir, env)
default:
if t.Runner == "" {
return errors.New("Runner not specified")
}
return fmt.Errorf("%s is not a supported runner", t.Runner)
}
if err != nil {
return err
}
runOut, runErr, err := run.GetOutputs(runner)
if err != nil {
return err
}
if t.Register == "" {
go io.Copy(stdout, runOut)
} else {
go io.Copy(register, runOut)
}
go io.Copy(stderr, runErr)
startTime = time.Now()
err = runner.Start()
if err != nil {
return err
}
err = runner.Wait()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); !ok {
exitStatus = 1 // For unknown error exit codes set it to 1
} else {
exitStatus = waitStatus.ExitStatus()
}
}
if ProvideExtraInfo {
fmt.Printf("-- %s (%s) failed with exit status %d\n",
t.Name, time.Since(startTime).String(), exitStatus)
}
return err
}
if t.Register != "" {
r := fmt.Sprintf("%s=%s", t.Register, register.String())
registers = append(registers, strings.TrimSpace(r))
}
if ProvideExtraInfo {
fmt.Printf("-- %s (%s) finished with exit status %d\n",
t.Name, time.Since(startTime).String(), exitStatus)
}
}
return nil
} | go | func (taskChain *TaskChain) Run(stdout, stderr io.Writer) error {
var startTime time.Time
var registers []string
for _, t := range taskChain.Tasks {
var err error
var runner run.Runner
register := new(bytes.Buffer)
exitStatus := 0
env := append(t.Env, registers...)
switch t.Runner {
case "sh":
runner, err = run.NewShRunner(t.Code, t.Workdir, env)
case "bash":
runner, err = run.NewBashRunner(t.Code, t.Workdir, env)
default:
if t.Runner == "" {
return errors.New("Runner not specified")
}
return fmt.Errorf("%s is not a supported runner", t.Runner)
}
if err != nil {
return err
}
runOut, runErr, err := run.GetOutputs(runner)
if err != nil {
return err
}
if t.Register == "" {
go io.Copy(stdout, runOut)
} else {
go io.Copy(register, runOut)
}
go io.Copy(stderr, runErr)
startTime = time.Now()
err = runner.Start()
if err != nil {
return err
}
err = runner.Wait()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); !ok {
exitStatus = 1 // For unknown error exit codes set it to 1
} else {
exitStatus = waitStatus.ExitStatus()
}
}
if ProvideExtraInfo {
fmt.Printf("-- %s (%s) failed with exit status %d\n",
t.Name, time.Since(startTime).String(), exitStatus)
}
return err
}
if t.Register != "" {
r := fmt.Sprintf("%s=%s", t.Register, register.String())
registers = append(registers, strings.TrimSpace(r))
}
if ProvideExtraInfo {
fmt.Printf("-- %s (%s) finished with exit status %d\n",
t.Name, time.Since(startTime).String(), exitStatus)
}
}
return nil
} | [
"func",
"(",
"taskChain",
"*",
"TaskChain",
")",
"Run",
"(",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"error",
"{",
"var",
"startTime",
"time",
".",
"Time",
"\n",
"var",
"registers",
"[",
"]",
"string",
"\n\n",
"for",
"_",
",",
"t",
":=",
... | // Run handles the execution of all tasks in the TaskChain. | [
"Run",
"handles",
"the",
"execution",
"of",
"all",
"tasks",
"in",
"the",
"TaskChain",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/chain.go#L87-L160 |
151,643 | dogtools/dog | run/run.go | NewShRunner | func NewShRunner(code string, workdir string, env []string) (Runner, error) {
return newCmdRunner(runCmdProperties{
runner: "sh",
fileExtension: ".sh",
code: code,
workdir: workdir,
env: env,
})
} | go | func NewShRunner(code string, workdir string, env []string) (Runner, error) {
return newCmdRunner(runCmdProperties{
runner: "sh",
fileExtension: ".sh",
code: code,
workdir: workdir,
env: env,
})
} | [
"func",
"NewShRunner",
"(",
"code",
"string",
",",
"workdir",
"string",
",",
"env",
"[",
"]",
"string",
")",
"(",
"Runner",
",",
"error",
")",
"{",
"return",
"newCmdRunner",
"(",
"runCmdProperties",
"{",
"runner",
":",
"\"",
"\"",
",",
"fileExtension",
"... | // NewShRunner creates a system standard shell script runner. | [
"NewShRunner",
"creates",
"a",
"system",
"standard",
"shell",
"script",
"runner",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/run/run.go#L29-L37 |
151,644 | dogtools/dog | run/run.go | GetOutputs | func GetOutputs(r Runner) (io.Reader, io.Reader, error) {
stdout, err := r.StdoutPipe()
if err != nil {
return nil, nil, err
}
stderr, err := r.StderrPipe()
if err != nil {
return nil, nil, err
}
return bufio.NewReader(stdout), bufio.NewReader(stderr), nil
} | go | func GetOutputs(r Runner) (io.Reader, io.Reader, error) {
stdout, err := r.StdoutPipe()
if err != nil {
return nil, nil, err
}
stderr, err := r.StderrPipe()
if err != nil {
return nil, nil, err
}
return bufio.NewReader(stdout), bufio.NewReader(stderr), nil
} | [
"func",
"GetOutputs",
"(",
"r",
"Runner",
")",
"(",
"io",
".",
"Reader",
",",
"io",
".",
"Reader",
",",
"error",
")",
"{",
"stdout",
",",
"err",
":=",
"r",
".",
"StdoutPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
... | // GetOutputs is a helper method that returns both stdout and stderr outputs
// from the runner. | [
"GetOutputs",
"is",
"a",
"helper",
"method",
"that",
"returns",
"both",
"stdout",
"and",
"stderr",
"outputs",
"from",
"the",
"runner",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/run/run.go#L52-L64 |
151,645 | dogtools/dog | run/cmd.go | Wait | func (c *runCmd) Wait() error {
defer func() {
_ = os.Remove(c.tmpFile)
}()
err := c.Cmd.Wait()
if err != nil {
return err
}
return nil
} | go | func (c *runCmd) Wait() error {
defer func() {
_ = os.Remove(c.tmpFile)
}()
err := c.Cmd.Wait()
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"runCmd",
")",
"Wait",
"(",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"_",
"=",
"os",
".",
"Remove",
"(",
"c",
".",
"tmpFile",
")",
"\n",
"}",
"(",
")",
"\n\n",
"err",
":=",
"c",
".",
"Cmd",
".",
"Wait",
"(",... | // Wait waits until the command finishes running and provides exit information.
//
// This method overrites the Wait method that comes from the embedded exec.Cmd
// type, adding the removal of the temporary file. | [
"Wait",
"waits",
"until",
"the",
"command",
"finishes",
"running",
"and",
"provides",
"exit",
"information",
".",
"This",
"method",
"overrites",
"the",
"Wait",
"method",
"that",
"comes",
"from",
"the",
"embedded",
"exec",
".",
"Cmd",
"type",
"adding",
"the",
... | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/run/cmd.go#L31-L41 |
151,646 | dogtools/dog | run/cmd.go | newCmdRunner | func newCmdRunner(p runCmdProperties) (Runner, error) {
if p.code == "" {
return nil, errors.New("No code specified to run")
}
cmd := runCmd{}
path, err := exec.LookPath(strings.Fields(p.runner)[0])
if err != nil {
return nil, err
}
cmd.Path = path
cmd.Args = append(cmd.Args, strings.Fields(p.runner)...)
err = cmd.writeTempFile(p.code, p.fileExtension)
if err != nil {
return nil, err
}
cmd.Args = append(cmd.Args, cmd.tmpFile)
cmd.Dir = p.workdir
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, p.env...)
cmd.Stdin = os.Stdin
return &cmd, nil
} | go | func newCmdRunner(p runCmdProperties) (Runner, error) {
if p.code == "" {
return nil, errors.New("No code specified to run")
}
cmd := runCmd{}
path, err := exec.LookPath(strings.Fields(p.runner)[0])
if err != nil {
return nil, err
}
cmd.Path = path
cmd.Args = append(cmd.Args, strings.Fields(p.runner)...)
err = cmd.writeTempFile(p.code, p.fileExtension)
if err != nil {
return nil, err
}
cmd.Args = append(cmd.Args, cmd.tmpFile)
cmd.Dir = p.workdir
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, p.env...)
cmd.Stdin = os.Stdin
return &cmd, nil
} | [
"func",
"newCmdRunner",
"(",
"p",
"runCmdProperties",
")",
"(",
"Runner",
",",
"error",
")",
"{",
"if",
"p",
".",
"code",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"cmd",
":=",
"ru... | // newCmdRunner creates a cmd type runner of the chosen executor. | [
"newCmdRunner",
"creates",
"a",
"cmd",
"type",
"runner",
"of",
"the",
"chosen",
"executor",
"."
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/run/cmd.go#L61-L85 |
151,647 | dogtools/dog | cmd/dog/main.go | printTasks | func printTasks(dtasks dog.Dogtasks) {
maxCharSize := 0
for taskName, task := range dtasks.Tasks {
if task.Description != "" && len(taskName) > maxCharSize {
maxCharSize = len(taskName)
}
}
var tasks []string
for taskName, task := range dtasks.Tasks {
if task.Description != "" {
tasks = append(tasks, taskName)
}
}
sort.Strings(tasks)
for _, taskName := range tasks {
separator := strings.Repeat(" ", maxCharSize-len(taskName)+2)
fmt.Printf("%s%s%s\n", taskName, separator, dtasks.Tasks[taskName].Description)
if len(dtasks.Tasks[taskName].Pre) > 0 {
taskSpace := strings.Repeat(" ", len(taskName))
fmt.Printf("%s%s <= %s\n", taskSpace, separator, strings.Join(dtasks.Tasks[taskName].Pre[:], " "))
}
if len(dtasks.Tasks[taskName].Post) > 0 {
taskSpace := strings.Repeat(" ", len(taskName))
fmt.Printf("%s%s => %s\n", taskSpace, separator, strings.Join(dtasks.Tasks[taskName].Post[:], " "))
}
}
} | go | func printTasks(dtasks dog.Dogtasks) {
maxCharSize := 0
for taskName, task := range dtasks.Tasks {
if task.Description != "" && len(taskName) > maxCharSize {
maxCharSize = len(taskName)
}
}
var tasks []string
for taskName, task := range dtasks.Tasks {
if task.Description != "" {
tasks = append(tasks, taskName)
}
}
sort.Strings(tasks)
for _, taskName := range tasks {
separator := strings.Repeat(" ", maxCharSize-len(taskName)+2)
fmt.Printf("%s%s%s\n", taskName, separator, dtasks.Tasks[taskName].Description)
if len(dtasks.Tasks[taskName].Pre) > 0 {
taskSpace := strings.Repeat(" ", len(taskName))
fmt.Printf("%s%s <= %s\n", taskSpace, separator, strings.Join(dtasks.Tasks[taskName].Pre[:], " "))
}
if len(dtasks.Tasks[taskName].Post) > 0 {
taskSpace := strings.Repeat(" ", len(taskName))
fmt.Printf("%s%s => %s\n", taskSpace, separator, strings.Join(dtasks.Tasks[taskName].Post[:], " "))
}
}
} | [
"func",
"printTasks",
"(",
"dtasks",
"dog",
".",
"Dogtasks",
")",
"{",
"maxCharSize",
":=",
"0",
"\n",
"for",
"taskName",
",",
"task",
":=",
"range",
"dtasks",
".",
"Tasks",
"{",
"if",
"task",
".",
"Description",
"!=",
"\"",
"\"",
"&&",
"len",
"(",
"... | // print tasks with description | [
"print",
"tasks",
"with",
"description"
] | fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1 | https://github.com/dogtools/dog/blob/fe618372012d022ecc7f0ebe113f2bf6b1d0f1c1/cmd/dog/main.go#L86-L114 |
151,648 | orijtech/otils | otils.go | FirstNonEmptyString | func FirstNonEmptyString(args ...string) string {
for _, arg := range args {
if arg == "" {
continue
}
if strings.TrimSpace(arg) != "" {
return arg
}
}
return ""
} | go | func FirstNonEmptyString(args ...string) string {
for _, arg := range args {
if arg == "" {
continue
}
if strings.TrimSpace(arg) != "" {
return arg
}
}
return ""
} | [
"func",
"FirstNonEmptyString",
"(",
"args",
"...",
"string",
")",
"string",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"args",
"{",
"if",
"arg",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"strings",
".",
"TrimSpace",
"(",
"arg",
")",
... | // FirstNonEmptyString iterates through its
// arguments trying to find the first string
// that is not blank or consists entirely of spaces. | [
"FirstNonEmptyString",
"iterates",
"through",
"its",
"arguments",
"trying",
"to",
"find",
"the",
"first",
"string",
"that",
"is",
"not",
"blank",
"or",
"consists",
"entirely",
"of",
"spaces",
"."
] | 2369a11e3b261765cd468491c47f8af1f41f54c3 | https://github.com/orijtech/otils/blob/2369a11e3b261765cd468491c47f8af1f41f54c3/otils.go#L283-L293 |
151,649 | choria-io/go-confkey | confkey.go | SetStructDefaults | func SetStructDefaults(target interface{}) error {
if reflect.TypeOf(target).Kind() != reflect.Ptr {
return errors.New("pointer is required")
}
st := reflect.TypeOf(target).Elem()
for i := 0; i <= st.NumField()-1; i++ {
field := st.Field(i)
if key, ok := field.Tag.Lookup("confkey"); ok {
if value, ok := field.Tag.Lookup("default"); ok {
err := SetStructFieldWithKey(target, key, value)
if err != nil {
return err
}
}
}
}
return nil
} | go | func SetStructDefaults(target interface{}) error {
if reflect.TypeOf(target).Kind() != reflect.Ptr {
return errors.New("pointer is required")
}
st := reflect.TypeOf(target).Elem()
for i := 0; i <= st.NumField()-1; i++ {
field := st.Field(i)
if key, ok := field.Tag.Lookup("confkey"); ok {
if value, ok := field.Tag.Lookup("default"); ok {
err := SetStructFieldWithKey(target, key, value)
if err != nil {
return err
}
}
}
}
return nil
} | [
"func",
"SetStructDefaults",
"(",
"target",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
... | // SetStructDefaults extract defaults out of the tags and set them to the key | [
"SetStructDefaults",
"extract",
"defaults",
"out",
"of",
"the",
"tags",
"and",
"set",
"them",
"to",
"the",
"key"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L53-L74 |
151,650 | choria-io/go-confkey | confkey.go | StringFieldWithKey | func StringFieldWithKey(target interface{}, key string) string {
item, err := fieldWithKey(target, key)
if err != nil {
return ""
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.String {
ptr := field.Addr().Interface().(*string)
return string(*ptr)
}
return ""
} | go | func StringFieldWithKey(target interface{}, key string) string {
item, err := fieldWithKey(target, key)
if err != nil {
return ""
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.String {
ptr := field.Addr().Interface().(*string)
return string(*ptr)
}
return ""
} | [
"func",
"StringFieldWithKey",
"(",
"target",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"string",
"{",
"item",
",",
"err",
":=",
"fieldWithKey",
"(",
"target",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"... | // StringFieldWithKey retrieves a string from target that matches key, "" when not found | [
"StringFieldWithKey",
"retrieves",
"a",
"string",
"from",
"target",
"that",
"matches",
"key",
"when",
"not",
"found"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L77-L92 |
151,651 | choria-io/go-confkey | confkey.go | BoolWithKey | func BoolWithKey(target interface{}, key string) bool {
item, err := fieldWithKey(target, key)
if err != nil {
return false
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Bool {
ptr := field.Addr().Interface().(*bool)
return bool(*ptr)
}
return false
} | go | func BoolWithKey(target interface{}, key string) bool {
item, err := fieldWithKey(target, key)
if err != nil {
return false
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Bool {
ptr := field.Addr().Interface().(*bool)
return bool(*ptr)
}
return false
} | [
"func",
"BoolWithKey",
"(",
"target",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"bool",
"{",
"item",
",",
"err",
":=",
"fieldWithKey",
"(",
"target",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
... | // BoolWithKey retrieves a bool from target that matches key, false when not found | [
"BoolWithKey",
"retrieves",
"a",
"bool",
"from",
"target",
"that",
"matches",
"key",
"false",
"when",
"not",
"found"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L117-L132 |
151,652 | choria-io/go-confkey | confkey.go | IntWithKey | func IntWithKey(target interface{}, key string) int {
item, err := fieldWithKey(target, key)
if err != nil {
return 0
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Int {
ptr := field.Addr().Interface().(*int)
return int(*ptr)
}
return 0
} | go | func IntWithKey(target interface{}, key string) int {
item, err := fieldWithKey(target, key)
if err != nil {
return 0
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Int {
ptr := field.Addr().Interface().(*int)
return int(*ptr)
}
return 0
} | [
"func",
"IntWithKey",
"(",
"target",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"int",
"{",
"item",
",",
"err",
":=",
"fieldWithKey",
"(",
"target",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"fie... | // IntWithKey retrieves an int from target that matches key, 0 when not found | [
"IntWithKey",
"retrieves",
"an",
"int",
"from",
"target",
"that",
"matches",
"key",
"0",
"when",
"not",
"found"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L135-L150 |
151,653 | choria-io/go-confkey | confkey.go | Int64WithKey | func Int64WithKey(target interface{}, key string) int64 {
item, err := fieldWithKey(target, key)
if err != nil {
return 0
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Int64 {
ptr := field.Addr().Interface().(*int64)
return int64(*ptr)
}
return 0
} | go | func Int64WithKey(target interface{}, key string) int64 {
item, err := fieldWithKey(target, key)
if err != nil {
return 0
}
field := reflect.ValueOf(target).Elem().FieldByName(item)
if field.Kind() == reflect.Int64 {
ptr := field.Addr().Interface().(*int64)
return int64(*ptr)
}
return 0
} | [
"func",
"Int64WithKey",
"(",
"target",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"int64",
"{",
"item",
",",
"err",
":=",
"fieldWithKey",
"(",
"target",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
... | // Int64WithKey retrieves an int from target that matches key, 0 when not found | [
"Int64WithKey",
"retrieves",
"an",
"int",
"from",
"target",
"that",
"matches",
"key",
"0",
"when",
"not",
"found"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L153-L168 |
151,654 | choria-io/go-confkey | confkey.go | fieldWithKey | func fieldWithKey(s interface{}, key string) (string, error) {
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
for i := 0; i <= st.NumField()-1; i++ {
field := st.Field(i)
if confkey, ok := field.Tag.Lookup("confkey"); ok {
if confkey == key {
return field.Name, nil
}
}
}
return "", fmt.Errorf("can't find any structure element configured with confkey '%s'", key)
} | go | func fieldWithKey(s interface{}, key string) (string, error) {
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
for i := 0; i <= st.NumField()-1; i++ {
field := st.Field(i)
if confkey, ok := field.Tag.Lookup("confkey"); ok {
if confkey == key {
return field.Name, nil
}
}
}
return "", fmt.Errorf("can't find any structure element configured with confkey '%s'", key)
} | [
"func",
"fieldWithKey",
"(",
"s",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"st",
":=",
"reflect",
".",
"TypeOf",
"(",
"s",
")",
"\n",
"if",
"st",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
... | // determines the struct key name that is tagged with a certain confkey | [
"determines",
"the",
"struct",
"key",
"name",
"that",
"is",
"tagged",
"with",
"a",
"certain",
"confkey"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L287-L304 |
151,655 | choria-io/go-confkey | confkey.go | tag | func tag(s interface{}, field string, tag string) (string, bool) {
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
for i := 0; i <= st.NumField()-1; i++ {
f := st.Field(i)
if f.Name == field {
if value, ok := f.Tag.Lookup(tag); ok {
return value, true
}
}
}
return "", false
} | go | func tag(s interface{}, field string, tag string) (string, bool) {
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
for i := 0; i <= st.NumField()-1; i++ {
f := st.Field(i)
if f.Name == field {
if value, ok := f.Tag.Lookup(tag); ok {
return value, true
}
}
}
return "", false
} | [
"func",
"tag",
"(",
"s",
"interface",
"{",
"}",
",",
"field",
"string",
",",
"tag",
"string",
")",
"(",
"string",
",",
"bool",
")",
"{",
"st",
":=",
"reflect",
".",
"TypeOf",
"(",
"s",
")",
"\n\n",
"if",
"st",
".",
"Kind",
"(",
")",
"==",
"refl... | // retrieve a tag for a struct field | [
"retrieve",
"a",
"tag",
"for",
"a",
"struct",
"field"
] | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L307-L325 |
151,656 | choria-io/go-confkey | confkey.go | strToBool | func strToBool(s string) (bool, error) {
clean := strings.TrimSpace(s)
if regexp.MustCompile(`(?i)^(1|yes|true|y|t)$`).MatchString(clean) {
return true, nil
}
if regexp.MustCompile(`(?i)^(0|no|false|n|f)$`).MatchString(clean) {
return false, nil
}
return false, errors.New("cannot convert string value '" + clean + "' into a boolean.")
} | go | func strToBool(s string) (bool, error) {
clean := strings.TrimSpace(s)
if regexp.MustCompile(`(?i)^(1|yes|true|y|t)$`).MatchString(clean) {
return true, nil
}
if regexp.MustCompile(`(?i)^(0|no|false|n|f)$`).MatchString(clean) {
return false, nil
}
return false, errors.New("cannot convert string value '" + clean + "' into a boolean.")
} | [
"func",
"strToBool",
"(",
"s",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"clean",
":=",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
"\n\n",
"if",
"regexp",
".",
"MustCompile",
"(",
"`(?i)^(1|yes|true|y|t)$`",
")",
".",
"MatchString",
"(",
"clea... | // StrToBool converts a typical boolianish string to bool.
//
// 1, yes, true, y, t will be true
// 0, no, false, n, f will be false
// anything else will be false with an error | [
"StrToBool",
"converts",
"a",
"typical",
"boolianish",
"string",
"to",
"bool",
".",
"1",
"yes",
"true",
"y",
"t",
"will",
"be",
"true",
"0",
"no",
"false",
"n",
"f",
"will",
"be",
"false",
"anything",
"else",
"will",
"be",
"false",
"with",
"an",
"error... | 634d2c41860498507b0c7eeb2f8a33b1aa6a809d | https://github.com/choria-io/go-confkey/blob/634d2c41860498507b0c7eeb2f8a33b1aa6a809d/confkey.go#L332-L344 |
151,657 | dc0d/workerpool | workerpool.go | Queue | func (pool *WorkerPool) Queue(job func(), timeout ...time.Duration) bool {
if pool.stopped() {
return false
}
var t <-chan time.Time
if len(timeout) > 0 && timeout[0] > 0 {
t = time.After(timeout[0])
}
select {
case pool.jobs <- job:
case <-t:
return false
case <-pool.quit:
return false
}
return true
} | go | func (pool *WorkerPool) Queue(job func(), timeout ...time.Duration) bool {
if pool.stopped() {
return false
}
var t <-chan time.Time
if len(timeout) > 0 && timeout[0] > 0 {
t = time.After(timeout[0])
}
select {
case pool.jobs <- job:
case <-t:
return false
case <-pool.quit:
return false
}
return true
} | [
"func",
"(",
"pool",
"*",
"WorkerPool",
")",
"Queue",
"(",
"job",
"func",
"(",
")",
",",
"timeout",
"...",
"time",
".",
"Duration",
")",
"bool",
"{",
"if",
"pool",
".",
"stopped",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"var",
"t",
"<-... | // Queue queues a job to be run by a worker. | [
"Queue",
"queues",
"a",
"job",
"to",
"be",
"run",
"by",
"a",
"worker",
"."
] | b089d6fbecae0a3e1364d825c7957359a9d75e38 | https://github.com/dc0d/workerpool/blob/b089d6fbecae0a3e1364d825c7957359a9d75e38/workerpool.go#L51-L67 |
151,658 | dc0d/workerpool | workerpool.go | Stop | func (pool *WorkerPool) Stop() {
pool.quitOnce.Do(func() { close(pool.quit) })
pool.wg.Wait()
} | go | func (pool *WorkerPool) Stop() {
pool.quitOnce.Do(func() { close(pool.quit) })
pool.wg.Wait()
} | [
"func",
"(",
"pool",
"*",
"WorkerPool",
")",
"Stop",
"(",
")",
"{",
"pool",
".",
"quitOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"pool",
".",
"quit",
")",
"}",
")",
"\n",
"pool",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // Stop stops the pool and waits for all workers to return. | [
"Stop",
"stops",
"the",
"pool",
"and",
"waits",
"for",
"all",
"workers",
"to",
"return",
"."
] | b089d6fbecae0a3e1364d825c7957359a9d75e38 | https://github.com/dc0d/workerpool/blob/b089d6fbecae0a3e1364d825c7957359a9d75e38/workerpool.go#L70-L73 |
151,659 | gkiryaziev/go-instagram | instagram.go | Login | func (i *Instagram) Login() error {
fetch := APIURL + "/si/fetch_headers/?challenge_type=signup&guid=" + generateUUID(false)
resp, err := i.requestLogin("GET", fetch, nil)
if err != nil {
return err
}
defer resp.Body.Close()
// get csrftoken
for _, cookie := range resp.Cookies() {
if cookie.Name == "csrftoken" {
i.token = cookie.Value
}
}
// login
login := &Login{
DeviceID: i.deviceID,
GUID: i.uuid,
UserName: i.userName,
Password: i.password,
Csrftoken: i.token,
LoginAttemptCount: "0",
}
jsonData, err := json.Marshal(login)
if err != nil {
return err
}
signature := generateSignature(jsonData)
resp, err = i.requestLogin("POST", APIURL+"/accounts/login/?", bytes.NewReader([]byte(signature)))
if err != nil {
return err
}
defer resp.Body.Close()
// get new csrftoken
for _, cookie := range resp.Cookies() {
if cookie.Name == "csrftoken" {
i.token = cookie.Value
}
}
i.cookies = resp.Cookies()
var object *LoginResponse
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&object)
if err != nil {
return err
}
if object.Status == "fail" {
return errors.New(object.Message)
}
i.userNameID = object.LoggedInUser.Pk
i.rankToken = strconv.FormatInt(i.userNameID, 10) + "_" + i.uuid
return nil
} | go | func (i *Instagram) Login() error {
fetch := APIURL + "/si/fetch_headers/?challenge_type=signup&guid=" + generateUUID(false)
resp, err := i.requestLogin("GET", fetch, nil)
if err != nil {
return err
}
defer resp.Body.Close()
// get csrftoken
for _, cookie := range resp.Cookies() {
if cookie.Name == "csrftoken" {
i.token = cookie.Value
}
}
// login
login := &Login{
DeviceID: i.deviceID,
GUID: i.uuid,
UserName: i.userName,
Password: i.password,
Csrftoken: i.token,
LoginAttemptCount: "0",
}
jsonData, err := json.Marshal(login)
if err != nil {
return err
}
signature := generateSignature(jsonData)
resp, err = i.requestLogin("POST", APIURL+"/accounts/login/?", bytes.NewReader([]byte(signature)))
if err != nil {
return err
}
defer resp.Body.Close()
// get new csrftoken
for _, cookie := range resp.Cookies() {
if cookie.Name == "csrftoken" {
i.token = cookie.Value
}
}
i.cookies = resp.Cookies()
var object *LoginResponse
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&object)
if err != nil {
return err
}
if object.Status == "fail" {
return errors.New(object.Message)
}
i.userNameID = object.LoggedInUser.Pk
i.rankToken = strconv.FormatInt(i.userNameID, 10) + "_" + i.uuid
return nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"Login",
"(",
")",
"error",
"{",
"fetch",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"generateUUID",
"(",
"false",
")",
"\n\n",
"resp",
",",
"err",
":=",
"i",
".",
"requestLogin",
"(",
"\"",
"\"",
",",
"fetch",
... | // Login to instagram. | [
"Login",
"to",
"instagram",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L50-L113 |
151,660 | gkiryaziev/go-instagram | instagram.go | GetMediaLikers | func (i *Instagram) GetMediaLikers(mediaID string) (*MediaLikers, error) {
endpoint := APIURL + "/media/" + mediaID + "/likers/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *MediaLikers
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) GetMediaLikers(mediaID string) (*MediaLikers, error) {
endpoint := APIURL + "/media/" + mediaID + "/likers/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *MediaLikers
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"GetMediaLikers",
"(",
"mediaID",
"string",
")",
"(",
"*",
"MediaLikers",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"mediaID",
"+",
"\"",
"\"",
"\n\n",
"resp",
",",
"err",
":=",... | // GetMediaLikers return media likers. | [
"GetMediaLikers",
"return",
"media",
"likers",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L116-L132 |
151,661 | gkiryaziev/go-instagram | instagram.go | GetMedia | func (i *Instagram) GetMedia(mediaID string) (*Media, error) {
endpoint := APIURL + "/media/" + mediaID + "/comments/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *Media
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) GetMedia(mediaID string) (*Media, error) {
endpoint := APIURL + "/media/" + mediaID + "/comments/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *Media
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"GetMedia",
"(",
"mediaID",
"string",
")",
"(",
"*",
"Media",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"mediaID",
"+",
"\"",
"\"",
"\n\n",
"resp",
",",
"err",
":=",
"i",
".... | // GetMedia return media comments. | [
"GetMedia",
"return",
"media",
"comments",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L135-L151 |
151,662 | gkiryaziev/go-instagram | instagram.go | GetRecentActivity | func (i *Instagram) GetRecentActivity() (*RecentActivity, error) {
endpoint := APIURL + "/news/inbox/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *RecentActivity
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) GetRecentActivity() (*RecentActivity, error) {
endpoint := APIURL + "/news/inbox/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *RecentActivity
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"GetRecentActivity",
"(",
")",
"(",
"*",
"RecentActivity",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"\n\n",
"resp",
",",
"err",
":=",
"i",
".",
"request",
"(",
"\"",
"\"",
",",
"e... | // GetRecentActivity return recent activity. | [
"GetRecentActivity",
"return",
"recent",
"activity",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L154-L170 |
151,663 | gkiryaziev/go-instagram | instagram.go | SearchUsers | func (i *Instagram) SearchUsers(query string) (*SearchUsers, error) {
endpoint := APIURL + "/users/search/?ig_sig_key_version=" + SIGKEYVERSION +
"&is_typeahead=true&query=" + query + "&rank_token=" + i.rankToken
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *SearchUsers
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) SearchUsers(query string) (*SearchUsers, error) {
endpoint := APIURL + "/users/search/?ig_sig_key_version=" + SIGKEYVERSION +
"&is_typeahead=true&query=" + query + "&rank_token=" + i.rankToken
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *SearchUsers
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"SearchUsers",
"(",
"query",
"string",
")",
"(",
"*",
"SearchUsers",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"SIGKEYVERSION",
"+",
"\"",
"\"",
"+",
"query",
"+",
"\"",
"\"",
... | // SearchUsers return users. | [
"SearchUsers",
"return",
"users",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L173-L190 |
151,664 | gkiryaziev/go-instagram | instagram.go | GetUserNameInfo | func (i *Instagram) GetUserNameInfo(userNameID int64) (*UserNameInfo, error) {
endpoint := APIURL + "/users/" + strconv.FormatInt(userNameID, 10) + "/info/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *UserNameInfo
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) GetUserNameInfo(userNameID int64) (*UserNameInfo, error) {
endpoint := APIURL + "/users/" + strconv.FormatInt(userNameID, 10) + "/info/?"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *UserNameInfo
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"GetUserNameInfo",
"(",
"userNameID",
"int64",
")",
"(",
"*",
"UserNameInfo",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"FormatInt",
"(",
"userNameID",
",",
"10",
... | // GetUserNameInfo return username info. | [
"GetUserNameInfo",
"return",
"username",
"info",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L193-L209 |
151,665 | gkiryaziev/go-instagram | instagram.go | GetUserTags | func (i *Instagram) GetUserTags(userNameID int64) (*UserTags, error) {
endpoint := APIURL + "/usertags/" + strconv.FormatInt(userNameID, 10) + "/feed/?rank_token=" +
i.rankToken + "&ranked_content=false"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *UserTags
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) GetUserTags(userNameID int64) (*UserTags, error) {
endpoint := APIURL + "/usertags/" + strconv.FormatInt(userNameID, 10) + "/feed/?rank_token=" +
i.rankToken + "&ranked_content=false"
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *UserTags
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"GetUserTags",
"(",
"userNameID",
"int64",
")",
"(",
"*",
"UserTags",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"FormatInt",
"(",
"userNameID",
",",
"10",
")",
"... | // GetUserTags return user tags. | [
"GetUserTags",
"return",
"user",
"tags",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L212-L229 |
151,666 | gkiryaziev/go-instagram | instagram.go | TagFeed | func (i *Instagram) TagFeed(tag, maxID string) (*TagFeed, error) {
endpoint := APIURL + "/feed/tag/" + tag + "/?rank_token=" + i.rankToken + "&ranked_content=false&max_id=" + maxID
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *TagFeed
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | go | func (i *Instagram) TagFeed(tag, maxID string) (*TagFeed, error) {
endpoint := APIURL + "/feed/tag/" + tag + "/?rank_token=" + i.rankToken + "&ranked_content=false&max_id=" + maxID
resp, err := i.request("GET", endpoint, nil)
if err != nil {
return nil, err
}
var object *TagFeed
err = json.Unmarshal(resp, &object)
if err != nil {
return nil, err
}
return object, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"TagFeed",
"(",
"tag",
",",
"maxID",
"string",
")",
"(",
"*",
"TagFeed",
",",
"error",
")",
"{",
"endpoint",
":=",
"APIURL",
"+",
"\"",
"\"",
"+",
"tag",
"+",
"\"",
"\"",
"+",
"i",
".",
"rankToken",
"+",
... | // TagFeed return tagged media. | [
"TagFeed",
"return",
"tagged",
"media",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L251-L267 |
151,667 | gkiryaziev/go-instagram | instagram.go | requestLogin | func (i *Instagram) requestLogin(method, endpoint string, body io.Reader) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", USERAGENT)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
} | go | func (i *Instagram) requestLogin(method, endpoint string, body io.Reader) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", USERAGENT)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"requestLogin",
"(",
"method",
",",
"endpoint",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}... | // requestLogin return http.Response. Needs to get the authorization cookies. | [
"requestLogin",
"return",
"http",
".",
"Response",
".",
"Needs",
"to",
"get",
"the",
"authorization",
"cookies",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L270-L282 |
151,668 | gkiryaziev/go-instagram | instagram.go | requestMain | func (i *Instagram) requestMain(method, endpoint string, body io.Reader) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", USERAGENT)
for _, cookie := range i.cookies {
req.AddCookie(cookie)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
} | go | func (i *Instagram) requestMain(method, endpoint string, body io.Reader) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", USERAGENT)
for _, cookie := range i.cookies {
req.AddCookie(cookie)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"requestMain",
"(",
"method",
",",
"endpoint",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}"... | // requestMain is main request for all other methods. Reading the authorization cookies. | [
"requestMain",
"is",
"main",
"request",
"for",
"all",
"other",
"methods",
".",
"Reading",
"the",
"authorization",
"cookies",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L285-L300 |
151,669 | gkiryaziev/go-instagram | instagram.go | request | func (i *Instagram) request(method, endpoint string, body io.Reader) ([]byte, error) {
for attempt := 0; attempt < 5; attempt++ {
resp, err := i.requestMain(method, endpoint, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
jsonBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var message *Message
err = json.Unmarshal(jsonBody, &message)
if err != nil {
return nil, err
}
if message.Status == "fail" {
if message.Message != "login_required" {
return nil, errors.New(message.Message)
}
// relogin
err = i.Login()
if err != nil {
return nil, err
}
time.Sleep(time.Millisecond * 500)
} else {
return jsonBody, nil
}
}
return nil, errors.New("max_attempts")
} | go | func (i *Instagram) request(method, endpoint string, body io.Reader) ([]byte, error) {
for attempt := 0; attempt < 5; attempt++ {
resp, err := i.requestMain(method, endpoint, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
jsonBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var message *Message
err = json.Unmarshal(jsonBody, &message)
if err != nil {
return nil, err
}
if message.Status == "fail" {
if message.Message != "login_required" {
return nil, errors.New(message.Message)
}
// relogin
err = i.Login()
if err != nil {
return nil, err
}
time.Sleep(time.Millisecond * 500)
} else {
return jsonBody, nil
}
}
return nil, errors.New("max_attempts")
} | [
"func",
"(",
"i",
"*",
"Instagram",
")",
"request",
"(",
"method",
",",
"endpoint",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"for",
"attempt",
":=",
"0",
";",
"attempt",
"<",
"5",
";",
"attem... | // request with five attempts re-login. Re-login if getting error 'login_required'. | [
"request",
"with",
"five",
"attempts",
"re",
"-",
"login",
".",
"Re",
"-",
"login",
"if",
"getting",
"error",
"login_required",
"."
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/instagram.go#L303-L340 |
151,670 | gkiryaziev/go-instagram | service.go | generateUUID | func generateUUID(t bool) string {
u := uuid.New()
if !t {
return strings.Replace(u, "-", "", -1)
}
return u
} | go | func generateUUID(t bool) string {
u := uuid.New()
if !t {
return strings.Replace(u, "-", "", -1)
}
return u
} | [
"func",
"generateUUID",
"(",
"t",
"bool",
")",
"string",
"{",
"u",
":=",
"uuid",
".",
"New",
"(",
")",
"\n",
"if",
"!",
"t",
"{",
"return",
"strings",
".",
"Replace",
"(",
"u",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
... | // generateUUID return uuid | [
"generateUUID",
"return",
"uuid"
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/service.go#L27-L33 |
151,671 | gkiryaziev/go-instagram | service.go | generateSignature | func generateSignature(data []byte) string {
h := hmac.New(sha256.New, []byte(IGSIGKEY))
h.Write(data)
hash := hex.EncodeToString(h.Sum(nil))
return "ig_sig_key_version=" + SIGKEYVERSION + "&signed_body=" + hash + "." + url.QueryEscape(string(data))
} | go | func generateSignature(data []byte) string {
h := hmac.New(sha256.New, []byte(IGSIGKEY))
h.Write(data)
hash := hex.EncodeToString(h.Sum(nil))
return "ig_sig_key_version=" + SIGKEYVERSION + "&signed_body=" + hash + "." + url.QueryEscape(string(data))
} | [
"func",
"generateSignature",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"IGSIGKEY",
")",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"hash",
... | // generateSignature return signature | [
"generateSignature",
"return",
"signature"
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/service.go#L36-L41 |
151,672 | gkiryaziev/go-instagram | service.go | generateDeviceID | func generateDeviceID() string {
buffer := make([]byte, 32)
rand.Read(buffer)
hash := md5.New()
hash.Write(buffer)
return "android-" + hex.EncodeToString(hash.Sum(nil))[:16]
} | go | func generateDeviceID() string {
buffer := make([]byte, 32)
rand.Read(buffer)
hash := md5.New()
hash.Write(buffer)
return "android-" + hex.EncodeToString(hash.Sum(nil))[:16]
} | [
"func",
"generateDeviceID",
"(",
")",
"string",
"{",
"buffer",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"32",
")",
"\n",
"rand",
".",
"Read",
"(",
"buffer",
")",
"\n",
"hash",
":=",
"md5",
".",
"New",
"(",
")",
"\n",
"hash",
".",
"Write",
"(",
... | // generateDeviceId return deviceId | [
"generateDeviceId",
"return",
"deviceId"
] | 7c6db0475139a1fd27a40dbea402508292ab592b | https://github.com/gkiryaziev/go-instagram/blob/7c6db0475139a1fd27a40dbea402508292ab592b/service.go#L44-L50 |
151,673 | kkirsche/go-scp | libscp/scpFile/create.go | Create | func Create(fn string) (*os.File, error) {
tfn := strings.TrimSpace(fn)
f, err := os.Create(tfn)
if err != nil {
return f, err
}
return f, nil
} | go | func Create(fn string) (*os.File, error) {
tfn := strings.TrimSpace(fn)
f, err := os.Create(tfn)
if err != nil {
return f, err
}
return f, nil
} | [
"func",
"Create",
"(",
"fn",
"string",
")",
"(",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"tfn",
":=",
"strings",
".",
"TrimSpace",
"(",
"fn",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"tfn",
")",
"\n",
"if",
"err",
"... | // Create is used to create a file with a specific name | [
"Create",
"is",
"used",
"to",
"create",
"a",
"file",
"with",
"a",
"specific",
"name"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/scpFile/create.go#L9-L17 |
151,674 | kkirsche/go-scp | libscp/key.go | NewKey | func NewKey(path, name string) (*Key, error) {
k := &Key{
P: path,
N: name,
}
if !k.Exists() {
return nil, fmt.Errorf("Key file with path `%s` does not exist", k.Path())
}
return k, nil
} | go | func NewKey(path, name string) (*Key, error) {
k := &Key{
P: path,
N: name,
}
if !k.Exists() {
return nil, fmt.Errorf("Key file with path `%s` does not exist", k.Path())
}
return k, nil
} | [
"func",
"NewKey",
"(",
"path",
",",
"name",
"string",
")",
"(",
"*",
"Key",
",",
"error",
")",
"{",
"k",
":=",
"&",
"Key",
"{",
"P",
":",
"path",
",",
"N",
":",
"name",
",",
"}",
"\n\n",
"if",
"!",
"k",
".",
"Exists",
"(",
")",
"{",
"return... | // NewKey is used to create a new SSHKey object and validate that the key file
// actually exists on the system | [
"NewKey",
"is",
"used",
"to",
"create",
"a",
"new",
"SSHKey",
"object",
"and",
"validate",
"that",
"the",
"key",
"file",
"actually",
"exists",
"on",
"the",
"system"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/key.go#L20-L31 |
151,675 | kkirsche/go-scp | libscp/key.go | Exists | func (s *Key) Exists() bool {
_, err := os.Stat(s.Path())
if os.IsNotExist(err) {
return false
}
return true
} | go | func (s *Key) Exists() bool {
_, err := os.Stat(s.Path())
if os.IsNotExist(err) {
return false
}
return true
} | [
"func",
"(",
"s",
"*",
"Key",
")",
"Exists",
"(",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"s",
".",
"Path",
"(",
")",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"false",
"\n",
"}",
"\n... | // Exists validates that the path to the SSH keyfile is valid and that the key
// actually exists | [
"Exists",
"validates",
"that",
"the",
"path",
"to",
"the",
"SSH",
"keyfile",
"is",
"valid",
"and",
"that",
"the",
"key",
"actually",
"exists"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/key.go#L35-L42 |
151,676 | kkirsche/go-scp | libscp/key.go | Path | func (s *Key) Path() string {
return fmt.Sprintf("%s/%s", s.P, s.N)
} | go | func (s *Key) Path() string {
return fmt.Sprintf("%s/%s", s.P, s.N)
} | [
"func",
"(",
"s",
"*",
"Key",
")",
"Path",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
".",
"P",
",",
"s",
".",
"N",
")",
"\n",
"}"
] | // Path returns the full path to the key file | [
"Path",
"returns",
"the",
"full",
"path",
"to",
"the",
"key",
"file"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/key.go#L45-L47 |
151,677 | kkirsche/go-scp | libscp/key.go | KeyConfig | func KeyConfig(u string, k *Key) (*ssh.ClientConfig, error) {
contents, err := ioutil.ReadFile(k.Path())
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(contents)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: u,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
return config, nil
} | go | func KeyConfig(u string, k *Key) (*ssh.ClientConfig, error) {
contents, err := ioutil.ReadFile(k.Path())
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(contents)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: u,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
return config, nil
} | [
"func",
"KeyConfig",
"(",
"u",
"string",
",",
"k",
"*",
"Key",
")",
"(",
"*",
"ssh",
".",
"ClientConfig",
",",
"error",
")",
"{",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"k",
".",
"Path",
"(",
")",
")",
"\n",
"if",
"err",
... | // KeyConfig is used to create the SSH Client Configuration when
// using raw SSH key files rather than the SSH Agent for the authentication
// mechanism | [
"KeyConfig",
"is",
"used",
"to",
"create",
"the",
"SSH",
"Client",
"Configuration",
"when",
"using",
"raw",
"SSH",
"key",
"files",
"rather",
"than",
"the",
"SSH",
"Agent",
"for",
"the",
"authentication",
"mechanism"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/key.go#L52-L71 |
151,678 | kkirsche/go-scp | libscp/command.go | ExecuteCommand | func (c *Client) ExecuteCommand(cmd string) (string, error) {
err := c.VerifyClient()
if err != nil {
return "", err
}
// Don't allocate something we may not need, e.g. if we can't build a client
var b bytes.Buffer
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
s, err := c.client.NewSession()
if err != nil {
return "", err
}
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
s.Stdout = &b
err = s.Run(cmd)
if err != nil {
return "", err
}
return b.String(), nil
} | go | func (c *Client) ExecuteCommand(cmd string) (string, error) {
err := c.VerifyClient()
if err != nil {
return "", err
}
// Don't allocate something we may not need, e.g. if we can't build a client
var b bytes.Buffer
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
s, err := c.client.NewSession()
if err != nil {
return "", err
}
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
s.Stdout = &b
err = s.Run(cmd)
if err != nil {
return "", err
}
return b.String(), nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ExecuteCommand",
"(",
"cmd",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"VerifyClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n"... | // ExecuteCommand is used to | [
"ExecuteCommand",
"is",
"used",
"to"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/command.go#L6-L32 |
151,679 | kkirsche/go-scp | libscp/credentials.go | NewCredentials | func NewCredentials(u, p string) *Credentials {
return &Credentials{
Username: u,
Password: p,
}
} | go | func NewCredentials(u, p string) *Credentials {
return &Credentials{
Username: u,
Password: p,
}
} | [
"func",
"NewCredentials",
"(",
"u",
",",
"p",
"string",
")",
"*",
"Credentials",
"{",
"return",
"&",
"Credentials",
"{",
"Username",
":",
"u",
",",
"Password",
":",
"p",
",",
"}",
"\n",
"}"
] | // NewCredentials creates a new credential object | [
"NewCredentials",
"creates",
"a",
"new",
"credential",
"object"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/credentials.go#L11-L16 |
151,680 | kkirsche/go-scp | libscp/send.go | SendFileWithAgent | func SendFileWithAgent(username, arg, port string) (logrus.Fields, error) {
res := strings.Split(arg, ":")
fname := res[1]
fp, err := scpFile.ExpandPath(fname)
if err != nil {
logrus.WithError(err).Errorln("Failed to get current directory")
return logrus.Fields{}, nil
}
creds := NewCredentials(username, "")
a := NewAgentClient(res[0], port, creds)
err = a.SendFileToRemote(fp)
if err != nil {
return logrus.Fields{
"address": res[0],
"port": port,
"file": fp,
"username": username,
}, err
}
return logrus.Fields{}, nil
} | go | func SendFileWithAgent(username, arg, port string) (logrus.Fields, error) {
res := strings.Split(arg, ":")
fname := res[1]
fp, err := scpFile.ExpandPath(fname)
if err != nil {
logrus.WithError(err).Errorln("Failed to get current directory")
return logrus.Fields{}, nil
}
creds := NewCredentials(username, "")
a := NewAgentClient(res[0], port, creds)
err = a.SendFileToRemote(fp)
if err != nil {
return logrus.Fields{
"address": res[0],
"port": port,
"file": fp,
"username": username,
}, err
}
return logrus.Fields{}, nil
} | [
"func",
"SendFileWithAgent",
"(",
"username",
",",
"arg",
",",
"port",
"string",
")",
"(",
"logrus",
".",
"Fields",
",",
"error",
")",
"{",
"res",
":=",
"strings",
".",
"Split",
"(",
"arg",
",",
"\"",
"\"",
")",
"\n",
"fname",
":=",
"res",
"[",
"1"... | // SendFileWithAgent is used to send a file's contents while using ssh agent
// for retrieving the necessary username information | [
"SendFileWithAgent",
"is",
"used",
"to",
"send",
"a",
"file",
"s",
"contents",
"while",
"using",
"ssh",
"agent",
"for",
"retrieving",
"the",
"necessary",
"username",
"information"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/send.go#L12-L35 |
151,681 | kkirsche/go-scp | libscp/agent.go | AgentConfig | func AgentConfig(u string) (*ssh.ClientConfig, error) {
a, err := Get()
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: u,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(a.Signers),
},
}
return config, nil
} | go | func AgentConfig(u string) (*ssh.ClientConfig, error) {
a, err := Get()
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: u,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(a.Signers),
},
}
return config, nil
} | [
"func",
"AgentConfig",
"(",
"u",
"string",
")",
"(",
"*",
"ssh",
".",
"ClientConfig",
",",
"error",
")",
"{",
"a",
",",
"err",
":=",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"config",
... | // AgentConfig is used to create the SSH Client Configuration when
// using the SSH Agent for the authentication mechanism | [
"AgentConfig",
"is",
"used",
"to",
"create",
"the",
"SSH",
"Client",
"Configuration",
"when",
"using",
"the",
"SSH",
"Agent",
"for",
"the",
"authentication",
"mechanism"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/agent.go#L13-L26 |
151,682 | kkirsche/go-scp | libscp/agent.go | Get | func Get() (agent.Agent, error) {
agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
return agent.NewClient(agentConn), err
} | go | func Get() (agent.Agent, error) {
agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
return agent.NewClient(agentConn), err
} | [
"func",
"Get",
"(",
")",
"(",
"agent",
".",
"Agent",
",",
"error",
")",
"{",
"agentConn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"agent",
".",
"NewClient",
"("... | // Get is used to retrieve the agent connection for use via SSH | [
"Get",
"is",
"used",
"to",
"retrieve",
"the",
"agent",
"connection",
"for",
"use",
"via",
"SSH"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/agent.go#L29-L32 |
151,683 | kkirsche/go-scp | libscp/copy.go | SendFileToRemote | func (c *Client) SendFileToRemote(fp string) error {
logrus.Debugln("Verifying client")
err := c.VerifyClient()
if err != nil {
return err
}
logrus.Debugln("Client passed verification")
logrus.Debugln("Creating session")
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
s, err := c.client.NewSession()
if err != nil {
return err
}
defer s.Close()
logrus.Debugln("Creating session client")
sc, err := NewSessionClient(s)
if err != nil {
return err
}
defer sc.writer.Close()
sc.wg.Add(1)
go sc.FileSource(fp)
logrus.Infoln("Beginning transfer")
go s.Run("/usr/bin/scp -t ./")
logrus.Debugln("Waiting for transfer to complete...")
sc.wg.Wait()
for err := range sc.errors {
logrus.WithError(err).Errorln("Error sending the file")
}
return nil
} | go | func (c *Client) SendFileToRemote(fp string) error {
logrus.Debugln("Verifying client")
err := c.VerifyClient()
if err != nil {
return err
}
logrus.Debugln("Client passed verification")
logrus.Debugln("Creating session")
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
s, err := c.client.NewSession()
if err != nil {
return err
}
defer s.Close()
logrus.Debugln("Creating session client")
sc, err := NewSessionClient(s)
if err != nil {
return err
}
defer sc.writer.Close()
sc.wg.Add(1)
go sc.FileSource(fp)
logrus.Infoln("Beginning transfer")
go s.Run("/usr/bin/scp -t ./")
logrus.Debugln("Waiting for transfer to complete...")
sc.wg.Wait()
for err := range sc.errors {
logrus.WithError(err).Errorln("Error sending the file")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendFileToRemote",
"(",
"fp",
"string",
")",
"error",
"{",
"logrus",
".",
"Debugln",
"(",
"\"",
"\"",
")",
"\n",
"err",
":=",
"c",
".",
"VerifyClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // SendFileToRemote is used to send a file using the SCP protocol to a remote
// host or machine | [
"SendFileToRemote",
"is",
"used",
"to",
"send",
"a",
"file",
"using",
"the",
"SCP",
"protocol",
"to",
"a",
"remote",
"host",
"or",
"machine"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/copy.go#L41-L75 |
151,684 | kkirsche/go-scp | libscp/scpFile/write.go | WriteBytes | func WriteBytes(file *os.File, content []byte) (int, error) {
w, err := file.Write(content)
if err != nil {
return 0, err
}
return w, nil
} | go | func WriteBytes(file *os.File, content []byte) (int, error) {
w, err := file.Write(content)
if err != nil {
return 0, err
}
return w, nil
} | [
"func",
"WriteBytes",
"(",
"file",
"*",
"os",
".",
"File",
",",
"content",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"w",
",",
"err",
":=",
"file",
".",
"Write",
"(",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // WriteBytes is used to write an array of bytes to a file | [
"WriteBytes",
"is",
"used",
"to",
"write",
"an",
"array",
"of",
"bytes",
"to",
"a",
"file"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/scpFile/write.go#L6-L13 |
151,685 | kkirsche/go-scp | libscp/sessionClient.go | NewSessionClient | func NewSessionClient(s *ssh.Session) (*SessionClient, error) {
writer, err := s.StdinPipe()
if err != nil {
return nil, err
}
reader, err := s.StdoutPipe()
if err != nil {
return nil, err
}
var wg sync.WaitGroup
return &SessionClient{
writer: writer,
reader: reader,
wg: &wg,
errors: make(chan error),
}, nil
} | go | func NewSessionClient(s *ssh.Session) (*SessionClient, error) {
writer, err := s.StdinPipe()
if err != nil {
return nil, err
}
reader, err := s.StdoutPipe()
if err != nil {
return nil, err
}
var wg sync.WaitGroup
return &SessionClient{
writer: writer,
reader: reader,
wg: &wg,
errors: make(chan error),
}, nil
} | [
"func",
"NewSessionClient",
"(",
"s",
"*",
"ssh",
".",
"Session",
")",
"(",
"*",
"SessionClient",
",",
"error",
")",
"{",
"writer",
",",
"err",
":=",
"s",
".",
"StdinPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",... | // NewSessionClient creates a new SessionClient structure from the ssh.Session
// pointer | [
"NewSessionClient",
"creates",
"a",
"new",
"SessionClient",
"structure",
"from",
"the",
"ssh",
".",
"Session",
"pointer"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/sessionClient.go#L26-L45 |
151,686 | kkirsche/go-scp | libscp/sessionClient.go | FileSink | func (c *SessionClient) FileSink(fp, fn string) {
// We must close the channel for the main thread to work properly. Defer ensures
// when the function ends, this is closed. We also want to be sure we mark this
// attempt as completed
defer close(c.errors)
defer c.wg.Done()
logrus.Debugln("Beginning transfer")
successfulByte := []byte{0}
// Send a null byte saying that we are ready to receive the data
c.writer.Write(successfulByte)
// We want to first receive the command input from remote machine
// e.g. C0644 113828 test.csv
scpCommandArray := make([]byte, 500)
bytesRead, err := c.reader.Read(scpCommandArray)
if err != nil {
if err == io.EOF {
//no problem.
} else {
c.errors <- err
return
}
}
scpStartLine := string(scpCommandArray[:bytesRead])
scpStartLineArray := strings.Split(scpStartLine, " ")
filePermission := scpStartLineArray[0][1:]
fileSize := scpStartLineArray[1]
fileName := scpStartLineArray[2]
logrus.Debugf("File with permissions: %s, File Size: %s, File Name: %s", filePermission, fileSize, fileName)
// Confirm to the remote host that we have received the command line
c.writer.Write(successfulByte)
// Now we want to start receiving the file itself from the remote machine
// one byte at a time
fileContents := make([]byte, 1)
var file *os.File
if fn == "" {
file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
if err != nil {
c.errors <- err
return
}
} else {
file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
if err != nil {
c.errors <- err
return
}
}
more := true
for more {
bytesRead, err = c.reader.Read(fileContents)
if err != nil {
if err == io.EOF {
more = false
} else {
c.errors <- err
return
}
}
_, err = scpFile.WriteBytes(file, fileContents[:bytesRead])
if err != nil {
c.errors <- err
return
}
c.writer.Write(successfulByte)
}
err = file.Sync()
if err != nil {
c.errors <- err
return
}
} | go | func (c *SessionClient) FileSink(fp, fn string) {
// We must close the channel for the main thread to work properly. Defer ensures
// when the function ends, this is closed. We also want to be sure we mark this
// attempt as completed
defer close(c.errors)
defer c.wg.Done()
logrus.Debugln("Beginning transfer")
successfulByte := []byte{0}
// Send a null byte saying that we are ready to receive the data
c.writer.Write(successfulByte)
// We want to first receive the command input from remote machine
// e.g. C0644 113828 test.csv
scpCommandArray := make([]byte, 500)
bytesRead, err := c.reader.Read(scpCommandArray)
if err != nil {
if err == io.EOF {
//no problem.
} else {
c.errors <- err
return
}
}
scpStartLine := string(scpCommandArray[:bytesRead])
scpStartLineArray := strings.Split(scpStartLine, " ")
filePermission := scpStartLineArray[0][1:]
fileSize := scpStartLineArray[1]
fileName := scpStartLineArray[2]
logrus.Debugf("File with permissions: %s, File Size: %s, File Name: %s", filePermission, fileSize, fileName)
// Confirm to the remote host that we have received the command line
c.writer.Write(successfulByte)
// Now we want to start receiving the file itself from the remote machine
// one byte at a time
fileContents := make([]byte, 1)
var file *os.File
if fn == "" {
file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
if err != nil {
c.errors <- err
return
}
} else {
file, err = scpFile.Create(fmt.Sprintf("%s/%s", fp, fn))
if err != nil {
c.errors <- err
return
}
}
more := true
for more {
bytesRead, err = c.reader.Read(fileContents)
if err != nil {
if err == io.EOF {
more = false
} else {
c.errors <- err
return
}
}
_, err = scpFile.WriteBytes(file, fileContents[:bytesRead])
if err != nil {
c.errors <- err
return
}
c.writer.Write(successfulByte)
}
err = file.Sync()
if err != nil {
c.errors <- err
return
}
} | [
"func",
"(",
"c",
"*",
"SessionClient",
")",
"FileSink",
"(",
"fp",
",",
"fn",
"string",
")",
"{",
"// We must close the channel for the main thread to work properly. Defer ensures",
"// when the function ends, this is closed. We also want to be sure we mark this",
"// attempt as com... | // FileSink is used to receive a file from the remote machine and save it to the local machine | [
"FileSink",
"is",
"used",
"to",
"receive",
"a",
"file",
"from",
"the",
"remote",
"machine",
"and",
"save",
"it",
"to",
"the",
"local",
"machine"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/sessionClient.go#L48-L127 |
151,687 | kkirsche/go-scp | libscp/sessionClient.go | FileSource | func (c *SessionClient) FileSource(p string) {
response := make([]byte, 1)
defer close(c.errors)
defer c.wg.Done()
logrus.Debugln("Opening file to send")
f, err := os.Open(p)
if err != nil {
c.errors <- err
return
}
defer f.Close()
logrus.Debugln("Getting file information")
i, err := f.Stat()
if err != nil {
c.errors <- err
return
}
logrus.WithFields(logrus.Fields{
"directory": i.IsDir(),
"modification_time": i.ModTime().String(),
"mode": i.Mode().String(),
"name": i.Name(),
"size": i.Size(),
}).Debugln("File information retrieved")
begin := []byte(fmt.Sprintf("C%#o %d %s\n", i.Mode(), i.Size(), i.Name()))
logrus.WithField("statement", string(begin)).Debugln("Beginning transfer")
_, err = c.writer.Write(begin)
if err != nil {
c.errors <- err
return
}
c.reader.Read(response)
if err != nil {
c.errors <- err
return
}
logrus.WithField("response", response).Debugln("Response to transfer request")
logrus.WithField("response", response).Debugln("Ready to start data transfer")
io.Copy(c.writer, f)
logrus.Debugln("Sending complete notice")
fmt.Fprint(c.writer, "\x00")
logrus.Debugln("Waiting for acceptence of termination")
_, err = c.reader.Read(response)
if err != nil {
c.errors <- err
return
}
logrus.WithField("response", response).Debugln("Data transfer response")
logrus.Debugln("Transfer complete")
} | go | func (c *SessionClient) FileSource(p string) {
response := make([]byte, 1)
defer close(c.errors)
defer c.wg.Done()
logrus.Debugln("Opening file to send")
f, err := os.Open(p)
if err != nil {
c.errors <- err
return
}
defer f.Close()
logrus.Debugln("Getting file information")
i, err := f.Stat()
if err != nil {
c.errors <- err
return
}
logrus.WithFields(logrus.Fields{
"directory": i.IsDir(),
"modification_time": i.ModTime().String(),
"mode": i.Mode().String(),
"name": i.Name(),
"size": i.Size(),
}).Debugln("File information retrieved")
begin := []byte(fmt.Sprintf("C%#o %d %s\n", i.Mode(), i.Size(), i.Name()))
logrus.WithField("statement", string(begin)).Debugln("Beginning transfer")
_, err = c.writer.Write(begin)
if err != nil {
c.errors <- err
return
}
c.reader.Read(response)
if err != nil {
c.errors <- err
return
}
logrus.WithField("response", response).Debugln("Response to transfer request")
logrus.WithField("response", response).Debugln("Ready to start data transfer")
io.Copy(c.writer, f)
logrus.Debugln("Sending complete notice")
fmt.Fprint(c.writer, "\x00")
logrus.Debugln("Waiting for acceptence of termination")
_, err = c.reader.Read(response)
if err != nil {
c.errors <- err
return
}
logrus.WithField("response", response).Debugln("Data transfer response")
logrus.Debugln("Transfer complete")
} | [
"func",
"(",
"c",
"*",
"SessionClient",
")",
"FileSource",
"(",
"p",
"string",
")",
"{",
"response",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
")",
"\n",
"defer",
"close",
"(",
"c",
".",
"errors",
")",
"\n",
"defer",
"c",
".",
"wg",
".",
"... | // FileSource allows us to acting as the machine sending a file to the remote host | [
"FileSource",
"allows",
"us",
"to",
"acting",
"as",
"the",
"machine",
"sending",
"a",
"file",
"to",
"the",
"remote",
"host"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/sessionClient.go#L130-L189 |
151,688 | kkirsche/go-scp | libscp/client.go | NewAgentClient | func NewAgentClient(addr, port string, creds *Credentials) *Client {
return &Client{
addr: addr,
port: port,
useAgent: true,
credentials: creds,
}
} | go | func NewAgentClient(addr, port string, creds *Credentials) *Client {
return &Client{
addr: addr,
port: port,
useAgent: true,
credentials: creds,
}
} | [
"func",
"NewAgentClient",
"(",
"addr",
",",
"port",
"string",
",",
"creds",
"*",
"Credentials",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"addr",
":",
"addr",
",",
"port",
":",
"port",
",",
"useAgent",
":",
"true",
",",
"credentials",
":",... | // NewAgentClient creates a new host object that will connect using the SSH
// Agent signers | [
"NewAgentClient",
"creates",
"a",
"new",
"host",
"object",
"that",
"will",
"connect",
"using",
"the",
"SSH",
"Agent",
"signers"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/client.go#L22-L29 |
151,689 | kkirsche/go-scp | libscp/client.go | NewKeyClient | func NewKeyClient(addr, port string, creds *Credentials, key *Key) *Client {
return &Client{
addr: addr,
port: port,
useAgent: false,
credentials: creds,
key: key,
}
} | go | func NewKeyClient(addr, port string, creds *Credentials, key *Key) *Client {
return &Client{
addr: addr,
port: port,
useAgent: false,
credentials: creds,
key: key,
}
} | [
"func",
"NewKeyClient",
"(",
"addr",
",",
"port",
"string",
",",
"creds",
"*",
"Credentials",
",",
"key",
"*",
"Key",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"addr",
":",
"addr",
",",
"port",
":",
"port",
",",
"useAgent",
":",
"false",... | // NewKeyClient creates a new host object that will connect using the SSH
// Agent signers | [
"NewKeyClient",
"creates",
"a",
"new",
"host",
"object",
"that",
"will",
"connect",
"using",
"the",
"SSH",
"Agent",
"signers"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/client.go#L33-L41 |
151,690 | kkirsche/go-scp | libscp/client.go | Connect | func (c *Client) Connect() error {
// An SSH client is represented with a ClientConn.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
var co *ssh.ClientConfig
var err error
if c.useAgent {
co, err = AgentConfig(c.credentials.Username)
if err != nil {
return err
}
} else {
co, err = KeyConfig(c.credentials.Username, c.key)
if err != nil {
return err
}
}
client, err := ssh.Dial("tcp", net.JoinHostPort(c.addr, c.port), co)
if err != nil {
return err
}
c.client = client
return nil
} | go | func (c *Client) Connect() error {
// An SSH client is represented with a ClientConn.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
var co *ssh.ClientConfig
var err error
if c.useAgent {
co, err = AgentConfig(c.credentials.Username)
if err != nil {
return err
}
} else {
co, err = KeyConfig(c.credentials.Username, c.key)
if err != nil {
return err
}
}
client, err := ssh.Dial("tcp", net.JoinHostPort(c.addr, c.port), co)
if err != nil {
return err
}
c.client = client
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Connect",
"(",
")",
"error",
"{",
"// An SSH client is represented with a ClientConn.",
"//",
"// To authenticate with the remote server you must pass at least one",
"// implementation of AuthMethod via the Auth field in ClientConfig.",
"var",
"... | // Connect takes the host object and connects, creating an SSH Client connection | [
"Connect",
"takes",
"the",
"host",
"object",
"and",
"connects",
"creating",
"an",
"SSH",
"Client",
"connection"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/client.go#L44-L72 |
151,691 | kkirsche/go-scp | libscp/client.go | VerifyClient | func (c *Client) VerifyClient() error {
// If we don't have a client yet, we should try to create one
if c.client == nil {
err := c.Connect()
if err != nil {
return err
}
}
return nil
} | go | func (c *Client) VerifyClient() error {
// If we don't have a client yet, we should try to create one
if c.client == nil {
err := c.Connect()
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"VerifyClient",
"(",
")",
"error",
"{",
"// If we don't have a client yet, we should try to create one",
"if",
"c",
".",
"client",
"==",
"nil",
"{",
"err",
":=",
"c",
".",
"Connect",
"(",
")",
"\n",
"if",
"err",
"!=",
... | // VerifyClient checks if we have a client, and if not attempts to connect | [
"VerifyClient",
"checks",
"if",
"we",
"have",
"a",
"client",
"and",
"if",
"not",
"attempts",
"to",
"connect"
] | 1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e | https://github.com/kkirsche/go-scp/blob/1f25f5ac5a8e5d2aa0e1037af94f4e7321ca439e/libscp/client.go#L75-L85 |
151,692 | bitpay/bitpay-go | key_utils/key_utils.go | GeneratePem | func GeneratePem() string {
priv, _ := btcec.NewPrivateKey(btcec.S256())
pub := priv.PubKey()
ecd := pub.ToECDSA()
oid := asn1.ObjectIdentifier{1, 3, 132, 0, 10}
curve := btcec.S256()
der, _ := asn1.Marshal(ecPrivateKey{
Version: 1,
PrivateKey: priv.D.Bytes(),
NamedCurveOID: oid,
PublicKey: asn1.BitString{Bytes: elliptic.Marshal(curve, ecd.X, ecd.Y)},
})
blck := pem.Block{Type: "EC PRIVATE KEY", Bytes: der}
pm := pem.EncodeToMemory(&blck)
return string(pm)
} | go | func GeneratePem() string {
priv, _ := btcec.NewPrivateKey(btcec.S256())
pub := priv.PubKey()
ecd := pub.ToECDSA()
oid := asn1.ObjectIdentifier{1, 3, 132, 0, 10}
curve := btcec.S256()
der, _ := asn1.Marshal(ecPrivateKey{
Version: 1,
PrivateKey: priv.D.Bytes(),
NamedCurveOID: oid,
PublicKey: asn1.BitString{Bytes: elliptic.Marshal(curve, ecd.X, ecd.Y)},
})
blck := pem.Block{Type: "EC PRIVATE KEY", Bytes: der}
pm := pem.EncodeToMemory(&blck)
return string(pm)
} | [
"func",
"GeneratePem",
"(",
")",
"string",
"{",
"priv",
",",
"_",
":=",
"btcec",
".",
"NewPrivateKey",
"(",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"pub",
":=",
"priv",
".",
"PubKey",
"(",
")",
"\n",
"ecd",
":=",
"pub",
".",
"ToECDSA",
"(",
")... | //All BitPay clients use a PEM file to store the private and public keys. | [
"All",
"BitPay",
"clients",
"use",
"a",
"PEM",
"file",
"to",
"store",
"the",
"private",
"and",
"public",
"keys",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/key_utils/key_utils.go#L26-L41 |
151,693 | bitpay/bitpay-go | key_utils/key_utils.go | GenerateSinFromPem | func GenerateSinFromPem(pm string) string {
key := ExtractKeyFromPem(pm)
sin := generateSinFromKey(key)
return sin
} | go | func GenerateSinFromPem(pm string) string {
key := ExtractKeyFromPem(pm)
sin := generateSinFromKey(key)
return sin
} | [
"func",
"GenerateSinFromPem",
"(",
"pm",
"string",
")",
"string",
"{",
"key",
":=",
"ExtractKeyFromPem",
"(",
"pm",
")",
"\n",
"sin",
":=",
"generateSinFromKey",
"(",
"key",
")",
"\n",
"return",
"sin",
"\n",
"}"
] | //GenerateSinFromPem returns a base58 encoding of a public key. It expects a pem string as the argument. | [
"GenerateSinFromPem",
"returns",
"a",
"base58",
"encoding",
"of",
"a",
"public",
"key",
".",
"It",
"expects",
"a",
"pem",
"string",
"as",
"the",
"argument",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/key_utils/key_utils.go#L44-L48 |
151,694 | bitpay/bitpay-go | key_utils/key_utils.go | ExtractCompressedPublicKey | func ExtractCompressedPublicKey(pm string) string {
key := ExtractKeyFromPem(pm)
pub := key.PubKey()
comp := pub.SerializeCompressed()
hexb := hex.EncodeToString(comp)
return hexb
} | go | func ExtractCompressedPublicKey(pm string) string {
key := ExtractKeyFromPem(pm)
pub := key.PubKey()
comp := pub.SerializeCompressed()
hexb := hex.EncodeToString(comp)
return hexb
} | [
"func",
"ExtractCompressedPublicKey",
"(",
"pm",
"string",
")",
"string",
"{",
"key",
":=",
"ExtractKeyFromPem",
"(",
"pm",
")",
"\n",
"pub",
":=",
"key",
".",
"PubKey",
"(",
")",
"\n",
"comp",
":=",
"pub",
".",
"SerializeCompressed",
"(",
")",
"\n",
"he... | //ExtractCompressedPublicKey returns a hexadecimal encoding of the compressed public key. It expects a pem string as the argument. | [
"ExtractCompressedPublicKey",
"returns",
"a",
"hexadecimal",
"encoding",
"of",
"the",
"compressed",
"public",
"key",
".",
"It",
"expects",
"a",
"pem",
"string",
"as",
"the",
"argument",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/key_utils/key_utils.go#L51-L57 |
151,695 | bitpay/bitpay-go | key_utils/key_utils.go | Sign | func Sign(message string, pm string) string {
key := ExtractKeyFromPem(pm)
byta := []byte(message)
hash := sha256.New()
hash.Write(byta)
bytb := hash.Sum(nil)
sig, _ := key.Sign(bytb)
ser := sig.Serialize()
hexa := hex.EncodeToString(ser)
return hexa
} | go | func Sign(message string, pm string) string {
key := ExtractKeyFromPem(pm)
byta := []byte(message)
hash := sha256.New()
hash.Write(byta)
bytb := hash.Sum(nil)
sig, _ := key.Sign(bytb)
ser := sig.Serialize()
hexa := hex.EncodeToString(ser)
return hexa
} | [
"func",
"Sign",
"(",
"message",
"string",
",",
"pm",
"string",
")",
"string",
"{",
"key",
":=",
"ExtractKeyFromPem",
"(",
"pm",
")",
"\n",
"byta",
":=",
"[",
"]",
"byte",
"(",
"message",
")",
"\n",
"hash",
":=",
"sha256",
".",
"New",
"(",
")",
"\n"... | //Returns a hexadecimal encoding of the signed sha256 hash of message, using the key provide in the pem string pm. | [
"Returns",
"a",
"hexadecimal",
"encoding",
"of",
"the",
"signed",
"sha256",
"hash",
"of",
"message",
"using",
"the",
"key",
"provide",
"in",
"the",
"pem",
"string",
"pm",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/key_utils/key_utils.go#L60-L70 |
151,696 | bitpay/bitpay-go | key_utils/key_utils.go | ExtractKeyFromPem | func ExtractKeyFromPem(pm string) *btcec.PrivateKey {
byta := []byte(pm)
blck, _ := pem.Decode(byta)
var ecp ecPrivateKey
asn1.Unmarshal(blck.Bytes, &ecp)
priv, _ := btcec.PrivKeyFromBytes(btcec.S256(), ecp.PrivateKey)
return priv
} | go | func ExtractKeyFromPem(pm string) *btcec.PrivateKey {
byta := []byte(pm)
blck, _ := pem.Decode(byta)
var ecp ecPrivateKey
asn1.Unmarshal(blck.Bytes, &ecp)
priv, _ := btcec.PrivKeyFromBytes(btcec.S256(), ecp.PrivateKey)
return priv
} | [
"func",
"ExtractKeyFromPem",
"(",
"pm",
"string",
")",
"*",
"btcec",
".",
"PrivateKey",
"{",
"byta",
":=",
"[",
"]",
"byte",
"(",
"pm",
")",
"\n",
"blck",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"byta",
")",
"\n",
"var",
"ecp",
"ecPrivateKey",
"... | //Returns a btec.Private key object if provided a correct secp256k1 encoded pem. | [
"Returns",
"a",
"btec",
".",
"Private",
"key",
"object",
"if",
"provided",
"a",
"correct",
"secp256k1",
"encoded",
"pem",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/key_utils/key_utils.go#L73-L80 |
151,697 | bitpay/bitpay-go | client/client.go | CreateInvoice | func (client *Client) CreateInvoice(price float64, currency string) (inv invoice, err error) {
match, _ := regexp.MatchString("^[[:upper:]]{3}$", currency)
if !match {
err = errors.New("BitPayArgumentError: invalid currency code")
return inv, err
}
paylo := make(map[string]string)
var floatPrec int
if currency == "BTC" {
floatPrec = 8
} else {
floatPrec = 2
}
priceString := strconv.FormatFloat(price, 'f', floatPrec, 64)
paylo["price"] = priceString
paylo["currency"] = currency
paylo["token"] = client.Token.Token
paylo["id"] = client.ClientId
response, _ := client.Post("invoices", paylo)
inv, err = processInvoice(response)
return inv, err
} | go | func (client *Client) CreateInvoice(price float64, currency string) (inv invoice, err error) {
match, _ := regexp.MatchString("^[[:upper:]]{3}$", currency)
if !match {
err = errors.New("BitPayArgumentError: invalid currency code")
return inv, err
}
paylo := make(map[string]string)
var floatPrec int
if currency == "BTC" {
floatPrec = 8
} else {
floatPrec = 2
}
priceString := strconv.FormatFloat(price, 'f', floatPrec, 64)
paylo["price"] = priceString
paylo["currency"] = currency
paylo["token"] = client.Token.Token
paylo["id"] = client.ClientId
response, _ := client.Post("invoices", paylo)
inv, err = processInvoice(response)
return inv, err
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"CreateInvoice",
"(",
"price",
"float64",
",",
"currency",
"string",
")",
"(",
"inv",
"invoice",
",",
"err",
"error",
")",
"{",
"match",
",",
"_",
":=",
"regexp",
".",
"MatchString",
"(",
"\"",
"\"",
",",
"c... | // CreateInvoice returns an invoice type or pass the error from the server. The method will create an invoice on the BitPay server. | [
"CreateInvoice",
"returns",
"an",
"invoice",
"type",
"or",
"pass",
"the",
"error",
"from",
"the",
"server",
".",
"The",
"method",
"will",
"create",
"an",
"invoice",
"on",
"the",
"BitPay",
"server",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/client/client.go#L58-L79 |
151,698 | bitpay/bitpay-go | client/client.go | GetInvoice | func (client *Client) GetInvoice(invId string) (inv invoice, err error) {
url := client.ApiUri + "/invoices/" + invId
htclient := setHttpClient(client)
response, _ := htclient.Get(url)
inv, err = processInvoice(response)
return inv, err
} | go | func (client *Client) GetInvoice(invId string) (inv invoice, err error) {
url := client.ApiUri + "/invoices/" + invId
htclient := setHttpClient(client)
response, _ := htclient.Get(url)
inv, err = processInvoice(response)
return inv, err
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"GetInvoice",
"(",
"invId",
"string",
")",
"(",
"inv",
"invoice",
",",
"err",
"error",
")",
"{",
"url",
":=",
"client",
".",
"ApiUri",
"+",
"\"",
"\"",
"+",
"invId",
"\n",
"htclient",
":=",
"setHttpClient",
... | // GetInvoice is a public facade method, any client which has the ApiUri field set can retrieve an invoice from that endpoint, provided they have the invoice id. | [
"GetInvoice",
"is",
"a",
"public",
"facade",
"method",
"any",
"client",
"which",
"has",
"the",
"ApiUri",
"field",
"set",
"can",
"retrieve",
"an",
"invoice",
"from",
"that",
"endpoint",
"provided",
"they",
"have",
"the",
"invoice",
"id",
"."
] | 52506f4eed29758eb3c2dd91c8887db6b7771d37 | https://github.com/bitpay/bitpay-go/blob/52506f4eed29758eb3c2dd91c8887db6b7771d37/client/client.go#L144-L150 |
151,699 | etsy/mixer | Godeps/_workspace/src/gopkg.in/gcfg.v1/scanner/scanner.go | next | func (s *Scanner) next() {
if s.rdOffset < len(s.src) {
s.offset = s.rdOffset
if s.ch == '\n' {
s.lineOffset = s.offset
s.file.AddLine(s.offset)
}
r, w := rune(s.src[s.rdOffset]), 1
switch {
case r == 0:
s.error(s.offset, "illegal character NUL")
case r >= 0x80:
// not ASCII
r, w = utf8.DecodeRune(s.src[s.rdOffset:])
if r == utf8.RuneError && w == 1 {
s.error(s.offset, "illegal UTF-8 encoding")
}
}
s.rdOffset += w
s.ch = r
} else {
s.offset = len(s.src)
if s.ch == '\n' {
s.lineOffset = s.offset
s.file.AddLine(s.offset)
}
s.ch = -1 // eof
}
} | go | func (s *Scanner) next() {
if s.rdOffset < len(s.src) {
s.offset = s.rdOffset
if s.ch == '\n' {
s.lineOffset = s.offset
s.file.AddLine(s.offset)
}
r, w := rune(s.src[s.rdOffset]), 1
switch {
case r == 0:
s.error(s.offset, "illegal character NUL")
case r >= 0x80:
// not ASCII
r, w = utf8.DecodeRune(s.src[s.rdOffset:])
if r == utf8.RuneError && w == 1 {
s.error(s.offset, "illegal UTF-8 encoding")
}
}
s.rdOffset += w
s.ch = r
} else {
s.offset = len(s.src)
if s.ch == '\n' {
s.lineOffset = s.offset
s.file.AddLine(s.offset)
}
s.ch = -1 // eof
}
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"next",
"(",
")",
"{",
"if",
"s",
".",
"rdOffset",
"<",
"len",
"(",
"s",
".",
"src",
")",
"{",
"s",
".",
"offset",
"=",
"s",
".",
"rdOffset",
"\n",
"if",
"s",
".",
"ch",
"==",
"'\\n'",
"{",
"s",
".",
... | // Read the next Unicode char into s.ch.
// s.ch < 0 means end-of-file.
// | [
"Read",
"the",
"next",
"Unicode",
"char",
"into",
"s",
".",
"ch",
".",
"s",
".",
"ch",
"<",
"0",
"means",
"end",
"-",
"of",
"-",
"file",
"."
] | 439e3e5fc3756b5f25399a2947c30f1df3de3f47 | https://github.com/etsy/mixer/blob/439e3e5fc3756b5f25399a2947c30f1df3de3f47/Godeps/_workspace/src/gopkg.in/gcfg.v1/scanner/scanner.go#L58-L86 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.